Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/remove-managed-client-lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'agent-device': minor
---

Clients attach to an existing daemon and no longer start, replace, or retire it on timeout. This also applies to `client.replay.run()` and `client.replay.test()`; they no longer start a private daemon. Remove `daemonLifecycle: 'managed'` and call `ensureDaemon({ stateDir })` before creating a client for a detached daemon. To own a daemon in your process, call `startAgentDevice({ stateDir })` from `agent-device` and close its returned handle. CLI and MCP commands continue to ensure their daemon, including private one-shot replay/test startup and cleanup.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,16 +101,21 @@ See [AI agent setup](https://agent-device.dev/docs/agent-setup) for per-client s
`createAgentDeviceClient()` gives Node.js code typed access to the same commands, as model tools in your own agent or from orchestration code:

```ts
import { createAgentDeviceClient } from 'agent-device';
import { createAgentDeviceClient, ensureDaemon, isAgentDeviceError } from 'agent-device';

await ensureDaemon();
const client = createAgentDeviceClient({ session: 'qa-run' });
try {
await client.apps.open({ app: 'com.apple.Preferences', platform: 'ios' });
const snapshot = await client.capture.snapshot({ interactiveOnly: true });
const button = snapshot.nodes.find((node) => node.role === 'button');
if (button) await client.interactions.press({ ref: button.ref });
} finally {
await client.sessions.close();
await client.sessions.close().catch((error) => {
if (isAgentDeviceError(error) && error.code === 'SESSION_NOT_FOUND') return;
console.error('Session cleanup failed:', error);
process.exitCode = 1;
});
}
```

Expand Down
4 changes: 2 additions & 2 deletions docs/adr/0034-provider-plugin-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ had to fake the store to load a plugin from its own dependencies (#3747).

## Daemon ownership

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()` in the host process is the only way to shut an embedded runtime down, and returns its `ShutdownReport`. `daemon stop` refuses live embedded ownership with `daemon-owner-embedded` and live unrecognized ownership with `daemon-owner-unrecognized`, without a request or signal. The embedded-ownership refusal names the host PID and directs the caller to close the runtime there. Stop may retire an embedded or unrecognized registration when its recorded host lifetime has provably exited. The CLI cannot replace a live embedded runtime. Registration and its lock remain held while requests or platform owners are unfinished.
Clients attach to an existing daemon and cannot start or replace one. Call `ensureDaemon()` to start or replace a detached daemon explicitly. 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()` in the host process is the only way to shut an embedded runtime down, and returns its `ShutdownReport`. `daemon stop` refuses live embedded ownership with `daemon-owner-embedded` and live unrecognized ownership with `daemon-owner-unrecognized`, without a request or signal. The embedded-ownership refusal names the host PID and directs the caller to close the runtime there. Stop may retire an embedded or unrecognized registration when its recorded host lifetime has provably exited. The CLI cannot replace a live embedded runtime. Registration and its lock remain held while requests or platform owners are unfinished.

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()`.

Decision history: owner-only close replaces external embedded shutdown so the CLI cannot end work its host owns; a proven host exit permits registration retirement. 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).
Decision history: owner-only close replaces external embedded shutdown so the CLI cannot end work its host owns; a proven host exit permits registration retirement. The former client-managed startup path was removed in 0.22; explicit ensuring keeps daemon replacement separate from attachment (#3759). 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).

## Alternatives refused

Expand Down
18 changes: 16 additions & 2 deletions examples/sdk/client-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* a node, then close the session — with typed error handling via the
* exported error helpers.
*
* Demonstrates: `createAgentDeviceClient`, `AppError`, `isAgentDeviceError`,
* Demonstrates: `ensureDaemon`, `createAgentDeviceClient`, `AppError`, `isAgentDeviceError`,
* and `normalizeAgentDeviceError` from the `agent-device` root export.
*
* Prerequisites: an `agent-device` daemon target (a booted iOS simulator).
Expand All @@ -15,6 +15,7 @@
import {
AppError,
createAgentDeviceClient,
ensureDaemon,
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
isAgentDeviceError,
normalizeAgentDeviceError,
} from 'agent-device';
Expand Down Expand Up @@ -47,6 +48,13 @@ function reportAgentDeviceError(error: unknown): void {
}

async function main(): Promise<void> {
try {
await ensureDaemon();
} catch (error) {
if (!isAgentDeviceError(error)) throw error;
reportAgentDeviceError(error);
return;
}
const client = createAgentDeviceClient({
session: 'sdk-example',
lockPolicy: 'reject',
Expand All @@ -72,7 +80,13 @@ async function main(): Promise<void> {
if (!isAgentDeviceError(error)) throw error;
reportAgentDeviceError(error);
} finally {
await client.sessions.close();
try {
await client.sessions.close();
} catch (error) {
if (!isAgentDeviceError(error) || error.code !== 'SESSION_NOT_FOUND') {
reportAgentDeviceError(error);
}
}
}
}

Expand Down
3 changes: 2 additions & 1 deletion examples/sdk/contracts-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
* Demonstrates: `centerOfRect` from `agent-device/contracts`, consumed
* against the `CaptureSnapshotResult` shape returned by the root client.
*
* Prerequisites: an `agent-device` daemon target with an app already open.
* Prerequisites: call `ensureDaemon()` to start the daemon, then open an app
* in the `sdk-example` session.
* This file typechecks without one.
*
* Run: node --experimental-strip-types examples/sdk/contracts-result.ts
Expand Down
50 changes: 30 additions & 20 deletions packages/client/src/__tests__/index-daemon-lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,57 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import type {
AgentDeviceDaemonTransport,
AgentDeviceDaemonTransportContext,
DaemonLifecycle,
} from '@agent-device/contracts/client';
import type { AgentDeviceDaemonTransport } from '@agent-device/contracts/client';
import { createAgentDeviceClient } from '../index.ts';

// `daemonLifecycle` is a client choice that only the transport can act on, so the client's job is to
// hand it over exactly and to refuse a value it does not know.
// A client always attaches, so `daemonLifecycle` is no longer a choice the transport acts on. The
// client's job is to accept `'attach'` (the only value, and the default) and to refuse any value that
// would mean managing a daemon, naming the explicit owners instead.

function recordingTransport() {
const contexts: Array<AgentDeviceDaemonTransportContext | undefined> = [];
const seen: Array<Record<string, unknown>> = [];
const transport: AgentDeviceDaemonTransport = async (_request, context) => {
contexts.push(context);
seen.push({ ...(context ?? {}) });
return { ok: true, data: { devices: [] } };
};
return { contexts, transport };
return { seen, transport };
}

test('the configured daemon lifecycle reaches the transport', async () => {
const { contexts, transport } = recordingTransport();
test('a client sends no daemon-management knob to its transport', async () => {
const { seen, transport } = recordingTransport();
const attached = createAgentDeviceClient({ daemonLifecycle: 'attach' }, { transport });
const plain = createAgentDeviceClient({}, { transport });

const managed = createAgentDeviceClient({ daemonLifecycle: 'managed' }, { transport });

await attached.devices.list();
await managed.devices.list();
await plain.devices.list();

// `'attach'` is what every request does, so it is not a per-request option either: the transport
// gets the caller's cancellation and pin, and nothing about who owns the daemon.
assert.deepEqual(
contexts.map((context) => context?.daemonLifecycle),
['attach', 'managed', undefined],
seen.map((context) => 'daemonLifecycle' in context),
[false, false],
);
});

test('the removed managed lifecycle is refused where the config is read', () => {
const { transport } = recordingTransport();

assert.throws(
() => createAgentDeviceClient({ daemonLifecycle: 'managed' as never }, { transport }),
(error: { code?: string; details?: { daemonLifecycle?: unknown; hint?: unknown } }) => {
assert.equal(error.code, 'INVALID_ARGS');
assert.equal(error.details?.daemonLifecycle, 'managed');
assert.match(String(error.details?.hint), /ensureDaemon\(\{ stateDir \}\)/);
assert.match(String(error.details?.hint), /startAgentDevice\(\{ stateDir \}\)/);
return true;
},
);
});

test('an unknown daemon lifecycle is refused instead of becoming managed', () => {
test('an unknown daemon lifecycle is refused instead of attaching blindly', () => {
const { transport } = recordingTransport();
const mistyped = 'Attach' as DaemonLifecycle;

assert.throws(
() => createAgentDeviceClient({ daemonLifecycle: mistyped }, { transport }),
() => createAgentDeviceClient({ daemonLifecycle: 'Attach' as never }, { transport }),
(error: { code?: string }) => error.code === 'INVALID_ARGS',
);
});
16 changes: 11 additions & 5 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,6 @@ export function createAgentDeviceClient(
await transport(request, {
authToken: merged.daemonAuthToken,
signal: merged.signal,
daemonLifecycle: merged.daemonLifecycle,
...(daemonBinding ? { daemonBinding } : {}),
}),
);
Expand Down Expand Up @@ -632,10 +631,17 @@ function optionalSnapshotResponseFields(
}

function readDaemonLifecycle(value: unknown): DaemonLifecycle | undefined {
if (value === undefined || value === 'attach' || value === 'managed') return value;
throw new AppError('INVALID_ARGS', "daemonLifecycle must be 'attach' or 'managed'.", {
daemonLifecycle: value,
});
if (value === undefined || value === 'attach') return value;
throw new AppError(
'INVALID_ARGS',
value === 'managed'
? "daemonLifecycle must be 'attach'. The 'managed' lifecycle was removed in 0.22."
: "daemonLifecycle must be 'attach'.",
{
daemonLifecycle: value,
hint: "Drop daemonLifecycle, or set it to 'attach'. To start or replace a detached daemon, call ensureDaemon({ stateDir }). To own one in this process, call startAgentDevice({ stateDir }) from 'agent-device'.",
},
);
}

/**
Expand Down
35 changes: 18 additions & 17 deletions packages/contracts/src/client-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,20 @@ import type {
} from './remote-config-fields.ts';

/**
* Who owns the daemon on a client's state directory.
* The one daemon lifecycle a client config selects: `attach`. The transport connects to its registered
* daemon without starting, replacing, retiring or timeout-killing it, including replay/test calls.
* CLI/MCP can own a private daemon for one-shot replay/test; library client calls cannot.
* A missing daemon fails with `details.reason: 'daemon-not-running'`; an incompatible one uses
* `'daemon-incompatible'`.
*
* - `managed`: the client starts a missing daemon and replaces an incompatible one itself, and may
* retire a hung one after a timeout. This is the default until 0.22.
* - `attach`: the client only connects to the daemon registered in the state directory. It never
* starts, replaces or kills one. A missing daemon fails with `details.reason: 'daemon-not-running'`
* and an incompatible one with `'daemon-incompatible'`; `ensureDaemon()` is the explicit way to
* start or replace one.
* `ensureDaemon()` is the explicit way to start or replace a detached daemon. `startAgentDevice()`
* imported from `agent-device` owns one in your process and refuses an already registered state
* directory. `ensureDaemon()` refuses to replace a daemon that holds another client's work.
*
* Independent of `daemonTransport`, `daemonServerMode` and `daemonBaseUrl`: a remote connection
* never starts or retires a local daemon in either mode.
* Independent of `daemonTransport`, `daemonServerMode` and `daemonBaseUrl`: a remote connection never
* starts or retires a local daemon.
*/
export type DaemonLifecycle = 'attach' | 'managed';
export type DaemonLifecycle = 'attach';

/** What a client can learn about a daemon without talking to it: how it identifies itself on disk. */
export type DaemonIdentity = {
Expand Down Expand Up @@ -89,8 +90,6 @@ export type DaemonConnection = {

export type AgentDeviceDaemonTransportContext = {
authToken?: string;
/** How this request treats the local daemon; `managed` when omitted. */
daemonLifecycle?: DaemonLifecycle;
/** See {@link DaemonBinding}. A client built with one sends this same pin on every request. */
daemonBinding?: DaemonBinding;
/**
Expand All @@ -109,7 +108,10 @@ export type AgentDeviceDaemonTransport = (

export type AgentDeviceClientConfig = RemoteConnectionProfileFields &
CloudProviderProfileFields & {
/** See `DaemonLifecycle`. */
/**
* See `DaemonLifecycle`. Only `'attach'` is accepted, and it is the default; the removed
* `'managed'` value fails validation instead of starting a daemon.
*/
daemonLifecycle?: DaemonLifecycle;
/**
* Pins this client to one daemon instance: every request addresses that instance, authenticates
Expand Down Expand Up @@ -191,10 +193,9 @@ export type AgentDeviceRequestOverrides = Pick<
* daemon reset.
*
* The guarantee covers the daemon request, and the built-in transports enforce it; a custom
* transport receives the signal on its context and may implement cancellation differently. Two
* phases run outside it: a response-artifact download started after the response begins is not
* canceled, and a canceled one-shot replay still runs the existing cleanup that may tear down a
* daemon this client started.
* transport receives the signal on its context and may implement cancellation differently. One
* phase runs outside it: a response-artifact download started after the response begins is not
* canceled.
*/
signal?: AbortSignal;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ test('attach reports a missing daemon without starting one', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir, paths } = stateDirAndPaths();

const error = await failureOf(sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' }));
const error = await failureOf(sendToDaemon(request(stateDir)));

assert.equal(error.details?.reason, 'daemon-not-running');
assert.match(String(error.details?.hint), /agent-device devices --state-dir /);
Expand All @@ -118,7 +118,7 @@ test('attach reports an incompatible daemon with both identities and leaves it r
});

try {
const error = await failureOf(sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' }));
const error = await failureOf(sendToDaemon(request(stateDir)));

assert.equal(error.details?.reason, 'daemon-incompatible');
assert.equal(identityIn(error, 'daemon').version, '0.0.0-stale');
Expand All @@ -141,7 +141,7 @@ for (const ownership of ['detached', 'embedded'] as const)
await closeLoopbackServer(closed.server);
const { child } = await registerDaemon(paths, { httpPort: closed.port, ownership });

const error = await failureOf(sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' }));
const error = await failureOf(sendToDaemon(request(stateDir)));

assert.equal(error.details?.reason, 'daemon-not-running');
assert.equal(identityIn(error, 'daemon').pid, child.pid);
Expand All @@ -163,29 +163,29 @@ test('attach uses a compatible daemon and never lets a timeout retire it', async
const send = vi.spyOn(transport, 'sendRequest');

try {
const response = await sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' });
const response = await sendToDaemon(request(stateDir));
assert.deepEqual(response, { ok: true, data: { via: 'live' } });
assert.equal(send.mock.calls.at(-1)?.[5]?.timeoutRecovery, 'none');

// The removed per-request lifecycle knob cannot resurrect the old kill path: an omitted context
// attaches too, and still may not retire the daemon on a timeout.
await sendToDaemon(request(stateDir));
assert.equal(send.mock.calls.at(-1)?.[5]?.timeoutRecovery, 'retire-unresponsive');
assert.equal(send.mock.calls.at(-1)?.[5]?.timeoutRecovery, 'none');
assert.equal(spawn.mock.calls.length, 0);
} finally {
await closeLoopbackServer(live.server);
}
});

test('a remote connection never starts a local daemon in either lifecycle', async (t) => {
test('a remote connection never starts a local daemon', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir } = stateDirAndPaths();
const unreachable = await startScriptedDaemon(okResult({}));
await closeLoopbackServer(unreachable.server);
const remote = { daemonBaseUrl: `http://127.0.0.1:${unreachable.port}` };

for (const daemonLifecycle of ['attach', 'managed'] as const) {
const error = await failureOf(sendToDaemon(request(stateDir, remote), { daemonLifecycle }));
assert.match(error.message, /Remote daemon is unavailable/);
}
const error = await failureOf(sendToDaemon(request(stateDir, remote)));
assert.match(error.message, /Remote daemon is unavailable/);
assert.equal(spawn.mock.calls.length, 0);
});

Expand Down Expand Up @@ -508,9 +508,7 @@ test('a live daemon on another transport is left alone when it cannot be asked t
assert.equal(ensured.details?.reason, 'daemon-incompatible');
assert.equal(ensured.details?.mismatch, 'no-quiesce');

const attached = await failureOf(
sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' }),
);
const attached = await failureOf(sendToDaemon(request(stateDir)));
assert.equal(attached.details?.reason, 'daemon-incompatible');
assert.equal(attached.details?.mismatch, 'transport');

Expand Down Expand Up @@ -688,9 +686,7 @@ test('a registration whose process is gone is not running, whatever version it n
);

try {
const attached = await failureOf(
sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' }),
);
const attached = await failureOf(sendToDaemon(request(stateDir)));
assert.equal(attached.details?.reason, 'daemon-not-running');

// ensureDaemon replaces the dead registration without asking anyone to leave.
Expand Down
Loading
Loading