Repository navigation
Expand file tree
/
Copy pathdaemon-runtime.ts
More file actions
906 lines (868 loc) · 35.6 KB
/
Copy pathdaemon-runtime.ts
File metadata and controls
906 lines (868 loc) · 35.6 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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
import crypto from 'node:crypto';
import { asAppError, AppError } from '@agent-device/kernel/errors';
import { SessionStore } from '../session-store.ts';
import { resolveSessionRequestLogPath } from '../session-artifact-paths.ts';
import { resolveDaemonPaths, resolveDaemonServerMode } from '../../daemon-resolution.ts';
import { createDaemonHttpServer } from './http-server.ts';
import { trackDownloadableArtifact } from '../artifact-tracking.ts';
import {
createProviderDeviceRuntimeRequestProviders,
isActiveProviderDevice,
} from '../../provider-device-runtime.ts';
import { installProviderDeviceAdmission } from '../provider-device-admission.ts';
import { assertDaemonPolicyAllowsCapability } from '../daemon-policy.ts';
import { loadDaemonPolicy, type DaemonPolicy } from '../../daemon-policy-file.ts';
import { getInteractor } from '../../core/interactors.ts';
import { installInteractorResolution } from '../interactor-resolution.ts';
import {
androidObservation,
createPlatformRuntimeGateway,
createPlatformDeviceInventoryGateways,
createRequestPlatformProviders,
} from '../../platform-runtime.ts';
import { createHostDiagnostics } from '../../platform-runtime-host-diagnostics.ts';
import {
createDaemonProviderRuntimeComposition,
DEFAULT_PROVIDER_RUNTIME_REQUIRED_IDS,
} from '../../provider-device-runtimes.ts';
import { LeaseRegistry } from '../lease-registry.ts';
import { createExpiredProviderLeaseReleaser } from '../provider-lease-expiry.ts';
import { clearDaemonShutdownReport, writeDaemonShutdownReport } from '../daemon-shutdown-report.ts';
import { createRequestHandler } from '../request-router.ts';
import { getLeaseRegistryExecutionLocks } from '../request-execution-scope.ts';
import { stopSessionAppLog, teardownSessionResources } from '../session-teardown.ts';
import { resolveDaemonSessionTeardownTimeoutMs } from '../session-teardown-budget.ts';
import { finalizeDaemonSessionApplicationLifecycle } from '../application-lifecycle-recovery.ts';
import { runtimeHintValues } from '../session-runtime.ts';
import { closeDaemonServers } from './server-shutdown.ts';
import type { DaemonInvokeFn } from '../daemon-request.ts';
import type { SessionState } from '../session-state.ts';
import { createDaemonIdleReap } from './daemon-idle-reap.ts';
import { createSessionIdleExpiry } from './daemon-session-idle-expiry.ts';
import { resolveSessionIdleExpiryMs } from '../session-idle-expiry.ts';
import { finalizeDaemonSessionLease } from './daemon-session-lease-finalizer.ts';
import {
processOwnsActiveDeviceClaim,
reconcileOrphanedDeviceClaims,
type DeviceClaimReconciler,
} from '../device/device-claims.ts';
import { createOwnerScopedDeviceClaimReconciler } from '../device/device-claim-owner-recovery.ts';
import { createDaemonShutdownClaimLedger } from './daemon-shutdown-claims.ts';
import { createAudioProbeAdmissionLedger } from '@agent-device/capture-kit/audio-probe-admission-ledger';
import { createPerfCaptureAdmissionLedger } from '@agent-device/capture-kit/perf-capture-admission-ledger';
import { createScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger';
import {
emitDiagnostic,
flushDiagnosticsToSessionFile,
withDiagnosticsScope,
type ResourceDiagnostic,
} from '@agent-device/host-kit/diagnostics';
import {
createOwnedProcessRecordStore,
type OwnedProcessRecordStore,
readCurrentOwnerIdentity,
reapOwnedProcessRecordsAtStartup,
type OwnerIdentity,
} from '@agent-device/host-kit/process';
import { isEnvTruthy, sleep } from '@agent-device/host-kit/retry';
import {
acquireDaemonLock,
parseIntegerEnv,
readVersion,
releaseDaemonLock,
removeInfoOwnedBy,
resolveDaemonCodeOrigin,
resolveDaemonCodeSignature,
writeInfo,
} from './server-lifecycle.ts';
import { watchDaemonMetadataLoss, type DaemonMetadataLoss } from './daemon-metadata-loss.ts';
import {
createSocketServer,
listenHttpServer,
listenNetServer,
type DaemonServer,
} from './transport.ts';
import { prewarmPngWorker, terminatePngWorker } from '@agent-device/capture-kit/png-worker-client';
import { platformResourceCleanup } from '../../platform-runtime-resource-cleanup.ts';
import { platformDaemonLifecycleOwners } from '../../platform-runtime-daemon-lifecycle.ts';
import { openWebSessionNames } from '../web-session-names.ts';
import { recoverAppLogResourcesAfterDaemonLock } from '../app-log-resource-recovery.ts';
import { createDaemonRecoveryPlatformScope } from '../platform-request-scope.ts';
import { createAppLogAdmissionLedger } from '../app-log-admission-ledger.ts';
const DAEMON_SESSION_LEASE_RELEASE_TIMEOUT_MS = 1_000;
const DAEMON_PNG_WORKER_TERMINATE_TIMEOUT_MS = 1_000;
const DAEMON_PROVIDER_RELEASE_DRAIN_TIMEOUT_MS = 2_000;
// An orphaned `simctl recordVideo` releases the host-wide recording lock only after it finishes
// finalizing on SIGINT; force-killing it sooner leaves every later recording failing with EBUSY
// (#2170). Bound the grace to the recorder purpose, so daemon startup stays under the client budget.
const DAEMON_RECORDING_REAP_TERM_TIMEOUT_MS = 5_000;
type WritableOutput = {
write: (chunk: string) => unknown;
};
async function settleDaemonTeardownStep(params: {
session: SessionState;
stderr: WritableOutput;
resource: 'app-log' | 'session' | 'lifecycle';
teardown: () => Promise<unknown>;
}): Promise<boolean> {
const { session, stderr, resource, teardown } = params;
try {
await teardown();
return true;
} catch (error) {
stderr.write(
`Daemon ${resource} teardown error (${session.name}): ${
error instanceof Error ? error.message : String(error)
}\n`,
);
return false;
}
}
/**
* Daemon-shutdown teardown of one session: bounded resource cleanup (budget
* from {@link resolveDaemonSessionTeardownTimeoutMs}, resolved BEFORE cleanup
* starts since finalizing the recording detaches `session.screenRecording`), then the
* repair-commit finalization and session deletion. Cleanup failures — including
* a recorder that could not be finalized — surface on stderr instead of being
* silently swallowed.
*/
export async function teardownDaemonSessionForShutdown(params: {
session: SessionState;
sessionStore: SessionStore;
stateDir?: string;
stderr: WritableOutput;
finalizeApplicationLifecycle?: (session: SessionState) => Promise<void>;
beforeDelete?: (session: SessionState) => Promise<void>;
afterSuccessfulTeardown?: (session: SessionState) => Promise<void>;
}): Promise<void> {
const {
session,
sessionStore,
stateDir,
stderr,
finalizeApplicationLifecycle,
beforeDelete,
afterSuccessfulTeardown,
} = params;
const sessionName = sessionStore.resolveStoredSessionName(session);
const timeoutMs = resolveDaemonSessionTeardownTimeoutMs(session);
// The ownership-fenced app-log side effect must settle while this process
// still owns the daemon lock. It is intentionally outside the generic
// teardown race so lock release and runtime shutdown cannot overtake it.
const appLogTeardownSucceeded = await settleDaemonTeardownStep({
session,
stderr,
resource: 'app-log',
teardown: async () => await stopSessionAppLog({ session, sessionName, sessionStore }),
});
const sessionAfterAppLog = sessionStore.get(sessionName) ?? session;
const teardown = (async () => {
const genericTeardownSucceeded = await settleDaemonTeardownStep({
session,
stderr,
resource: 'session',
teardown: async () =>
await teardownSessionResources({
appLog: 'already-settled',
session: sessionAfterAppLog,
sessionName,
sessionStore,
stateDir,
platformCleanup: platformResourceCleanup,
}),
});
const lifecycleTeardownSucceeded = finalizeApplicationLifecycle
? await settleDaemonTeardownStep({
session,
stderr,
resource: 'lifecycle',
teardown: async () => await finalizeApplicationLifecycle(sessionAfterAppLog),
})
: true;
return genericTeardownSucceeded && lifecycleTeardownSucceeded;
})();
const genericTeardownSucceeded = await Promise.race([
teardown,
sleep(timeoutMs).then(() => {
stderr.write(`Daemon session teardown timed out (${session.name}).\n`);
return false;
}),
]);
const teardownSucceeded = appLogTeardownSucceeded && genericTeardownSucceeded;
// ADR 0012 decision 6, R7 + commit semantics (C2/C5a): commit the healed
// `.ad` iff the repair transaction completed, else leave a bounded
// `REPAIR_SESSION_EXPIRED` tombstone for the reaped-before-finalize case.
sessionStore.finalizeRepairTeardown(session);
await beforeDelete?.(session);
if (teardownSucceeded) await afterSuccessfulTeardown?.(session);
sessionStore.delete(sessionName);
}
export type DaemonRuntimeOptions = {
env?: NodeJS.ProcessEnv;
stdout?: WritableOutput;
stderr?: WritableOutput;
exit?: (code: number) => void;
registerProcessHandlers?: boolean;
};
export type DaemonRuntimeController = {
httpPort?: number;
socketPort?: number;
shutdown: (options?: { exitCode?: number; cause?: unknown }) => Promise<void>;
token: string;
};
export async function flushDaemonStartupDiagnostics(
logPath: string,
diagnostics: readonly ResourceDiagnostic[],
): Promise<void> {
if (diagnostics.length === 0) return;
await withDiagnosticsScope(
{ command: 'daemon-startup', session: 'daemon', logPath, debug: false },
async () => {
for (const diagnostic of diagnostics) {
emitDiagnostic({
level: 'warn',
phase: diagnostic.phase,
data: { resourcePath: diagnostic.resourcePath, ...diagnostic.data },
});
}
flushDiagnosticsToSessionFile({ force: true });
},
);
}
/**
* Records one daemon-level event. These run outside any request, so there is no request scope and no
* resolved debug level to inherit; debug is forced on for the same reason the #2681 handoff forces it —
* the event is the point of the record and must not be dropped by a level that was never set for it.
*/
async function emitDaemonDiagnostic(
logPath: string,
phase: string,
data: Record<string, unknown>,
): Promise<void> {
await withDiagnosticsScope(
{ command: 'daemon', session: 'daemon', logPath, debug: true },
async () => {
emitDiagnostic({ level: 'warn', phase, data });
flushDiagnosticsToSessionFile({ force: true });
},
);
}
/**
* Removes this daemon's `daemon.json` at exit, and only while the record still names it: a shutdown
* that unlinked whatever file was present took the metadata of the daemon now serving clients (#3087).
* An absent record is not a decline worth logging, because client cleanup removes it routinely and a
* startup that failed before publication must not leave a `daemon.log` behind.
*/
async function removeOwnDaemonInfo(params: {
infoPath: string;
logPath: string;
owner: OwnerIdentity;
}): Promise<void> {
const removal = removeInfoOwnedBy(params.infoPath, params.owner);
if (removal.removed || removal.reason === 'absent') return;
await emitDaemonDiagnostic(params.logPath, 'daemon_info_removal_declined', {
infoPath: params.infoPath,
...removal,
});
}
async function noteDaemonMetadataLoss(params: {
infoPath: string;
logPath: string;
loss: DaemonMetadataLoss;
}): Promise<void> {
await emitDaemonDiagnostic(params.logPath, 'daemon_metadata_lost', {
infoPath: params.infoPath,
...params.loss,
});
}
/**
* Starts the watch that reports this daemon's registration being taken over, and returns the handle
* that stops it. It is armed only once this process has published its own record: before publication
* the file legitimately describes a predecessor, and losing that is not this daemon's event.
*/
function armDaemonMetadataLossWatch(
stateDir: string,
infoPath: string,
logPath: string,
owner: OwnerIdentity,
): () => void {
return watchDaemonMetadataLoss({
infoPath,
stateDir,
owner,
onLoss: (loss) => void noteDaemonMetadataLoss({ infoPath, logPath, loss }).catch(() => {}),
});
}
export async function startDaemonRuntime(
options: DaemonRuntimeOptions = {},
): Promise<DaemonRuntimeController | null> {
const env = options.env ?? process.env;
const stdout = options.stdout ?? process.stdout;
const stderr = options.stderr ?? process.stderr;
const exit = options.exit ?? ((code: number) => process.exit(code));
const daemonPaths = resolveDaemonPaths(env.AGENT_DEVICE_STATE_DIR);
const { baseDir, infoPath, lockPath, logPath, sessionsDir } = daemonPaths;
const daemonServerMode = resolveDaemonServerMode(env.AGENT_DEVICE_DAEMON_SERVER_MODE);
const retainArtifacts = isEnvTruthy(env.AGENT_DEVICE_RETAIN_ARTIFACTS);
// ADR 0029: a policy that cannot be read or validated stops startup; the daemon never runs
// with a weaker policy than its operator named.
let daemonPolicy: DaemonPolicy | undefined;
try {
daemonPolicy = loadDaemonPolicy(env);
} catch (error) {
stderr.write(`Daemon error: ${asAppError(error).message}\n`);
exit(1);
return null;
}
const sessionStore = new SessionStore(sessionsDir);
const ownedProcessRecords = createOwnedProcessRecordStore({
stateDir: baseDir,
sessionsDir,
resolveSessionDir: (sessionId) => sessionStore.resolveSessionDir(sessionId),
});
const appLogAdmissionLedger = createAppLogAdmissionLedger();
const audioProbeAdmissionLedger = createAudioProbeAdmissionLedger();
const perfCaptureAdmissionLedger = createPerfCaptureAdmissionLedger();
const hostDiagnostics = createHostDiagnostics();
const screenRecordingAdmissionLedger = createScreenRecordingAdmissionLedger();
const version = readVersion();
const token = crypto.randomBytes(24).toString('hex');
const daemonIdentity = readCurrentOwnerIdentity();
const daemonProcessStartTime = daemonIdentity.startTime ?? undefined;
const daemonCodeOrigin = resolveDaemonCodeOrigin();
const daemonCodeSignature = resolveDaemonCodeSignature();
const providerComposition = await createDaemonProviderRuntimeComposition(env);
const providerDeviceRuntimes = [...providerComposition.runtimes];
const deviceRuntimeGateway = createPlatformRuntimeGateway({
assertShutdownAllowed: daemonPolicy
? () => assertDaemonPolicyAllowsCapability(daemonPolicy, 'device-shutdown')
: undefined,
providerRuntimes: providerDeviceRuntimes,
providerModules: providerComposition.platformModules,
sessionsDir,
ownedProcesses: ownedProcessRecords,
resolveSessionArtifacts: (sessionId) => ({
outputPath: sessionStore.resolveAppLogPath(sessionId),
pidPath: sessionStore.resolveAppLogPidPath(sessionId),
}),
});
const applicationLifecycle = deviceRuntimeGateway.applicationLifecycle;
if (!applicationLifecycle) {
throw new AppError('COMMAND_FAILED', 'Platform lifecycle gateway is not configured.', {
reason: 'runtime-gateway-missing',
});
}
const providerRuntimeProviders = createProviderDeviceRuntimeRequestProviders(
providerDeviceRuntimes,
{ providerRuntimeRequiredIds: DEFAULT_PROVIDER_RUNTIME_REQUIRED_IDS },
);
installProviderDeviceAdmission({ isActive: (device) => isActiveProviderDevice(device) });
installInteractorResolution({ resolve: getInteractor });
const requestPlatformProviders = createRequestPlatformProviders({
providers: {
appleRunnerProvider: providerRuntimeProviders.appleRunnerProvider,
appleRunnerScreenRecordingTransport:
providerRuntimeProviders.appleRunnerScreenRecordingTransport,
},
defaultWebProvider: {
stateDir: baseDir,
openWebSessionNames: () => openWebSessionNames(sessionStore),
ownedProcessRecords,
},
});
const expiredProviderLeaseReleaser = createExpiredProviderLeaseReleaser({
leaseLifecycleProvider: providerRuntimeProviders.leaseLifecycleProvider,
providerRuntimeIds: providerRuntimeProviders.providerRuntimeIds,
recoverExpiredLease: providerRuntimeProviders.recoverExpiredLease,
stateDir: baseDir,
recoverableProviderIds: providerRuntimeProviders.recoverableProviderIds,
});
void expiredProviderLeaseReleaser.retryPending();
const leaseRegistry = new LeaseRegistry({
maxActiveSimulatorLeases: parseIntegerEnv(env.AGENT_DEVICE_MAX_SIMULATOR_LEASES),
defaultLeaseTtlMs: parseIntegerEnv(env.AGENT_DEVICE_LEASE_TTL_MS),
minLeaseTtlMs: parseIntegerEnv(env.AGENT_DEVICE_LEASE_MIN_TTL_MS),
maxLeaseTtlMs: parseIntegerEnv(env.AGENT_DEVICE_LEASE_MAX_TTL_MS),
onLeaseExpired: (lease) => {
void expiredProviderLeaseReleaser.release(lease);
},
});
const cloudArtifactProvider = providerRuntimeProviders.cloudArtifactProvider;
const providerAppCatalog = providerRuntimeProviders.providerAppCatalog;
const deviceInventoryGateways = createPlatformDeviceInventoryGateways(
providerRuntimeProviders.deviceInventorySource,
);
const dispatchRequest = createRequestHandler({
logPath,
token,
sessionStore,
leaseRegistry,
leaseLifecycleProvider: providerRuntimeProviders.leaseLifecycleProvider,
cloudArtifactProvider,
providerAppCatalog,
deviceInventoryGateways,
deviceRuntimeGateway,
appLogAdmissionLedger,
audioProbeAdmissionLedger,
perfCaptureAdmissionLedger,
hostDiagnostics,
screenRecordingAdmissionLedger,
requestPlatformProviders,
androidObservation,
platformResourceCleanup,
providerRuntimeIds: providerRuntimeProviders.providerRuntimeIds,
providerRuntimeRequiredIds: providerRuntimeProviders.providerRuntimeRequiredIds,
providerDeviceRuntimeScope: providerRuntimeProviders.providerDeviceRuntimeScope,
trackDownloadableArtifact,
daemonPolicy,
});
let stopMetadataLossWatch: () => void = () => {};
const emitFatalDiagnostic = async (error: unknown): Promise<void> => {
await withDiagnosticsScope(
{ command: 'daemon', session: 'daemon', logPath, debug: true },
async () => {
emitDiagnostic({
level: 'error',
phase: 'daemon_fatal',
data: {
error: error instanceof Error ? error.message : String(error),
},
});
flushDiagnosticsToSessionFile({ force: true });
},
);
};
const shutdownClaimLedger = createDaemonShutdownClaimLedger();
const teardownDaemonSession = async (session: SessionState): Promise<void> => {
try {
await teardownDaemonSessionForShutdown({
session,
sessionStore,
stderr,
finalizeApplicationLifecycle: async (sessionToFinalize) =>
await finalizeDaemonSessionApplicationLifecycle({
gateway: deviceRuntimeGateway,
scope: createDaemonRecoveryPlatformScope(),
session: sessionToFinalize,
stateDir: baseDir,
runtimeHints: runtimeHintValues(sessionStore.getRuntimeHints(sessionToFinalize.name)),
}),
beforeDelete: async (sessionToFinalize) => {
await finalizeDaemonSessionLease({
session: sessionToFinalize,
leaseRegistry,
expiredProviderLeaseReleaser,
timeoutMs: DAEMON_SESSION_LEASE_RELEASE_TIMEOUT_MS,
});
},
afterSuccessfulTeardown: shutdownClaimLedger.releaseClaim,
});
} finally {
shutdownClaimLedger.finalize(session);
}
};
const teardownDaemonSessions = async (): Promise<void> => {
const sessionsToStop = sessionStore.toArray();
await Promise.all(sessionsToStop.map(teardownDaemonSession));
};
// #2833: settles the resources of a session this daemon expires for idleness. Deliberately NOT
// `teardownDaemonSession`: that one exists for a daemon that is leaving, so it hands a healthy
// execution host to its successor, finalizes a remote lease, and deletes the session whether the
// bounded teardown finished or not. An idle expiry is the opposite situation — the daemon is
// staying alive, there is no successor, and a session whose resources would not release has to
// survive so the next pass can retry rather than leave a claim owned by a process that no longer
// knows what it holds. So: resources, then the platform finalization that stops the execution host
// and releases its lease, then the claim, cleared last, by the reaper.
const settleIdleExpiredSession = async (
session: SessionState,
sessionName: string,
): Promise<void> => {
await teardownSessionResources({
appLog: 'run',
session,
sessionName,
sessionStore,
stateDir: baseDir,
platformCleanup: platformResourceCleanup,
});
await finalizeDaemonSessionApplicationLifecycle({
gateway: deviceRuntimeGateway,
scope: createDaemonRecoveryPlatformScope(),
session,
stateDir: baseDir,
runtimeHints: runtimeHintValues(sessionStore.getRuntimeHints(sessionName)),
// The one caller that must say so: this daemon is staying alive, so there is no shutdown
// phase a healthy runner could be deferred to. Taking the ordinary-close path stops the
// runner and releases its lease instead of parking it until process exit.
daemonLeaving: false,
});
// ADR 0012 R7 binds this teardown too — the healed `.ad` is committed by
// `SessionStore.finalizeRepairTeardown` — but NOT from in here. That call publishes the script
// and stamps COMMITTED onto the record it is handed, which makes it part of ENDING the session
// rather than part of releasing its resources, and a settle that cannot confirm its claim gone
// holds the session back to retry. The reaper runs it once the expiry is committed to.
};
const sessionIdleExpiry = createSessionIdleExpiry({
sessionStore,
idleExpiryMs: resolveSessionIdleExpiryMs(env),
executionLocks: getLeaseRegistryExecutionLocks(leaseRegistry),
settleSession: settleIdleExpiredSession,
// The same bounded teardown budget every other session teardown gets. It bounds only how long a
// sweep waits, never the settle itself, so a stuck recorder cannot make a sweep hang but also
// cannot make an expiry give up on a device that does come free.
settleBudgetMs: (session) => resolveDaemonSessionTeardownTimeoutMs(session),
// A sweep is out-of-request work, so it has no request scope and `emitDiagnostic` would drop
// everything it reports — including the record of what was reclaimed and why a reclaim failed.
withinDiagnosticsScope: async (run) =>
await withDiagnosticsScope(
{ command: 'daemon', session: 'daemon', logPath, debug: true },
async () => {
try {
return await run();
} finally {
flushDiagnosticsToSessionFile({ force: true });
}
},
),
// An expiry can be the event that makes this daemon fully idle, and no request follows it to
// arm the process-level reap.
onSessionExpired: () => {
idleReap.noteActivity();
},
});
// Reaps this daemon process when it sits fully idle (no open sessions, no
// in-flight requests, no active recording) past AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS.
// `shutdown` is defined below but only invoked asynchronously by the timer,
// well after this closure captures it.
let inFlightRequestCount = 0;
const idleReap = createDaemonIdleReap({
sessionStore,
getInFlightRequestCount: () => inFlightRequestCount,
onIdleReap: () => {
void shutdown();
},
env,
});
const handleRequest: DaemonInvokeFn = async (req) => {
inFlightRequestCount++;
idleReap.cancel();
try {
return await dispatchRequest(req);
} finally {
inFlightRequestCount--;
idleReap.noteActivity();
// One hook covers every way a deadline changes: an `open` has added one, a `close` has removed
// one, and any other command has just re-stamped the session it ran on. Reading the session set
// here — after the request's own session stamp landed inside its execution lock — is what keeps
// the reaper's view of a session's deadline identical to the lock-guarded one.
sessionIdleExpiry.noteSessionsChanged();
}
};
const openDaemonServers = async (): Promise<{
servers: DaemonServer[];
socketPort?: number;
httpPort?: number;
}> => {
const servers: DaemonServer[] = [];
let socketPort: number | undefined;
let httpPort: number | undefined;
const startSocketServer = daemonServerMode !== 'http';
const startHttpServer = daemonServerMode !== 'socket';
if (startSocketServer) {
const socketServer = createSocketServer(handleRequest);
servers.push(socketServer);
socketPort = await listenNetServer(socketServer);
}
if (startHttpServer) {
const httpServer = await createDaemonHttpServer({
handleRequest,
leaseRegistry,
token,
retainArtifacts,
env,
// #1801: the same record `DaemonError.logPath` names, addressed by its
// locator so a remote caller can fetch what it cannot read by path.
resolveRequestDiagnosticsPath: (ref) =>
resolveSessionRequestLogPath(sessionStore.resolveSessionDir(ref.session), ref.requestId),
});
servers.push(httpServer);
httpPort = await listenHttpServer(httpServer);
}
return { servers, socketPort, httpPort };
};
const publishDaemonInfo = (socketPort: number | undefined, httpPort: number | undefined) => {
writeInfo(baseDir, infoPath, logPath, {
socketPort,
httpPort,
token,
version,
codeOrigin: daemonCodeOrigin,
codeSignature: daemonCodeSignature,
processStartTime: daemonProcessStartTime,
policyDigest: daemonPolicy?.digest,
});
if (socketPort) stdout.write(`AGENT_DEVICE_DAEMON_PORT=${socketPort}\n`);
if (httpPort) stdout.write(`AGENT_DEVICE_DAEMON_HTTP_PORT=${httpPort}\n`);
};
const closeServersBestEffort = (servers: DaemonServer[]): void => {
for (const server of servers) {
try {
server.close(() => {});
} catch {}
}
};
const lockData = {
pid: process.pid,
version,
startedAt: Date.now(),
processStartTime: daemonProcessStartTime,
};
if (!acquireDaemonLock(baseDir, lockPath, lockData)) {
await Promise.allSettled(
providerDeviceRuntimes.map(async (runtime) => await runtime.shutdown()),
);
stderr.write('Daemon lock is held by another process; exiting.\n');
exit(0);
return null;
}
clearDaemonShutdownReport(baseDir);
let servers: DaemonServer[] = [];
let socketPort: number | undefined;
let httpPort: number | undefined;
const startupDiagnostics: ResourceDiagnostic[] = [];
try {
await platformDaemonLifecycleOwners.configureForDaemonLock({
stateDir: baseDir,
hasDeviceClaimAuthority: processOwnsActiveDeviceClaim,
onDiagnostic: (diagnostic) => startupDiagnostics.push(diagnostic),
});
const legacyMarkerRecovery =
await platformDaemonLifecycleOwners.recoverLegacyAppLogMarkers(sessionsDir);
appLogAdmissionLedger.retainLegacyMarkers(legacyMarkerRecovery.retained);
for (const markerPath of legacyMarkerRecovery.recovered) {
startupDiagnostics.push({
phase: 'app_log_legacy_marker_recovered',
resourcePath: markerPath,
data: {},
});
}
for (const retained of legacyMarkerRecovery.retained) {
startupDiagnostics.push({
phase: 'app_log_legacy_marker_retained',
resourcePath: retained.markerPath,
data: {
reason: retained.reason,
...(retained.message === undefined ? {} : { message: retained.message }),
},
});
}
await recoverAppLogResourcesAfterDaemonLock({
sessionsDir,
gateway: deviceRuntimeGateway,
scope: createDaemonRecoveryPlatformScope(),
onDiagnostic: (diagnostic) => startupDiagnostics.push(diagnostic),
});
await reapOwnedProcessRecordsAtStartup(ownedProcessRecords, {
openWebSessionNames: openWebSessionNames(sessionStore),
purposes: ['simctl-screen-recording'],
termTimeoutMs: DAEMON_RECORDING_REAP_TERM_TIMEOUT_MS,
});
await cleanupWebBrowserOrphansForDaemonStartup({
stateDir: baseDir,
sessionStore,
ownedProcessRecords,
});
// Marker-gated lifecycle recovery owns test-IME orphan repair. Its implementation remains
// lazy until the marker exists, so a normal daemon startup does not load or probe adb.
void applicationLifecycle.recoverStartupResources({ stateDir: baseDir }).catch((error) => {
emitDiagnostic({
level: 'warn',
phase: 'daemon_lifecycle_startup_recovery_failed',
data: { error: error instanceof Error ? error.message : String(error) },
});
});
const opened = await openDaemonServers();
servers = opened.servers;
socketPort = opened.socketPort;
httpPort = opened.httpPort;
publishDaemonInfo(socketPort, httpPort);
stopMetadataLossWatch = armDaemonMetadataLossWatch(baseDir, infoPath, logPath, daemonIdentity);
await flushDaemonStartupDiagnostics(logPath, startupDiagnostics);
// After publication: publishDaemonInfo truncates daemon.log, so anything
// written before it is lost — including reconciliation diagnostics.
await reconcileDeviceClaimsForDaemonStartup(
logPath,
createOwnerScopedDeviceClaimReconciler(createDaemonRecoveryPlatformScope()),
baseDir,
);
// Arms the initial idle-reap timer: a daemon that starts and never
// receives a request must still be able to reap itself.
idleReap.noteActivity();
// The #2833 deadline needs no equivalent arm: the store is empty until a request puts a session
// in it, and that request's own completion re-arms the reaper.
} catch (error) {
const appErr = asAppError(error);
stderr.write(`Daemon error: ${appErr.message}\n`);
closeServersBestEffort(servers);
stopMetadataLossWatch();
await removeOwnDaemonInfo({ infoPath, logPath, owner: daemonIdentity });
await Promise.allSettled(
providerDeviceRuntimes.map(async (runtime) => await runtime.shutdown()),
);
releaseDaemonLock(lockPath);
await platformDaemonLifecycleOwners.clearDaemonLockConfiguration();
exit(1);
return null;
}
// Spawn the PNG worker ahead of the first screenshot request so its
// cold-start cost is not paid on a user-visible call. Best effort: when it
// cannot start, PNG processing falls back to the in-process sync path.
prewarmPngWorker();
let shuttingDown = false;
const shutdown = async (shutdownOptions: { exitCode?: number; cause?: unknown } = {}) => {
idleReap.cancel();
sessionIdleExpiry.cancel();
if (shuttingDown) return;
shuttingDown = true;
stopMetadataLossWatch();
if (shutdownOptions.cause) {
await emitFatalDiagnostic(shutdownOptions.cause);
}
await closeDaemonServers(servers);
// Hand healthy runners off before durable session teardown. The lifecycle gateway later
// terminates only still-owned generations once all resources have finalized.
//
// The scope is what makes this step observable: a SIGTERM shutdown has no request, and therefore
// no diagnostics scope, so `emitDiagnostic` would drop every detach reason. Daemon debug level is
// forced on here because the declines are the point of the record — a handoff that silently
// skipped is indistinguishable from a rebuild (#2681).
try {
await withDiagnosticsScope(
{ command: 'daemon', session: 'daemon', logPath, debug: true },
async () => {
await applicationLifecycle.detachForDaemonShutdown();
flushDiagnosticsToSessionFile({ force: true });
},
);
} catch {}
expiredProviderLeaseReleaser.beginShutdown();
await teardownDaemonSessions();
try {
await platformDaemonLifecycleOwners.resetAndroidSnapshotHelper();
} catch (error) {
emitDiagnostic({
level: 'warn',
phase: 'daemon_shutdown_android_snapshot_helper_cleanup_failed',
data: { error: error instanceof Error ? error.message : String(error) },
});
}
const providerReleaseDrain = await expiredProviderLeaseReleaser.drain(
DAEMON_PROVIDER_RELEASE_DRAIN_TIMEOUT_MS,
);
writeDaemonShutdownReport(baseDir, {
providerReleases: providerReleaseDrain,
claims: shutdownClaimLedger.claims,
});
emitDiagnostic({
level: providerReleaseDrain.pending.length === 0 ? 'info' : 'warn',
phase: 'daemon_shutdown_provider_release_drain',
data: {
releasedLeaseIds: providerReleaseDrain.released.map((lease) => lease.leaseId),
pendingLeaseIds: providerReleaseDrain.pending.map((lease) => lease.leaseId),
releasedDeviceKeys: shutdownClaimLedger.claims.released.map((claim) => claim.deviceKey),
orphanedDeviceKeys: shutdownClaimLedger.claims.orphaned.map((claim) => claim.deviceKey),
},
});
expiredProviderLeaseReleaser.shutdown();
await deviceRuntimeGateway.shutdown();
await Promise.allSettled(
providerDeviceRuntimes.map(async (runtime) => await runtime.shutdown()),
);
await applicationLifecycle.finalizeDaemonShutdown();
// Best effort: stop the PNG worker so an in-flight job cannot delay exit.
await Promise.race([
terminatePngWorker().catch(() => {}),
sleep(DAEMON_PNG_WORKER_TERMINATE_TIMEOUT_MS),
]);
await removeOwnDaemonInfo({ infoPath, logPath, owner: daemonIdentity });
releaseDaemonLock(lockPath);
await platformDaemonLifecycleOwners.clearDaemonLockConfiguration();
exit(shutdownOptions.exitCode ?? 0);
};
if (options.registerProcessHandlers !== false) {
process.on('SIGINT', () => {
void shutdown();
});
process.on('SIGTERM', () => {
void shutdown();
});
process.on('SIGHUP', () => {
void shutdown();
});
process.on('uncaughtException', (err) => {
const appErr = err instanceof AppError ? err : asAppError(err);
stderr.write(`Daemon error: ${appErr.message}\n`);
void shutdown({ exitCode: 1, cause: err });
});
process.on('unhandledRejection', (reason) => {
const err = reason instanceof Error ? reason : new Error(String(reason));
const appErr = err instanceof AppError ? err : asAppError(err);
stderr.write(`Daemon error: ${appErr.message}\n`);
void shutdown({ exitCode: 1, cause: err });
});
}
return {
httpPort,
shutdown,
socketPort,
token,
};
}
async function reconcileDeviceClaimsForDaemonStartup(
logPath: string,
reconcile: DeviceClaimReconciler,
stateDir: string,
): Promise<void> {
// Startup runs outside any diagnostics scope, where emitDiagnostic is a no-op,
// so reconciliation has to open one of its own for its events to be recorded.
await withDiagnosticsScope(
{ command: 'daemon', session: 'daemon', logPath, debug: true },
async () => {
try {
const summary = await reconcileOrphanedDeviceClaims(reconcile, stateDir);
if (summary.examined > 0) {
emitDiagnostic({ phase: 'device_claim_reconcile', data: summary });
flushDiagnosticsToSessionFile({ force: true });
}
} catch (error) {
emitDiagnostic({
level: 'warn',
phase: 'device_claim_reconcile_failed',
data: { error: error instanceof Error ? error.message : String(error) },
});
flushDiagnosticsToSessionFile({ force: true });
}
},
);
}
export async function cleanupWebBrowserOrphansForDaemonStartup(params: {
stateDir: string;
sessionStore: SessionStore;
ownedProcessRecords?: OwnedProcessRecordStore;
}): Promise<void> {
try {
await platformDaemonLifecycleOwners.cleanupManagedWebOrphans({
stateDir: params.stateDir,
openWebSessionNames: openWebSessionNames(params.sessionStore),
...(params.ownedProcessRecords === undefined
? {}
: { ownedProcessRecords: params.ownedProcessRecords }),
});
} catch (error) {
emitDiagnostic({
level: 'warn',
phase: 'web_agent_browser_orphan_cleanup_failed',
data: { error: error instanceof Error ? error.message : String(error) },
});
}
}