Skip to content

Commit b2e2c8f

Browse files
committed
feat(cli): replace cloud connection profiles with hosted session leases
1 parent 6e0c761 commit b2e2c8f

43 files changed

Lines changed: 3776 additions & 915 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/adr/0007-remote-device-leases.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@ Hosted devices can continue to incur charges after their daemon stops.
1414

1515
A remote device lease gives one client logical ownership of a selected device for a connection provider.
1616
The daemon is authoritative for admission, ownership, and session lifetime.
17-
`connect` establishes client identity and a connection profile. Allocation is lazy, when the device, backend, and provider are known.
17+
`connect` establishes client identity and a connection profile for direct providers. Allocation is lazy, when the device, backend, and provider are known.
1818
`open` is the natural acquisition point.
1919
Runner and process locks remain separate backend guards.
2020

21+
For `connect cloud`, the hosted session API owns the device rental. The CLI asks it to allocate during connect so it can enforce the session deadline and return a scoped attachment. The CLI records the allocation identity before attaching. It can recover an interrupted allocation or end the rental without a live daemon. The daemon retains authority over the requests it receives.
22+
2123
The proxy token authenticates the host, not the client: every client of one proxy can hold the same token.
2224
The lease id is the credential that proves ownership of a leased session.
2325
A request on a session that holds a lease must send that lease's id. The daemon refuses a request that omits it with `LEASE_SESSION_MISMATCH` and never fills it from the session.

‎packages/command-registry/src/flag-definitions-connection.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,46 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
437437
projectConfig: true,
438438
recorded: false,
439439
},
440+
{
441+
key: 'vendor',
442+
names: ['--vendor'],
443+
type: 'string',
444+
usageLabel: '--vendor <id>',
445+
usageDescription: 'Connect cloud: choose a device vendor',
446+
projectConfig: false,
447+
recorded: false,
448+
},
449+
{
450+
key: 'maxMinutes',
451+
names: ['--max-minutes'],
452+
type: 'int',
453+
min: 1,
454+
max: Number.MAX_SAFE_INTEGER,
455+
usageLabel: '--max-minutes <minutes>',
456+
usageDescription: 'Connect cloud: request a maximum session duration in minutes',
457+
projectConfig: false,
458+
recorded: false,
459+
},
460+
461+
{
462+
key: 'needs',
463+
names: ['--needs'],
464+
type: 'string',
465+
usageLabel: '--needs <capability,...>',
466+
usageDescription: 'Connect cloud: require each of these comma-separated capabilities',
467+
projectConfig: false,
468+
recorded: false,
469+
},
470+
471+
{
472+
key: 'showViewer',
473+
names: ['--show-viewer'],
474+
type: 'boolean',
475+
usageLabel: '--show-viewer',
476+
usageDescription: 'Connect cloud: print the private live viewer link',
477+
projectConfig: false,
478+
recorded: false,
479+
},
440480
{
441481
key: 'live',
442482
names: ['--live'],

‎packages/command-surface/src/schema/command-overrides.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,14 @@ const CONNECT_ALLOWED_FLAGS = [
4343
...LEASE_DEVICE_SPEC_FLAGS,
4444
'force',
4545
'noLogin',
46+
'vendor',
47+
'maxMinutes',
48+
'needs',
49+
'showViewer',
4650
] as const;
51+
52+
const CONNECT_LIST_FLAGS = ['live', 'stateDir', 'daemonAuthToken'] as const;
53+
4754
const CONNECT_SUPPORTED_FLAGS = [
4855
'stateDir',
4956
'daemonAuthToken',
@@ -54,7 +61,6 @@ const CONNECT_SUPPORTED_FLAGS = [
5461
...CONNECT_METRO_HINT_FLAGS,
5562
'launchUrl',
5663
] as const;
57-
const CONNECT_LIST_FLAGS = ['live', 'stateDir', 'daemonAuthToken'] as const;
5864

5965
const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
6066
plugins: {
@@ -125,14 +131,14 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
125131
text: {
126132
summary: 'Configure remote or provider state',
127133
description:
128-
'List cloud vendors or configure remote access without allocating a device. Direct providers validate credentials/resources before saving state and print the exact device/app preparation needed before open. AGENT_DEVICE_CLOUD_BASE_URL is the bridge/control-plane API origin; use AGENT_DEVICE_DAEMON_AUTH_TOKEN=adc_live_... for CI/service-token automation.',
134+
'List cloud vendors, start a cloud session, or configure remote access. Direct providers validate credentials/resources before saving state and print the exact device/app preparation needed before open. AGENT_DEVICE_CLOUD_BASE_URL is the cloud session API origin; use AGENT_DEVICE_DAEMON_AUTH_TOKEN=adc_live_... for CI/service-token automation.',
129135
},
130136
usageOverride:
131-
'connect list [--live] [--json] | connect [provider] [--remote-config <path>] [--daemon-base-url <url>] [--tenant <id>] [--run-id <id>] [--lease-id <id>] [--lease-backend <backend>] [--force] [--no-login]',
137+
'connect list [--live] [--json] | connect [provider] [--remote-config <path>] [--daemon-base-url <url>] [--tenant <id>] [--run-id <id>] [--lease-id <id>] [--lease-backend <backend>] [--force] [--no-login] [--vendor <id>] [--max-minutes <minutes>] [--needs <capability,...>] [--device <model>] [--os <version>] [--show-viewer]',
132138
usageFlags: [],
133139
listUsageOverride: 'connect',
134140
positionalArgs: ['list|provider?'],
135-
allowedFlags: [...CONNECT_ALLOWED_FLAGS, 'live'],
141+
allowedFlags: [...CONNECT_ALLOWED_FLAGS, ...CONNECT_LIST_FLAGS],
136142
supportedFlags: CONNECT_SUPPORTED_FLAGS,
137143
flagsByAction: {
138144
cloud: [...CONNECT_ALLOWED_FLAGS, ...CONNECT_SUPPORTED_FLAGS],
@@ -156,7 +162,7 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
156162
},
157163
listUsageOverride: 'disconnect',
158164
allowedFlags: ['shutdown'],
159-
supportedFlags: ['remoteConfig', 'stateDir', 'session'],
165+
supportedFlags: ['remoteConfig', 'stateDir', 'session', 'daemonAuthToken'],
160166
},
161167
mcp: {
162168
text: {

‎packages/contracts/src/cli-flags.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ export type CliFlags = CloudProviderProfileFields &
5656
force?: boolean;
5757
clean?: boolean;
5858
noLogin?: boolean;
59+
vendor?: string;
60+
maxMinutes?: number;
61+
needs?: string;
62+
showViewer?: boolean;
5963
live?: boolean;
6064
kind?: string;
6165
perfTemplate?: string;

‎packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,42 @@ test('concurrent first requests share one ensure through the CLI and MCP transpo
318318
}
319319
});
320320

321+
test('a failed attach checks admission again before restarting the daemon', async () => {
322+
const { stateDir } = stateDirAndPaths();
323+
let admitted = false;
324+
let closing = false;
325+
const ensure = vi.spyOn(ensureModule, 'ensureDaemon').mockImplementation(async () => {
326+
assert.equal(admitted, true);
327+
return undefined as never;
328+
});
329+
const send = vi.fn(async () => {
330+
assert.equal(admitted, false);
331+
closing = true;
332+
throw daemonNotRunningError(stateDir);
333+
});
334+
const ensuring = withEnsuredDaemon(send, {
335+
admit: async (start) => {
336+
if (closing) {
337+
throw new AppError('COMMAND_FAILED', 'Connection closed.', { reason: 'connection_closed' });
338+
}
339+
admitted = true;
340+
try {
341+
return await start();
342+
} finally {
343+
admitted = false;
344+
}
345+
},
346+
});
347+
348+
await assert.rejects(ensuring(request('open', { stateDir })), (error: unknown) => {
349+
assert.ok(error instanceof AppError);
350+
assert.equal(error.details?.reason, 'connection_closed');
351+
return true;
352+
});
353+
assert.equal(ensure.mock.calls.length, 1);
354+
assert.equal(send.mock.calls.length, 1);
355+
});
356+
321357
test('a request canceled before it starts does not start a daemon', async (t) => {
322358
if (await skipWhenLoopbackUnavailable(t)) return;
323359
const { stateDir, paths } = stateDirAndPaths();

‎packages/daemon-client/src/daemon-client-ensuring.ts‎

Lines changed: 29 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
11
import type { DaemonIdentity, EnsureDaemonOptions } from '@agent-device/contracts/client';
22
import type { HostEnvironment } from '@agent-device/kernel/source-value';
33
import { captureHostEnvironment } from '@agent-device/host-kit/environment';
4-
import { createRequestCanceledError } from '@agent-device/kernel/errors';
4+
import { createRequestGuard } from './daemon-client-transport.ts';
55
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
66
import type { DaemonTransport } from './daemon-client-request.ts';
77
import { isDaemonNotRunningError } from './daemon-lifecycle-errors.ts';
88

99
export type EnsuringTransportOptions = {
1010
/** The host the ensured daemon is resolved and started from; the process's own when omitted. */
1111
host?: HostEnvironment;
12+
/** Controls local daemon startup and the request's final transport handoff. */
13+
admit?: <T>(
14+
start: () => Promise<T>,
15+
phase: 'startup' | 'dispatch',
16+
req: Parameters<DaemonTransport>[0],
17+
) => Promise<T>;
1218
/**
1319
* Called when ensuring replaced a daemon: an `incompatible` one that held no work, or an
1420
* `unreachable` one that answered nothing.
@@ -41,16 +47,29 @@ export function withEnsuredDaemon(
4147
// Loaded on the first request: the lifecycle module is not part of what every CLI start pays for.
4248
const { resolveEnsurableDaemon } = await import('./daemon-client-lifecycle.ts');
4349
const host = options.host ?? captureHostEnvironment(process);
50+
const { admit } = options;
51+
const transportContext: Parameters<DaemonTransport>[1] = admit
52+
? { ...context, dispatch: (send) => admit(send, 'dispatch', req) }
53+
: context;
4454
const target = resolveEnsurableDaemon(req, host);
45-
if (!target) return await transport(req, context);
55+
if (!target) {
56+
await admit?.(async () => {}, 'startup', req);
57+
return await transport(req, transportContext);
58+
}
4659
const stateDir = resolveDaemonPaths(target.stateDir, { env: host.env, cwd: host.cwd }).baseDir;
4760
// A caller that has already given up starts nothing: attaching refuses before any connection.
4861
if (context?.signal?.aborted) {
4962
return await transport(req, context);
5063
}
64+
const admissionGuard = createRequestGuard({
65+
signal: context?.signal,
66+
requestId: req.meta?.requestId,
67+
dispatchedOnAbort: 'no',
68+
});
5169
// A finished ensure is kept for the rest of this transport's life. A rejected one is dropped so
5270
// the next request retries, and one whose daemon has since gone is dropped by the attach below.
5371
const ensure = async (): Promise<{ relied: Promise<unknown> }> => {
72+
admissionGuard.refuseIfAborted();
5473
let pending = ensured.get(stateDir);
5574
if (!pending) {
5675
const started = ensureLocalDaemon(target, stateDir, host, options);
@@ -60,11 +79,15 @@ export function withEnsuredDaemon(
6079
if (ensured.get(stateDir) === started) ensured.delete(stateDir);
6180
});
6281
}
63-
await settleUnlessAborted(pending, context?.signal, req.meta?.requestId);
82+
await pending;
6483
return { relied: pending };
6584
};
66-
const { relied } = await ensure();
67-
const attach = async () => await transport(req, context);
85+
// Cancellation ends the caller's wait. A startup already in progress must finish before
86+
// admission releases the connection lock.
87+
const admitAndEnsure = () =>
88+
admissionGuard.guard(() => (admit ? admit(ensure, 'startup', req) : ensure()));
89+
const { relied } = await admitAndEnsure();
90+
const attach = async () => await transport(req, transportContext);
6891
try {
6992
return await attach();
7093
} catch (error) {
@@ -74,44 +97,12 @@ export function withEnsuredDaemon(
7497
// Only the promise this attach relied on is dropped: a concurrent request may already have
7598
// replaced it with a fresh one.
7699
if (ensured.get(stateDir) === relied) ensured.delete(stateDir);
77-
await ensure();
100+
await admitAndEnsure();
78101
return await attach();
79102
}
80103
};
81104
}
82105

83-
/**
84-
* Waits for a shared ensure on behalf of one request. An abort settles only this request, with
85-
* nothing sent (`dispatched: 'no'`): the ensure keeps running, because concurrent requests share it
86-
* and stopping a daemon launch half way would leave its state directory undecided.
87-
*/
88-
async function settleUnlessAborted(
89-
pending: Promise<unknown>,
90-
signal: AbortSignal | undefined,
91-
requestId: string | undefined,
92-
): Promise<void> {
93-
if (!signal) {
94-
await pending;
95-
return;
96-
}
97-
const canceled = () => createRequestCanceledError({ requestId, dispatched: 'no' }, signal.reason);
98-
if (signal.aborted) throw canceled();
99-
await new Promise<void>((resolve, reject) => {
100-
const onAbort = (): void => reject(canceled());
101-
signal.addEventListener('abort', onAbort, { once: true });
102-
pending.then(
103-
() => {
104-
signal.removeEventListener('abort', onAbort);
105-
resolve();
106-
},
107-
(error: unknown) => {
108-
signal.removeEventListener('abort', onAbort);
109-
reject(error);
110-
},
111-
);
112-
});
113-
}
114-
115106
async function ensureLocalDaemon(
116107
target: EnsureDaemonOptions,
117108
stateDir: string,

‎packages/daemon-client/src/daemon-client-request.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,31 @@ import type { AgentDeviceDaemonTransportContext } from '@agent-device/contracts/
55

66
export type DaemonRequest = DaemonWireRequest;
77
export type DaemonResponse = SharedDaemonResponse;
8+
export type DaemonDispatch = <T>(send: () => Promise<T>) => Promise<T>;
9+
810
export type DaemonTransportOptions = AgentDeviceDaemonTransportContext & {
911
onProgress?: RequestProgressSink;
12+
/** Runs the synchronous request handoff while the caller's admission is held. */
13+
dispatch?: DaemonDispatch;
1014
};
1115

1216
/** What a client sends one daemon request through. */
1317
export type DaemonTransport = (
1418
req: Omit<DaemonRequest, 'token'>,
1519
options?: DaemonTransportOptions,
1620
) => Promise<DaemonResponse>;
21+
22+
/** Keeps admission through handoff and releases it while the daemon processes the request. */
23+
export async function dispatchDaemonRequest<T>(
24+
dispatch: DaemonDispatch | undefined,
25+
send: () => T | Promise<T>,
26+
): Promise<T> {
27+
if (!dispatch) return await send();
28+
const { result } = await dispatch(async () => {
29+
const result = send();
30+
// A transport can reject before admission finishes releasing its lock.
31+
if (result instanceof Promise) void result.catch(() => {});
32+
return { result };
33+
});
34+
return await result;
35+
}

0 commit comments

Comments
 (0)