Skip to content

Commit d4df7a0

Browse files
committed
refactor(daemon): move the runtime dependency construction to the process root
startDaemonRuntime now receives its composed dependencies instead of building them: provider runtimes, the platform gateway and inventory gateways, request platform providers, host diagnostics, credential fingerprinting, the platform lifecycle owners, the platform-services and claim-recovery compositions, and the command-surface factory all move to src/daemon-composition.ts, which src/daemon.ts composes and injects. The operational server keeps startup sequencing, listeners, shutdown, the metadata watch, idle reap, and request-handler creation, with the same order on both paths. DaemonProviderCredentials moves to @agent-device/daemon-contracts/provider-credentials, the #2559 shared home beside daemon-policy-file; the fingerprint implementation stays in the root. Tests boot the runtime through one shared fixture. No production file under src/daemon/ now reads a non-package src/ module except the direct-ios-selector edge owned by #2273/#2274.
1 parent 7e5ed4d commit d4df7a0

24 files changed

Lines changed: 591 additions & 355 deletions

‎packages/daemon-contracts/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@
4747
"types": "./src/daemon-shutdown-report.ts",
4848
"default": "./src/daemon-shutdown-report.ts"
4949
},
50+
"./provider-credentials": {
51+
"types": "./src/provider-credentials.ts",
52+
"default": "./src/provider-credentials.ts"
53+
},
5054
"./request-progress-protocol": {
5155
"types": "./src/request-progress-protocol.ts",
5256
"default": "./src/request-progress-protocol.ts"
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* The provider credentials a daemon started with, and the state dir that names that daemon.
3+
*
4+
* A `lease_allocate` request carries the caller's own fingerprint so a lease can be fenced to one
5+
* credential set (#2559): the daemon compares the request's value against the fingerprint it
6+
* computed from its own startup environment, and both sides read this one declaration — the
7+
* daemon's implementation stays in the process root (`src/provider-credential-fingerprint.ts`),
8+
* and the wire-comparing client reads only this vocabulary.
9+
*/
10+
export type DaemonProviderCredentials = Readonly<{
11+
/** Undefined when the daemon's environment holds none of the credentials such a lease reads. */
12+
fingerprint(provider: string, leaseBackend?: string): string | undefined;
13+
stateDir: string;
14+
}>;

src/daemon/server/daemon-runtime-web-cleanup.test.ts renamed to src/__tests__/daemon-composition-web-cleanup.test.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ import assert from 'node:assert/strict';
22
import fs from 'node:fs';
33
import path from 'node:path';
44
import { beforeEach, test, vi } from 'vitest';
5-
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
6-
import { installFakeManagedAgentBrowser } from '../../__tests__/test-utils/web-managed-agent-browser.ts';
5+
import { mkdtempForTestSync } from './test-utils/tmp-dir.ts';
6+
import { installFakeManagedAgentBrowser } from './test-utils/web-managed-agent-browser.ts';
77

88
const { cleanupManagedAgentBrowserOrphansMock } = vi.hoisted(() => ({
99
cleanupManagedAgentBrowserOrphansMock: vi.fn(),
@@ -17,9 +17,10 @@ vi.mock('@agent-device/platform-web', async (importOriginal) => {
1717
};
1818
});
1919

20-
import { WEB_DESKTOP_DEVICE } from '../../__tests__/test-utils/device-fixtures.ts';
21-
import { SessionStore } from '../session-store.ts';
22-
import { cleanupWebBrowserOrphansForDaemonStartup } from './daemon-runtime.ts';
20+
import { WEB_DESKTOP_DEVICE } from './test-utils/device-fixtures.ts';
21+
import { SessionStore } from '../daemon/session-store.ts';
22+
import { openWebSessionNames } from '../daemon/web-session-names.ts';
23+
import { cleanupWebBrowserOrphansForDaemonStartup } from '../daemon-composition.ts';
2324

2425
const mockCleanupManagedAgentBrowserOrphans = vi.mocked(cleanupManagedAgentBrowserOrphansMock);
2526

@@ -39,7 +40,10 @@ test('daemon-startup web cleanup passes open web sessions to the reaper', async
3940
actions: [],
4041
});
4142

42-
await cleanupWebBrowserOrphansForDaemonStartup({ stateDir, sessionStore });
43+
await cleanupWebBrowserOrphansForDaemonStartup({
44+
stateDir,
45+
openWebSessionNames: openWebSessionNames(sessionStore),
46+
});
4347

4448
assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls.length, 1);
4549
assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls[0]?.[1], 'daemon-startup');
@@ -56,7 +60,10 @@ test('daemon-startup web cleanup does not run when the managed backend is absent
5660
try {
5761
const sessionStore = new SessionStore(path.join(stateDir, 'sessions'));
5862

59-
await cleanupWebBrowserOrphansForDaemonStartup({ stateDir, sessionStore });
63+
await cleanupWebBrowserOrphansForDaemonStartup({
64+
stateDir,
65+
openWebSessionNames: openWebSessionNames(sessionStore),
66+
});
6067

6168
assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls.length, 0);
6269
} finally {

‎src/__tests__/daemon-entrypoint.test.ts‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import http from 'node:http';
66
import path from 'node:path';
77
import { test } from 'vitest';
88
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
9-
import { startDaemonRuntime } from '../daemon/server/daemon-runtime.ts';
9+
import { startDaemonRuntimeFixture } from '../daemon/__tests__/daemon-runtime-fixture.ts';
10+
import type { DaemonRuntimeController } from '../daemon/server/daemon-runtime.ts';
1011
import {
1112
cleanupDownloadableArtifact,
1213
trackDownloadableArtifact,
@@ -24,7 +25,6 @@ import { screenRecordingDurableResource } from '@agent-device/capture-kit/screen
2425

2526
import { closeLoopbackServer, listenOnLoopback, waitForHttpOk } from './test-utils/loopback.ts';
2627
import { mkdtempForTestSync } from './test-utils/tmp-dir.ts';
27-
import { testCreateCommandSurface } from '../daemon/__tests__/command-surface-fixture.ts';
2828

2929
type DaemonInfoFile = {
3030
httpPort?: number;
@@ -87,8 +87,7 @@ test('daemon runtime starts HTTP transport in-process and shuts down cleanly', a
8787
let exitCode: number | undefined;
8888

8989
try {
90-
const runtime = await startDaemonRuntime({
91-
createCommandSurface: testCreateCommandSurface,
90+
const runtime = await startDaemonRuntimeFixture({
9291
env: {
9392
...process.env,
9493
AGENT_DEVICE_STATE_DIR: stateDir,
@@ -147,8 +146,7 @@ test('daemon runtime publishes dual transport metadata', async () => {
147146
let exitCode: number | undefined;
148147

149148
try {
150-
const runtime = await startDaemonRuntime({
151-
createCommandSurface: testCreateCommandSurface,
149+
const runtime = await startDaemonRuntimeFixture({
152150
env: {
153151
...process.env,
154152
AGENT_DEVICE_STATE_DIR: stateDir,
@@ -195,11 +193,10 @@ test('daemon rejects unowned cloud artifacts over RPC', async () => {
195193
);
196194
});
197195
const providerPort = await listenOnLoopback(providerServer);
198-
let runtime: Awaited<ReturnType<typeof startDaemonRuntime>> = null;
196+
let runtime: DaemonRuntimeController | null = null;
199197

200198
try {
201-
runtime = await startDaemonRuntime({
202-
createCommandSurface: testCreateCommandSurface,
199+
runtime = await startDaemonRuntimeFixture({
203200
env: {
204201
...process.env,
205202
AGENT_DEVICE_STATE_DIR: stateDir,
@@ -329,8 +326,7 @@ test('daemon runtime records startup device-claim reconciliation in daemon.log',
329326
}),
330327
);
331328

332-
const runtime = await startDaemonRuntime({
333-
createCommandSurface: testCreateCommandSurface,
329+
const runtime = await startDaemonRuntimeFixture({
334330
env: {
335331
...process.env,
336332
AGENT_DEVICE_STATE_DIR: stateDir,
@@ -399,7 +395,7 @@ test('startup sweep settles a foreign dead owner without touching a live same-na
399395
command: readProcessCommand(orphanPid) ?? '',
400396
};
401397
assert.ok(orphanMarker.startTime.length > 0 && orphanMarker.command.length > 0);
402-
let runtime: Awaited<ReturnType<typeof startDaemonRuntime>> = null;
398+
let runtime: DaemonRuntimeController | null = null;
403399

404400
try {
405401
const foreignSessionDir = path.join(resolveDaemonPaths(foreignStateDir).sessionsDir, 'shared');
@@ -455,8 +451,7 @@ test('startup sweep settles a foreign dead owner without touching a live same-na
455451
}),
456452
);
457453

458-
runtime = await startDaemonRuntime({
459-
createCommandSurface: testCreateCommandSurface,
454+
runtime = await startDaemonRuntimeFixture({
460455
env: {
461456
...process.env,
462457
AGENT_DEVICE_STATE_DIR: daemonStateDir,

‎src/daemon-composition.ts‎

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
// The daemon runtime's dependency construction, extracted from `src/daemon/server/daemon-runtime.ts`
2+
// so the operational server owns sequencing and this module owns naming runtimes (ADR 0019).
3+
// Everything here that names a platform runtime, a provider runtime, an interactor, host
4+
// diagnostics, credential fingerprinting, resource cleanup, the platform lifecycle owners, the
5+
// platform-services composition, or the claim-recovery gateway lives in the process root;
6+
// `src/daemon.ts` calls `createDaemonRuntimeDeps` and hands the result to `startDaemonRuntime`.
7+
//
8+
// The static import set is exactly the family `daemon-runtime.ts` already evaluated eagerly, so
9+
// the daemon entry's eager closure does not grow; the platform-services and claim-recovery
10+
// compositions stay behind function-scoped `await import`, and the command surface loads on first
11+
// request use. Nothing here value-imports `src/daemon/`: the daemon's session data enters through
12+
// plain callbacks, so the platform-runtime zone keeps its value-free direction toward the daemon.
13+
14+
import {
15+
createProviderDeviceRuntimeRequestProviders,
16+
isActiveProviderDevice,
17+
} from './provider-device-runtime.ts';
18+
import {
19+
createDaemonProviderRuntimeComposition,
20+
DEFAULT_PROVIDER_RUNTIME_REQUIRED_IDS,
21+
} from './provider-device-runtimes.ts';
22+
import { readDaemonProviderCredentials } from './provider-credential-fingerprint.ts';
23+
import { getInteractor } from './core/interactors.ts';
24+
import {
25+
androidObservation,
26+
createPlatformRuntimeGateway,
27+
createPlatformDeviceInventoryGateways,
28+
createRequestPlatformProviders,
29+
} from './platform-runtime.ts';
30+
import { createHostDiagnostics } from './platform-runtime-host-diagnostics.ts';
31+
import { platformResourceCleanup } from './platform-runtime-resource-cleanup.ts';
32+
import { platformDaemonLifecycleOwners } from './platform-runtime-daemon-lifecycle.ts';
33+
import {
34+
createOwnedProcessRecordStore,
35+
type OwnedProcessRecordStore,
36+
} from '@agent-device/host-kit/process';
37+
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
38+
import { withDaemonDiagnosticsScope } from '@agent-device/daemon-contracts/daemon-diagnostics-scope';
39+
import type { AppLogSessionArtifacts } from '@agent-device/contracts/app-log-runtime';
40+
import type { AgentDeviceRuntimeConfig } from '@agent-device/contracts/runtime-contract';
41+
import type { DeviceInfo } from '@agent-device/kernel/device';
42+
import type { DaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file';
43+
import type { DaemonRuntimeDeps } from './daemon/server/daemon-runtime.ts';
44+
45+
/**
46+
* Best-effort startup cleanup of managed-agent-browser orphans left by a previous daemon. It runs
47+
* only after this process holds the daemon lock, and it never fails startup: a cleanup the host
48+
* refuses is a diagnostic, not a reason to keep the next daemon from serving.
49+
*/
50+
export async function cleanupWebBrowserOrphansForDaemonStartup(params: {
51+
stateDir: string;
52+
openWebSessionNames: readonly string[];
53+
ownedProcessRecords?: OwnedProcessRecordStore;
54+
}): Promise<void> {
55+
try {
56+
await platformDaemonLifecycleOwners.cleanupManagedWebOrphans(params);
57+
} catch (error) {
58+
emitDiagnostic({
59+
level: 'warn',
60+
phase: 'web_agent_browser_orphan_cleanup_failed',
61+
data: { error: error instanceof Error ? error.message : String(error) },
62+
});
63+
}
64+
}
65+
66+
/**
67+
* Builds every capability the daemon runtime cannot construct for itself, in the order the
68+
* runtime used to build them. All members are required: a daemon process either receives this
69+
* composition or cannot start, and a test passes the same shared fixture (ADR 0019). The
70+
* session-scoped callbacks are the daemon's own data seen as questions — recording artifact
71+
* paths, session directories, and which web sessions are open — so no daemon value crosses here.
72+
*/
73+
export async function createDaemonRuntimeDeps(
74+
input: Readonly<{
75+
env: NodeJS.ProcessEnv;
76+
/** Resolved daemon paths' state-dir root; the daemon owns path resolution and passes it down. */
77+
baseDir: string;
78+
sessionsDir: string;
79+
/** ADR 0029: the operator's policy, loaded by the executable so a bad policy stops startup. */
80+
daemonPolicy: DaemonPolicy | undefined;
81+
/** Refuses the shutdown capability the operator denied; undefined when no policy names it. */
82+
assertShutdownAllowed: (() => void) | undefined;
83+
resolveSessionDir(sessionId: string): string;
84+
resolveSessionArtifacts(sessionId: string): AppLogSessionArtifacts;
85+
openWebSessionNames(): readonly string[];
86+
}>,
87+
): Promise<DaemonRuntimeDeps> {
88+
const {
89+
env,
90+
baseDir,
91+
sessionsDir,
92+
daemonPolicy,
93+
assertShutdownAllowed,
94+
resolveSessionDir,
95+
resolveSessionArtifacts,
96+
openWebSessionNames,
97+
} = input;
98+
const ownedProcessRecords = createOwnedProcessRecordStore({
99+
stateDir: baseDir,
100+
sessionsDir,
101+
resolveSessionDir,
102+
});
103+
const hostDiagnostics = createHostDiagnostics();
104+
const providerComposition = await createDaemonProviderRuntimeComposition(env);
105+
const providerDeviceRuntimes = [...providerComposition.runtimes];
106+
const deviceRuntimeGateway = createPlatformRuntimeGateway({
107+
assertShutdownAllowed,
108+
providerRuntimes: providerDeviceRuntimes,
109+
providerModules: providerComposition.platformModules,
110+
sessionsDir,
111+
ownedProcesses: ownedProcessRecords,
112+
resolveSessionArtifacts,
113+
});
114+
const providerRuntimeProviders = createProviderDeviceRuntimeRequestProviders(
115+
providerDeviceRuntimes,
116+
{ providerRuntimeRequiredIds: DEFAULT_PROVIDER_RUNTIME_REQUIRED_IDS },
117+
);
118+
const requestPlatformProviders = createRequestPlatformProviders({
119+
providers: {
120+
appleRunnerProvider: providerRuntimeProviders.appleRunnerProvider,
121+
appleRunnerScreenRecordingTransport:
122+
providerRuntimeProviders.appleRunnerScreenRecordingTransport,
123+
},
124+
defaultWebProvider: {
125+
stateDir: baseDir,
126+
openWebSessionNames,
127+
ownedProcessRecords,
128+
},
129+
});
130+
const deviceInventoryGateways = createPlatformDeviceInventoryGateways(
131+
providerRuntimeProviders.deviceInventorySource,
132+
);
133+
// Root composition of the platform-services port and the owner-scoped claim-recovery gateway.
134+
// platform-runtime.ts is already static in this module, so the deferred imports keep these thin
135+
// composition modules (and the readiness/open-target adapters only the services module pulls)
136+
// off `src/daemon.ts`'s eager closure; what each adapter itself loads stays as lazy as it was.
137+
const { createDaemonPlatformServices } = await import('./platform-runtime-daemon-services.ts');
138+
const { createClaimRecoveryGateway } = await import('./platform-runtime-claim-recovery.ts');
139+
140+
return Object.freeze({
141+
daemonPolicy,
142+
ownedProcessRecords,
143+
hostDiagnostics,
144+
ownerLifecycle: platformDaemonLifecycleOwners,
145+
providerDeviceRuntimes,
146+
interactorResolution: Object.freeze({ resolve: getInteractor }),
147+
providerDeviceAdmission: Object.freeze({
148+
isActive: (device: DeviceInfo) => isActiveProviderDevice(device),
149+
}),
150+
cleanupManagedWebOrphans: cleanupWebBrowserOrphansForDaemonStartup,
151+
notifySkippedProviderRuntimes: async (logPath: string) => {
152+
// Outside any request, so debug is forced on for the same reason the #2681 handoff forces
153+
// it — the event is the point of the record and must not be dropped by a level that was
154+
// never set for it.
155+
for (const { provider, error } of providerComposition.skipped ?? []) {
156+
await withDaemonDiagnosticsScope({ logPath }, () => {
157+
emitDiagnostic({
158+
level: 'warn',
159+
phase: 'provider_runtime_skipped',
160+
data: {
161+
provider,
162+
code: error.code,
163+
message: error.message,
164+
hint: error.details?.hint,
165+
},
166+
});
167+
});
168+
}
169+
},
170+
providerRuntimeProviders: Object.freeze({
171+
leaseLifecycleProvider: providerRuntimeProviders.leaseLifecycleProvider,
172+
providerRuntimeIds: providerRuntimeProviders.providerRuntimeIds,
173+
recoverExpiredLease: providerRuntimeProviders.recoverExpiredLease,
174+
recoverableProviderIds: providerRuntimeProviders.recoverableProviderIds,
175+
}),
176+
requestRouter: Object.freeze({
177+
requestPlatformProviders,
178+
deviceInventoryGateways,
179+
deviceRuntimeGateway,
180+
platformServices: createDaemonPlatformServices(),
181+
claimRecoveryGateway: createClaimRecoveryGateway,
182+
androidObservation,
183+
platformResourceCleanup,
184+
providerCredentials: readDaemonProviderCredentials(env, baseDir),
185+
createCommandSurface: async (config: AgentDeviceRuntimeConfig) =>
186+
(
187+
await import('./command-runtime/runtime-command-surface.ts')
188+
).createCommandSurfaceAgentDevice(config),
189+
cloudArtifactProvider: providerRuntimeProviders.cloudArtifactProvider,
190+
providerAppCatalog: providerRuntimeProviders.providerAppCatalog,
191+
leaseLifecycleProvider: providerRuntimeProviders.leaseLifecycleProvider,
192+
providerRuntimeIds: providerRuntimeProviders.providerRuntimeIds,
193+
providerRuntimeRequiredIds: providerRuntimeProviders.providerRuntimeRequiredIds,
194+
providerDeviceRuntimeScope: providerRuntimeProviders.providerDeviceRuntimeScope,
195+
}),
196+
});
197+
}

‎src/daemon.ts‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,36 @@
1-
import { startDaemonRuntime } from './daemon/server/daemon-runtime.ts';
21
import { asAppError } from '@agent-device/kernel/errors';
2+
import { SessionStore } from './daemon/session-store.ts';
3+
import { assertDaemonPolicyAllowsCapability } from './daemon/daemon-policy.ts';
4+
import { startDaemonRuntime } from './daemon/server/daemon-runtime.ts';
5+
import { loadDaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file';
6+
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
7+
import { openWebSessionNames } from './daemon/web-session-names.ts';
8+
import { createDaemonRuntimeDeps } from './daemon-composition.ts';
39

4-
void startDaemonRuntime({
5-
// The composition root's surface stays behind `await import`, loaded on first request use.
6-
createCommandSurface: async (config) =>
7-
(await import('./command-runtime/runtime-command-surface.ts')).createCommandSurfaceAgentDevice(
8-
config,
9-
),
10-
}).catch((error) => {
10+
void (async () => {
11+
const env = process.env;
12+
const daemonPaths = resolveDaemonPaths(env.AGENT_DEVICE_STATE_DIR);
13+
// ADR 0029: a policy that cannot be read or validated stops startup; the daemon never runs
14+
// with a weaker policy than its operator named.
15+
const daemonPolicy = loadDaemonPolicy(env);
16+
const sessionStore = new SessionStore(daemonPaths.sessionsDir);
17+
const deps = await createDaemonRuntimeDeps({
18+
env,
19+
baseDir: daemonPaths.baseDir,
20+
sessionsDir: daemonPaths.sessionsDir,
21+
daemonPolicy,
22+
assertShutdownAllowed: daemonPolicy
23+
? () => assertDaemonPolicyAllowsCapability(daemonPolicy, 'device-shutdown')
24+
: undefined,
25+
resolveSessionDir: (sessionId) => sessionStore.resolveSessionDir(sessionId),
26+
resolveSessionArtifacts: (sessionId) => ({
27+
outputPath: sessionStore.resolveAppLogPath(sessionId),
28+
pidPath: sessionStore.resolveAppLogPidPath(sessionId),
29+
}),
30+
openWebSessionNames: () => openWebSessionNames(sessionStore),
31+
});
32+
await startDaemonRuntime({ env, sessionStore, deps });
33+
})().catch((error) => {
1134
const appErr = asAppError(error);
1235
process.stderr.write(`Daemon error: ${appErr.message}\n`);
1336
process.exit(1);

0 commit comments

Comments
 (0)