diff --git a/packages/capture-kit/src/snapshot-quality-verdict.ts b/packages/capture-kit/src/snapshot-quality-verdict.ts index 475d09009f..4a939931a6 100644 --- a/packages/capture-kit/src/snapshot-quality-verdict.ts +++ b/packages/capture-kit/src/snapshot-quality-verdict.ts @@ -1,3 +1,4 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; import type { SnapshotQualityState, SnapshotQualityVerdict } from '@agent-device/kernel/snapshot'; import { SNAPSHOT_QUALITY_BACKEND_CAPABILITIES } from './snapshot-quality-backend-capabilities.ts'; @@ -93,6 +94,15 @@ function readCustomActionCoverage( }; } +/** + * Why `find` refuses a capture whose verdict is sparse. The daemon and command-runtime `find` + * paths both raise it; the runner's own wording moves to `details.verdictReason`. + */ +export const FIND_READ_REASONS = { + // The capture came back sparse, so no selector could be resolved against it. + snapshotUnreadable: { reason: 'find_snapshot_unreadable' }, +} as const satisfies ReasonTable<'find'>; + export function isSparseSnapshotQualityVerdict( verdict: SnapshotQualityVerdict | undefined, ): verdict is SnapshotQualityVerdict { diff --git a/packages/command-registry/src/batch.ts b/packages/command-registry/src/batch.ts index ca1973fa89..67d5b16514 100644 --- a/packages/command-registry/src/batch.ts +++ b/packages/command-registry/src/batch.ts @@ -11,7 +11,7 @@ import { import { AppError, asAppError, - BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, + BOUNDED_COMPOSITE_REASONS, type DaemonError, } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; @@ -172,7 +172,7 @@ function batchStepFailure( ...(error.details ?? {}), ...(progress.executedSteps.some(stepMayMutateApp) && !( - error.details?.reason === BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON && + error.details?.reason === BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason && error.details.dispatched === 'no' ) ? { dispatched: 'unknown' } diff --git a/packages/contracts/src/alert-contract.ts b/packages/contracts/src/alert-contract.ts index 231bddfdaf..da953bc620 100644 --- a/packages/contracts/src/alert-contract.ts +++ b/packages/contracts/src/alert-contract.ts @@ -31,15 +31,6 @@ export const ALERT_ACTION_RETRY_MS = 2_000; */ export const MAX_ALERT_WINDOW_MS = 2_147_483_647; -/** - * `alert wait` was given a window longer than the command can honour. The request envelope is a - * timer too, and it is armed above the window with the daemon-result margin, so past that ceiling - * the wait would be cut off mid-window or misfire at 1 ms. The command refuses the window before - * anything runs, with `details.maxWaitWindowMs` naming what it will accept; it never shortens the - * window the caller asked for. - */ -export const ALERT_WAIT_WINDOW_TOO_LONG_REASON = 'alert-wait-window-too-long'; - /** * The one alert failure the family retries on: the backend looked and there was no alert *yet*. * Both Apple backends state it in typed form — the XCTest runner as this `ErrorPayload.code` diff --git a/packages/contracts/src/device-inventory.ts b/packages/contracts/src/device-inventory.ts index c9279d78d1..4933ae5b3d 100644 --- a/packages/contracts/src/device-inventory.ts +++ b/packages/contracts/src/device-inventory.ts @@ -11,7 +11,7 @@ import { type DeviceTarget, type PlatformSelector, } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; export const LOCAL_DEVICE_INVENTORY_PLATFORM_SELECTORS = [ 'android', @@ -107,19 +107,24 @@ function deviceInventoryGroupForDevice(device: DeviceInfo): DeviceInventoryGroup * The refusal reasons a host-local device claim can answer with when another owner holds the * device. Replay reads them to tell an infrastructure conflict from a script failure. */ +export const DEVICE_CLAIM_CONFLICT_REASONS = { + // A live session in another workspace or daemon owns the device. + liveOwner: { reason: 'DEVICE_CLAIM_LIVE_OWNER' }, + // The recorded owner is gone and its resources still need settling before the claim is released. + recoveryPending: { reason: 'DEVICE_CLAIM_RECOVERY_PENDING' }, + // A claim exists, but its owner cannot be verified as live or gone. + ownerUncertain: { reason: 'DEVICE_CLAIM_OWNER_UNCERTAIN' }, +} as const satisfies ReasonTable<'device claims'>; + export type DeviceClaimConflictReason = - | 'DEVICE_CLAIM_LIVE_OWNER' - | 'DEVICE_CLAIM_RECOVERY_PENDING' - | 'DEVICE_CLAIM_OWNER_UNCERTAIN'; + (typeof DEVICE_CLAIM_CONFLICT_REASONS)[keyof typeof DEVICE_CLAIM_CONFLICT_REASONS]['reason']; -const DEVICE_CLAIM_CONFLICT_REASONS = new Set([ - 'DEVICE_CLAIM_LIVE_OWNER', - 'DEVICE_CLAIM_RECOVERY_PENDING', - 'DEVICE_CLAIM_OWNER_UNCERTAIN', -]); +const DEVICE_CLAIM_CONFLICT_REASON_VALUES = new Set( + Object.values(DEVICE_CLAIM_CONFLICT_REASONS).map((row) => row.reason), +); export function isDeviceClaimConflictReason(value: unknown): value is DeviceClaimConflictReason { - return DEVICE_CLAIM_CONFLICT_REASONS.has(value as DeviceClaimConflictReason); + return typeof value === 'string' && DEVICE_CLAIM_CONFLICT_REASON_VALUES.has(value); } /** A provider connection that has no live instance: none was allocated, or the last one ended. */ diff --git a/packages/contracts/src/facades/device.ts b/packages/contracts/src/facades/device.ts index f79eb99d50..4671393079 100644 --- a/packages/contracts/src/facades/device.ts +++ b/packages/contracts/src/facades/device.ts @@ -3,6 +3,7 @@ export { assertResolvedAppsFilter, resolveAppsFilter } from '../app-inventory.ts export type { AppsFilter } from '../app-inventory.ts'; export type { AppStateCommandResult } from '../app-state.ts'; export { + DEVICE_CLAIM_CONFLICT_REASONS, LOCAL_DEVICE_INVENTORY_PLATFORM_SELECTORS, WEB_DESKTOP_DEVICE, countDeviceInventoryByGroup, diff --git a/packages/daemon-client/src/daemon-client-lifecycle-request.ts b/packages/daemon-client/src/daemon-client-lifecycle-request.ts index 604bc8f4f9..8746ad0b2a 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle-request.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle-request.ts @@ -1,6 +1,5 @@ import { DAEMON_LIFECYCLE_REASONS, - DAEMON_SHUTTING_DOWN_REASON, buildDaemonLifecycleRequest, readDaemonLifecycleCensus, type DaemonPaths, @@ -98,7 +97,7 @@ function judgeRefusedAnswer( } if ( refusal.reason === DAEMON_LIFECYCLE_REASONS.instanceMismatch.reason || - refusal.reason === DAEMON_SHUTTING_DOWN_REASON + refusal.reason === DAEMON_LIFECYCLE_REASONS.shuttingDown.reason ) { return { outcome: 'gone' }; } diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index c994f6b190..0df93a1bf0 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -315,9 +315,6 @@ export function readDaemonOwnership(value: unknown): DaemonOwnership { /** Stop if idle: refuses while the detached daemon holds work. */ export const DAEMON_QUIESCE_COMMAND = 'daemon_quiesce'; -/** The reason a daemon gives every request it refuses once it has begun to leave. */ -export const DAEMON_SHUTTING_DOWN_REASON = 'daemon_shutting_down'; - /** Why a daemon refuses a lifecycle request: one entry per rule the admission seam enforces. */ export const DAEMON_LIFECYCLE_REASONS = { // The daemon still holds work, so it refused to leave; `details` counts that work. @@ -326,6 +323,8 @@ export const DAEMON_LIFECYCLE_REASONS = { instanceMismatch: { reason: 'daemon-instance-mismatch' }, // A live host process owns this daemon and ends it through its own `close()`. ownerEmbedded: { reason: 'daemon-owner-embedded' }, + // The daemon has begun to leave, so it refuses every new request; retry against a new daemon. + shuttingDown: { reason: 'daemon_shutting_down' }, } as const satisfies ReasonTable<'daemon lifecycle'>; /** diff --git a/packages/daemon/src/core/__tests__/session-store-lifetime.test.ts b/packages/daemon/src/core/__tests__/session-store-lifetime.test.ts index c0332342e5..a185f48055 100644 --- a/packages/daemon/src/core/__tests__/session-store-lifetime.test.ts +++ b/packages/daemon/src/core/__tests__/session-store-lifetime.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import { test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { DAEMON_SHUTTING_DOWN_REASON } from '@agent-device/daemon-contracts/daemon-resolution'; +import { DAEMON_LIFECYCLE_REASONS } from '@agent-device/daemon-contracts/daemon-resolution'; import { makeSession, makeRepairCompleteSession, @@ -130,7 +130,9 @@ test('shutdown closes draft admission while allowing the current lifetime to set store.closeAdmission(); assert.throws( () => store.publish('late-draft', makeSession('late-draft')), - (error) => error instanceof AppError && error.details?.reason === DAEMON_SHUTTING_DOWN_REASON, + (error) => + error instanceof AppError && + error.details?.reason === DAEMON_LIFECYCLE_REASONS.shuttingDown.reason, ); store.update(ref, { appName: 'Settled' }); assert.equal(store.requireCurrent(ref).appName, 'Settled'); diff --git a/packages/daemon/src/core/daemon-policy.ts b/packages/daemon/src/core/daemon-policy.ts index 81c6357bda..4dda489e8f 100644 --- a/packages/daemon/src/core/daemon-policy.ts +++ b/packages/daemon/src/core/daemon-policy.ts @@ -12,7 +12,7 @@ import { isHostScopedDeviceOf, type DeviceInfo, } from '@agent-device/kernel/device'; -import { AppError, isRequestCanceledError } from '@agent-device/kernel/errors'; +import { AppError, isRequestCanceledError, type ReasonTable } from '@agent-device/kernel/errors'; import { resolveDaemonPolicyCommandName, type DaemonPolicy, @@ -20,6 +20,12 @@ import { } from '@agent-device/daemon-contracts/daemon-policy-file'; import type { DaemonRequest } from './daemon-request.ts'; +const DAEMON_POLICY_REASONS = { + // The daemon operator's policy denies this command, device, capability, or lease; `details.rule` + // names which. + denied: { reason: 'DAEMON_POLICY_DENIED' }, +} as const satisfies ReasonTable<'daemon policy'>; + /** * ADR 0029 enforcement: every request the daemon admits, including `batch` steps and `replay` * actions, which re-enter request admission rather than the HTTP edge. The policy file itself is @@ -181,7 +187,7 @@ function policyDenied( ): AppError { return new AppError('UNAUTHORIZED', message, { ...details, - reason: 'DAEMON_POLICY_DENIED', + reason: DAEMON_POLICY_REASONS.denied.reason, rule, policyDigest: policy.digest, retriable: false, diff --git a/packages/daemon/src/core/interactor-resolution.ts b/packages/daemon/src/core/interactor-resolution.ts index cdd02f098e..96832360f6 100644 --- a/packages/daemon/src/core/interactor-resolution.ts +++ b/packages/daemon/src/core/interactor-resolution.ts @@ -1,7 +1,12 @@ import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +const INTERACTOR_RESOLUTION_REASONS = { + // This process never composed interactor resolution, so it cannot reach a device. + missing: { reason: 'interactor-resolution-missing' }, +} as const satisfies ReasonTable<'daemon runtime'>; /** * Resolves the interactor that speaks to a device — the provider-owned one when a @@ -22,7 +27,7 @@ const NO_INTERACTOR_RESOLUTION: InteractorResolution = { 'COMMAND_FAILED', 'Interactor resolution is not composed for this process.', { - reason: 'interactor-resolution-missing', + reason: INTERACTOR_RESOLUTION_REASONS.missing.reason, }, ); }, diff --git a/packages/daemon/src/core/lease-context.ts b/packages/daemon/src/core/lease-context.ts index f7a5c71f3c..ce75c12099 100644 --- a/packages/daemon/src/core/lease-context.ts +++ b/packages/daemon/src/core/lease-context.ts @@ -1,9 +1,6 @@ import type { DaemonRequest } from './daemon-request.ts'; import { getRequestExecutionDeadlineMs } from '@agent-device/host-kit/request'; -import { - AppError, - BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, -} from '@agent-device/kernel/errors'; +import { AppError, BOUNDED_COMPOSITE_REASONS } from '@agent-device/kernel/errors'; import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; import { resolveCommandStandaloneProjection } from '@agent-device/command-registry/registry'; import type { LeaseBackend } from '@agent-device/kernel/contracts'; @@ -23,7 +20,7 @@ export type { LeaseScope }; export function refuseBoundedCompositeResourceOperation(req: DaemonRequest, shape: string): never { const commandName = resolveCommandStandaloneProjection(req.command)?.command; throw new AppError('UNSUPPORTED_OPERATION', `${shape} cannot run within a bounded composite`, { - reason: BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, + reason: BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason, shape, ...(commandName ? { standaloneCommandName: commandName } : {}), hint: `Run the original ${commandName ?? 'refused'} operation separately with its original arguments and options, the same --session value, and the same private CLI context. Inspect completed steps before retrying the batch or replay.`, diff --git a/packages/daemon/src/core/ref-frame.ts b/packages/daemon/src/core/ref-frame.ts index 4947a57a8e..b66941004b 100644 --- a/packages/daemon/src/core/ref-frame.ts +++ b/packages/daemon/src/core/ref-frame.ts @@ -1,4 +1,5 @@ import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; +import type { ReasonTable } from '@agent-device/kernel/errors'; import { expiredRefFrame, issuedRefFrame, @@ -37,11 +38,21 @@ const outdatedObservations = new WeakSet(); * Typed admission-failure reasons, evaluated in this order so the caller can * distinguish "capture a complete snapshot" from "use the emitted pinned ref". */ +export const REF_FRAME_REASONS = { + // A device action since the snapshot expired the ref frame, so a mutation using its refs is + // refused; a read that still has retained evidence answers with a staleness warning instead. + frameExpired: { reason: 'ref_frame_expired' }, + // The pinned ref was minted from a snapshot generation that a newer one superseded. + generationMismatch: { reason: 'ref_generation_mismatch' }, + // A plain ref needs a complete frame. Retry with the pinned ref in `details.suggestedRef` when + // present; otherwise capture a fresh interactive snapshot or use a stable selector. + plainRefRequiresCompleteFrame: { reason: 'plain_ref_requires_complete_frame' }, + // The current ref frame did not issue this ref, so it no longer names a node. + notIssued: { reason: 'ref_not_issued' }, +} as const satisfies ReasonTable<'ref frames'>; + export type RefFrameRejectReason = - | 'ref_frame_expired' - | 'ref_generation_mismatch' - | 'plain_ref_requires_complete_frame' - | 'ref_not_issued'; + (typeof REF_FRAME_REASONS)[keyof typeof REF_FRAME_REASONS]['reason']; export type RefFrameAdmission = | { admitted: true } @@ -225,20 +236,20 @@ export function admitRefMutation(params: { const { session, refBody, mintedGeneration } = params; if (refFrameState(session) === 'expired') { - return { admitted: false, reason: 'ref_frame_expired' }; + return { admitted: false, reason: REF_FRAME_REASONS.frameExpired.reason }; } if (mintedGeneration !== undefined && mintedGeneration !== refFrameEpoch(session)) { - return { admitted: false, reason: 'ref_generation_mismatch' }; + return { admitted: false, reason: REF_FRAME_REASONS.generationMismatch.reason }; } const scope = refFrameScope(session); if (scope !== 'all') { if (mintedGeneration === undefined) { - return { admitted: false, reason: 'plain_ref_requires_complete_frame' }; + return { admitted: false, reason: REF_FRAME_REASONS.plainRefRequiresCompleteFrame.reason }; } if (!scope.has(refBody)) { - return { admitted: false, reason: 'ref_not_issued' }; + return { admitted: false, reason: REF_FRAME_REASONS.notIssued.reason }; } } @@ -253,6 +264,8 @@ export function admitRefMutation(params: { */ export function admitRefRead(session: SessionState, refBody: string): RefFrameAdmission { const scope = refFrameScope(session); - if (scope !== 'all' && !scope.has(refBody)) return { admitted: false, reason: 'ref_not_issued' }; + if (scope !== 'all' && !scope.has(refBody)) { + return { admitted: false, reason: REF_FRAME_REASONS.notIssued.reason }; + } return { admitted: true }; } diff --git a/packages/daemon/src/core/runtime-admission.ts b/packages/daemon/src/core/runtime-admission.ts index e8fe2c39f7..ba2b064f4c 100644 --- a/packages/daemon/src/core/runtime-admission.ts +++ b/packages/daemon/src/core/runtime-admission.ts @@ -8,7 +8,7 @@ import { } from '@agent-device/contracts/platform-runtime'; import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { BindDeviceRuntime, InspectDeviceRuntimeFacts, @@ -19,6 +19,12 @@ import type { DaemonCommandContext } from './context.ts'; import type { ResolvedGenericExecution } from './generic-leaf-execution.ts'; import { type DaemonFailureResponse, errorResponse } from '@agent-device/kernel/contracts'; +export const RUNTIME_GATEWAY_REASONS = { + // The daemon was composed without the runtime gateway, admission ledger, or diagnostics service + // this command needs. + missing: { reason: 'runtime-gateway-missing' }, +} as const satisfies ReasonTable<'daemon runtime'>; + /** Builds the failure a command reports when its exact device cell does not admit an operation. */ export type UnavailableRuntimeResponse = ( unavailable: RuntimeOperationUnavailability, @@ -166,13 +172,13 @@ function requireFactsInspection( ): InspectDeviceRuntimeFacts { if (inspectFacts) return inspectFacts; throw new AppError('COMMAND_FAILED', 'Device runtime facts inspection is unavailable.', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } function requireDeviceBinding(bindDevice: BindDeviceRuntime | undefined): BindDeviceRuntime { if (bindDevice) return bindDevice; throw new AppError('COMMAND_FAILED', 'Device runtime binding is unavailable.', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } diff --git a/packages/daemon/src/core/session-recovery-hints.ts b/packages/daemon/src/core/session-recovery-hints.ts index 2a75abbbda..7001dfc2a8 100644 --- a/packages/daemon/src/core/session-recovery-hints.ts +++ b/packages/daemon/src/core/session-recovery-hints.ts @@ -1,8 +1,14 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; import type { SessionRef, SessionState } from './session-state.ts'; import { errorResponse, type DaemonFailureResponse } from '@agent-device/kernel/contracts'; +const WORKSPACE_SESSION_REASONS = { + // A session in another workspace already uses the device; `details.session` names it. + scopeConflict: { reason: 'WORKSPACE_SESSION_SCOPE_CONFLICT' }, +} as const satisfies ReasonTable<'sessions'>; + export type SessionRecoveryContext = 'device-in-use' | 'selector-conflict'; export type SessionRecoveryOptions = { @@ -78,7 +84,7 @@ export function buildForeignWorkspaceSessionConflict( 'DEVICE_IN_USE', `Device is already in use by workspace session "${inUse.address}".`, { - reason: 'WORKSPACE_SESSION_SCOPE_CONFLICT', + reason: WORKSPACE_SESSION_REASONS.scopeConflict.reason, session: inUse.address, deviceId: device.id, deviceName: device.name, diff --git a/packages/daemon/src/core/session-runtime-admission.ts b/packages/daemon/src/core/session-runtime-admission.ts index 7f2c203315..a167e25952 100644 --- a/packages/daemon/src/core/session-runtime-admission.ts +++ b/packages/daemon/src/core/session-runtime-admission.ts @@ -12,7 +12,7 @@ import { AppError } from '@agent-device/kernel/errors'; import type { BindDeviceRuntime, InspectDeviceRuntimeFacts } from './request-runtime-binding.ts'; import type { SessionStore } from './session-store.ts'; import type { DaemonRequest } from './daemon-request.ts'; -import { unsupportedOperationResponse } from './runtime-admission.ts'; +import { RUNTIME_GATEWAY_REASONS, unsupportedOperationResponse } from './runtime-admission.ts'; export type RuntimeCommandHandlerParams = Readonly<{ host: HostEnvironment; @@ -41,7 +41,7 @@ export function requireRuntimeFacts( ): InspectDeviceRuntimeFacts { if (inspectFacts) return inspectFacts; throw new AppError('COMMAND_FAILED', 'Device runtime facts inspection is unavailable.', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } @@ -156,6 +156,6 @@ export function requireRuntimeBinding( ): BindDeviceRuntime { if (bindDevice) return bindDevice; throw new AppError('COMMAND_FAILED', 'Device runtime binding is unavailable.', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index 11a1409481..5663dcec34 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import { publicPlatformString } from '@agent-device/kernel/device'; import { dragGesturePayloadFromPositionals } from '@agent-device/gestures/gesture-normalization'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { recordedSelectorExpression } from '@agent-device/selectors'; import { inferFillText, @@ -40,6 +40,12 @@ import { validateActivePublicationActions, } from './session-script-active-publication.ts'; +const SCRIPT_WRITE_REASONS = { + // Writing the session script failed; check the target path and its permissions, then record + // again. + writeFailed: { reason: 'script_write_failed' }, +} as const satisfies ReasonTable<'script recording'>; + /** * `{ written: true; path }` — committed. `{ written: false }` (no `error`) — intentionally not * written (not recording, an aborted/incomplete repair transaction, an aborted ordinary authoring @@ -252,7 +258,7 @@ function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): 'COMMAND_FAILED', `Failed to write the session script${scriptPath ? ` to ${scriptPath}` : ''}: ${detail}`, { - reason: 'script_write_failed', + reason: SCRIPT_WRITE_REASONS.writeFailed.reason, ...(scriptPath ? { path: scriptPath } : {}), hint: 'Check the target path and its permissions, then re-record with open --save-script.', }, diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 203d1277c2..404acd0522 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -3,11 +3,11 @@ import { resolveSessionAppLogPath, resolveSessionAppLogPidPath, } from '@agent-device/daemon-contracts/session-artifact-paths'; -import { DAEMON_SHUTTING_DOWN_REASON } from '@agent-device/daemon-contracts/daemon-resolution'; +import { DAEMON_LIFECYCLE_REASONS } from '@agent-device/daemon-contracts/daemon-resolution'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import path from 'node:path'; import fs from 'node:fs'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { devicesOverlap } from '@agent-device/kernel/device'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { SessionRef, SessionRuntimeHints, SessionState } from './session-state.ts'; @@ -49,6 +49,13 @@ import { type SessionEventLogPage, } from '@agent-device/session-journal/session-event-log'; +const SESSION_STORE_REASONS = { + // Another live session already holds this session address. + addressOccupied: { reason: 'session_address_occupied' }, + // The session the command ran in ended first; open a new session before retrying. + lifetimeEnded: { reason: 'session_lifetime_ended' }, +} as const satisfies ReasonTable<'sessions'>; + const REPAIR_TOMBSTONE_TTL_MS = 60 * 60_000; type SessionEntry = { current: SessionState }; type SessionPatch = Partial | ((current: SessionState) => Partial); @@ -94,7 +101,7 @@ export class SessionStore { assertAdmissionOpen(address: string): void { if (!this.acceptingSessions) { throw new AppError('COMMAND_FAILED', 'Daemon is shutting down', { - reason: DAEMON_SHUTTING_DOWN_REASON, + reason: DAEMON_LIFECYCLE_REASONS.shuttingDown.reason, session: address, }); } @@ -104,7 +111,7 @@ export class SessionStore { this.assertAdmissionOpen(address); if (this.sessions.has(address)) { throw new AppError('COMMAND_FAILED', 'Session address is already occupied', { - reason: 'session_address_occupied', + reason: SESSION_STORE_REASONS.addressOccupied.reason, session: address, }); } @@ -137,7 +144,7 @@ export class SessionStore { const session = this.resolveCurrent(ref); if (!session) { throw new AppError('COMMAND_FAILED', 'Session lifetime has ended', { - reason: 'session_lifetime_ended', + reason: SESSION_STORE_REASONS.lifetimeEnded.reason, session: ref.address, hint: 'Open a new session before retrying the command.', }); diff --git a/packages/daemon/src/core/session-tenant-scope.ts b/packages/daemon/src/core/session-tenant-scope.ts index 6d47e3c280..4c0f52ec6d 100644 --- a/packages/daemon/src/core/session-tenant-scope.ts +++ b/packages/daemon/src/core/session-tenant-scope.ts @@ -1,9 +1,15 @@ import { isTenantOwnedSessionName } from '@agent-device/contracts/daemon-http'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { WebSessionIdentity } from '@agent-device/kernel/device'; import type { SessionScope } from '@agent-device/contracts/session'; import type { DaemonRequest } from './daemon-request.ts'; +const REQUEST_SCOPE_REASONS = { + // A request reached device resolution without the web session its request scope derives; this is + // a daemon bug. + webSessionMissing: { reason: 'request_web_session_missing' }, +} as const satisfies ReasonTable<'daemon runtime'>; + /** * The one rule that says which sessions belong to a tenant: under tenant * isolation every session name lives beneath its own `:` prefix @@ -79,7 +85,7 @@ export function requestWebSession(req: DaemonRequest): WebSessionIdentity { const webSession = req.internal?.webSession; if (webSession === undefined) { throw new AppError('UNKNOWN', 'A request reached device resolution outside a request scope.', { - reason: 'request_web_session_missing', + reason: REQUEST_SCOPE_REASONS.webSessionMissing.reason, }); } return webSession; diff --git a/packages/daemon/src/core/snapshot-runtime-binding.ts b/packages/daemon/src/core/snapshot-runtime-binding.ts index dac4e3bb27..1ae65cd6fa 100644 --- a/packages/daemon/src/core/snapshot-runtime-binding.ts +++ b/packages/daemon/src/core/snapshot-runtime-binding.ts @@ -46,9 +46,14 @@ import { type BoundNativeTextRead, } from './selector-operation-binding.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { isHandheldAppleDevice } from '@agent-device/kernel/device'; +const SNAPSHOT_SESSION_REASONS = { + // The iOS command needs an active app session on the target device; run `open` first. + iosAppSessionRequired: { reason: 'ios_app_session_required' }, +} as const satisfies ReasonTable<'snapshot capture'>; + export type SnapshotRuntimeRouteParams = { /** Builds the command surface this request's snapshot runtime executes through. */ createCommandSurface: CreateDaemonCommandSurface; @@ -483,7 +488,7 @@ async function snapshotPlanUnavailableResponse( 'SESSION_NOT_FOUND', `iOS ${params.command} requires an active app session on the target device. Run open first (for example: open --session ${params.session?.name ?? 'sim'} --platform ios --device "" ).`, { - reason: 'ios_app_session_required', + reason: SNAPSHOT_SESSION_REASONS.iosAppSessionRequired.reason, ...(openCommandHint ? { hint: openCommandHint } : {}), }, ); diff --git a/packages/daemon/src/core/tenant-owned-entry.ts b/packages/daemon/src/core/tenant-owned-entry.ts index 5367ca2a78..15018221c3 100644 --- a/packages/daemon/src/core/tenant-owned-entry.ts +++ b/packages/daemon/src/core/tenant-owned-entry.ts @@ -1,4 +1,9 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +export const TENANT_RESOURCE_REASONS = { + // The artifact, upload, or path id expired or never existed; the daemon cannot tell which. + expired: { reason: 'RESOURCE_EXPIRED' }, +} as const satisfies ReasonTable<'daemon resources'>; type TenantOwnedEntry = { tenantId?: string }; @@ -15,7 +20,7 @@ export type TenantOwnedResourceKind = { */ export function expiredTenantOwnedEntryError(kind: TenantOwnedResourceKind, id: string): AppError { return new AppError('COMMAND_FAILED', `${kind.label} not found or expired: ${id}`, { - reason: 'RESOURCE_EXPIRED', + reason: TENANT_RESOURCE_REASONS.expired.reason, hint: kind.expiredHint, }); } diff --git a/packages/daemon/src/execution/generic-runtime-execution.ts b/packages/daemon/src/execution/generic-runtime-execution.ts index 3af1dc5781..361334b9ee 100644 --- a/packages/daemon/src/execution/generic-runtime-execution.ts +++ b/packages/daemon/src/execution/generic-runtime-execution.ts @@ -1,3 +1,4 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; import type { ResolvedGenericExecution } from '../core/generic-leaf-execution.ts'; import { resolveBoundFocusRuntime } from './focus-runtime.ts'; import { resolveBoundScrollRuntime } from './scroll-runtime.ts'; @@ -17,6 +18,11 @@ import { resolveBoundFoldRuntime } from './fold-runtime.ts'; import { resolveBoundTvRemoteRuntime } from './tv-remote-runtime.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; +const GENERIC_ROUTE_REASONS = { + // The command reached the generic route, which has no runtime execution for it. + runtimeMissing: { reason: 'generic-route-runtime-missing' }, +} as const satisfies ReasonTable<'daemon runtime'>; + /** * The generic route's runtime-owned leaves (ADR 0019). Each one admits its own exact owner facts * and binds once here, before the dispatcher runs, so the dispatcher itself never learns a command @@ -136,7 +142,7 @@ export async function resolveGenericRuntimeExecution( response: errorResponse( 'COMMAND_FAILED', `${params.req.command} has no runtime execution on the generic route`, - { reason: 'generic-route-runtime-missing' }, + { reason: GENERIC_ROUTE_REASONS.runtimeMissing.reason }, ), }; } diff --git a/packages/daemon/src/execution/handlers/__tests__/react-native.test.ts b/packages/daemon/src/execution/handlers/__tests__/react-native.test.ts index 38c13f2182..9c96389c2c 100644 --- a/packages/daemon/src/execution/handlers/__tests__/react-native.test.ts +++ b/packages/daemon/src/execution/handlers/__tests__/react-native.test.ts @@ -754,7 +754,9 @@ test('react-native dismiss-overlay reports sparse verdict instead of no overlay message: 'React Native overlay state could not be determined because the accessibility tree is unreadable', details: { - reason: 'sparse tree', + reason: 'overlay_snapshot_unreadable', + verdictReason: 'sparse tree', + verdictReasonCode: 'sparse-tree', hint: expect.stringContaining('snapshot quality verdict is sparse'), }, }); diff --git a/packages/daemon/src/execution/handlers/__tests__/snapshot-alert.test.ts b/packages/daemon/src/execution/handlers/__tests__/snapshot-alert.test.ts index c6fa79da33..e57879ebe2 100644 --- a/packages/daemon/src/execution/handlers/__tests__/snapshot-alert.test.ts +++ b/packages/daemon/src/execution/handlers/__tests__/snapshot-alert.test.ts @@ -2,7 +2,6 @@ import { test, expect, vi, beforeEach } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { ALERT_RUNNER_MAX_BUDGET_MS, - ALERT_WAIT_WINDOW_TOO_LONG_REASON, DEFAULT_ALERT_TIMEOUT_MS, MAX_ALERT_WINDOW_MS, } from '@agent-device/contracts/alert-contract'; @@ -223,7 +222,7 @@ test('alert wait refuses a window the request envelope cannot be armed for, nami ]).catch((error: unknown) => error); expect(refusal).toBeInstanceOf(AppError); expect((refusal as AppError).code).toBe('INVALID_ARGS'); - expect((refusal as AppError).details?.reason).toBe(ALERT_WAIT_WINDOW_TOO_LONG_REASON); + expect((refusal as AppError).details?.reason).toBe('alert-wait-window-too-long'); expect((refusal as AppError).details?.maxWaitWindowMs).toBe(MAX_ARMABLE_ALERT_WAIT_WINDOW_MS); // The contract's own larger ceiling is refused for the same typed reason: the command never // accepts a window it cannot honour and shortens it on the way down. @@ -232,7 +231,7 @@ test('alert wait refuses a window the request envelope cannot be armed for, nami ).rejects.toMatchObject({ code: 'INVALID_ARGS', details: { - reason: ALERT_WAIT_WINDOW_TOO_LONG_REASON, + reason: 'alert-wait-window-too-long', maxWaitWindowMs: MAX_ARMABLE_ALERT_WAIT_WINDOW_MS, }, }); diff --git a/packages/daemon/src/execution/handlers/react-native.ts b/packages/daemon/src/execution/handlers/react-native.ts index d88fe29d19..04457826e5 100644 --- a/packages/daemon/src/execution/handlers/react-native.ts +++ b/packages/daemon/src/execution/handlers/react-native.ts @@ -10,7 +10,7 @@ import { type ReactNativeOverlayDismissTarget, } from '@agent-device/capture-kit/react-native-overlay'; import { reactNativeOverlaySurfaceFromCapture } from '@agent-device/contracts/react-native-overlay'; -import { normalizeError } from '@agent-device/kernel/errors'; +import { normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; import { stripUndefined } from '@agent-device/kernel/record'; import { successText } from '@agent-device/kernel/success-text'; @@ -28,6 +28,12 @@ import { expireRefFrame } from '../../core/ref-frame.ts'; import { readSnapshotNodesReferenceFrame } from '@agent-device/capture-kit/touch-reference-frame'; import { errorResponse, noActiveSessionError } from '@agent-device/kernel/contracts'; +const REACT_NATIVE_OVERLAY_REASONS = { + // `react-native dismiss-overlay` got a sparse capture, so it cannot tell whether an overlay is + // showing. + snapshotUnreadable: { reason: 'overlay_snapshot_unreadable' }, +} as const satisfies ReasonTable<'react-native'>; + export async function handleReactNativeCommands( params: InteractionRouteInput, ): Promise { @@ -130,7 +136,9 @@ function responseForSparseReactNativeOverlaySnapshot( 'COMMAND_FAILED', 'React Native overlay state could not be determined because the accessibility tree is unreadable', { - reason: verdict.reason, + reason: REACT_NATIVE_OVERLAY_REASONS.snapshotUnreadable.reason, + verdictReason: verdict.reason, + verdictReasonCode: verdict.reasonCode, hint: 'The snapshot quality verdict is sparse. Use screenshot as visual truth; if an overlay is visible, report it or navigate with coordinates, then retry snapshot or dismiss-overlay on a readable screen.', }, ); diff --git a/packages/daemon/src/execution/handlers/snapshot-alert.ts b/packages/daemon/src/execution/handlers/snapshot-alert.ts index 74e4c706b6..04432a26b8 100644 --- a/packages/daemon/src/execution/handlers/snapshot-alert.ts +++ b/packages/daemon/src/execution/handlers/snapshot-alert.ts @@ -6,9 +6,8 @@ import { parseAlertAction, type AlertAction, DEFAULT_ALERT_TIMEOUT_MS as DEFAULT_TIMEOUT_MS, - ALERT_WAIT_WINDOW_TOO_LONG_REASON, } from '@agent-device/contracts/alert-contract'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { alertAcceptUse, alertDismissUse, @@ -34,6 +33,12 @@ import { admitRuntimeUse, type RuntimeAdmissionBindings } from '../../core/runti import { runtimeExecutionFromContext } from '../../core/snapshot-runtime-capture-input.ts'; import type { DaemonFailureResponse, DaemonResponse } from '@agent-device/kernel/contracts'; +const ALERT_WAIT_REASONS = { + // `alert wait` was given a longer window than it can honour; the command refuses it before + // running and never shortens it. `details.maxWaitWindowMs` names the limit. + windowTooLong: { reason: 'alert-wait-window-too-long' }, +} as const satisfies ReasonTable<'alert'>; + type HandleAlertCommandParams = { req: DaemonRequest; logPath: string; @@ -182,7 +187,7 @@ function alertTimeoutMs(action: AlertAction, rawTimeout: string | undefined): nu `alert wait timeoutMs exceeds the maximum of ${MAX_ARMABLE_ALERT_WAIT_WINDOW_MS} ms`, { hint: 'Pass a shorter timeout, or run repeated alert waits.', - reason: ALERT_WAIT_WINDOW_TOO_LONG_REASON, + reason: ALERT_WAIT_REASONS.windowTooLong.reason, maxWaitWindowMs: MAX_ARMABLE_ALERT_WAIT_WINDOW_MS, }, ); diff --git a/packages/daemon/src/execution/interaction/internal/__tests__/find.test.ts b/packages/daemon/src/execution/interaction/internal/__tests__/find.test.ts index 8b524a2a6c..0c381d3cb8 100644 --- a/packages/daemon/src/execution/interaction/internal/__tests__/find.test.ts +++ b/packages/daemon/src/execution/interaction/internal/__tests__/find.test.ts @@ -188,74 +188,84 @@ test('handleFindCommands click hands the leaf the baseline its own capture minte expect(carried?.tree.nodes).toContain(carried?.node); }); -test('handleFindCommands click tries query-scoped full retry before failing sparse verdict', async () => { - const session = makeSession('default'); - session.snapshot = { - nodes: [ - { - index: 0, - ref: 'e1', - type: 'Application', - rect: { x: 0, y: 0, width: 390, height: 844 }, - }, - { - index: 1, - ref: 'e2', - type: 'Button', - label: 'Previous Search', - rect: { x: 80, y: 792, width: 78, height: 48 }, - }, - ], - createdAt: Date.now(), - backend: 'xctest', - }; - mockDispatch.mockImplementation(async (_device, command) => { - if (command !== 'snapshot') return {}; - return { - backend: 'xctest', - quality: { - state: 'sparse', - backend: 'private-ax', - reason: 'sparse tree', - reasonCode: 'sparse-tree', - }, +test.each([ + ['click', ['Search', 'click']], + ['fill', ['Search', 'fill', 'text']], + ['focus', ['Search', 'focus']], + ['type', ['Search', 'type', 'text']], +])( + 'handleFindCommands %s tries query-scoped full retry before failing sparse verdict', + async (_action, positionals) => { + const session = makeSession('default'); + session.snapshot = { nodes: [ { index: 0, + ref: 'e1', type: 'Application', - rect: { x: 0, y: 0, width: 0, height: 0 }, + rect: { x: 0, y: 0, width: 390, height: 844 }, + }, + { + index: 1, + ref: 'e2', + type: 'Button', + label: 'Previous Search', + rect: { x: 80, y: 792, width: 78, height: 48 }, }, ], + createdAt: Date.now(), + backend: 'xctest', }; - }); + mockDispatch.mockImplementation(async (_device, command) => { + if (command !== 'snapshot') return {}; + return { + backend: 'xctest', + quality: { + state: 'sparse', + backend: 'private-ax', + reason: 'sparse tree', + reasonCode: 'sparse-tree', + }, + nodes: [ + { + index: 0, + type: 'Application', + rect: { x: 0, y: 0, width: 0, height: 0 }, + }, + ], + }; + }); - const previousSnapshot = session.snapshot; - const { response, invokeCalls } = await runFindClickScenario({ - positionals: ['Search', 'click'], - session, - }); + const previousSnapshot = session.snapshot; + const { response, invokeCalls } = await runFindClickScenario({ + positionals, + session, + }); - expect(response.ok).toBe(false); - expect(session.snapshot).toBe(previousSnapshot); - expect(invokeCalls).toHaveLength(0); - expect(!response.ok && response.error).toMatchObject({ - code: 'COMMAND_FAILED', - message: 'find could not read the current accessibility tree', - details: { - reason: 'sparse tree', - hint: expect.stringContaining('snapshot quality verdict is sparse'), - }, - }); - const snapshotCalls = mockDispatch.mock.calls.filter((call) => call[1] === 'snapshot'); - expect(snapshotCalls).toHaveLength(2); - expect(snapshotCalls[0]![4]).toMatchObject({ - snapshotInteractiveOnly: true, - }); - expect(snapshotCalls[1]![4]).toMatchObject({ - snapshotInteractiveOnly: false, - snapshotScope: 'Search', - }); -}); + expect(response.ok).toBe(false); + expect(session.snapshot).toBe(previousSnapshot); + expect(invokeCalls).toHaveLength(0); + expect(!response.ok && response.error).toMatchObject({ + code: 'COMMAND_FAILED', + message: 'find could not read the current accessibility tree', + details: { + reason: 'find_snapshot_unreadable', + verdictReason: 'sparse tree', + verdictReasonCode: 'sparse-tree', + hint: expect.stringContaining('snapshot quality verdict is sparse'), + }, + }); + const snapshotCalls = mockDispatch.mock.calls.filter((call) => call[1] === 'snapshot'); + expect(snapshotCalls).toHaveLength(2); + expect(snapshotCalls[0]![4]).toMatchObject({ + snapshotInteractiveOnly: true, + }); + expect(snapshotCalls[1]![4]).toMatchObject({ + snapshotInteractiveOnly: false, + snapshotScope: 'Search', + }); + }, +); test('handleFindCommands click uses query-scoped full retry when sparse verdict recovers', async () => { const snapshotResponses = [ diff --git a/packages/daemon/src/execution/interaction/internal/find-target-capture.ts b/packages/daemon/src/execution/interaction/internal/find-target-capture.ts index 6e041fc64c..de0598d3a5 100644 --- a/packages/daemon/src/execution/interaction/internal/find-target-capture.ts +++ b/packages/daemon/src/execution/interaction/internal/find-target-capture.ts @@ -2,6 +2,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { FindLocator } from '@agent-device/selectors'; import type { BoundSelectorCapture } from '../../selector-capture-binding.ts'; import type { SnapshotQualityVerdict } from '@agent-device/kernel/snapshot'; +import { FIND_READ_REASONS } from '@agent-device/capture-kit/snapshot-quality-verdict'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import type { CaptureProvenance, RequestCaptureProof } from '../../../core/capture-disclosure.ts'; import { createSelectorCaptureRuntime } from '../../selector-capture-runtime.ts'; @@ -73,7 +74,9 @@ export function createFindTargetCapture( export function sparseFindSnapshotResponse(verdict: SnapshotQualityVerdict): DaemonResponse { return errorResponse('COMMAND_FAILED', 'find could not read the current accessibility tree', { - reason: verdict.reason, + reason: FIND_READ_REASONS.snapshotUnreadable.reason, + verdictReason: verdict.reason, + verdictReasonCode: verdict.reasonCode, hint: 'The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.', }); } diff --git a/packages/daemon/src/execution/interaction/internal/interaction-recorded-input.ts b/packages/daemon/src/execution/interaction/internal/interaction-recorded-input.ts index 8553bae632..5cc43a6fb4 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-recorded-input.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-recorded-input.ts @@ -1,7 +1,15 @@ import type { CommandFlags } from '@agent-device/contracts/command'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { validateRecordedInputVariableName } from '@agent-device/ad-script'; +const FILL_RECORDING_REASONS = { + // `fill --record-as` needs an armed script recording; open a session with `--save-script` first. + recordAsRequiresArmedRecording: { reason: 'fill_record_as_requires_armed_recording' }, + // `fill --text-stdin` needs `--record-as` or `--no-record` while a recording is armed, so the + // stdin text stays out of the script. + textStdinUnparameterizedRecording: { reason: 'fill_text_stdin_unparameterized_recording' }, +} as const satisfies ReasonTable<'fill'>; + export function assertRecordedFillParameterization(params: { flags: CommandFlags | undefined; replayPlanStep: boolean; @@ -23,7 +31,7 @@ export function assertRecordedFillParameterization(params: { throw new AppError( 'INVALID_ARGS', 'fill --record-as requires an armed script recording. Start a fresh session with open --save-script, then retry the fill.', - { reason: 'fill_record_as_requires_armed_recording' }, + { reason: FILL_RECORDING_REASONS.recordAsRequiresArmedRecording.reason }, ); } } @@ -42,6 +50,6 @@ function assertStdinFillNotRecordedLiterally(params: { throw new AppError( 'INVALID_ARGS', 'fill --text-stdin needs --record-as or --no-record while script recording is armed, so the stdin text is not published in the script.', - { reason: 'fill_text_stdin_unparameterized_recording' }, + { reason: FILL_RECORDING_REASONS.textStdinUnparameterizedRecording.reason }, ); } diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-press-admission.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-press-admission.ts index f8fd91e7c5..41292d5c8a 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-press-admission.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-press-admission.ts @@ -1,3 +1,4 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { CommandFlags } from '@agent-device/contracts/command'; import type { InteractionRequestTarget } from '@agent-device/contracts/interaction'; @@ -29,6 +30,13 @@ import { } from './interaction-touch-targets.ts'; import { errorResponse, noActiveSessionError } from '@agent-device/kernel/contracts'; +const PRESS_SEQUENCE_REASONS = { + // A multi-ref press sequence cannot be recorded; record one press per key, or pass `--no-record`. + recordingUnsupported: { reason: 'sequence-recording-unsupported' }, + // A multi-ref press sequence cannot carry a replay target guard; re-record one press per key. + replayGuardUnsupported: { reason: 'sequence-replay-guard-unsupported' }, +} as const satisfies ReasonTable<'press'>; + /** * Whether a targeted `press`/`click`/`longpress`/`hover` may act, and on what: macOS * surface and capability policy, click-option validation, target parsing, and @@ -210,14 +218,14 @@ function sequenceRecordingGuardResponse( return errorResponse( 'INVALID_ARGS', 'A multi-ref press sequence cannot be recorded: the recorder binds one target per step, so the recorded step would press only the first key. Record one press per key, or pass --no-record on this step.', - { reason: 'sequence-recording-unsupported' }, + { reason: PRESS_SEQUENCE_REASONS.recordingUnsupported.reason }, ); } if (req.internal?.replayTargetGuard !== undefined) { return errorResponse( 'INVALID_ARGS', 'A multi-ref press sequence cannot carry a replay target guard: the guard binds one target, so the replayed step would press only the first key. Re-record the journey as one press per key.', - { reason: 'sequence-replay-guard-unsupported' }, + { reason: PRESS_SEQUENCE_REASONS.replayGuardUnsupported.reason }, ); } return undefined; diff --git a/packages/daemon/src/execution/request-dispatch-disclosure.test.ts b/packages/daemon/src/execution/request-dispatch-disclosure.test.ts index c77411bb8d..6f98bd9980 100644 --- a/packages/daemon/src/execution/request-dispatch-disclosure.test.ts +++ b/packages/daemon/src/execution/request-dispatch-disclosure.test.ts @@ -36,7 +36,7 @@ vi.mock('../core/device/device-ready.ts', () => ({ import { AppError, - BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, + BOUNDED_COMPOSITE_REASONS, PRE_DISPATCH_REFUSAL_REASONS, } from '@agent-device/kernel/errors'; import { resolveCommandRecordingEffect } from '@agent-device/command-registry/registry'; @@ -373,7 +373,7 @@ async function batchReadThenRefusedStep(): Promise { async function batchMutationThenResourceRefusal(): Promise { gestureRuntimeSpies.captureSnapshot.mockRejectedValueOnce( new AppError('UNSUPPORTED_OPERATION', 'resource shape unsupported', { - reason: BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, + reason: BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason, dispatched: 'no', }), ); @@ -390,7 +390,7 @@ async function batchMutationThenResourceRefusal(): Promise { assert.ok(failure instanceof AppError); assert.equal(routeOperationSpies.tapPoint.mock.calls.length, 1); assert.equal(failure.details?.dispatchedSteps, 1); - assert.equal(failure.details?.reason, BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON); + assert.equal(failure.details?.reason, BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason); throw failure; } @@ -480,7 +480,7 @@ test('a typed refusal discloses no dispatch for its step after an earlier dispat code: 'UNSUPPORTED_OPERATION' as const, message: 'resource shape unsupported', details: { - reason: BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, + reason: BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason, dispatched: 'no' as const, }, }, diff --git a/packages/daemon/src/execution/request-dispatch-disclosure.ts b/packages/daemon/src/execution/request-dispatch-disclosure.ts index f729648755..55edec5d71 100644 --- a/packages/daemon/src/execution/request-dispatch-disclosure.ts +++ b/packages/daemon/src/execution/request-dispatch-disclosure.ts @@ -5,7 +5,7 @@ import { detailsAfterDispatchedSteps, discloseDispatch, type ErrorWireDetails, - BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, + BOUNDED_COMPOSITE_REASONS, } from '@agent-device/kernel/errors'; import { resolveCommandDispatchDisclosure } from '@agent-device/command-registry/registry'; import type { DaemonRequest } from '../core/daemon-request.ts'; @@ -51,7 +51,7 @@ function disclosedDetails( ): ErrorWireDetails | undefined { if (ledger.dispatchedSteps > 0) { const disclosed = detailsAfterDispatchedSteps(details, ledger.dispatchedSteps); - return details?.reason === BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON && + return details?.reason === BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason && details.dispatched === 'no' ? { ...disclosed, dispatched: 'no' } : disclosed; diff --git a/packages/daemon/src/execution/screenshot-artifact-adapter.ts b/packages/daemon/src/execution/screenshot-artifact-adapter.ts index 43086e8d61..7ed74f4429 100644 --- a/packages/daemon/src/execution/screenshot-artifact-adapter.ts +++ b/packages/daemon/src/execution/screenshot-artifact-adapter.ts @@ -1,11 +1,20 @@ import { publishFileSync } from '@agent-device/host-kit/file'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { ArtifactAdapter, ReservedOutputFile } from '@agent-device/contracts/artifact-adapter'; -import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; import { promises as fs } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +const SCREENSHOT_DESTINATION_REASONS = { + // Writing the screenshot to its output path failed; `details.filesystemCode` names the error. + publicationFailed: { reason: 'screenshot_publication_failed' }, + // The output path is a symbolic link to a file that does not exist. + danglingSymlink: { reason: 'screenshot_destination_dangling_symlink' }, + // The output path exists and is not a regular file. + notFile: { reason: 'screenshot_destination_not_file' }, +} as const satisfies ReasonTable<'screenshot'>; + export function createDaemonScreenshotArtifactAdapter( atomic: boolean, signal: AbortSignal | undefined, @@ -66,7 +75,7 @@ export function createDaemonScreenshotArtifactAdapter( function screenshotPublicationError(error: unknown, outputPath: string): AppError { return new AppError('COMMAND_FAILED', 'Failed to publish screenshot', { - reason: 'screenshot_publication_failed', + reason: SCREENSHOT_DESTINATION_REASONS.publicationFailed.reason, path: outputPath, ...(error instanceof Error && 'code' in error ? { filesystemCode: error.code } : {}), cause: errorMessage(error), @@ -123,7 +132,7 @@ async function resolveScreenshotDestination(outputPath: string): Promise 'INVALID_ARGS', 'Screenshot destination is a dangling symbolic link', { - reason: 'screenshot_destination_dangling_symlink', + reason: SCREENSHOT_DESTINATION_REASONS.danglingSymlink.reason, path: outputPath, }, ); @@ -137,7 +146,7 @@ async function resolveScreenshotDestination(outputPath: string): Promise }); if (target && !target.isFile()) { throw new AppError('INVALID_ARGS', 'Screenshot destination must be a regular file', { - reason: 'screenshot_destination_not_file', + reason: SCREENSHOT_DESTINATION_REASONS.notFile.reason, path: outputPath, }); } diff --git a/packages/daemon/src/execution/session-snapshot.ts b/packages/daemon/src/execution/session-snapshot.ts index 6500935eaf..6fe7a50692 100644 --- a/packages/daemon/src/execution/session-snapshot.ts +++ b/packages/daemon/src/execution/session-snapshot.ts @@ -8,6 +8,7 @@ import { refFrameEpoch, refFrameScope, refFrameState, + REF_FRAME_REASONS, } from '../core/ref-frame.ts'; import type { SessionRef, SessionState } from '../core/session-state.ts'; import type { SessionStore } from '../core/session-store.ts'; @@ -270,7 +271,7 @@ export function unissuedRefReadError( const scope = refFrameScope(session); const currentGeneration = refFrameEpoch(session); return new AppError('COMMAND_FAILED', `Ref @${refBody} was not issued by the current ref frame`, { - reason: 'ref_not_issued', + reason: REF_FRAME_REASONS.notIssued.reason, ref: `@${refBody}`, ...(currentGeneration !== undefined ? { currentGeneration } : {}), scope: scope === 'all' ? 'all' : Array.from(scope), diff --git a/packages/daemon/src/resources/device/device-claim-conflict.ts b/packages/daemon/src/resources/device/device-claim-conflict.ts index 259bc692bd..4c024075e2 100644 --- a/packages/daemon/src/resources/device/device-claim-conflict.ts +++ b/packages/daemon/src/resources/device/device-claim-conflict.ts @@ -13,7 +13,10 @@ import { type InspectedDeviceClaim, } from '@agent-device/daemon-contracts/device-claims'; import { errorResponse } from '@agent-device/kernel/contracts'; -import type { DeviceClaimConflictReason } from '@agent-device/contracts/device'; +import { + DEVICE_CLAIM_CONFLICT_REASONS, + type DeviceClaimConflictReason, +} from '@agent-device/contracts/device'; export function buildDeviceClaimInspectionCommand( device: DeviceInfo, @@ -102,14 +105,14 @@ function claimRefusalResponse(error: AppError): DaemonResponse { function conflictReason(classification: DeviceClaimClassification): DeviceClaimConflictReason { switch (classification) { case 'live': - return 'DEVICE_CLAIM_LIVE_OWNER'; + return DEVICE_CLAIM_CONFLICT_REASONS.liveOwner.reason; case 'owner-process-dead': case 'owner-daemon-superseded': - return 'DEVICE_CLAIM_RECOVERY_PENDING'; + return DEVICE_CLAIM_CONFLICT_REASONS.recoveryPending.reason; case 'owner-process-reused': case 'owner-state-dir-gone': case 'unknown': case 'inconsistent': - return 'DEVICE_CLAIM_OWNER_UNCERTAIN'; + return DEVICE_CLAIM_CONFLICT_REASONS.ownerUncertain.reason; } } diff --git a/packages/daemon/src/resources/human-control-contract.ts b/packages/daemon/src/resources/human-control-contract.ts index 266260e322..5caa4defa4 100644 --- a/packages/daemon/src/resources/human-control-contract.ts +++ b/packages/daemon/src/resources/human-control-contract.ts @@ -3,13 +3,19 @@ import type { HumanControlHoldOptions, HumanControlHoldScope, } from '@agent-device/contracts/client'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { normalizeDeviceKey, normalizeLeaseBackend, normalizeLeaseProvider, } from './lease-registry-scope.ts'; +const HUMAN_CONTROL_REASONS = { + // A human holds the device, so state-changing commands are refused while the hold is active; + // retry after it is released. + active: { reason: 'human_control_active' }, +} as const satisfies ReasonTable<'human control'>; + export const HUMAN_CONTROL_HTTP_PREFIX = '/admin/human-control/holds'; export type HumanControlHoldInput = HumanControlHoldOptions & { @@ -88,7 +94,7 @@ export function humanControlActiveError(hold: HumanControlHold): AppError { 'DEVICE_IN_USE', 'A human is interacting with this simulator or device; agent interactions are temporarily disabled.', { - reason: 'human_control_active', + reason: HUMAN_CONTROL_REASONS.active.reason, blockedBy: 'human_control', holdId: hold.id, deviceKey: hold.scope.deviceKey, diff --git a/packages/daemon/src/resources/lease-registry-scope.ts b/packages/daemon/src/resources/lease-registry-scope.ts index 922eb93fbc..4a1c2827d9 100644 --- a/packages/daemon/src/resources/lease-registry-scope.ts +++ b/packages/daemon/src/resources/lease-registry-scope.ts @@ -7,9 +7,15 @@ import { leaseProviderRequiringRuntime, } from '@agent-device/contracts/lease-scope'; import { LEASE_BACKENDS, type LeaseBackend } from '@agent-device/kernel/contracts'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { normalizeTenantId } from '@agent-device/contracts/daemon-http'; +export const DEVICE_LEASE_REASONS = { + // Another lease, or this tenant run, already holds the device; retry after that lease is released + // or expires. + busy: { reason: 'DEVICE_LEASE_BUSY' }, +} as const satisfies ReasonTable<'leases'>; + export type LeaseRegistryOptions = { maxActiveSimulatorLeases?: number; defaultLeaseTtlMs?: number; @@ -389,7 +395,7 @@ export function leaseOwnTtlMs(lease: Pick; + /** * A `macos-app` lease rents one app on the host Mac, never the desktop. Its device key is the app's * bundle id, optionally pinned to one process: `` or `@`. @@ -97,7 +102,7 @@ function macOsAppLeaseDenied( ): AppError { return new AppError('UNAUTHORIZED', message, { ...details, - reason: 'MACOS_APP_LEASE_DENIED', + reason: MACOS_APP_LEASE_REASONS.denied.reason, rule, retriable: false, hint: 'This lease is limited to one macOS app; retrying will not help. Use an allowed command on the leased app.', diff --git a/packages/daemon/src/server/__tests__/daemon-runtime-app-log.test.ts b/packages/daemon/src/server/__tests__/daemon-runtime-app-log.test.ts index 18f5f902cb..cc68ebca94 100644 --- a/packages/daemon/src/server/__tests__/daemon-runtime-app-log.test.ts +++ b/packages/daemon/src/server/__tests__/daemon-runtime-app-log.test.ts @@ -34,7 +34,10 @@ test('daemon startup configures the Apple runner owner after acquiring the lock, const source = fs.readFileSync(new URL('../http/daemon-runtime.ts', import.meta.url), 'utf8'); const acquiredLock = source.indexOf("if (acquisition.status !== 'acquired')"); const runnerOwnerConfigured = source.indexOf('await deps.ownerLifecycle.configureForDaemonLock('); - const lockFailureExit = source.indexOf("reason: 'daemon_registration_refused'", acquiredLock); + const lockFailureExit = source.indexOf( + 'reason: DAEMON_REGISTRATION_REASONS.refused.reason', + acquiredLock, + ); expect(acquiredLock).toBeGreaterThanOrEqual(0); expect(lockFailureExit).toBeGreaterThan(acquiredLock); diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 59fce82a46..5bd12ae641 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -2,7 +2,7 @@ import http from 'node:http'; import { once } from 'node:events'; import { Transform } from 'node:stream'; import { finished, pipeline } from 'node:stream/promises'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { cleanupDownloadableArtifact, @@ -13,6 +13,12 @@ import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; +const ARTIFACT_DOWNLOAD_REASONS = { + // The artifact stream ended at a different size than the daemon recorded; `details` gives both + // sizes. + sizeMismatch: { reason: 'artifact_size_mismatch' }, +} as const satisfies ReasonTable<'artifact downloads'>; + type DownloadableArtifactHttpRoute = | { kind: 'inventory' } | { kind: 'download'; artifactId: string }; @@ -130,7 +136,7 @@ async function handleArtifactDownload( if (bytesRead !== artifact.sizeBytes) { callback( new AppError('COMMAND_FAILED', 'Artifact read did not match its declared size', { - reason: 'artifact_size_mismatch', + reason: ARTIFACT_DOWNLOAD_REASONS.sizeMismatch.reason, expectedBytes: artifact.sizeBytes, actualBytes: bytesRead, }), diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index da020258a2..fb0d85e6f5 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -6,7 +6,12 @@ import { createRecoveryPlatformScope, } from '@agent-device/daemon-contracts/device-claim-recovery'; import crypto from 'node:crypto'; -import { asAppError, AppError, normalizeError } from '@agent-device/kernel/errors'; +import { + asAppError, + AppError, + normalizeError, + type ReasonTable, +} from '@agent-device/kernel/errors'; import { SessionStore } from '../../core/session-store.ts'; import { DAEMON_CAPABILITIES, @@ -23,6 +28,7 @@ import { } from '@agent-device/daemon-contracts/daemon-policy-file'; import { assertDaemonPolicyAllowsCapability } from '../../core/daemon-policy.ts'; import { installInteractorResolution } from '../../core/interactor-resolution.ts'; +import { RUNTIME_GATEWAY_REASONS } from '../../core/runtime-admission.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { createExpiredProviderLeaseReleaser, @@ -94,6 +100,12 @@ import { retainPngWorker } from '@agent-device/capture-kit/png-worker-client'; import { openWebSessionNames } from '../../sessions/web-session-names.ts'; import { createAppLogAdmissionLedger } from '../../resources/app-log-admission-ledger.ts'; +const DAEMON_REGISTRATION_REASONS = { + // Another daemon holds this state directory, or its registration could not be proven free, so + // this daemon did not start; `details.status` says which. + refused: { reason: 'daemon_registration_refused' }, +} as const satisfies ReasonTable<'daemon lifecycle'>; + const DAEMON_LEASE_RELEASE_TIMEOUT_MS = 1_000; const LEASE_EXPIRY_SWEEP_INTERVAL_MS = 1_000; const DAEMON_PNG_WORKER_TERMINATE_TIMEOUT_MS = 1_000; @@ -258,7 +270,7 @@ async function startDaemonRuntimeOnHost( const applicationLifecycle = deviceRuntimeGateway.applicationLifecycle; if (!applicationLifecycle) { throw new AppError('COMMAND_FAILED', 'Platform lifecycle gateway is not configured.', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } installProviderDeviceAdmission(deps.providerDeviceAdmission); @@ -540,7 +552,7 @@ async function startDaemonRuntimeOnHost( const acquisition = await tryAcquireDaemonRegistration(daemonPaths); if (acquisition.status !== 'acquired') { throw new AppError('COMMAND_FAILED', `Daemon registration ${acquisition.status}.`, { - reason: 'daemon_registration_refused', + reason: DAEMON_REGISTRATION_REASONS.refused.reason, status: acquisition.status, exitCode: DAEMON_STARTUP_EXIT_CODES[acquisition.status], }); diff --git a/packages/daemon/src/server/remote-host-input-policy.ts b/packages/daemon/src/server/remote-host-input-policy.ts index 3b866d5108..623de0ff2b 100644 --- a/packages/daemon/src/server/remote-host-input-policy.ts +++ b/packages/daemon/src/server/remote-host-input-policy.ts @@ -1,10 +1,16 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog'; import { validateAndNormalizeBatchSteps } from '@agent-device/command-registry/batch'; import { DEFAULT_BATCH_MAX_STEPS } from '@agent-device/contracts/command'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { remoteScriptOpen } from '../core/session-script-publication-capability.ts'; +const REMOTE_HOST_INPUT_REASONS = { + // A remote request supplied a host path or other host input (`details.field`), which a remote + // daemon refuses. + denied: { reason: 'REMOTE_HOST_INPUT_DENIED' }, +} as const satisfies ReasonTable<'remote daemon'>; + const HOST_PATH_FIELDS = [ 'sessionSaveScript', 'launchConsole', @@ -203,7 +209,7 @@ const REMOTE_SCRIPT_PUBLICATION_HINT = function remoteHostInputDenied(field: string, hint = REMOTE_HOST_INPUT_HINT): AppError { return new AppError('INVALID_ARGS', `Remote requests cannot supply the host input ${field}.`, { - reason: 'REMOTE_HOST_INPUT_DENIED', + reason: REMOTE_HOST_INPUT_REASONS.denied.reason, field, retriable: false, hint, diff --git a/packages/daemon/src/server/request-execution-locks.ts b/packages/daemon/src/server/request-execution-locks.ts index a6c025b774..deffb54864 100644 --- a/packages/daemon/src/server/request-execution-locks.ts +++ b/packages/daemon/src/server/request-execution-locks.ts @@ -5,9 +5,15 @@ import { type KeyedLockHolder, } from '@agent-device/kernel/keyed-lock'; import { hostDeviceIdOf } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { RequestExecutionLockKey } from './request-binding.ts'; +const REQUEST_EXECUTION_REASONS = { + // Another request is using the device while this request holds another device of the same host; + // run the step as its own request. + deviceLockBusy: { reason: 'DEVICE_EXECUTION_LOCK_BUSY' }, +} as const satisfies ReasonTable<'request execution'>; + export type RequestExecutionLocks = { run(task: () => Promise): Promise; retainDevice(deviceId: string): Promise; @@ -103,7 +109,7 @@ function deviceExecutionLockBusy(deviceId: string): AppError { 'DEVICE_IN_USE', `Another request is using ${deviceId}, and this request already holds another device of the same host.`, { - reason: 'DEVICE_EXECUTION_LOCK_BUSY', + reason: REQUEST_EXECUTION_REASONS.deviceLockBusy.reason, deviceId, hint: 'Run this step as a separate request, or retry once the other request finishes.', }, diff --git a/packages/daemon/src/server/resumable-upload-transfer.ts b/packages/daemon/src/server/resumable-upload-transfer.ts index a864d7e9ef..3542bec600 100644 --- a/packages/daemon/src/server/resumable-upload-transfer.ts +++ b/packages/daemon/src/server/resumable-upload-transfer.ts @@ -3,11 +3,19 @@ import crypto from 'node:crypto'; import type { IncomingMessage } from 'node:http'; import { PassThrough, finished, type Transform, type Writable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { createByteLimitStream } from '@agent-device/host-kit/archive'; import { parseUploadContentLength, parseUploadContentRange } from './resumable-upload-range.ts'; import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; +const UPLOAD_TRANSFER_REASONS = { + // The staged upload holds more bytes than it declared, so it cannot resume; start a new upload. + stateCorrupt: { reason: 'UPLOAD_STATE_CORRUPT' }, + // A failed chunk could not be rolled back, so the upload ticket was invalidated; start a new + // upload. + rollbackFailed: { reason: 'UPLOAD_ROLLBACK_FAILED' }, +} as const satisfies ReasonTable<'uploads'>; + export type ResumableTransferEntry = { payloadPath: string; sizeBytes: number; @@ -164,7 +172,7 @@ async function currentOffset(entry: ResumableTransferEntry): Promise { const size = stat?.size ?? 0; if (size > entry.sizeBytes) { throw new AppError('COMMAND_FAILED', 'Upload state is corrupt', { - reason: 'UPLOAD_STATE_CORRUPT', + reason: UPLOAD_TRANSFER_REASONS.stateCorrupt.reason, }); } return size; @@ -182,7 +190,10 @@ async function rollback( const failure = new AppError( 'COMMAND_FAILED', 'Upload rollback failed; the upload ticket was invalidated', - { reason: 'UPLOAD_ROLLBACK_FAILED', originalError: String(originalError) }, + { + reason: UPLOAD_TRANSFER_REASONS.rollbackFailed.reason, + originalError: String(originalError), + }, cleanupError, ); await invalidate(failure); diff --git a/packages/daemon/src/server/resumable-upload.ts b/packages/daemon/src/server/resumable-upload.ts index 61f9cb444e..af3536a0f5 100644 --- a/packages/daemon/src/server/resumable-upload.ts +++ b/packages/daemon/src/server/resumable-upload.ts @@ -3,11 +3,12 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import type { IncomingMessage } from 'node:http'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { extractTarInstallableArtifact } from './artifact-archive.ts'; import { requireTenantOwnedEntry, + TENANT_RESOURCE_REASONS, type TenantOwnedResourceKind, } from '../core/tenant-owned-entry.ts'; import { @@ -18,6 +19,12 @@ import { import { computeUploadHash, receiveResumableTransfer } from './resumable-upload-transfer.ts'; import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; +const UPLOAD_FINALIZE_REASONS = { + // Finalizing the upload failed, and removing its staged files failed too; `details.originalError` + // holds the first failure. + cleanupFailed: { reason: 'UPLOAD_FINALIZE_CLEANUP_FAILED' }, +} as const satisfies ReasonTable<'uploads'>; + const RESUMABLE_UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; const RESUMABLE_UPLOAD_RESOURCE: TenantOwnedResourceKind = { label: 'Upload', @@ -307,7 +314,7 @@ function expireEntry(entry: ResumableUploadEntry, generation: number): void { closeEntry(entry); entry.activeReceive?.abort( new AppError('COMMAND_FAILED', 'Upload expired while receiving data', { - reason: 'RESOURCE_EXPIRED', + reason: TENANT_RESOURCE_REASONS.expired.reason, }), ); const cleanup = entry.tail.then(async () => { @@ -391,7 +398,10 @@ async function cleanupTerminalFinalizeFailure( return new AppError( 'COMMAND_FAILED', 'Upload finalize cleanup failed', - { reason: 'UPLOAD_FINALIZE_CLEANUP_FAILED', originalError: String(originalError) }, + { + reason: UPLOAD_FINALIZE_REASONS.cleanupFailed.reason, + originalError: String(originalError), + }, cleanupError, ); } diff --git a/packages/daemon/src/server/session-idle-expiry.ts b/packages/daemon/src/server/session-idle-expiry.ts index d20fcc4885..52ba781e5c 100644 --- a/packages/daemon/src/server/session-idle-expiry.ts +++ b/packages/daemon/src/server/session-idle-expiry.ts @@ -1,8 +1,14 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { DeviceClaimClearOutcome } from '@agent-device/daemon-contracts/device-claims'; import type { SessionState } from '../core/session-state.ts'; import type { IdleSessionTombstone } from '../core/session-idle-tombstone.ts'; +const SESSION_IDLE_REASONS = { + // The session expired after its idle window (`details.idleExpiryMs`); run `open` to start a new + // one. + expired: { reason: 'SESSION_IDLE_EXPIRED' }, +} as const satisfies ReasonTable<'sessions'>; + /** * #2833: an opt-in inactivity deadline for a session holding a local device claim, off by default. * @@ -30,9 +36,6 @@ import type { IdleSessionTombstone } from '../core/session-idle-tombstone.ts'; */ export const SESSION_IDLE_EXPIRY_ENV = 'AGENT_DEVICE_SESSION_IDLE_TIMEOUT_MS'; -/** The typed reason naming why an absent session is absent. Keyed behavior, never message text. */ -const SESSION_IDLE_EXPIRED_REASON = 'SESSION_IDLE_EXPIRED'; - /** A marker lives long enough for the command that comes next, not for an unrelated future session. */ const IDLE_EXPIRY_TOMBSTONE_TTL_MS = 60 * 60_000; @@ -163,7 +166,7 @@ export function sessionIdleExpiredError( 'SESSION_NOT_FOUND', `Session "${tombstone.owner}" expired ${formatIdle(sinceExpiredMs)} ago for idleness (window ${formatIdle(tombstone.idleExpiryMs)}). Run open again to start a new session.`, { - reason: SESSION_IDLE_EXPIRED_REASON, + reason: SESSION_IDLE_REASONS.expired.reason, session: sessionName, idleExpiryMs: tombstone.idleExpiryMs, ...(tombstone.deviceKey ? { deviceKey: tombstone.deviceKey } : {}), diff --git a/packages/daemon/src/server/upload-ingress.ts b/packages/daemon/src/server/upload-ingress.ts index daf5eb6bdc..401a0b5494 100644 --- a/packages/daemon/src/server/upload-ingress.ts +++ b/packages/daemon/src/server/upload-ingress.ts @@ -1,6 +1,6 @@ import type { IncomingMessage, ServerResponse } from 'node:http'; import type { Socket } from 'node:net'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; import { TRANSFER_BODY_INACTIVITY_TIMEOUT_MS } from '@agent-device/host-kit/transport'; import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; import { UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS } from './http/ingress-budget.ts'; @@ -15,7 +15,14 @@ import { sendRestJsonError } from './http-errors.ts'; * through the existing response-disconnect signal. */ const TRANSFER_PHASE_TIMEOUT_REASON = 'transfer_phase_timeout'; -const TRANSFER_INGRESS_AGGREGATE_REASON = 'transfer_ingress_deadline_exceeded'; + +const UPLOAD_INGRESS_REASONS = { + // The upload request exceeded its aggregate deadline (`details.timeoutMs`), which also covers + // processing after the body arrived. + deadlineExceeded: { reason: 'transfer_ingress_deadline_exceeded' }, + // The client disconnected or canceled before the upload finished. + canceled: { reason: 'upload_canceled' }, +} as const satisfies ReasonTable<'uploads'>; export type UploadTransferIngress = { /** Aborts on aggregate expiry or client disconnect while the request is unfinished. */ @@ -189,7 +196,7 @@ export function beginUploadTransferIngress(params: { function aggregateExpiry(): AppError { return new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { - reason: TRANSFER_INGRESS_AGGREGATE_REASON, + reason: UPLOAD_INGRESS_REASONS.deadlineExceeded.reason, transferPhase: 'request-body', timeoutMs: UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS, }); @@ -309,5 +316,7 @@ export function resolveIngressFailure(signal: AbortSignal | undefined, failure: export function throwIfIngressAborted(signal: AbortSignal | undefined): void { if (!signal?.aborted) return; if (signal.reason instanceof Error) throw signal.reason; - throw new AppError('COMMAND_FAILED', 'Upload canceled', { reason: 'upload_canceled' }); + throw new AppError('COMMAND_FAILED', 'Upload canceled', { + reason: UPLOAD_INGRESS_REASONS.canceled.reason, + }); } diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 7f4c7ba238..295fa9afb7 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -46,13 +46,33 @@ import { } from '@agent-device/contracts/lease-scope'; import { publicPlatformString } from '@agent-device/kernel/device'; import { platformForLeaseBackend } from '@agent-device/kernel/contracts'; -import { AppError, createRequestCanceledError, errorMessage } from '@agent-device/kernel/errors'; +import { + AppError, + createRequestCanceledError, + errorMessage, + type ReasonTable, +} from '@agent-device/kernel/errors'; import { LEASE_ALLOCATION_BUDGET_MS } from '@agent-device/command-registry/timeout-policy'; import { getRequestSignal, isRequestCanceled } from '@agent-device/host-kit/request'; import { listDownloadableArtifacts } from '../../resources/artifact-tracking.ts'; import type { DaemonProviderCredentials } from '@agent-device/daemon-contracts/provider-credentials'; import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; +const LEASE_HANDLER_REASONS = { + // The lease names a provider this daemon has not registered; `details.failedPlugins` lists + // plugins that failed to load. + providerNotRegistered: { reason: 'provider-not-registered' }, + // The running daemon holds different provider credentials than this shell; stop the daemon and + // rerun. + providerCredentialsChanged: { reason: 'provider-credentials-changed' }, + // The provider session belongs to another tenant. + providerSessionNotOwned: { reason: 'PROVIDER_SESSION_NOT_OWNED' }, + // Only the host administrator releases a `macos-app` lease. + macOsAppHostOwned: { reason: 'MACOS_APP_LEASE_HOST_OWNED' }, + // Only the host administrator allocates a `macos-app` lease. + macOsAppHostAllocated: { reason: 'MACOS_APP_LEASE_HOST_ALLOCATED' }, +} as const satisfies ReasonTable<'leases'>; + type LeaseHandlerArgs = { host: HostEnvironment; req: DaemonRequest; @@ -453,7 +473,7 @@ function assertProviderRuntimeRegistered( 'UNSUPPORTED_OPERATION', `Provider "${provider}" is not available in this daemon runtime.`, { - reason: 'provider-not-registered', + reason: LEASE_HANDLER_REASONS.providerNotRegistered.reason, provider, registeredProviders: [...registeredProviders], ...(failures.length > 0 ? { failedPlugins: failures } : {}), @@ -482,7 +502,7 @@ function assertProviderCredentialsUnchanged( ? `The running daemon holds different ${provider} credentials than this shell.` : `The running daemon was started without the ${provider} credentials this shell holds.`, { - reason: 'provider-credentials-changed', + reason: LEASE_HANDLER_REASONS.providerCredentialsChanged.reason, provider, hint: `Stop it with agent-device daemon stop --state-dir ${shellQuoteIfNeeded(daemon.stateDir)}, then rerun the command so a new daemon starts with this shell's environment.`, }, @@ -575,7 +595,7 @@ function resolveProviderSession( }); if (providerSession) return providerSession; throw new AppError('UNAUTHORIZED', 'Provider session is not owned by the request tenant', { - reason: 'PROVIDER_SESSION_NOT_OWNED', + reason: LEASE_HANDLER_REASONS.providerSessionNotOwned.reason, }); } @@ -591,7 +611,7 @@ function readFlagString( function assertTenantMayRelease(lease: DeviceLease | undefined): void { if (lease?.backend !== 'macos-app') return; throw new AppError('UNAUTHORIZED', 'A macos-app lease is released by the host administrator.', { - reason: 'MACOS_APP_LEASE_HOST_OWNED', + reason: LEASE_HANDLER_REASONS.macOsAppHostOwned.reason, retriable: false, hint: 'Disconnect only drops the client connection; the host ends the lease.', }); @@ -601,7 +621,7 @@ function assertTenantMayRelease(lease: DeviceLease | undefined): void { function assertTenantMayAllocate(leaseBackend: string | undefined): void { if (normalizeLeaseBackend(leaseBackend) !== 'macos-app') return; throw new AppError('UNAUTHORIZED', 'A macos-app lease is allocated by the host administrator.', { - reason: 'MACOS_APP_LEASE_HOST_ALLOCATED', + reason: LEASE_HANDLER_REASONS.macOsAppHostAllocated.reason, retriable: false, hint: 'Ask the host administrator for a macos-app lease and connect with its leaseId.', }); diff --git a/packages/daemon/src/sessions/handlers/session-doctor.ts b/packages/daemon/src/sessions/handlers/session-doctor.ts index 2a7276cbf2..5fa3952bd0 100644 --- a/packages/daemon/src/sessions/handlers/session-doctor.ts +++ b/packages/daemon/src/sessions/handlers/session-doctor.ts @@ -6,6 +6,7 @@ import { isIosFamily, publicPlatformString, type DeviceInfo } from '@agent-devic import { AppError } from '@agent-device/kernel/errors'; import { emitRequestProgress } from '@agent-device/host-kit/request'; import { isActiveProviderDevice } from '../../core/provider-device-admission.ts'; +import { RUNTIME_GATEWAY_REASONS } from '../../core/runtime-admission.ts'; import { listLocalDeviceInventory, shouldPropagateDeviceInventoryProbeError, @@ -114,7 +115,7 @@ export async function handleDoctorCommand(params: { function requireHostDiagnostics(value: HostDiagnostics | undefined): HostDiagnostics { if (!value) { throw new AppError('COMMAND_FAILED', 'Host diagnostics gateway is not configured', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } return value; diff --git a/packages/daemon/src/sessions/handlers/session-script-publication.ts b/packages/daemon/src/sessions/handlers/session-script-publication.ts index 806a36857e..88f802bfec 100644 --- a/packages/daemon/src/sessions/handlers/session-script-publication.ts +++ b/packages/daemon/src/sessions/handlers/session-script-publication.ts @@ -1,6 +1,6 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; import { successText } from '@agent-device/kernel/success-text'; import { effectiveWriteForce, @@ -14,6 +14,12 @@ import { SessionStore } from '../../core/session-store.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import type { SessionState } from '../../core/session-state.ts'; +const SCRIPT_PUBLICATION_REASONS = { + // A remote recording is delivered to its `--save-script` path, so `session save-script` cannot + // publish it. + remoteUnsupported: { reason: 'remote_script_publication_unsupported' }, +} as const satisfies ReasonTable<'session'>; + export function handleSessionScriptPublication(params: { req: DaemonRequest; sessionName: string; @@ -100,7 +106,7 @@ const PUBLICATION_INELIGIBILITY_ERRORS: Record A 'COMMAND_FAILED', 'A remote recording is delivered to its --save-script path, not published from the session.', { - reason: 'remote_script_publication_unsupported', + reason: SCRIPT_PUBLICATION_REASONS.remoteUnsupported.reason, hint: 'The --save-script file already holds the recording through the last action, and close writes the final script there.', }, ), diff --git a/packages/daemon/src/sessions/server/daemon-idle-reap.ts b/packages/daemon/src/sessions/server/daemon-idle-reap.ts index 8fa9dcca20..3ac8d2f607 100644 --- a/packages/daemon/src/sessions/server/daemon-idle-reap.ts +++ b/packages/daemon/src/sessions/server/daemon-idle-reap.ts @@ -1,6 +1,5 @@ import { DAEMON_LIFECYCLE_REASONS, - DAEMON_SHUTTING_DOWN_REASON, DAEMON_QUIESCE_COMMAND, readDaemonLifecycleFence, type DaemonLifecycleCensus, @@ -203,7 +202,7 @@ export function daemonShuttingDownResponse(): DaemonResponse { error: { code: 'COMMAND_FAILED', message: 'Daemon is shutting down.', - details: { reason: DAEMON_SHUTTING_DOWN_REASON }, + details: { reason: DAEMON_LIFECYCLE_REASONS.shuttingDown.reason }, }, }; } diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts index f9dccee84b..911c1ece8a 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts @@ -37,6 +37,7 @@ import { AppError, createRequestCanceledError, readDispatchDisclosure, + type ReasonTable, } from '@agent-device/kernel/errors'; import { SessionStore } from '../../../core/session-store.ts'; import { @@ -74,6 +75,11 @@ import { buildDeviceClaimConflictError } from '../../../resources/device/device- import { deviceClaimRuleForOwner } from '../../../resources/device/device-claim-rule.ts'; import { errorResponse, type DaemonResponse } from '@agent-device/kernel/contracts'; +const OPEN_CLAIM_REASONS = { + // The device lost the claim this open was made with; close the session and open the device again. + claimLost: { reason: 'claim-lost-during-open' }, +} as const satisfies ReasonTable<'open'>; + export type SessionOpenResult = | Readonly<{ type: 'opened'; response: DaemonResponse; ref: SessionRef }> | Readonly<{ type: 'response'; response: DaemonResponse }>; @@ -218,7 +224,7 @@ export async function renewOpenSessionClaim( 'DEVICE_IN_USE', `${device.name} no longer holds the claim this open was made with.`, { - reason: 'claim-lost-during-open', + reason: OPEN_CLAIM_REASONS.claimLost.reason, deviceKey: ownership.deviceKey, hint: 'Close this session and open the device again to claim it.', }, diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts index 742759e358..9490802011 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts @@ -11,6 +11,7 @@ import type { DaemonPlatformServices } from '../../../core/platform-services.ts' import { hasRuntimeTransportHints, maybeClearRemovedRuntimeTransportHints, + RUNTIME_HINTS_REASONS, shouldClearRemovedRuntimeTransportHints, tryResolveOpenRuntimeHints, } from '../../session-runtime.ts'; @@ -193,7 +194,7 @@ export async function prepareOpenCommandDetails(params: { 'COMMAND_FAILED', 'Runtime hint clear operation was not admitted for this open.', { - reason: 'runtime-hints-operation-missing', + reason: RUNTIME_HINTS_REASONS.operationMissing.reason, dispatched: 'unknown', }, ); diff --git a/packages/daemon/src/sessions/session-observability/internal/session-network.ts b/packages/daemon/src/sessions/session-observability/internal/session-network.ts index b7bc332fb5..02f1ef2cb2 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-network.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-network.ts @@ -12,7 +12,10 @@ import { type DaemonResponse, } from '@agent-device/kernel/contracts'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { unsupportedOperationResponse } from '../../../core/runtime-admission.ts'; +import { + RUNTIME_GATEWAY_REASONS, + unsupportedOperationResponse, +} from '../../../core/runtime-admission.ts'; import type { BindDeviceRuntime } from '../../../core/request-runtime-binding.ts'; import type { SessionStore } from '../../../core/session-store.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; @@ -75,7 +78,7 @@ export async function handleNetworkCommand(params: NetworkHandlerParams): Promis function requireNetworkBindDevice(bindDevice: BindDeviceRuntime | undefined): BindDeviceRuntime { if (bindDevice) return bindDevice; throw new AppError('COMMAND_FAILED', 'Device runtime gateway is not configured', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } diff --git a/packages/daemon/src/sessions/session-observability/internal/session-observability.ts b/packages/daemon/src/sessions/session-observability/internal/session-observability.ts index d1ec5e460e..2284c9ecd7 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-observability.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-observability.ts @@ -33,7 +33,10 @@ import type { InspectDeviceRuntimeFacts, } from '../../../core/request-runtime-binding.ts'; import type { SessionStore } from '../../../core/session-store.ts'; -import { unsupportedOperationResponse } from '../../../core/runtime-admission.ts'; +import { + RUNTIME_GATEWAY_REASONS, + unsupportedOperationResponse, +} from '../../../core/runtime-admission.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import type { SessionRef, SessionState } from '../../../core/session-state.ts'; import { handleAudioCommand } from './session-audio.ts'; @@ -404,12 +407,12 @@ async function startSessionAppLog( function requireAudioSeams(params: ObservabilityInput): Parameters[0] { if (!params.bindDevice || !params.inspectFacts) { throw new AppError('COMMAND_FAILED', 'Device runtime gateway is not configured', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } if (!params.audioProbeAdmissionLedger) { throw new AppError('COMMAND_FAILED', 'Audio probe admission ledger is not configured', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } return { @@ -429,12 +432,12 @@ function requireLogsHandlerParams( ): LogsHandlerParams { if (!params.bindDevice) { throw new AppError('COMMAND_FAILED', 'Device runtime gateway is not configured', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } if (!params.appLogAdmissionLedger) { throw new AppError('COMMAND_FAILED', 'App-log admission ledger is not configured', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } return { diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index ff50235ab6..789baa3217 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -46,6 +46,7 @@ import { unwrapAdmittedRuntimePlan, type AdmittedRuntimePlan, } from '../../../core/session-runtime-admission.ts'; +import { RUNTIME_GATEWAY_REASONS } from '../../../core/runtime-admission.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; export type PerfRuntimeHandlerParams = Readonly<{ @@ -279,7 +280,7 @@ function requirePerfCaptureAdmissionLedger( ): PerfCaptureAdmissionLedger { if (params.perfCaptureAdmissionLedger) return params.perfCaptureAdmissionLedger; throw new AppError('COMMAND_FAILED', 'Perf capture admission ledger is not configured', { - reason: 'runtime-gateway-missing', + reason: RUNTIME_GATEWAY_REASONS.missing.reason, }); } diff --git a/packages/daemon/src/sessions/session-runtime.ts b/packages/daemon/src/sessions/session-runtime.ts index 794b52fb8b..d26c85acdc 100644 --- a/packages/daemon/src/sessions/session-runtime.ts +++ b/packages/daemon/src/sessions/session-runtime.ts @@ -5,7 +5,7 @@ import { type RuntimeHintsApplicationInput, hasRuntimeTransportHintValues, } from '@agent-device/contracts/application-lifecycle-runtime'; -import { AppError, asAppError } from '@agent-device/kernel/errors'; +import { AppError, asAppError, type ReasonTable } from '@agent-device/kernel/errors'; import { type DaemonFailureResponse, errorResponse, @@ -17,6 +17,12 @@ import { SessionStore } from '../core/session-store.ts'; import { trimRuntimeValue } from '@agent-device/host-kit/runtime-transport-hints'; import { isAndroidEmulator, isIosSimulator } from './device/device-targets.ts'; +export const RUNTIME_HINTS_REASONS = { + // Runtime hints were requested, but the device runtime admitted no operation to apply or clear + // them. + operationMissing: { reason: 'runtime-hints-operation-missing' }, +} as const satisfies ReasonTable<'open'>; + type SessionRuntimeHintsStore = Readonly<{ getRuntimeHints: SessionStore['getRuntimeHints']; }>; @@ -71,7 +77,7 @@ export function openApplicationRuntimeHints( throw new AppError( 'COMMAND_FAILED', 'Transport runtime hints were requested without the fact-admitted apply operation; pair the hints with the operation or drop them.', - { reason: 'runtime-hints-operation-missing', dispatched: 'no' }, + { reason: RUNTIME_HINTS_REASONS.operationMissing.reason, dispatched: 'no' }, ); } return { values: runtimeHintValues(runtime), apply }; diff --git a/packages/daemon/src/sessions/session-teardown.ts b/packages/daemon/src/sessions/session-teardown.ts index 912cd24e91..111f9e5bdb 100644 --- a/packages/daemon/src/sessions/session-teardown.ts +++ b/packages/daemon/src/sessions/session-teardown.ts @@ -1,4 +1,4 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { isCompletedDurableCaptureError } from '@agent-device/capture-kit/durable-capture'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { cleanupRetainedMaterializedPathsForSession } from './materialized-path-registry.ts'; @@ -15,6 +15,12 @@ import { finishLiveScreenRecording } from '@agent-device/capture-kit/screen-reco import { openWebSessionNames } from './web-session-names.ts'; import type { PlatformResourceCleanup } from '../core/platform-resource-cleanup.ts'; +const SESSION_TEARDOWN_REASONS = { + // Session cleanup was incomplete; `details.failedSteps` lists the steps that failed, and the hint + // says whether the session was kept (retry `close`) or retired, and what to do next. + cleanupIncomplete: { reason: 'session_cleanup_incomplete' }, +} as const satisfies ReasonTable<'sessions'>; + export async function stopSessionAppLog(params: { ref: SessionRef; sessionStore: SessionStore; @@ -103,7 +109,7 @@ export function reportSessionCleanupFailures(params: { 'COMMAND_FAILED', `Session cleanup left ${params.failures.length} resource(s) unreleased: ${stepMessages.join('; ')}`, { - reason: 'session_cleanup_incomplete', + reason: SESSION_TEARDOWN_REASONS.cleanupIncomplete.reason, session: params.sessionName, failedSteps, hint: diff --git a/packages/daemon/src/sessions/target-lease-release.ts b/packages/daemon/src/sessions/target-lease-release.ts index 310ed7e192..0fe6c2c9af 100644 --- a/packages/daemon/src/sessions/target-lease-release.ts +++ b/packages/daemon/src/sessions/target-lease-release.ts @@ -1,7 +1,7 @@ import type { LeaseLifecycleProvider, TargetShutdownResult } from '@agent-device/contracts/device'; import { LEASE_REASONS, leaseScopeToReleaseRequest } from '@agent-device/contracts/lease-scope'; import type { RuntimeOwnerRef } from '@agent-device/contracts/platform-runtime'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionState } from '../core/session-state.ts'; import { @@ -13,6 +13,11 @@ import { recordEndedLease } from '../core/request-ended-leases.ts'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; import { releaseLease } from '../resources/lease-release.ts'; +const TARGET_SHUTDOWN_REASONS = { + // The selected target does not own the lease this request names, so it will not release it. + leaseMismatch: { reason: 'TARGET_SHUTDOWN_LEASE_MISMATCH' }, +} as const satisfies ReasonTable<'shutdown'>; + /** A runtime can end only the lease admitted for this request and owned by that runtime's provider. */ export async function releaseTargetLease(params: { req: DaemonRequest; @@ -34,7 +39,7 @@ export async function releaseTargetLease(params: { !params.leaseLifecycleProvider?.release ) { throw new AppError('UNAUTHORIZED', 'The selected target does not own this request lease.', { - reason: 'TARGET_SHUTDOWN_LEASE_MISMATCH', + reason: TARGET_SHUTDOWN_REASONS.leaseMismatch.reason, }); } const request = leaseScopeToReleaseRequest(scope); diff --git a/packages/kernel/src/errors.ts b/packages/kernel/src/errors.ts index 45fc2c301f..5d7ec4d4c4 100644 --- a/packages/kernel/src/errors.ts +++ b/packages/kernel/src/errors.ts @@ -324,9 +324,17 @@ export const PRE_DISPATCH_REFUSAL_REASONS = { malformedRequest: { reason: 'malformed_request' }, } as const satisfies ReasonTable<'request admission'>; -/** The refused composite step did not dispatch; earlier steps may already have dispatched. */ -export const BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON = - 'bounded_composite_resource_unsupported' as const; +/** Why a bounded composite (`batch`, a replay, or a `test` script) refuses one of its steps. */ +export const BOUNDED_COMPOSITE_REASONS = { + // The composite refused this step before dispatch because it must run as its own command, such as + // a recording, trace, log, audio or perf capture. `details.shape` names the refused operation or + // option, and `details.standaloneCommandName` the public command to run instead. Earlier steps + // may have run. + resourceUnsupported: { + reason: 'bounded_composite_resource_unsupported', + commands: ['replay', 'test'], + }, +} as const satisfies ReasonTable<'batch'>; export type PreDispatchRefusalReason = (typeof PRE_DISPATCH_REFUSAL_REASONS)[keyof typeof PRE_DISPATCH_REFUSAL_REASONS]['reason']; diff --git a/packages/replay-port/src/daemon-port/__tests__/session-replay-runtime-failure-response.test.ts b/packages/replay-port/src/daemon-port/__tests__/session-replay-runtime-failure-response.test.ts index f3a850b939..ff288c10fe 100644 --- a/packages/replay-port/src/daemon-port/__tests__/session-replay-runtime-failure-response.test.ts +++ b/packages/replay-port/src/daemon-port/__tests__/session-replay-runtime-failure-response.test.ts @@ -1,6 +1,6 @@ import { test, expect } from 'vitest'; import { ANDROID_TEXT_CHANNEL_REASONS } from '@agent-device/contracts/input-validation'; -import { BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON } from '@agent-device/kernel/errors'; +import { BOUNDED_COMPOSITE_REASONS } from '@agent-device/kernel/errors'; import { ANDROID_TEST_IME_FLOW_HINT, buildReplayDivergenceFailureResponseFromDescriptor, @@ -60,7 +60,7 @@ test('bounded resource refusal keeps canonical typed fields on a replay-variable message: 'record:start secret-value cannot run within a bounded composite', hint: 'Use the original secret-value input in the same session.', details: { - reason: BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, + reason: BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason, shape: 'record:start', standaloneCommandName: 'record', dispatched: 'no', @@ -80,7 +80,7 @@ test('bounded resource refusal keeps canonical typed fields on a replay-variable }); if (response.ok) throw new Error('expected a failure response'); expect(response.error.details).toMatchObject({ - reason: BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, + reason: BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason, shape: 'record:start', standaloneCommandName: 'record', dispatched: 'no', @@ -119,6 +119,35 @@ test('cleanup failed steps retain their type while replay variables are scrubbed expect(JSON.stringify(response)).not.toContain('secret-value'); }); +test('a sparse find refusal keeps its verdict while replay variables are scrubbed', () => { + const response = buildReplayDivergenceFailureResponseFromDescriptor({ + error: { + code: 'COMMAND_FAILED', + message: 'find could not read the current accessibility tree', + details: { + reason: 'find_snapshot_unreadable', + verdictReason: 'sparse tree near secret-value', + verdictReasonCode: 'sparse-tree', + }, + }, + actionLabel: 'find', + action: 'find', + positionals: ['label', 'Submit', 'click'], + step: 1, + replayPath: '/tmp/find.ad', + artifactPaths: [], + divergence: {}, + scrubVars: [{ name: 'SECRET', value: 'secret-value' }], + }); + if (response.ok) throw new Error('expected a failure response'); + expect(response.error.details).toMatchObject({ + reason: 'find_snapshot_unreadable', + verdictReason: 'sparse tree near ', + verdictReasonCode: 'sparse-tree', + }); + expect(JSON.stringify(response)).not.toContain('secret-value'); +}); + // #2997: the Android platform states `open --test-ime` because it sees one dispatched // session-open. On this surface that advice is unactionable — a flow caller never runs // `open` — so the cause's hint is replaced off the typed reason, never off the message. diff --git a/packages/replay-port/src/daemon-port/session-replay-divergence.ts b/packages/replay-port/src/daemon-port/session-replay-divergence.ts index e4bfd9db79..bed72394d0 100644 --- a/packages/replay-port/src/daemon-port/session-replay-divergence.ts +++ b/packages/replay-port/src/daemon-port/session-replay-divergence.ts @@ -5,10 +5,7 @@ import { isUnreadableCaptureContentError } from '@agent-device/contracts/android import { isSparseSnapshotQualityVerdict } from '@agent-device/capture-kit/snapshot-quality-verdict'; import { displayLabel, formatRole } from '@agent-device/capture-kit/snapshot-lines'; import type { ResponseLevel } from '@agent-device/kernel/contracts'; -import { - BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, - type DaemonError, -} from '@agent-device/kernel/errors'; +import { BOUNDED_COMPOSITE_REASONS, type DaemonError } from '@agent-device/kernel/errors'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import { collectReplaySelectorCandidates } from '@agent-device/replay-port/session-replay-heal'; import { buildSelectorCandidates, resolveReplaySuggestionCandidate } from '@agent-device/selectors'; @@ -104,7 +101,7 @@ export async function buildReplayFailureDivergence(params: { }; const refusedBeforeDispatch = - error.details?.reason === BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON && + error.details?.reason === BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason && error.details.dispatched === 'no'; const observation = refusedBeforeDispatch ? ({ diff --git a/packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts b/packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts index f9a7f2744d..13b2211a8f 100644 --- a/packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts +++ b/packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts @@ -1,6 +1,6 @@ import type { SessionAction } from '@agent-device/contracts/session'; import { ANDROID_TEXT_CHANNEL_REASONS } from '@agent-device/contracts/input-validation'; -import { BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON } from '@agent-device/kernel/errors'; +import { BOUNDED_COMPOSITE_REASONS } from '@agent-device/kernel/errors'; import { scrubReplayVarValues, type ReplayVarScrubEntry } from '@agent-device/ad-replay/divergence'; import { formatDivergenceActionLabel } from '@agent-device/ad-script'; import type { SnapshotDiagnosticsSummary } from '@agent-device/contracts/capture'; @@ -151,8 +151,12 @@ const SAFE_CAUSE_DETAIL_KEYS = [ 'snapshotQuality', 'supportedOn', 'systemSurface', + 'verdictReasonCode', ] as const; +// Free text a cause may echo from the device, such as a sparse capture verdict, so it is scrubbed. +const SCRUBBED_CAUSE_DETAIL_KEYS = ['verdictReason'] as const; + function pickSafeCauseDetails( details: Record | undefined, scrubVars: readonly ReplayVarScrubEntry[], @@ -162,21 +166,30 @@ function pickSafeCauseDetails( for (const key of SAFE_CAUSE_DETAIL_KEYS) { if (details[key] !== undefined) safe[key] = details[key]; } - if ( - details.reason === 'session_cleanup_incomplete' && - Array.isArray(details.failedSteps) && - details.failedSteps.every((step) => typeof step === 'string') - ) { - safe.failedSteps = details.failedSteps.map((step: string) => - scrubReplayVarValues(step, scrubVars), - ); - } - if (details.reason === BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON) { - if (details.dispatched === 'no') safe.dispatched = 'no'; - const shape = readStringDetail(details, 'shape'); - if (shape !== undefined) safe.shape = shape; - const commandName = readStringDetail(details, 'standaloneCommandName'); - if (commandName !== undefined) safe.standaloneCommandName = commandName; + for (const key of SCRUBBED_CAUSE_DETAIL_KEYS) { + const value = readStringDetail(details, key); + if (value !== undefined) safe[key] = scrubReplayVarValues(value, scrubVars); } + return { ...safe, ...pickCleanupFailedSteps(details, scrubVars), ...pickBoundedRefusal(details) }; +} + +function pickCleanupFailedSteps( + details: Record, + scrubVars: readonly ReplayVarScrubEntry[], +): Record { + const steps = details.failedSteps; + if (details.reason !== 'session_cleanup_incomplete' || !Array.isArray(steps)) return {}; + if (!steps.every((step) => typeof step === 'string')) return {}; + return { failedSteps: steps.map((step: string) => scrubReplayVarValues(step, scrubVars)) }; +} + +function pickBoundedRefusal(details: Record): Record { + if (details.reason !== BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason) return {}; + const safe: Record = {}; + if (details.dispatched === 'no') safe.dispatched = 'no'; + const shape = readStringDetail(details, 'shape'); + if (shape !== undefined) safe.shape = shape; + const commandName = readStringDetail(details, 'standaloneCommandName'); + if (commandName !== undefined) safe.standaloneCommandName = commandName; return safe; } diff --git a/packages/replay-port/src/daemon-port/session-test-outcome.ts b/packages/replay-port/src/daemon-port/session-test-outcome.ts index 088616de5c..dcf18f0658 100644 --- a/packages/replay-port/src/daemon-port/session-test-outcome.ts +++ b/packages/replay-port/src/daemon-port/session-test-outcome.ts @@ -1,6 +1,6 @@ import { readSnapshotDiagnosticsSummary } from '@agent-device/contracts/capture'; import { readResponseWarnings } from '@agent-device/kernel/success-text'; -import { BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON } from '@agent-device/kernel/errors'; +import { BOUNDED_COMPOSITE_REASONS } from '@agent-device/kernel/errors'; import { isReplayInfrastructureFailure } from './session-test-infrastructure.ts'; import type { ReplayTestAttemptFailed, ReplayTestAttemptOutcome } from '@agent-device/replay-test'; import { type DaemonResponse } from '@agent-device/kernel/contracts'; @@ -22,7 +22,7 @@ export function toReplayTestAttemptOutcome(response: DaemonResponse): ReplayTest artifactPaths: readArtifactPaths(response.error.details?.artifactPaths), warnings: readResponseWarnings(response.error.details), infrastructure: isReplayInfrastructureFailure(response), - ...(response.error.details?.reason === BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON + ...(response.error.details?.reason === BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason ? { stopRetries: true as const } : {}), ...snapshotDiagnostics(response.error.details?.snapshotDiagnostics), diff --git a/packages/replay-port/src/daemon-port/test-command.ts b/packages/replay-port/src/daemon-port/test-command.ts index 3a4f01747c..8c4c3901aa 100644 --- a/packages/replay-port/src/daemon-port/test-command.ts +++ b/packages/replay-port/src/daemon-port/test-command.ts @@ -22,11 +22,7 @@ import { } from '@agent-device/replay-test'; import { runReplayCommand } from './native-command.ts'; import { collectReplayActionArtifactPaths } from '@agent-device/replay-port/session-replay-runtime-artifacts'; -import { - AppError, - asAppError, - BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, -} from '@agent-device/kernel/errors'; +import { AppError, asAppError, BOUNDED_COMPOSITE_REASONS } from '@agent-device/kernel/errors'; import { emitRequestProgress, clearRequestCanceled, @@ -308,7 +304,7 @@ function withOriginalTestRefusalGuidance( ): ReplayTestAttemptOutcome { if ( attempt.status !== 'failed' || - attempt.error.details?.reason !== BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON + attempt.error.details?.reason !== BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason ) return attempt; const details = attempt.error.details; diff --git a/test/repo-guards/runner-refusal-reason-docs.test.ts b/test/repo-guards/runner-refusal-reason-docs.test.ts index d4caa1bedb..65c8f9f7b0 100644 --- a/test/repo-guards/runner-refusal-reason-docs.test.ts +++ b/test/repo-guards/runner-refusal-reason-docs.test.ts @@ -14,12 +14,12 @@ import { * undocumented member as an unknown value. Every exported typed published-reason table must have * each reason documented at the surfaces that enumerate it, in the same change that adds it. * Reason tables are read by the collector the reasons page uses; the runner code rows, which are not a - * reason table, and the claim-conflict union are read as typed syntax (oxc), so an unreadable member - * fails here instead of being dropped. + * reason table, are read as typed syntax (oxc), so an unreadable member fails here instead of being + * dropped. */ type Surface = Readonly<{ name: string; relativePath: string }>; -type Kind = 'table' | 'runnerCodes' | 'union'; +type Kind = 'table' | 'runnerCodes'; const commandsDoc: Surface = { name: 'commands.md', relativePath: 'website/docs/docs/commands.md' }; const cliHelpWorkflows: Surface = { name: 'cli-help-workflows.ts', @@ -46,7 +46,11 @@ const REASON_TABLES = [ commandsDoc, cliHelpWorkflows, ]), - reasonTable('DeviceClaimConflictReason', 'packages/contracts/src/device-inventory.ts', 'union'), + reasonTable( + 'DEVICE_CLAIM_CONFLICT_REASONS', + 'packages/contracts/src/device-inventory.ts', + 'table', + ), ]; test('every reason of every exported published-reason table is documented at its surfaces', () => { @@ -122,18 +126,6 @@ test('the extractors read every member and reject unsupported ones instead of dr 'table', ['wait_capture_stalled'], ); - expectRead( - `export type DeviceClaimConflictReason = 'DEVICE_CLAIM_LIVE_OWNER' | 'DEVICE_CLAIM_OWNER_UNCERTAIN';`, - 'DeviceClaimConflictReason', - 'union', - ['DEVICE_CLAIM_LIVE_OWNER', 'DEVICE_CLAIM_OWNER_UNCERTAIN'], - ); - expectReject( - `export type DeviceClaimConflictReason = string;`, - 'DeviceClaimConflictReason', - 'union', - /unsupported member in DeviceClaimConflictReason/, - ); }); /** Whether `docs` names `reason` as a whole token, so a longer reason that extends it does not count. */ @@ -144,7 +136,6 @@ function documentsReason(docs: string, reason: string): boolean { /** Reads a published-reason table's members, failing on anything unreadable. */ function readReasons(source: string, filename: string, name: string, kind: Kind): string[] { - if (kind === 'union') return readUnionReasons(parseTs(filename, source), filename, name); const tables = collectReasonTables(new Map([[filename, source]])); if (kind === 'table') { const table = tables.find((candidate) => candidate.name === name); @@ -198,32 +189,3 @@ function readRunnerCodeRow(name: string, property: any): any { ); return row; } - -/** The string members of an exported `type Name = 'a' | 'b'` union. */ -function readUnionReasons( - parsed: ReturnType, - filename: string, - name: string, -): string[] { - const aliases = parsed.program.body.flatMap((statement) => - statement.type === 'ExportNamedDeclaration' && - statement.declaration?.type === 'TSTypeAliasDeclaration' - ? [statement.declaration] - : [], - ); - const alias = aliases.find( - (candidate) => candidate.id.type === 'Identifier' && candidate.id.name === name, - ); - assert.ok(alias !== undefined, `${filename} must export the ${name} union.`); - const annotation = alias.typeAnnotation; - const members = annotation.type === 'TSUnionType' ? annotation.types : [annotation]; - return members.map((member) => { - assert.ok( - member.type === 'TSLiteralType' && - member.literal.type === 'Literal' && - typeof member.literal.value === 'string', - `unsupported member in ${name}: ${member.type}`, - ); - return member.literal.value; - }); -} diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 39fc991669..259fed6713 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -73,7 +73,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:fbb1ffa587ffb8b2975936fd35113c1970da16c58a713014df2c6ba885eecdd5", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:9f72097ae602ee8040c7a42104d682e4ea6b4c5999aa653a72b3cf47d4f5b81d", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", @@ -274,8 +274,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:fbb1ffa587ffb8b2975936fd35113c1970da16c58a713014df2c6ba885eecdd5", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field. Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. Artifact expiry and download deadlines keep their existing reasons. The shared HTTP disconnect helper preserves typed cancellation on aborted requests and unfinished response closes. Directory preparation counts inventory and download callers together, so one disconnected download cannot abort an inventory caller's build; successful response fields and authorization stay unchanged." + "digest": "sha256:9f72097ae602ee8040c7a42104d682e4ea6b4c5999aa653a72b3cf47d4f5b81d", + "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field. Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. Artifact expiry and download deadlines keep their existing reasons. The shared HTTP disconnect helper preserves typed cancellation on aborted requests and unfinished response closes. Directory preparation counts inventory and download callers together, so one disconnected download cannot abort an inventory caller's build; successful response fields and authorization stay unchanged. The size-mismatch failure reads artifact_size_mismatch from a ReasonTable row; the published reason value is unchanged." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 20cc7127d6..05da6ce326 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -11,6 +11,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r ## Commands +### `alert` + +| Reason | Meaning | +| --- | --- | +| `alert-wait-window-too-long` | `alert wait` was given a longer window than it can honour; the command refuses it before running and never shortens it. `details.maxWaitWindowMs` names the limit. | + ### `audit` | Reason | Meaning | @@ -27,6 +33,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `back_swipe_not_dispatched` | The back swipe was refused before it reached the device. | | `in_app_back_control_unavailable` | On macOS, the app's accessibility tree exposes no in-app back control. | +### `batch` + +| Reason | Meaning | +| --- | --- | +| `bounded_composite_resource_unsupported` | The composite refused this step before dispatch because it must run as its own command, such as a recording, trace, log, audio or perf capture. `details.shape` names the refused operation or option, and `details.standaloneCommandName` the public command to run instead. Earlier steps may have run. | + ### `clipboard` | Reason | Meaning | @@ -65,12 +77,20 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `android_shell_text_unsupported` | The adb-shell fallback carries ASCII text only; a helper or provider channel is needed. | | `android_ime_helper_no_ack` | The test IME helper gave no evidence it attempted the dispatch, so nothing is proven typed. | | `android_ime_helper_dispatch_rejected` | The test IME helper answered that it rejected the dispatch, so nothing was typed. | +| `fill_record_as_requires_armed_recording` | `fill --record-as` needs an armed script recording; open a session with `--save-script` first. | +| `fill_text_stdin_unparameterized_recording` | `fill --text-stdin` needs `--record-as` or `--no-record` while a recording is armed, so the stdin text stays out of the script. | | `android_test_ime_rebind_unconfirmed` | The test IME rebind could not be confirmed, so the focused field may have no input session. | | `fill_text_stdin_tty` | stdin is a terminal, so the command would wait for input no one is piping. | | `fill_text_stdin_too_large` | The piped input passed the byte limit of 64 KiB. | | `fill_text_stdin_empty` | The piped input decoded to an empty string. | | `fill_text_stdin_invalid_utf8` | The piped input is not valid UTF-8, a lone surrogate included. | +### `find` + +| Reason | Meaning | +| --- | --- | +| `find_snapshot_unreadable` | The capture came back sparse, so no selector could be resolved against it. | + ### `fold` | Reason | Meaning | @@ -107,6 +127,8 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | +| `claim-lost-during-open` | The device lost the claim this open was made with; close the session and open the device again. | +| `runtime-hints-operation-missing` | Runtime hints were requested, but the device runtime admitted no operation to apply or clear them. | | `android_port_reverse_rebind_refused` | The endpoint already has a device mapping, which a `--no-rebind` reverse never replaces. | | `invalid-android-activity-component` | The `--activity` value is not an Android component name. | | `android-launch-not-foreground` | The app the helper launched never reached the foreground before the launch budget ran out. | @@ -146,6 +168,13 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `prepare_deadline_expired` | `prepare ios-runner` ran out of its deadline before the named `details.phase` began. | | `prepare_rebuilt_runner_unhealthy` | The cached runner failed its health check, and the rebuilt runner failed it too; `details.rebuiltFailureMessage` says how. | +### `press` + +| Reason | Meaning | +| --- | --- | +| `sequence-recording-unsupported` | A multi-ref press sequence cannot be recorded; record one press per key, or pass `--no-record`. | +| `sequence-replay-guard-unsupported` | A multi-ref press sequence cannot carry a replay target guard; re-record one press per key. | + ### `proxy` | Reason | Meaning | @@ -169,6 +198,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `start-failed` | The React renderer refused to start profiling. | | `tree-unavailable` | Another DevTools frontend owns the component tree of this app runtime. | +### `react-native` + +| Reason | Meaning | +| --- | --- | +| `overlay_snapshot_unreadable` | `react-native dismiss-overlay` got a sparse capture, so it cannot tell whether an overlay is showing. | + ### `record` | Reason | Meaning | @@ -191,6 +226,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | | `wait_landmark_identity_mismatch` | A replay destination guard refused the match because its identity differs from the recorded landmark. | +| `bounded_composite_resource_unsupported` | The composite refused this step before dispatch because it must run as its own command, such as a recording, trace, log, audio or perf capture. `details.shape` names the refused operation or option, and `details.standaloneCommandName` the public command to run instead. Earlier steps may have run. | | `android-process-probe-unavailable` | `adb pidof` or the resumed-activity read did not answer, so process state is unknown. | | `android-kill-process-survived` | `am kill` returned and the process is still running; force-stop it instead. | | `android-kill-requires-background-app` | `am kill` only reaps background processes, so it refuses the foreground app. | @@ -210,6 +246,9 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `CROP_FRAME_MISMATCH` | `--crop-on` was combined with `--overlay-refs` or `--fullscreen`, which move the captured frame. | | `PENDING_PIXEL_IDENTITY_EVIDENCE` | The `details.rejectionReason` of a target whose crop is not yet verified against an independent capture. | | `SCREENSHOT_FULLSCREEN_MACOS_HELPER_SURFACE_FIXED_FRAME` | `--fullscreen` names a macOS helper surface, which always captures the main display. | +| `screenshot_publication_failed` | Writing the screenshot to its output path failed; `details.filesystemCode` names the error. | +| `screenshot_destination_dangling_symlink` | The output path is a symbolic link to a file that does not exist. | +| `screenshot_destination_not_file` | The output path exists and is not a regular file. | | `simulator-screenshot-timeout` | `simctl io screenshot` timed out (ETIMEDOUT) on the simulator. | ### `scroll` @@ -229,6 +268,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `scroll_edge_no_progress` | The `scroll top` or `scroll bottom` gestures did not move the content. | | `scroll_edge_capture_unreadable` | `scroll top` or `scroll bottom` could not read the screen between passes. | +### `session` + +| Reason | Meaning | +| --- | --- | +| `remote_script_publication_unsupported` | A remote recording is delivered to its `--save-script` path, so `session save-script` cannot publish it. | + ### `settings` | Reason | Meaning | @@ -249,6 +294,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `shake-rest-acceleration-unreadable` | The console gave no accelerometer reading to restore afterwards, so nothing was sent. | | `shake-console-refused` | The emulator console refused an accelerometer command; `details.consoleReason` is its reply. | +### `shutdown` + +| Reason | Meaning | +| --- | --- | +| `TARGET_SHUTDOWN_LEASE_MISMATCH` | The selected target does not own the lease this request names, so it will not release it. | + ### `snapshot` | Reason | Meaning | @@ -266,6 +317,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | +| `bounded_composite_resource_unsupported` | The composite refused this step before dispatch because it must run as its own command, such as a recording, trace, log, audio or perf capture. `details.shape` names the refused operation or option, and `details.standaloneCommandName` the public command to run instead. Earlier steps may have run. | | `android-process-probe-unavailable` | `adb pidof` or the resumed-activity read did not answer, so process state is unknown. | | `android-kill-process-survived` | `am kill` returned and the process is still running; force-stop it instead. | | `android-kill-requires-background-app` | `am kill` only reaps background processes, so it refuses the foreground app. | @@ -400,6 +452,12 @@ These reasons can come from more than one command. | `apple_toolchain_unreadable` | The Xcode toolchain version files the runner cache is keyed on could not be read. | | `apple_runner_host_unbound` | The Apple runner was asked for its host before the daemon bound one. | +### Artifact downloads + +| Reason | Meaning | +| --- | --- | +| `artifact_size_mismatch` | The artifact stream ended at a different size than the daemon recorded; `details` gives both sizes. | + ### Artifact extraction | Reason | Meaning | @@ -434,8 +492,31 @@ These reasons can come from more than one command. | `daemon-busy` | The daemon still holds work, so it refused to leave; `details` counts that work. | | `daemon-instance-mismatch` | The request names a different daemon instance than the one answering it. | | `daemon-owner-embedded` | A live host process owns this daemon and ends it through its own `close()`. | +| `daemon_shutting_down` | The daemon has begun to leave, so it refuses every new request; retry against a new daemon. | +| `daemon_registration_refused` | Another daemon holds this state directory, or its registration could not be proven free, so this daemon did not start; `details.status` says which. | | `daemon-clean-not-detached` | The record does not prove the process is a daemon of its own, so its process tree may be someone else's work. | +### Daemon policy + +| Reason | Meaning | +| --- | --- | +| `DAEMON_POLICY_DENIED` | The daemon operator's policy denies this command, device, capability, or lease; `details.rule` names which. | + +### Daemon resources + +| Reason | Meaning | +| --- | --- | +| `RESOURCE_EXPIRED` | The artifact, upload, or path id expired or never existed; the daemon cannot tell which. | + +### Daemon runtime + +| Reason | Meaning | +| --- | --- | +| `interactor-resolution-missing` | This process never composed interactor resolution, so it cannot reach a device. | +| `runtime-gateway-missing` | The daemon was composed without the runtime gateway, admission ledger, or diagnostics service this command needs. | +| `request_web_session_missing` | A request reached device resolution without the web session its request scope derives; this is a daemon bug. | +| `generic-route-runtime-missing` | The command reached the generic route, which has no runtime execution for it. | + ### Daemon transport | Reason | Meaning | @@ -447,6 +528,14 @@ These reasons can come from more than one command. | `daemon_response_read_failure` | The response body could not be read before the connection ended. | | `daemon_request_too_large` | The serialized request passes `DAEMON_REQUEST_MAX_BYTES`, so it was refused before being sent. | +### Device claims + +| Reason | Meaning | +| --- | --- | +| `DEVICE_CLAIM_LIVE_OWNER` | A live session in another workspace or daemon owns the device. | +| `DEVICE_CLAIM_RECOVERY_PENDING` | The recorded owner is gone and its resources still need settling before the claim is released. | +| `DEVICE_CLAIM_OWNER_UNCERTAIN` | A claim exists, but its owner cannot be verified as live or gone. | + ### Device selection | Reason | Meaning | @@ -491,6 +580,12 @@ These reasons can come from more than one command. | --- | --- | | `host_instance_unreadable` | The host could not prove its own process start time, so it cannot issue a daemon pin. | +### Human control + +| Reason | Meaning | +| --- | --- | +| `human_control_active` | A human holds the device, so state-changing commands are refused while the hold is active; retry after it is released. | + ### Interaction | Reason | Meaning | @@ -513,8 +608,15 @@ These reasons can come from more than one command. | `LEASE_SCOPE_MISMATCH` | The lease does not match the tenant, run, backend, provider, device, or client of the request. | | `LEASE_SCOPE_REQUIRED` | The lease was allocated with an owner scope that the request does not repeat. | | `provider-instance-ended` | The device instance behind the lease ended outside the daemon, which ends the lease with it. | +| `DEVICE_LEASE_BUSY` | Another lease, or this tenant run, already holds the device; retry after that lease is released or expires. | | `LEASE_ID_IN_USE` | The requested lease id already names a lease that this daemon issued. | | `LEASE_CAPACITY_EXCEEDED` | Every iOS simulator lease slot is taken; retry after another lease is released. | +| `MACOS_APP_LEASE_DENIED` | A `macos-app` lease does not cover this request; `details.rule` names the limit. | +| `provider-not-registered` | The lease names a provider this daemon has not registered; `details.failedPlugins` lists plugins that failed to load. | +| `provider-credentials-changed` | The running daemon holds different provider credentials than this shell; stop the daemon and rerun. | +| `PROVIDER_SESSION_NOT_OWNED` | The provider session belongs to another tenant. | +| `MACOS_APP_LEASE_HOST_OWNED` | Only the host administrator releases a `macos-app` lease. | +| `MACOS_APP_LEASE_HOST_ALLOCATED` | Only the host administrator allocates a `macos-app` lease. | | `LEASE_SESSION_MISMATCH` | The lease scope of the request differs from the lease of its session; `details.field` names the field. | | `LEASE_LEDGER_OVERWRITE` | The CLI already tracks an allocated lease and must release or transfer it before it allocates another. | @@ -590,6 +692,15 @@ These reasons can come from more than one command. | --- | --- | | `provider-session-unavailable` | The provider's session for the device ended, so the runtime has nothing left to serve. | +### Ref frames + +| Reason | Meaning | +| --- | --- | +| `ref_frame_expired` | A device action since the snapshot expired the ref frame, so a mutation using its refs is refused; a read that still has retained evidence answers with a staleness warning instead. | +| `ref_generation_mismatch` | The pinned ref was minted from a snapshot generation that a newer one superseded. | +| `plain_ref_requires_complete_frame` | A plain ref needs a complete frame. Retry with the pinned ref in `details.suggestedRef` when present; otherwise capture a fresh interactive snapshot or use a stable selector. | +| `ref_not_issued` | The current ref frame did not issue this ref, so it no longer names a node. | + ### Remote connection | Reason | Meaning | @@ -598,6 +709,12 @@ These reasons can come from more than one command. | `CONNECTION_DEVICE_CONFLICT` | The connection is bound to another device, or its lease was allocated by another device spec; `details.keys` names the disagreeing keys, and is present only for a device-spec mismatch. | | `CONNECTION_PLATFORM_CONFLICT` | The connection is bound to another platform, or the request names one its lease backend does not rent. | +### Remote daemon + +| Reason | Meaning | +| --- | --- | +| `REMOTE_HOST_INPUT_DENIED` | A remote request supplied a host path or other host input (`details.field`), which a remote daemon refuses. | + ### Remote transfer | Reason | Meaning | @@ -623,6 +740,12 @@ These reasons can come from more than one command. | --- | --- | | `duplicate_request_id` | A request arrived with an id another request is still in flight under. | +### Request execution + +| Reason | Meaning | +| --- | --- | +| `DEVICE_EXECUTION_LOCK_BUSY` | Another request is using the device while this request holds another device of the same host; run the step as its own request. | + ### Revyl provider | Reason | Meaning | @@ -659,10 +782,27 @@ These reasons can come from more than one command. | --- | --- | | `script_ancestor_untrusted` | The script path is not one absolute file name under existing directories private to this user. | +### Script recording + +| Reason | Meaning | +| --- | --- | +| `script_write_failed` | Writing the session script failed; check the target path and its permissions, then record again. | + +### Sessions + +| Reason | Meaning | +| --- | --- | +| `WORKSPACE_SESSION_SCOPE_CONFLICT` | A session in another workspace already uses the device; `details.session` names it. | +| `session_address_occupied` | Another live session already holds this session address. | +| `session_lifetime_ended` | The session the command ran in ended first; open a new session before retrying. | +| `SESSION_IDLE_EXPIRED` | The session expired after its idle window (`details.idleExpiryMs`); run `open` to start a new one. | +| `session_cleanup_incomplete` | Session cleanup was incomplete; `details.failedSteps` lists the steps that failed, and the hint says whether the session was kept (retry `close`) or retired, and what to do next. | + ### Snapshot capture | Reason | Meaning | | --- | --- | +| `ios_app_session_required` | The iOS command needs an active app session on the target device; run `open` first. | | `runner-snapshot-bridge-target-unavailable` | The runner could not name the app's foreground process; `details.bridgeFailureCode` says why. | | `simulator-target-discovery-pending` | The wait ran out while the discovery of the app's simulator process was still running. | | `simulator-target-unavailable` | The app has no running process on the simulator. | @@ -678,6 +818,16 @@ These reasons can come from more than one command. | `daemon_request_timeout` | The daemon request's deadline left no time to finish its work. | | `operation_deadline_expired` | An `AbortSignal.timeout` ended the wait before the operation it guarded finished. | +### Uploads + +| Reason | Meaning | +| --- | --- | +| `UPLOAD_STATE_CORRUPT` | The staged upload holds more bytes than it declared, so it cannot resume; start a new upload. | +| `UPLOAD_ROLLBACK_FAILED` | A failed chunk could not be rolled back, so the upload ticket was invalidated; start a new upload. | +| `UPLOAD_FINALIZE_CLEANUP_FAILED` | Finalizing the upload failed, and removing its staged files failed too; `details.originalError` holds the first failure. | +| `transfer_ingress_deadline_exceeded` | The upload request exceeded its aggregate deadline (`details.timeoutMs`), which also covers processing after the body arrived. | +| `upload_canceled` | The client disconnected or canceled before the upload finished. | + ### Web session naming | Reason | Meaning |