Skip to content

Commit b425b03

Browse files
thymikeeclaude
andauthored
feat(sdk): start an embedded runtime from the main entry (#3843)
* feat(client): pin a client to one daemon instance Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(host): expose an embedder-owned runtime and packed consumer coverage Part of #3747. Refs #3757. Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(gates): declare the public host process boundary Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(host): cover startup rollback and instance replacement races Use distinct host working directories and exercise disposal through the packed consumer. Keep the subprocess source with its integration test. Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(gates): verify host entry process capture is permitted Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(host): import the packed consumer plugin as a standalone module Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(ios): wait for the automation sheet control before clicking Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(sdk): expose lazy in-process host from main entry Route pinned clients through attach compatibility before checking their instance pin. Publish the embedded runtime's package code identity rather than the host application's entry identity. Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(gates): name main-entry host in process capture policy Keep src/host.ts as the actual capture boundary behind the SDK's lazy factory. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(host): preserve refusal and code identity metadata Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent b51e7ea commit b425b03

29 files changed

Lines changed: 1368 additions & 49 deletions

‎.changeset/host-entry.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'agent-device': patch
3+
---
4+
5+
Add `startAgentDevice()` to the main `agent-device` entry to own a daemon inside a Node.js process. Its client configuration pins attaching processes to that runtime, and `close()` returns the shutdown report.

‎.fallowrc.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
"examples/sdk/contracts-result.ts",
4242
"examples/sdk/batch-orchestration.ts",
4343
"examples/sdk/ai-sdk-tools.ts",
44+
"examples/sdk/host-runtime.ts",
4445
"test/integration/**/*.test.ts",
4546
"website/docs/404.mdx",
4647
"website/rspress.config.ts"

‎docs/adr/0034-provider-plugin-registry.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Status: accepted. Umbrella #3747; contract and registry #3755.
77
- One contract. A provider plugin is a factory that returns `{ apiVersion: 2, provider, credentials,
88
connection?, setup(host) }`. `setup` returns `{ runtime, platformModule, dispose? }` or
99
`{ webDriver, dispose? }`. A `{ webDriver }` result stays a data descriptor the host interprets.
10-
- One registry. Sources compose in the order built-in, store, embedder; the embedder slot arrives with #3757. Built-in providers use the
10+
- One registry. Composition selects built-in, store, or embedder sources. Built-in providers use the
1111
same shape as an installed plugin, and one function validates what every factory returns.
1212
- Plugins import only types from agent-device. The type-only contract is `agent-device/plugins`;
1313
there is no runtime helper, and the contract does not depend on a plugin's module URL.
@@ -58,10 +58,11 @@ had to fake the store to load a plugin from its own dependencies (#3747).
5858

5959
## Daemon ownership
6060

61-
The target is that starting or replacing a daemon is an explicit act, not a side effect of a client
62-
call. Today a client call can still start a daemon; #3754 makes that explicit for the client
63-
lifecycle, and #3757 adds `agent-device/host`, where an embedder owns its daemon and passes its
64-
plugins as the third source.
61+
Clients retain managed and attach lifecycles. Managed clients may start a daemon; attach clients cannot start or replace one. An embedder calls `startAgentDevice({ stateDir, plugins?, host? })` from `agent-device` to own a runtime in its process. The main entry loads the runtime when called. The returned client and serializable `clientConfig` identify that exact instance. Attaching checks normal version and code compatibility before checking the instance pin. `close()` shuts the runtime down. The CLI cannot signal or replace an embedder-owned runtime.
62+
63+
The embedder supplies plugin objects directly. They follow the built-ins through the same registry validation; this runtime does not read the plugin store. Plugin failures remain inventory data. Logging adapters, a separate package entry, and disposal protocols are not required to own a daemon: the library exposes the client, its attach configuration, and `close()`.
64+
65+
Decision history: the former explicit-start target is dropped; the client lifecycle continues to choose startup behavior. The main-entry API replaces the proposed host subpath and optional host controls, keeping ownership and attachment on the existing runtime and client paths (#3757).
6566

6667
## Alternatives refused
6768

‎examples/sdk/host-runtime.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Host-owned runtime: start the daemon inside this process, drive it through the
3+
* client it hands back, and end it with one `close()`.
4+
*
5+
* Demonstrates: `startAgentDevice` from `agent-device`.
6+
*
7+
* Prerequisites: none — the runtime is this process's own, so no daemon needs to
8+
* be running and no device is touched here. `sessions.list()` asks that runtime
9+
* for its sessions, which is empty until something opens one.
10+
*
11+
* Run: node --experimental-strip-types examples/sdk/host-runtime.ts
12+
*/
13+
import { startAgentDevice } from 'agent-device';
14+
15+
const host = await startAgentDevice({
16+
// Required: a host claims a directory of its own rather than attaching to
17+
// whatever an ambient AGENT_DEVICE_STATE_DIR happens to name.
18+
stateDir: './.host-runtime-state',
19+
});
20+
21+
try {
22+
console.log(`state dir: ${host.clientConfig.stateDir}`);
23+
// The pin names exactly this instance — token, pid and process start time — so a
24+
// second process handed this config reaches this runtime and refuses anything
25+
// that later replaced it. It carries a bearer token: keep it inside this host.
26+
console.log(`pinned pid: ${host.clientConfig.daemonBinding?.pid}`);
27+
const sessions = await host.client.sessions.list();
28+
console.log(`sessions: ${sessions.length}`);
29+
} finally {
30+
// One close, safe to repeat or overlap, and it never exits this process. What the
31+
// runtime could not finish comes back in the report instead of being swallowed.
32+
const report = await host.close();
33+
const unfinished = [
34+
...report.providerReleases.pending,
35+
...report.providerReleases.unknown,
36+
...report.runners.handedOff,
37+
...report.plugins.pending,
38+
];
39+
if (report.requests.abandoned > 0 || report.sessions.failed > 0 || unfinished.length > 0) {
40+
console.log(`closed with unfinished work: ${JSON.stringify(report)}`);
41+
}
42+
}

‎packages/contracts/src/client-connection.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,27 @@ export type DaemonIdentity = {
4242
processStartTime?: string;
4343
};
4444

45+
/**
46+
* The one daemon instance a client is pinned to: its credentials and its process lifetime together.
47+
*
48+
* A pin is checked against the registered daemon before a request is dispatched, and the pinned
49+
* token is what authenticates the request — never a token discovered on the way. So a state
50+
* directory whose daemon was replaced fails with `details.reason: 'daemon-binding-mismatch'` instead
51+
* of sending a caller's work to a different instance, and a replacement that lands between that
52+
* check and the write is refused by the new instance's own token check. A pinned client never
53+
* starts, replaces, retires, or redirects a daemon.
54+
*
55+
* The token is a bearer capability for that instance: treat the object that carries it as a
56+
* credential, and keep it inside the host that owns the daemon.
57+
*/
58+
export type DaemonBinding = {
59+
/** The instance's daemon token, as its `daemon.json` published it. */
60+
token: string;
61+
pid: number;
62+
/** The instance's process start time; a pid alone cannot tell a lifetime from its successor. */
63+
processStartTime: string;
64+
};
65+
4566
export type EnsureDaemonOptions = {
4667
/** The state directory the daemon owns; defaults to `AGENT_DEVICE_STATE_DIR`, then the user default. */
4768
stateDir?: string;
@@ -70,6 +91,8 @@ export type AgentDeviceDaemonTransportContext = {
7091
authToken?: string;
7192
/** How this request treats the local daemon; `managed` when omitted. */
7293
daemonLifecycle?: DaemonLifecycle;
94+
/** See {@link DaemonBinding}. A client built with one sends this same pin on every request. */
95+
daemonBinding?: DaemonBinding;
7396
/**
7497
* Cancels this one in-flight request. A built-in transport that sees an abort destroys the
7598
* request's connection, which makes the daemon mark the request canceled; the promise rejects
@@ -88,6 +111,12 @@ export type AgentDeviceClientConfig = RemoteConnectionProfileFields &
88111
CloudProviderProfileFields & {
89112
/** See `DaemonLifecycle`. */
90113
daemonLifecycle?: DaemonLifecycle;
114+
/**
115+
* Pins this client to one daemon instance: every request addresses that instance, authenticates
116+
* with its token, and refuses a state directory whose daemon is any other instance. See
117+
* {@link DaemonBinding}.
118+
*/
119+
daemonBinding?: DaemonBinding;
91120
session?: string;
92121
lockPolicy?: DaemonLockPolicy;
93122
lockPlatform?: PlatformSelector;

‎packages/contracts/src/facades/client.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ export type {
3737
DaemonConnection,
3838
DaemonIdentity,
3939
DaemonLifecycle,
40+
DaemonBinding,
4041
DeviceCommandBaseOptions,
4142
EnsureDaemonOptions,
4243
} from '../client-connection.ts';

‎packages/daemon-contracts/src/daemon-registration-owner.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export type DaemonRegistrationFields = Readonly<{
5656
token: string;
5757
version: string;
5858
codeOrigin: DaemonCodeOrigin;
59-
codeSignature: string;
59+
codeSignature?: string;
6060
policyDigest?: string;
6161
/** What this daemon can do beyond the base RPC contract; absent from daemons that predate it. */
6262
capabilities?: readonly DaemonCapability[];

‎packages/daemon/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ export type {
55
DaemonRuntimeController,
66
DaemonRuntimeDeps,
77
} from './server/http/daemon-runtime.ts';
8+
export type { ShutdownReport } from './server/http/server-shutdown.ts';
89
export type { DaemonInvokeFn, DaemonRequest } from './core/daemon-request.ts';
910
export type { DaemonPlatformServices } from './core/platform-services.ts';
1011
export type { PlatformOwnerLifecycle } from './core/platform-owner-lifecycle.ts';

‎packages/daemon/src/server/http/daemon-runtime.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,13 @@ import {
7474
type RuntimeStateHandle,
7575
} from '@agent-device/host-kit/runtime-slots';
7676
import { emitDiagnostic, type ResourceDiagnostic } from '@agent-device/host-kit/diagnostics';
77+
import type { DaemonCodeOrigin } from '@agent-device/host-kit/code-signature';
7778
import type { HostEnvironment } from '@agent-device/kernel/source-value';
7879
import {
7980
readCurrentOwnerIdentity,
8081
reapOwnedProcessRecordsAtStartup,
8182
type OwnedProcessRecordStore,
83+
type OwnerIdentity,
8284
} from '@agent-device/host-kit/process';
8385
import { isEnvTruthy, sleep } from '@agent-device/host-kit/retry';
8486
import {
@@ -227,9 +229,13 @@ export type DaemonRuntimeOptions = {
227229
* record it cannot place, and a runtime always knows which of these two it is.
228230
*/
229231
ownership?: DaemonRuntimeOwnership;
232+
/** The daemon code an embedder loaded; its process entry belongs to the host application. */
233+
codeIdentity?: { origin: DaemonCodeOrigin; codeSignature?: string };
230234
};
231235

232236
export type DaemonRuntimeController = {
237+
/** The runtime process lifetime used in its registration and lifecycle protocol. */
238+
identity: Readonly<OwnerIdentity>;
233239
httpPort?: number;
234240
socketPort?: number;
235241
/**
@@ -262,14 +268,21 @@ export function daemonStartupExitCode(error: unknown): number {
262268
export async function startDaemonRuntime(
263269
options: DaemonRuntimeOptions,
264270
): Promise<DaemonRuntimeController> {
271+
const runtimeOptions = {
272+
...options,
273+
codeIdentity: options.codeIdentity ?? {
274+
origin: resolveDaemonCodeOrigin(),
275+
codeSignature: resolveDaemonCodeSignature(),
276+
},
277+
};
265278
const runtimeState = createRuntimeStateHandle();
266279
return await runtimeState.run(
267280
async () =>
268281
await withCommandHost({ host: options.host, requestEnv: undefined }, async () => {
269282
const rollback = createStartupRollback();
270283
rollback.onRollback(() => runtimeState.dispose());
271284
try {
272-
return await startDaemonRuntimeOnHost(options, rollback, runtimeState);
285+
return await startDaemonRuntimeOnHost(runtimeOptions, rollback, runtimeState);
273286
} catch (error) {
274287
await rollback.run();
275288
throw error;
@@ -279,7 +292,9 @@ export async function startDaemonRuntime(
279292
}
280293

281294
async function startDaemonRuntimeOnHost(
282-
options: DaemonRuntimeOptions,
295+
options: DaemonRuntimeOptions & {
296+
codeIdentity: NonNullable<DaemonRuntimeOptions['codeIdentity']>;
297+
},
283298
rollback: StartupRollback,
284299
runtimeState: RuntimeStateHandle,
285300
): Promise<DaemonRuntimeController> {
@@ -328,8 +343,7 @@ async function startDaemonRuntimeOnHost(
328343
const version = readVersion();
329344
const token = crypto.randomBytes(24).toString('hex');
330345
const daemonIdentity = readCurrentOwnerIdentity();
331-
const daemonCodeOrigin = resolveDaemonCodeOrigin();
332-
const daemonCodeSignature = resolveDaemonCodeSignature();
346+
const { codeIdentity } = options;
333347
const requestDrainTimeoutMs =
334348
options.shutdownBudgets?.requestDrainMs ?? DAEMON_REQUEST_DRAIN_TIMEOUT_MS;
335349
// The registry is the one plugin cleanup owner: closing it shuts each runtime down, then disposes
@@ -586,8 +600,8 @@ async function startDaemonRuntimeOnHost(
586600
httpPort,
587601
token,
588602
version,
589-
codeOrigin: daemonCodeOrigin,
590-
codeSignature: daemonCodeSignature,
603+
codeOrigin: codeIdentity.origin,
604+
codeSignature: codeIdentity.codeSignature,
591605
policyDigest: daemonPolicy?.digest,
592606
capabilities: DAEMON_CAPABILITIES,
593607
plugins: deps.pluginInventory,
@@ -952,5 +966,6 @@ async function startDaemonRuntimeOnHost(
952966
run: runtimeState.run,
953967
socketPort,
954968
token,
969+
identity: Object.freeze({ ...daemonIdentity }),
955970
};
956971
}

‎scripts/layering/process-globals-policy.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ test('entry declarations permit process reads but do not permit ambient command-
5454
'src/cli/commands/example.ts',
5555
'src/daemon.ts',
5656
'src/agent-device-client.ts',
57+
'src/host.ts',
5758
'packages/capture-kit/src/png-worker.ts',
5859
'packages/maestro/src/daemon-port/run-script-http-child.ts',
5960
'packages/react-native/src/companion/client-companion-tunnel-worker.ts',

0 commit comments

Comments
 (0)