Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
c5573ea
feat(remote): deliver a remote open --save-script recording to the ca…
thymikee Nov 15, 2026
0d9e89b
chore(gates): record the remote script delivery wire fields and owner…
thymikee Nov 15, 2026
08e22c3
chore(gates): gate the moved artifact loop and the session-script fie…
thymikee Nov 15, 2026
fb46d09
fix(remote): keep an armed recording when its first download fails
thymikee Nov 15, 2026
7e1e9f4
fix(remote): keep the record of an open that may have armed, reclaim …
thymikee Nov 15, 2026
68f1e03
test(wire-compat): describe the session-script manifest group accurately
thymikee Nov 15, 2026
7ecee5a
fix(remote): recheck a stale record under its lock before sweeping it
thymikee Nov 15, 2026
80eacfa
fix(remote): keep the action's success when this machine cannot save …
thymikee Nov 15, 2026
c54d00a
fix(remote): keep close successful when retirement fails, and gate re…
thymikee Nov 15, 2026
3dfb8dd
test(remote): isolate the close retirement failure from the version w…
thymikee Nov 15, 2026
95bfc9a
fix: keep script delivery facts in digest responses and journal staging
thymikee Nov 15, 2026
83e4663
fix(remote): remove a staging directory before unlisting it
thymikee Nov 15, 2026
33981fc
fix(remote): keep staging listed until it is removed, and never recre…
thymikee Nov 15, 2026
0444b83
fix(daemon): refuse a batch that would close an armed remote recording
thymikee Nov 15, 2026
b0ac8ee
fix(daemon): check normalized batch steps for a remote recording close
thymikee Nov 15, 2026
e7e1554
fix(remote): stop naming an interrupted version before retiring its s…
thymikee Nov 15, 2026
12736b6
fix(remote): never let an unsweepable stale record block a new open
thymikee Nov 15, 2026
9e61d60
fix: state each surface's script delivery failure, and check batches …
thymikee Nov 15, 2026
837f1a4
docs(remote): state the script-artifacts requirement on the remote pr…
thymikee Nov 15, 2026
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
42 changes: 42 additions & 0 deletions docs/adr/0016-active-session-script-publication.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Accepted.
This ADR is implemented on `main`, including the #1349 identity-level destination-guard amendment.

Implementation owners are `packages/daemon/src/sessions/handlers/session-script-publication.ts` and `packages/daemon/src/core/session-script-active-publication.ts`.
Remote delivery (#4511 amendment) is owned by `packages/daemon/src/core/session-script-publication-capability.ts` and, on the client, `packages/remote/src/session-script-destination.ts`.

## Rules at a glance

Expand All @@ -25,6 +26,9 @@ This section is a normative summary.
Every refusal happens before filesystem work and names its recovery.
- Repair transactions (ADR 0012) are disjoint from this lifecycle.
A session with `saveScriptBoundary` set refuses this action without a change to repair state.
- A remote recording is delivered, not published (#4511 amendment).
Each recorded action refreshes the caller's `--save-script` file, and close overwrites it with the final script.
`session save-script` refuses a remote recording.
- `ReplayCommandResult.sessionActive` comes from the daemon's session store, never from a re-parse of the script.
This signal lets a one-shot client keep the daemon alive on a close-less handoff.
- Sensitive `fill` inputs must be recorded as placeholders through `fill --record-as <VAR>` (ADR 0017, shipped for #1348).
Expand Down Expand Up @@ -172,6 +176,44 @@ This amendment deliberately does not answer one real question: should a *committ
The old flag said yes.
A change to that answer is a behavior change, not a derivation.

**Amendment (#4511, shipped).** A remote caller cannot read the daemon target, so a remote `open --save-script=<path>` delivers its recording to the caller.
It adds no state name, command, or flag:

- Before it sends the open, the client mints a random publication ID and records the destination and the `--force` grant under it in its state directory (`remote-connections/session-scripts/`), keyed by the endpoint, the tenant, the session, and that ID.
The open carries the ID in `meta.scriptPublicationId` and never the caller path.
A daemon answer that does not name the ID removes the record.
A failed open may still have armed the recording, so it keeps its record.
- The daemon arms the recording under that ID, which `open` and `close` name in `scriptPublicationId`.
After each successful request that records into the ARMED recording, the daemon writes the recording so far, without a terminal `close`, and returns it as a `session-script` artifact with the ID and a growing `scriptRevision`.
The close-time write is the final version and has the highest revision; close takes it from the close-time write itself, so a capture that close stops first never hides recorded actions.
Each version, the final one included, is a fresh 0600 file in a 0700 directory under the daemon's sessions directory, and is downloaded once.
It registers for download for the tenant that opened the recording, whatever the tenant, capture filters, or network marker of the request that recorded it.
- The client writes a version only to the destination of a record that matches its ID and scope, and only when its revision is newer than the last published one.
The `savedScript` field and the `session-script` type are reserved for this path, so a script artifact under another field writes nothing.
Thus, a daemon response never establishes a destination, and another publication's or another session's version writes nothing.
The download streams, capped at 8 MiB, into a new 0600 file, created exclusively and never through a symbolic link, in a 0700 staging directory beside the destination.
Under the record lock, the record names the version and the staged file's device and inode before the rename or link, and the next version settles that entry from the destination's identity.
A second name keeps the staged inode, and its staging directory, on disk while the record may name it, so no later file can reuse that inode; settling or retiring the entry removes the staging directory.
The record lists each staging directory before a download writes to it, so retiring or sweeping the record also removes the staging that a crashed download left behind.
The first version is linked exclusively, as a local close-time write is, unless the open granted `--force`; a symbolic or hard link at the destination is replaced as a directory entry and never written through.
- If this machine cannot download or save a version, the action also keeps its success and carries the same `scriptDeliveryFailure` and warning; a script delivery failure never changes the outcome of the action that recorded it.
- A close retires the record it names, even when the final version or another artifact fails, and reports the first error.
A record that outlives its open stays inert, because only its own ID matches it; creating a record removes records untouched for seven days.
- If the daemon cannot write a version, the action keeps its success and returns `scriptDeliveryFailure` (`script_delivery_failed`) and a warning without the daemon-host path; the caller file keeps the previous version.
A local close that cannot write its script still fails as before.
- Teardown without `close` writes no daemon file; the caller keeps the version from the last recorded action.
- At the public HTTP boundary, `saveScript` is accepted only as `true` on `open` with a well-formed publication ID.
`session save-script` refuses a remote recording (`remote_script_publication_unsupported`), and remote `close --save-script`, `replay --save-script`, and `--save-script` in batch steps stay refused.
A batch whose steps would close an armed remote recording is refused before any step runs (`remote_script_batch_close_unsupported`), because a batch delivers no script versions from its steps.
- The daemon reports the `script-artifacts` capability in `/health`, through a proxy in its upstream health; the client refuses a remote `--save-script` before dispatch without it.

The destination keeps local `--save-script` semantics: the client creates a missing parent directory and checks no ancestor ownership, so another local user who can write an ancestor directory can redirect the file, locally and remotely alike (#4565).
Known limitation (#4564): the RPC response is the contract for `scriptDeliveryFailure`; the SDK, CLI, and MCP results do not carry it yet, the SDK close drops its warnings, and a batch delivers no step script versions.
Rejected: a remote `session save-script` download, because it added a second publication path and a retry protocol.
Rejected: delivery only at close, because a session that an external owner closes would lose its recording.
Rejected: daemon-minted recording IDs bound through per-request claims, because the claim, binding, and tombstone protocol cost more than a client-minted ID that only its own client can match.
Consequence: each recorded action of a remote ARMED recording costs one script write and one artifact download.

This lifecycle is distinct from the ADR 0012 repair transaction.
`session save-script` rejects a session with `saveScriptBoundary` set.
The refusal directs the caller to finish or abort the repair through its existing `replay --from` and teardown commit protocol.
Expand Down
2 changes: 1 addition & 1 deletion packages/command-surface/src/schema/command-overrides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
text: {
summary: 'Expose a local daemon through an HTTP tunnel',
description:
'Expose the local daemon HTTP contract through a tunnel-friendly reverse proxy.\n\nRun this on the host that has access to simulators/devices, expose the printed local proxy URL through a tunnel, then point another machine at the tunnel URL with connect proxy.\n\nThe proxy starts or reuses a local HTTP daemon, accepts /health, /rpc, /upload and resumable /upload/* routes, and /artifacts plus /artifacts/*, and also accepts the same routes under /agent-device/*. Health is unauthenticated for reachability probes. Other routes require the generated bearer token printed at startup, or the explicit --daemon-auth-token value when provided. The proxy rewrites authorized client requests to the upstream daemon token instead of exposing the local daemon token.\n\nFor a TLS-terminated tunnel, set --public-origin to the public HTTP(S) origin, for example --public-origin https://public.example:8443. Forwarded and X-Forwarded-* headers do not select upload ticket origins. For an ephemeral tunnel, obtain its public name first, then configure and restart the proxy. Without a fixed origin, Node uses the actual socket scheme and validated Host.\n\nUse the /agent-device base path when connecting through cloudflared, ngrok, or another shared origin. Treat the bearer token as a secret; anyone with it can control the proxied daemon. This direct proxy flow does not use agent-device auth.\n\nRemote captures write generated artifacts on the daemon. Screenshot, recording, performance, and trace paths select downloads on the client; they never select host files. Direct RPC callers download returned artifact IDs through /artifacts/<id>. Remote requests ignore client cwd and refuse host tooling paths, --launch-console, and script publication.\n\nExamples:\n cloudflared tunnel --url http://127.0.0.1:4310\n agent-device proxy --port 4310 --public-origin https://example.trycloudflare.com\n agent-device connect proxy --daemon-base-url https://example.trycloudflare.com/agent-device --daemon-auth-token <token>',
'Expose the local daemon HTTP contract through a tunnel-friendly reverse proxy.\n\nRun this on the host that has access to simulators/devices, expose the printed local proxy URL through a tunnel, then point another machine at the tunnel URL with connect proxy.\n\nThe proxy starts or reuses a local HTTP daemon, accepts /health, /rpc, /upload and resumable /upload/* routes, and /artifacts plus /artifacts/*, and also accepts the same routes under /agent-device/*. Health is unauthenticated for reachability probes. Other routes require the generated bearer token printed at startup, or the explicit --daemon-auth-token value when provided. The proxy rewrites authorized client requests to the upstream daemon token instead of exposing the local daemon token.\n\nFor a TLS-terminated tunnel, set --public-origin to the public HTTP(S) origin, for example --public-origin https://public.example:8443. Forwarded and X-Forwarded-* headers do not select upload ticket origins. For an ephemeral tunnel, obtain its public name first, then configure and restart the proxy. Without a fixed origin, Node uses the actual socket scheme and validated Host.\n\nUse the /agent-device base path when connecting through cloudflared, ngrok, or another shared origin. Treat the bearer token as a secret; anyone with it can control the proxied daemon. This direct proxy flow does not use agent-device auth.\n\nRemote captures write generated artifacts on the daemon. Screenshot, recording, performance, and trace paths select downloads on the client; they never select host files. Direct RPC callers download returned artifact IDs through /artifacts/<id>. Remote requests ignore client cwd and refuse host tooling paths and --launch-console. A fresh open --save-script=<path> arms recording; after each recorded action the client refreshes that caller file, and close writes the final script there. Remote session save-script, close/replay --save-script, and --save-script in batch steps remain refused.\n\nExamples:\n cloudflared tunnel --url http://127.0.0.1:4310\n agent-device proxy --port 4310 --public-origin https://example.trycloudflare.com\n agent-device connect proxy --daemon-base-url https://example.trycloudflare.com/agent-device --daemon-auth-token <token>',
},
listUsageOverride: 'proxy',
allowedFlags: ['proxyHost', 'proxyPort', 'publicOrigin', 'daemonAuthToken', 'stateDir'],
Expand Down
4 changes: 4 additions & 0 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ export type DaemonHealthPayload = {
rpcProtocolVersion: number;
instanceId?: string;
hostArch?: string;
/** The subset of `DAEMON_CAPABILITIES` this daemon serves over HTTP; omitted by older daemons. */
capabilities?: readonly string[];
/** The lease backends this daemon admits; a host checks it before relying on one. */
leaseBackends?: readonly string[];
upstream?: unknown;
Expand All @@ -165,6 +167,7 @@ export function buildDaemonHealthPayload(
upstream?: unknown;
instanceId?: string;
hostArch?: string;
capabilities?: readonly string[];
leaseBackends?: readonly string[];
} = {},
): DaemonHealthPayload {
Expand All @@ -175,6 +178,7 @@ export function buildDaemonHealthPayload(
rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),
...(options.hostArch !== undefined ? { hostArch: options.hostArch } : {}),
...(options.capabilities !== undefined ? { capabilities: options.capabilities } : {}),
...(options.leaseBackends !== undefined ? { leaseBackends: options.leaseBackends } : {}),
...(options.upstream !== undefined ? { upstream: options.upstream } : {}),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ test('remote fill recording errors give a recovery path the remote client suppor
const remote = attachSessionAddressHints(response, {} as never, settings);
assert.equal(remote.ok, false);
if (remote.ok) return;
assert.match(remote.error.message, /remote clients cannot start one/);
assert.match(remote.error.message, /Connect to a local daemon/);
assert.equal(remote.error.message, response.error.message);
assert.equal(remote.error.details?.reason, 'fill_record_as_requires_armed_recording');

const local = attachSessionAddressHints(response, {} as never, {} as never);
Expand Down
103 changes: 103 additions & 0 deletions packages/daemon-client/src/__tests__/index-script-capability.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import http from 'node:http';
import path from 'node:path';
import { expect, test } from 'vitest';
import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit';
import { DAEMON_HTTP_INSTANCE_MISMATCH_HEADER } from '@agent-device/contracts/daemon-http';
import { sendToDaemon } from '../index.ts';

test.each([
{ name: 'legacy daemon', health: {}, supported: false },
{
name: 'upgraded proxy with legacy daemon',
health: { capabilities: ['script-artifacts'], upstream: {} },
supported: false,
},
{
name: 'upgraded daemon',
health: { capabilities: ['script-artifacts'] },
supported: true,
},
{
name: 'forwarding proxy with upgraded daemon',
health: { upstream: { capabilities: ['script-artifacts'] } },
supported: true,
},
])('remote recording negotiates $name before dispatch', async ({ health, supported }) => {
let rpcCount = 0;
const server = http.createServer((req, res) => {
res.setHeader('content-type', 'application/json');
if (req.url === '/health') {
res.end(JSON.stringify({ ok: true, ...health }));
return;
}
rpcCount += 1;
res.end(JSON.stringify({ jsonrpc: '2.0', id: 'test', result: { ok: true, data: {} } }));
});
const root = mkdtempForTestSync('script-capability-');
try {
const result = sendToDaemon(
{
command: 'open',
session: 'owned',
positionals: ['Demo'],
flags: {
daemonBaseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}`,
saveScript: path.join(root, 'journey.ad'),
stateDir: path.join(root, 'state'),
},
},
{ authToken: 'test' },
);
if (supported) await expect(result).resolves.toMatchObject({ ok: true });
else
await expect(result).rejects.toMatchObject({
code: 'INVALID_ARGS',
details: { reason: 'remote_script_artifacts_unsupported', daemonRequestSent: false },
});
expect(rpcCount).toBe(supported ? 1 : 0);
} finally {
await closeLoopbackServer(server);
}
});

test('a remote recording is not resent to a replacement daemon that cannot deliver scripts', async () => {
let rpcCount = 0;
let replaced = false;
const server = http.createServer((req, res) => {
res.setHeader('content-type', 'application/json');
if (req.url === '/health') {
const health = replaced
? { instanceId: 'legacy' }
: { instanceId: 'capable', capabilities: ['script-artifacts'] };
res.end(JSON.stringify({ ok: true, ...health }));
return;
}
rpcCount += 1;
replaced = true;
res.statusCode = 409;
res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true');
res.end(JSON.stringify({ jsonrpc: '2.0', id: 'test', error: { code: -32000, message: 'x' } }));
});
const root = mkdtempForTestSync('script-capability-retry-');
try {
const result = sendToDaemon(
{
command: 'open',
session: 'owned',
positionals: ['Demo'],
flags: {
daemonBaseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}`,
saveScript: path.join(root, 'journey.ad'),
stateDir: path.join(root, 'state'),
},
},
{ authToken: 'test' },
);
await expect(result).rejects.toMatchObject({
details: { reason: 'remote_script_artifacts_unsupported', daemonRequestSent: false },
});
expect(rpcCount).toBe(1);
} finally {
await closeLoopbackServer(server);
}
});
14 changes: 1 addition & 13 deletions packages/daemon-client/src/daemon-client-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ async function ensureRemoteDaemon(
hint: 'Fix or unset --daemon-base-url or AGENT_DEVICE_DAEMON_BASE_URL so the client targets a reachable daemon or the local one. If this CLI was connected with connect proxy, run agent-device disconnect to clear the saved connection and return to the local daemon.',
});
}
remoteInfo.capabilities = (health.upstream ?? health).capabilities;
remoteInfo.remoteInstanceId = health.instanceId;
remoteInfo.remoteUpstreamInstanceId = health.upstream?.instanceId;
return { info: remoteInfo, startedByClient: false };
Expand Down Expand Up @@ -551,19 +552,6 @@ export function attachSessionAddressHints(
settings: DaemonClientSettings,
): DaemonResponse {
if (!response.ok) {
if (
settings.remoteBaseUrl &&
response.error.details?.reason === 'fill_record_as_requires_armed_recording'
) {
return {
...response,
error: {
...response.error,
message:
'fill --record-as requires an armed script recording, but remote clients cannot start one. Connect to a local daemon, start a fresh session with open --save-script, then retry the fill, or omit --record-as.',
},
};
}
return settings.ownedStateDir && isHeldRepairDivergence(response)
? attachRepairSessionAddressHint(response, settings.paths.baseDir)
: response;
Expand Down
6 changes: 3 additions & 3 deletions packages/daemon-client/src/daemon-client-rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export function handleDaemonHttpResponseBody(
);
return;
}
void resolveDaemonHttpResult(info, req, parsed.result, host, resolve, reject);
void resolveDaemonHttpResult(info, req, parsed.result, { host, stateDir }, resolve, reject);
} catch (err) {
reject(
new AppError(
Expand Down Expand Up @@ -155,14 +155,14 @@ async function resolveDaemonHttpResult(
info: DaemonInfo,
req: DaemonWireRequest,
result: DaemonResponse,
host: HostEnvironment,
client: { host: HostEnvironment; stateDir: string },
resolve: (response: DaemonResponse | PromiseLike<DaemonResponse>) => void,
reject: (error: unknown) => void,
): Promise<void> {
try {
resolve(
info.baseUrl && result.ok
? await materializeRemoteArtifacts(info, req, result, host)
? await materializeRemoteArtifacts(info, req, result, client.host, client.stateDir)
: result,
);
} catch (error) {
Expand Down
Loading
Loading