Repository navigation
Expand file tree
/
Copy pathrequest-router.ts
More file actions
795 lines (750 loc) · 30.5 KB
/
Copy pathrequest-router.ts
File metadata and controls
795 lines (750 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
import { withResolveTargetDeviceCacheScope } from '@agent-device/device-selection/dispatch-resolve';
import { withDeviceInventoryContext } from '@agent-device/device-selection/device-inventory-context';
import type { LeaseLifecycleProvider, ProviderAppCatalog } from '@agent-device/contracts/device';
import type { ComposedDeviceInventoryGateways } from '@agent-device/contracts/platform-module';
import type { DeviceRuntimeGateway } from '@agent-device/contracts/platform-runtime';
import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations';
import {
AppError,
normalizeError,
retriableForErrorCode,
type DaemonError,
} from '@agent-device/kernel/errors';
import { withRequestCommandEnv } from '@agent-device/host-kit/command';
import { timingSafeStringEqual } from '@agent-device/host-kit/transport';
import {
type ResponseCost,
errorResponse,
noActiveSessionError,
} from '@agent-device/kernel/contracts';
import type { CloudArtifactProvider } from '@agent-device/contracts/observability';
import type { TrackDownloadableArtifact } from './artifact-tracking.ts';
import type {
RequestPlatformProviderScope,
RequestPlatformProviders,
} from '@agent-device/contracts/platform-providers';
import type {
DaemonInvokeFn,
DaemonRequest,
DaemonResponse,
DaemonResponseData,
} from './daemon-request.ts';
import { RESPONSE_VIEWS } from './response-views.ts';
import { SessionStore } from './session-store.ts';
import { resolvePlatformProviderRequestContext } from './request-platform-provider-context.ts';
import {
countDiagnosticEventsByPhase,
emitDiagnostic,
flushDiagnosticsToSessionFile,
getDiagnosticsMeta,
redactRegisteredSensitiveValues,
registerDiagnosticSensitiveValue,
withDiagnosticsScope,
} from '@agent-device/host-kit/diagnostics';
import type { LeaseRegistry } from './lease-registry.ts';
import {
loadGenericRequestHandlerModule,
runRequestHandlerChain,
} from './request-handler-chain.ts';
import {
createRequestExecutionScope,
finalizeRequestExecutionScope,
type LockedRequestScope,
prepareLockedRequestScope,
type RequestExecutionScope,
} from './request-execution-scope.ts';
import { unsupportedSaveScriptFlagResponse } from './request-save-script-policy.ts';
import { canRunReplayScopedAction } from './daemon-command-registry.ts';
import { isWebSession } from './web-session-names.ts';
import { inferFillText, isSensitiveFillText } from '@agent-device/ad-script';
import { createPlatformRequestScope } from './platform-request-scope.ts';
import { createOwnerScopedDeviceClaimReconciler } from './device/device-claim-owner-recovery.ts';
import { isConfinedToAppLease, scopeRequestSession } from './request-admission.ts';
import { redactMacOsAppLeaseResponse } from './macos-app-lease.ts';
import { resolveEffectiveSessionName } from './session-routing.ts';
import { sessionIdleExpiredError } from './session-idle-expiry.ts';
import type { IdleSessionTombstone } from './session-idle-tombstone.ts';
import {
createAppLogAdmissionLedger,
type AppLogAdmissionLedger,
} from './app-log-admission-ledger.ts';
import {
type AudioProbeAdmissionLedger,
createAudioProbeAdmissionLedger,
} from '@agent-device/capture-kit/audio-probe-admission-ledger';
import {
createPerfCaptureAdmissionLedger,
type PerfCaptureAdmissionLedger,
} from '@agent-device/capture-kit/perf-capture-admission-ledger';
import {
createScreenRecordingAdmissionLedger,
type ScreenRecordingAdmissionLedger,
} from '@agent-device/capture-kit/screen-recording-admission-ledger';
import type { HostDiagnostics } from '@agent-device/contracts/host-diagnostics';
import { resolveGenericRuntimeExecution } from './generic-runtime-execution.ts';
import { discloseRequestDispatch, refusedBeforeDispatch } from './request-dispatch-disclosure.ts';
import { recordNestedRequests } from './request-dispatch-ledger.ts';
import type { AndroidObservationAdapter } from '@agent-device/contracts/android-observation';
import type { PlatformResourceCleanup } from './platform-resource-cleanup.ts';
import type { DaemonProviderCredentials } from '../provider-credential-fingerprint.ts';
import { restrictDeviceInventoryToDaemonPolicy } from './daemon-policy.ts';
import type { DaemonPolicy } from '../daemon-policy-file.ts';
// ---------------------------------------------------------------------------
// Request handler API
// ---------------------------------------------------------------------------
export type RequestRouterDeps = {
logPath: string;
token: string;
sessionStore: SessionStore;
leaseRegistry: LeaseRegistry;
requestPlatformProviders?: RequestPlatformProviders;
deviceInventoryGateways: ComposedDeviceInventoryGateways;
deviceRuntimeGateway: DeviceRuntimeGateway<PlatformRuntimeOperations>;
appLogAdmissionLedger?: AppLogAdmissionLedger;
audioProbeAdmissionLedger?: AudioProbeAdmissionLedger;
perfCaptureAdmissionLedger?: PerfCaptureAdmissionLedger;
screenRecordingAdmissionLedger?: ScreenRecordingAdmissionLedger;
hostDiagnostics?: HostDiagnostics;
providerRuntimeIds?: readonly string[];
providerRuntimeRequiredIds?: readonly string[];
providerCredentials: DaemonProviderCredentials;
leaseLifecycleProvider?: LeaseLifecycleProvider;
cloudArtifactProvider?: CloudArtifactProvider;
providerAppCatalog?: ProviderAppCatalog;
androidObservation?: AndroidObservationAdapter;
platformResourceCleanup?: PlatformResourceCleanup;
providerDeviceRuntimeScope?: <T>(task: () => Promise<T>) => Promise<T>;
/** ADR 0029: the daemon policy every admitted request, including nested steps, obeys. */
daemonPolicy?: DaemonPolicy;
trackDownloadableArtifact: TrackDownloadableArtifact;
};
const unavailableAndroidObservation = new Proxy({} as AndroidObservationAdapter, {
get() {
return async () => {
throw new AppError(
'INTERNAL_ERROR',
'Android observation was not supplied by root runtime composition',
);
};
},
});
function missingPlatformResourceCleanup(): AppError {
return new AppError(
'INTERNAL_ERROR',
'Platform resource cleanup was not supplied by root runtime composition',
);
}
const unavailablePlatformResourceCleanup: PlatformResourceCleanup = Object.freeze({
stopSnapshotHelper: async () => {
throw missingPlatformResourceCleanup();
},
closeManagedBrowser: async () => {
throw missingPlatformResourceCleanup();
},
cleanupSessionlessExecutionHost: async () => {
throw missingPlatformResourceCleanup();
},
retainExecutionHostAfterClose: () => {
throw missingPlatformResourceCleanup();
},
});
export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn {
const {
logPath,
token,
requestPlatformProviders = EMPTY_REQUEST_PLATFORM_PROVIDERS,
deviceRuntimeGateway,
appLogAdmissionLedger = createAppLogAdmissionLedger(),
audioProbeAdmissionLedger = createAudioProbeAdmissionLedger(),
perfCaptureAdmissionLedger = createPerfCaptureAdmissionLedger(),
screenRecordingAdmissionLedger = createScreenRecordingAdmissionLedger(),
hostDiagnostics,
providerRuntimeIds,
providerRuntimeRequiredIds,
providerCredentials,
leaseLifecycleProvider,
cloudArtifactProvider,
providerAppCatalog,
androidObservation = unavailableAndroidObservation,
platformResourceCleanup = unavailablePlatformResourceCleanup,
providerDeviceRuntimeScope,
trackDownloadableArtifact,
daemonPolicy,
} = deps;
const { sessionStore, leaseRegistry } = deps;
const deviceInventoryGateways = daemonPolicy
? restrictDeviceInventoryToDaemonPolicy(deps.deviceInventoryGateways, daemonPolicy)
: deps.deviceInventoryGateways;
async function handleRequest(req: DaemonRequest): Promise<DaemonResponse> {
const start = Date.now();
const debug = Boolean(req.meta?.debug || req.flags?.verbose);
return await withDiagnosticsScope(
{
session: req.session,
requestId: req.meta?.requestId,
command: req.command,
debug,
logPath,
},
async () => {
const response = await withRequestCommandEnv(
requestCommandEnv(req),
async () => await runRequestWithinScope(req),
);
if (!response.ok) {
// ADR 0012 decision 6, R7 (C5a): a command that finds no session but
// hits a live repair tombstone gets `REPAIR_SESSION_EXPIRED` with
// re-run guidance, never a bare SESSION_NOT_FOUND. #2833 adds the
// sibling case: an idle-expired session explains itself the same way.
const error = idleExpiredIfTombstoned(
req,
repairExpiredIfTombstoned(req, response.error, sessionStore),
sessionStore,
);
return { ok: false, error: redactRegisteredSensitiveValues(enrichDaemonError(error)) };
}
// Phase 4 (agent-cost) grafts on the success path. Runs inside the
// diagnostics scope so cost can read this request's runner-round-trip tally.
return applyAgentCostGrafts(req, response, start);
},
);
}
async function runRequestWithinScope(req: DaemonRequest): Promise<DaemonResponse> {
if (!timingSafeStringEqual(req.token, token)) {
return unauthorizedResponse();
}
registerParameterizedFillDiagnosticValue(req);
const invalidRecordingFlags = recordingFlagsResponse(req);
if (invalidRecordingFlags) return invalidRecordingFlags;
const invalidCustomActionFlags = customActionFlagsResponse(req);
if (invalidCustomActionFlags) return invalidCustomActionFlags;
// #1478: raw `flags.saveScript` on a non-owner command never reaches
// admission, device work, or a handler that could arm publication.
const unsupportedSaveScript = unsupportedSaveScriptFlagResponse(req);
if (unsupportedSaveScript) return unsupportedSaveScript;
let scope: RequestExecutionScope | undefined;
let response: DaemonResponse;
const platformRequestScope = createPlatformRequestScope(req);
try {
response = await withDeviceInventoryContext(
{
...deviceInventoryGateways,
requestScope: platformRequestScope,
},
async () =>
await withResolveTargetDeviceCacheScope(async () => {
scope = await createRequestExecutionScope({
req,
sessionStore,
leaseRegistry,
deviceRuntimeGateway,
platformRequestScope,
platformResourceCleanup,
providerAppCatalog,
daemonPolicy,
});
return await executeRequestScope(scope);
}),
);
} catch (error) {
response = finalizeThrownRequestError(error);
}
return redactForMacOsAppLease(req, scope, await finalizeRequestBindingCleanup(scope, response));
}
// Not covered, by choice: a request refused before its scope exists that names no lease in its
// own metadata and relies on its session's lease. Leased remote clients always send the lease.
function redactForMacOsAppLease(
req: DaemonRequest,
scope: RequestExecutionScope | undefined,
response: DaemonResponse,
): DaemonResponse {
const session = scope ? sessionStore.lookup(scope.sessionName)?.session : undefined;
return isConfinedToAppLease(scope?.req ?? req, leaseRegistry, session, daemonPolicy)
? redactMacOsAppLeaseResponse(req.command, response)
: response;
}
async function executeRequestScope(
scope: RequestExecutionScope,
inheritedProviderScope?: RequestPlatformProviderScope,
): Promise<DaemonResponse> {
const run = async (): Promise<DaemonResponse> => {
const locked = await prepareLockedRequestScope({
scope,
sessionStore,
trackDownloadableArtifact,
});
if (locked.type === 'response') return locked.response;
const lockedScope = locked.scope;
const executeLocked = async (providerScope: RequestPlatformProviderScope) => {
const runLockedRequest = async () =>
await executeLockedRequest({
lockedScope,
providerScope,
allowReplayActions: inheritedProviderScope === undefined,
});
return providerDeviceRuntimeScope
? await providerDeviceRuntimeScope(runLockedRequest)
: await runLockedRequest();
};
if (inheritedProviderScope) return await executeLocked(inheritedProviderScope);
const useDefaultWebProvider = shouldUseDefaultWebProvider(lockedScope);
if (!requestPlatformProviders.hasConfiguredResolvers && !useDefaultWebProvider) {
return await executeLocked({});
}
const context = await resolvePlatformProviderRequestContext({
req: lockedScope.req,
existingSession: lockedScope.existingSession,
useDefaultWebProvider,
});
return context
? await requestPlatformProviders.run(context, executeLocked)
: await executeLocked({});
};
return inheritedProviderScope ? await scope.runAdmitted(run) : await scope.runLocked(run);
}
async function executeLockedRequest(params: {
lockedScope: LockedRequestScope;
providerScope: RequestPlatformProviderScope;
allowReplayActions: boolean;
}): Promise<DaemonResponse> {
const { lockedScope, providerScope, allowReplayActions } = params;
return await discloseRequestDispatch(
lockedScope.req,
lockedScope.dispatchLedger,
async () => await routeLockedRequest({ lockedScope, providerScope, allowReplayActions }),
);
}
async function routeLockedRequest(params: {
lockedScope: LockedRequestScope;
providerScope: RequestPlatformProviderScope;
allowReplayActions: boolean;
}): Promise<DaemonResponse> {
const { lockedScope, providerScope, allowReplayActions } = params;
const { dispatchLedger } = lockedScope;
const requestScope = createPlatformRequestScope(lockedScope.req);
const handlerResponse = await runRequestHandlerChain({
req: lockedScope.req,
sessionName: lockedScope.sessionName,
logPath: lockedScope.logPath,
sessionStore,
leaseRegistry,
leaseLifecycleProvider,
providerRuntimeIds,
providerRuntimeRequiredIds,
providerCredentials,
cloudArtifactProvider,
providerAppCatalog,
invoke: recordNestedRequests(handleRequest, dispatchLedger),
invokeReplayAction: allowReplayActions
? recordNestedRequests(
createReplayScopedActionInvoker(lockedScope, providerScope),
dispatchLedger,
)
: undefined,
providerScope,
androidObservation,
platformResourceCleanup,
bindDevice: lockedScope.bindDevice,
inspectFacts: lockedScope.inspectFacts,
bindExactDevice: lockedScope.bindExactDevice,
reconcileOrphanedDeviceClaim: createOwnerScopedDeviceClaimReconciler(requestScope),
appLogAdmissionLedger,
audioProbeAdmissionLedger,
perfCaptureAdmissionLedger,
screenRecordingAdmissionLedger,
hostDiagnostics,
requestScope,
retainDeviceExecutionLock: lockedScope.retainDeviceExecutionLock,
throwIfCanceled: lockedScope.throwIfCanceled,
contextFromFlags: lockedScope.handlerContextFromFlags,
});
if (handlerResponse) return handlerResponse;
return await dispatchGenericForLockedScope({
lockedScope,
logPath: lockedScope.logPath,
sessionStore,
androidObservation,
});
}
function createReplayScopedActionInvoker(
parentScope: LockedRequestScope,
providerScope: RequestPlatformProviderScope,
): DaemonInvokeFn {
return async (req) => {
if (!canRunReplayActionInCurrentScope(req, parentScope)) return await handleRequest(req);
if (!timingSafeStringEqual(req.token, token)) {
return unauthorizedResponse();
}
registerParameterizedFillDiagnosticValue(req);
let childScope: RequestExecutionScope | undefined;
let response: DaemonResponse;
try {
const scopedReq = bindReplayDeviceExecutionLock(req, parentScope);
childScope = await createRequestExecutionScope({
req: scopedReq,
sessionStore,
leaseRegistry,
deviceRuntimeGateway,
platformRequestScope: createPlatformRequestScope(scopedReq),
platformResourceCleanup,
providerAppCatalog,
daemonPolicy,
});
// The outer replay keeps its stable session lock plus the device lock
// from the first device binding through response projection and ref
// finalization. A same-session replay action reuses that admitted scope
// instead of reacquiring the non-reentrant locks. Nested changes remain
// visible to capture lineage through snapshot/frame/runtime/store state.
response =
childScope.sessionName === parentScope.sessionName
? await executeRequestScope(childScope, providerScope)
: await executeRequestScope(childScope);
} catch (error) {
response = finalizeThrownRequestError(error);
}
return await finalizeRequestBindingCleanup(childScope, response);
};
}
return handleRequest;
}
function requestCommandEnv(req: DaemonRequest): NodeJS.ProcessEnv | undefined {
const developerDir = req.meta?.developerDir;
return typeof developerDir === 'string' ? { DEVELOPER_DIR: developerDir } : undefined;
}
const EMPTY_REQUEST_PLATFORM_PROVIDERS: RequestPlatformProviders = Object.freeze({
hasConfiguredResolvers: false,
run: async (_context, task) => await task({}),
});
function shouldUseDefaultWebProvider(scope: LockedRequestScope): boolean {
return (
(scope.existingSession !== undefined && isWebSession(scope.existingSession)) ||
scope.req.flags?.platform === 'web'
);
}
function unauthorizedResponse(): DaemonResponse {
return {
ok: false,
error: normalizeError(new AppError('UNAUTHORIZED', 'Invalid token')),
};
}
/**
* #1271 stage 2 (ADR 0012 amendment): `--record` and `--no-record` express
* opposite recording intents for the same action — force it into a
* repair-armed heal versus opt it out entirely — so both together is a
* contradiction the daemon rejects up front, uniformly for every surface
* (CLI/Node client/MCP all funnel through this same request entry point),
* rather than silently letting one win.
*/
function mutuallyExclusiveRecordFlagsResponse(): DaemonResponse {
return errorResponse(
'INVALID_ARGS',
'--record and --no-record are mutually exclusive; pass at most one.',
);
}
const FILL_ONLY_FLAGS = [
['recordAs', '--record-as', 'string'],
['textStdin', '--text-stdin', 'boolean'],
] as const;
function recordingFlagsResponse(req: DaemonRequest): DaemonResponse | undefined {
if (req.flags?.record && req.flags?.noRecord) return mutuallyExclusiveRecordFlagsResponse();
if (req.command === 'fill') return malformedFillOnlyFlagResponse(req);
const fillOnly = FILL_ONLY_FLAGS.find(([key]) => req.flags?.[key] !== undefined);
if (!fillOnly) return undefined;
return errorResponse('INVALID_ARGS', `${fillOnly[1]} is supported only by fill.`);
}
/**
* Both fill-only flags mark the text as sensitive, and the request boundary only checks that
* `flags` is an object. A marker of the wrong type is refused here instead of read as unmarked.
*/
function malformedFillOnlyFlagResponse(req: DaemonRequest): DaemonResponse | undefined {
const malformed = FILL_ONLY_FLAGS.find(([key, , type]) => {
const value = req.flags?.[key];
return value !== undefined && typeof value !== type;
});
if (!malformed) return undefined;
return errorResponse('INVALID_ARGS', `${malformed[1]} must be a ${malformed[2]}.`);
}
/**
* `--actions` reads custom actions through the private-AX snapshot path, which
* a raw capture deliberately does not take (ADR 0004: raw preserves the tree
* backend's own errors). Asking for both is a contradiction, and answering it
* with a capture that structurally cannot carry actions would be a requested
* capability silently no-opped. Rejected at the request seam so CLI, Node
* client, and MCP all get the same answer before any device work.
*/
function customActionFlagsResponse(req: DaemonRequest): DaemonResponse | undefined {
if (req.flags?.snapshotCustomActions !== true) return undefined;
if (req.flags?.snapshotRaw === true) {
return errorResponse(
'INVALID_ARGS',
'--actions and --raw are mutually exclusive: custom actions are only readable through the private-AX snapshot path, which a raw capture does not use.',
);
}
return undefined;
}
function registerParameterizedFillDiagnosticValue(req: DaemonRequest): void {
if (req.command !== 'fill' || !isSensitiveFillText(req.flags)) return;
registerDiagnosticSensitiveValue(
inferFillText({
ts: 0,
command: 'fill',
positionals: req.positionals ?? [],
flags: req.flags,
}),
);
}
async function dispatchGenericForLockedScope(params: {
lockedScope: LockedRequestScope;
logPath: string;
sessionStore: SessionStore;
androidObservation: AndroidObservationAdapter;
}): Promise<DaemonResponse> {
const { lockedScope, logPath, sessionStore, androidObservation } = params;
const ref = sessionStore.lookup(lockedScope.sessionName);
if (!ref) {
return noActiveSessionError();
}
const session = sessionStore.requireCurrent(ref);
const runtimeExecution = await resolveGenericRuntimeExecution({
req: lockedScope.req,
session,
// `scroll` parses its distance/timing flags during admission, so the resolved context is
// needed before the dispatcher builds its own.
context: lockedScope.contextFromFlags(
lockedScope.req.flags,
session.appBundleId,
session.trace?.outPath,
),
inspectFacts: lockedScope.inspectFacts,
bindDevice: lockedScope.bindDevice,
});
if (!runtimeExecution.ok) return refusedBeforeDispatch(runtimeExecution.response);
const { dispatchGenericCommand } = await loadGenericRequestHandlerModule();
const dispatchResponse = await dispatchGenericCommand({
req: lockedScope.req,
ref,
sessionName: lockedScope.sessionName,
logPath,
sessionStore,
contextFromFlags: lockedScope.contextFromFlags,
executePlatformCommand: runtimeExecution.execute,
androidObservation,
...(runtimeExecution.recorded ? { recordedRequest: runtimeExecution.recorded } : {}),
});
return dispatchResponse;
}
function bindReplayDeviceExecutionLock(
req: DaemonRequest,
parentScope: LockedRequestScope,
): DaemonRequest {
if (req.command !== 'open') return req;
const retainDeviceExecutionLock = req.internal?.retainDeviceExecutionLock;
return {
...req,
internal: {
...req.internal,
retainDeviceExecutionLock: async (deviceId) => {
await parentScope.retainDeviceExecutionLock(deviceId);
await retainDeviceExecutionLock?.(deviceId);
},
},
};
}
function canRunReplayActionInCurrentScope(
req: DaemonRequest,
parentScope: LockedRequestScope,
): boolean {
return req.session === parentScope.sessionName && canRunReplayScopedAction(req.command);
}
function finalizeThrownRequestError(error: unknown): DaemonResponse {
emitDiagnostic({
level: 'error',
phase: 'request_failed',
data: {
error: error instanceof Error ? error.message : String(error),
},
});
const details = getDiagnosticsMeta();
const flushed = flushDiagnosticsToSessionFile({ force: true });
const normalizedError = normalizeError(error, {
diagnosticId: details.diagnosticId,
logPath: flushed?.path,
diagnosticsRecord: flushed?.ref,
});
return { ok: false, error: normalizedError };
}
async function finalizeRequestBindingCleanup(
scope: RequestExecutionScope | undefined,
response: DaemonResponse,
): Promise<DaemonResponse> {
if (!scope) return response;
let finalResponse = response;
try {
await scope[Symbol.asyncDispose]();
} catch (cleanupError) {
if (response.ok) {
finalResponse = finalizeThrownRequestError(cleanupError);
} else {
emitDiagnostic({
level: 'error',
phase: 'request_binding_cleanup_failed',
data: {
primaryCode: response.error.code,
cleanupError: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
},
});
flushDiagnosticsToSessionFile({ force: true });
}
}
return finalizeRequestExecutionScope(scope, finalResponse);
}
/**
* ADR 0012 decision 6, R7 (C5a, BLOCKER 2): when a request finds no session
* (SESSION_NOT_FOUND) but a live repair tombstone exists for its session key,
* rewrite the error to an actionable recovery error. Any other error, or the
* absence of a (non-expired) tombstone, passes through untouched.
*
* BLOCKER 2: a tombstone carrying `commitFailure` means the transaction
* actually COMPLETED and a commit was attempted at teardown but FAILED (e.g.
* no-clobber refusal, a filesystem error) — that is a materially different,
* more specific situation than "reaped before it ever finished", so it gets
* its own `REPAIR_COMMIT_FAILED` code carrying the real cause, rather than
* being folded into the generic `REPAIR_SESSION_EXPIRED` expiry message.
*/
function repairExpiredIfTombstoned(
req: DaemonRequest,
error: DaemonError,
sessionStore: SessionStore,
): DaemonError {
if (error.code !== 'SESSION_NOT_FOUND') return error;
const address = resolveTombstoneSessionAddress(req, sessionStore);
if (address === undefined) return error;
const tombstone = sessionStore.readRepairTombstone(address);
if (!tombstone) return error;
const reRun = tombstone.sourcePath
? `re-run: replay ${tombstone.sourcePath} --save-script`
: 're-run your replay <script> --save-script from the start';
if (tombstone.commitFailure) {
return normalizeError(
new AppError(
'REPAIR_COMMIT_FAILED',
`The repair transaction for session "${req.session}" completed, but committing its healed script failed at teardown: ${tombstone.commitFailure.message}. ${reRun}.`,
),
);
}
return normalizeError(
new AppError(
'REPAIR_SESSION_EXPIRED',
`The --save-script repair session "${req.session}" was reaped before it was finalized (idle-reap); ${reRun}.`,
),
);
}
/**
* #2833: when a command finds no session because this daemon already expired it for idleness, the
* answer stays `SESSION_NOT_FOUND` — the session genuinely is gone — but carries the typed reason,
* the window it missed, and the device it released. A bare "Run open first" tells an agent on a
* shared machine to retry an `open` that will collide with its own expired session's claim if the
* release is still in flight, and gives it nothing to reason about either way.
*
* Consulted after the repair tombstone so an abandoned repair transaction keeps its own, more
* specific recovery guidance. The address is resolved through the same routing the request took; a
* name that cannot be resolved has no marker rather than an error that would replace the caller's.
*/
function idleExpiredIfTombstoned(
req: DaemonRequest,
error: DaemonError,
sessionStore: SessionStore,
): DaemonError {
if (error.code !== 'SESSION_NOT_FOUND') return error;
const tombstone = readIdleExpiryTombstoneSafely(req, sessionStore);
if (!tombstone) return error;
return normalizeError(sessionIdleExpiredError(tombstone.owner, tombstone));
}
function resolveTombstoneSessionAddress(
req: DaemonRequest,
sessionStore: SessionStore,
): string | undefined {
try {
return resolveEffectiveSessionName(scopeRequestSession(req), sessionStore, {
attachesToSession: false,
});
} catch {
return undefined;
}
}
function readIdleExpiryTombstoneSafely(
req: DaemonRequest,
sessionStore: SessionStore,
): IdleSessionTombstone | undefined {
const address = resolveTombstoneSessionAddress(req, sessionStore);
if (address === undefined) return undefined;
try {
return sessionStore.readIdleExpiryTombstone(address);
} catch {
return undefined;
}
}
// Phase 2 typed-error graft: add machine-readable signals to an error response.
// Returns the error unchanged unless a signal applies, so the default wire shape
// is preserved for the common codes.
function enrichDaemonError(error: DaemonError): DaemonError {
// A throw-site classification (lifted from details by normalizeError) wins
// over the conservative code-level policy.
const retriable = error.retriable ?? retriableForErrorCode(error.code);
if (retriable === undefined) return error;
return {
...error,
retriable,
};
}
// Phase 4 (agent-cost) success-path grafts: a leveled response view and an
// opt-in cost block, both purely additive. With responseLevel `default` (or
// unset) AND no registered view AND no --cost, the original `response` object is
// returned unchanged — byte-identical to today (Maestro `.ad` recompare safe).
function applyAgentCostGrafts(
req: DaemonRequest,
response: Extract<DaemonResponse, { ok: true }>,
startedAt: number,
): DaemonResponse {
const viewed = applyResponseLevelView(req, response);
if (!req.meta?.includeCost) return viewed;
const cost = buildResponseCost(response.data, startedAt);
return { ok: true, data: { ...(viewed.data ?? {}), cost } };
}
// Returns the response untouched when responseLevel is `default` (or unset) or no
// view is registered for the command — preserving today's byte-exact wire shape.
function applyResponseLevelView(
req: DaemonRequest,
response: Extract<DaemonResponse, { ok: true }>,
): Extract<DaemonResponse, { ok: true }> {
const level = req.meta?.responseLevel ?? 'default';
if (level === 'default') return response;
const view = RESPONSE_VIEWS[req.command];
return view ? { ok: true, data: view(response.data ?? {}, level) } : response;
}
// Diagnostic phases emitted once per real iOS-runner round-trip. `..._command_send`
// is the command itself; `..._readiness_preflight` is the pre-command uptime probe
// (a real network round-trip). The `..._skipped` / `..._recovered` markers do NOT
// hit the runner and are intentionally excluded.
const RUNNER_ROUND_TRIP_PHASES = [
'ios_runner_command_send',
'ios_runner_readiness_preflight',
] as const;
function buildResponseCost(
originalData: DaemonResponseData | undefined,
startedAt: number,
): ResponseCost {
const cost: ResponseCost = {
wallClockMs: Date.now() - startedAt,
// Counts this request's real runner round-trips from the flush-surviving
// diagnostics phase tally. Reads 0 when no runner was hit (e.g. a no-op or a
// command served entirely from the daemon). Must run inside the request's
// diagnostics scope (see `applyAgentCostGrafts` call site).
runnerRoundTrips: countDiagnosticEventsByPhase(RUNNER_ROUND_TRIP_PHASES),
};
// nodeCount reads the ORIGINAL node tree (the digest view may have already
// collapsed `data.nodes`), so the count stays accurate.
const nodes = originalData?.nodes;
if (Array.isArray(nodes)) cost.nodeCount = nodes.length;
return cost;
}