Skip to content

Commit 8252080

Browse files
committed
feat: typed errors — supportedOn + retriable signals — Phase 2
Graft the Phase 2 TypedError signals onto DaemonError: machine-readable hints an agent can act on without a wasted round-trip. - supportedOn: for UNSUPPORTED_OPERATION / UNSUPPORTED_PLATFORM errors, the platform families that DO support the command, DERIVED from the capability matrix (new supportedPlatformsForCommand in core/capabilities.ts). So an agent that hit a platform mismatch learns where the command works. - retriable: flags transient failures worth retrying. Conservative policy (retriableForErrorCode in utils/errors.ts) — currently only DEVICE_IN_USE (device healthy but busy); ambiguous/deterministic codes stay undefined. Both are additive and applied at a single chokepoint (handleRequest, where the command is in scope) only when a signal applies, so the default error wire shape is unchanged for the common codes — verified across 1632 daemon/core/contracts/ utils/commands tests (no error-shape ripple). New unit + router e2e test covers all three cases (supportedOn present, retriable true, deterministic unchanged). Verified: tsc --noEmit, oxfmt + oxlint --deny-warnings, fallow audit clean, Layering Guard empty.
1 parent e9975e1 commit 8252080

5 files changed

Lines changed: 207 additions & 8 deletions

File tree

‎src/contracts.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,18 @@ export type DaemonError = {
123123
diagnosticId?: string;
124124
logPath?: string;
125125
details?: Record<string, unknown>;
126+
/**
127+
* Machine-readable typed-error signals (Phase 2). Additive: present only when
128+
* derivable, so the default error wire shape is unchanged.
129+
*
130+
* `retriable` flags a transient failure an agent should retry (vs. a
131+
* deterministic one where a retry is wasted). `supportedOn` lists the platform
132+
* families that DO support the command (derived from the capability matrix),
133+
* surfaced on platform-mismatch errors so an agent self-corrects without a
134+
* wasted round-trip.
135+
*/
136+
retriable?: boolean;
137+
supportedOn?: string;
126138
};
127139

128140
export type DaemonResponse =

‎src/core/capabilities.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,22 @@ export function unsupportedHintForDevice(command: string, device: DeviceInfo): s
101101
export function listCapabilityCommands(): string[] {
102102
return Object.keys(COMMAND_CAPABILITY_MATRIX).sort();
103103
}
104+
105+
/**
106+
* The platform families that DO support `command`, derived from the capability
107+
* matrix (a family counts when it has at least one supported device kind). Used
108+
* by the typed-error graft to populate `DaemonError.supportedOn` on platform
109+
* mismatches. Returns `[]` for commands with no capability row (supported
110+
* everywhere) so callers can omit the signal.
111+
*/
112+
export function supportedPlatformsForCommand(command: string): string[] {
113+
const capability = COMMAND_CAPABILITY_MATRIX[command];
114+
if (!capability) return [];
115+
const families: Array<keyof CommandCapability> = ['apple', 'android', 'linux', 'web'];
116+
const supported: string[] = [];
117+
for (const family of families) {
118+
const kinds = capability[family] as KindMatrix | undefined;
119+
if (kinds && Object.values(kinds).some((value) => value === true)) supported.push(family);
120+
}
121+
return supported;
122+
}
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { test, expect, vi, beforeEach } from 'vitest';
2+
import os from 'node:os';
3+
import path from 'node:path';
4+
5+
vi.mock('../../core/dispatch.ts', async (importOriginal) => {
6+
const actual = await importOriginal<typeof import('../../core/dispatch.ts')>();
7+
return { ...actual, dispatchCommand: vi.fn(async () => ({})) };
8+
});
9+
10+
vi.mock('../../platforms/ios/runner-client.ts', async (importOriginal) => {
11+
const actual = await importOriginal<typeof import('../../platforms/ios/runner-client.ts')>();
12+
return { ...actual, stopIosRunnerSession: vi.fn(async () => {}) };
13+
});
14+
15+
vi.mock('../device-ready.ts', () => ({ ensureDeviceReady: vi.fn(async () => {}) }));
16+
17+
import { dispatchCommand } from '../../core/dispatch.ts';
18+
import { createRequestHandler } from '../request-router.ts';
19+
import type { DaemonRequest, SessionState } from '../types.ts';
20+
import { LeaseRegistry } from '../lease-registry.ts';
21+
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
22+
import { AppError, retriableForErrorCode } from '../../utils/errors.ts';
23+
import { supportedPlatformsForCommand } from '../../core/capabilities.ts';
24+
25+
const mockDispatch = vi.mocked(dispatchCommand);
26+
27+
function makeIosSession(name: string): SessionState {
28+
return {
29+
name,
30+
createdAt: 1_700_000_000_000,
31+
actions: [],
32+
device: {
33+
platform: 'ios',
34+
target: 'mobile',
35+
id: 'SIM-001',
36+
name: 'iPhone 16',
37+
kind: 'simulator',
38+
booted: true,
39+
simulatorSetPath: '/tmp/tenant-a/set',
40+
},
41+
};
42+
}
43+
44+
function makeHandler(sessionStore = makeSessionStore('agent-device-router-typed-error-')) {
45+
return {
46+
sessionStore,
47+
handler: createRequestHandler({
48+
logPath: path.join(os.tmpdir(), 'daemon.log'),
49+
token: 'test-token',
50+
sessionStore,
51+
leaseRegistry: new LeaseRegistry(),
52+
trackDownloadableArtifact: () => 'artifact-id',
53+
}),
54+
};
55+
}
56+
57+
function request(command: string, overrides: Partial<DaemonRequest> = {}): DaemonRequest {
58+
return {
59+
token: 'test-token',
60+
session: 'typed-error',
61+
command,
62+
positionals: [],
63+
flags: {},
64+
...overrides,
65+
};
66+
}
67+
68+
beforeEach(() => {
69+
mockDispatch.mockReset();
70+
});
71+
72+
test('retriableForErrorCode is a conservative policy: transient => true, others => undefined', () => {
73+
expect(retriableForErrorCode('DEVICE_IN_USE')).toBe(true);
74+
expect(retriableForErrorCode('INVALID_ARGS')).toBeUndefined();
75+
expect(retriableForErrorCode('UNSUPPORTED_OPERATION')).toBeUndefined();
76+
expect(retriableForErrorCode('COMMAND_FAILED')).toBeUndefined();
77+
});
78+
79+
test('UNSUPPORTED_OPERATION errors carry supportedOn derived from the capability matrix', async () => {
80+
const { sessionStore, handler } = makeHandler();
81+
sessionStore.set('typed-error', makeIosSession('typed-error'));
82+
mockDispatch.mockRejectedValue(new AppError('UNSUPPORTED_OPERATION', 'nope on this platform'));
83+
84+
// `home` routes through the (mocked) generic dispatch and is platform-restricted.
85+
const response = await handler(request('home'));
86+
87+
expect(response.ok).toBe(false);
88+
if (response.ok) return;
89+
const expected = supportedPlatformsForCommand('home');
90+
expect(expected.length).toBeGreaterThan(0); // home is a platform-restricted command
91+
expect(response.error.supportedOn).toBe(expected.join(', '));
92+
});
93+
94+
test('DEVICE_IN_USE errors are flagged retriable; supportedOn stays absent', async () => {
95+
const { sessionStore, handler } = makeHandler();
96+
sessionStore.set('typed-error', makeIosSession('typed-error'));
97+
mockDispatch.mockRejectedValue(new AppError('DEVICE_IN_USE', 'device busy'));
98+
99+
const response = await handler(request('home'));
100+
101+
expect(response.ok).toBe(false);
102+
if (response.ok) return;
103+
expect(response.error.retriable).toBe(true);
104+
expect('supportedOn' in response.error).toBe(false);
105+
});
106+
107+
test('deterministic errors (INVALID_ARGS) are returned with the default shape — no typed-error fields', async () => {
108+
const { sessionStore, handler } = makeHandler();
109+
sessionStore.set('typed-error', makeIosSession('typed-error'));
110+
111+
// Conflicting explicit selector under a reject lock policy fails with INVALID_ARGS
112+
// before dispatch — a deterministic error.
113+
const response = await handler(
114+
request('home', { flags: { udid: 'SIM-999' }, meta: { lockPolicy: 'reject' } }),
115+
);
116+
117+
expect(response.ok).toBe(false);
118+
if (response.ok) return;
119+
expect(response.error.code).toBe('INVALID_ARGS');
120+
expect('retriable' in response.error).toBe(false);
121+
expect('supportedOn' in response.error).toBe(false);
122+
expect(mockDispatch).not.toHaveBeenCalled();
123+
});

‎src/daemon/request-router.ts‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ import {
22
type DeviceInventoryProvider,
33
withTargetDeviceResolutionScope,
44
} from '../core/dispatch-resolve.ts';
5-
import { AppError, normalizeError } from '../utils/errors.ts';
5+
import { AppError, normalizeError, retriableForErrorCode } from '../utils/errors.ts';
6+
import { supportedPlatformsForCommand } from '../core/capabilities.ts';
67
import { timingSafeStringEqual } from '../utils/timing-safe-equal.ts';
7-
import type { ResponseCost } from '../contracts.ts';
8+
import type { DaemonError, ResponseCost } from '../contracts.ts';
89
import type { DaemonInvokeFn, DaemonRequest, DaemonResponse } from './types.ts';
910
import { SessionStore } from './session-store.ts';
1011
import { noActiveSessionError } from './handlers/response.ts';
@@ -102,13 +103,21 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn {
102103
},
103104
async () => {
104105
const response = await runRequestWithinScope(req);
106+
// Phase 2 (typed errors) graft: enrich error responses with additive,
107+
// machine-readable signals — `supportedOn` for platform mismatches and
108+
// `retriable` for transient failures — so an agent self-corrects without a
109+
// wasted round-trip. Returned unchanged when neither applies, so the
110+
// default error wire shape is preserved.
111+
if (!response.ok) {
112+
return { ok: false, error: enrichDaemonError(req.command, response.error) };
113+
}
105114
// Phase 4 (agent-cost) graft: cost is purely additive and opt-in. With
106-
// the flag off — or on an error response — the serialized DaemonResponse
107-
// is byte-identical to today (Maestro `.ad` recompare diffs it). Mirrors
108-
// the conditional `registerDownloadableArtifacts` spread in
109-
// request-finalization. Runs inside the diagnostics scope so it can read
110-
// this request's accumulated runner-round-trip tally.
111-
if (!req.meta?.includeCost || !response.ok) return response;
115+
// the flag off the serialized DaemonResponse is byte-identical to today
116+
// (Maestro `.ad` recompare diffs it). Mirrors the conditional
117+
// `registerDownloadableArtifacts` spread in request-finalization. Runs
118+
// inside the diagnostics scope so it can read this request's accumulated
119+
// runner-round-trip tally.
120+
if (!req.meta?.includeCost) return response;
112121
const cost: ResponseCost = {
113122
wallClockMs: Date.now() - start,
114123
runnerRoundTrips: countDiagnosticEventsByPhase(RUNNER_ROUND_TRIP_PHASES),
@@ -301,3 +310,21 @@ function finalizeThrownRequestError(error: unknown): DaemonResponse {
301310
});
302311
return { ok: false, error: normalizedError };
303312
}
313+
314+
// Phase 2 typed-error graft: add machine-readable signals to an error response.
315+
// Returns the error unchanged unless a signal applies, so the default wire shape
316+
// is preserved for the common codes.
317+
function enrichDaemonError(command: string, error: DaemonError): DaemonError {
318+
const supportedPlatforms =
319+
error.code === 'UNSUPPORTED_OPERATION' || error.code === 'UNSUPPORTED_PLATFORM'
320+
? supportedPlatformsForCommand(command)
321+
: [];
322+
const supportedOn = supportedPlatforms.length > 0 ? supportedPlatforms.join(', ') : undefined;
323+
const retriable = retriableForErrorCode(error.code);
324+
if (supportedOn === undefined && retriable === undefined) return error;
325+
return {
326+
...error,
327+
...(retriable !== undefined ? { retriable } : {}),
328+
...(supportedOn !== undefined ? { supportedOn } : {}),
329+
};
330+
}

‎src/utils/errors.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,24 @@ function stripDiagnosticMeta(
144144
return Object.keys(output).length > 0 ? output : undefined;
145145
}
146146

147+
/**
148+
* Conservative retriability policy for the Phase 2 typed-error graft. Returns
149+
* `true` only for codes that are clearly transient (a retry can succeed without
150+
* the caller changing anything) and `undefined` for ambiguous/deterministic
151+
* codes — so the error wire shape is unchanged unless we have a confident answer.
152+
* Intentionally small; extend as codes gain a clear retriability verdict.
153+
*/
154+
export function retriableForErrorCode(code: string): boolean | undefined {
155+
switch (code) {
156+
// The device is healthy but currently leased/busy — the same request can
157+
// succeed once it frees up.
158+
case 'DEVICE_IN_USE':
159+
return true;
160+
default:
161+
return undefined;
162+
}
163+
}
164+
147165
export function defaultHintForCode(code: string): string | undefined {
148166
switch (code) {
149167
case 'INVALID_ARGS':

0 commit comments

Comments
 (0)