Repository navigation
Expand file tree
/
Copy pathdaemon-client.ts
More file actions
561 lines (533 loc) · 21.2 KB
/
Copy pathdaemon-client.ts
File metadata and controls
561 lines (533 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
import type { RequestProgressSink } from '@agent-device/contracts/progress';
import type {
DaemonRequest as SharedDaemonRequest,
DaemonResponse as SharedDaemonResponse,
} from '../daemon/daemon-request.ts';
import type { AgentDeviceDaemonTransportContext } from '@agent-device/contracts/client';
import { AppError } from '@agent-device/kernel/errors';
import {
createRequestId,
emitDiagnostic,
withDiagnosticTimer,
} from '@agent-device/host-kit/diagnostics';
import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog';
import { resolveCommandTimeoutPolicy } from '@agent-device/command-registry/registry';
import { resolveCommandRequestTimeoutMs } from '@agent-device/command-registry/timeout-policy';
import { prepareRemoteRequestArtifacts } from '../remote/daemon-artifacts.ts';
import { isRemoteDaemon } from './daemon-client-metadata.ts';
import {
leaseScopeFromRequest,
leaseScopeToRequestMeta,
type LeaseScope,
} from '@agent-device/contracts/lease-scope';
import {
attachActiveSessionAddressHint,
attachRepairSessionAddressHint,
cleanupDaemonAfterRequest,
ensureDaemon,
isActiveReplaySessionResponse,
isHeldRepairDivergence,
resolveClientSettings,
type DaemonClientSettings,
type EnsuredDaemon,
} from './daemon-client-lifecycle.ts';
import { sendRequest } from './daemon-client-transport.ts';
export type DaemonRequest = SharedDaemonRequest;
export type DaemonResponse = SharedDaemonResponse;
type DaemonTransportOptions = AgentDeviceDaemonTransportContext & {
onProgress?: RequestProgressSink;
};
export async function sendToDaemon(
req: Omit<DaemonRequest, 'token'>,
options: DaemonTransportOptions = {},
): Promise<DaemonResponse> {
const requestId = req.meta?.requestId ?? createRequestId();
const debug = Boolean(req.meta?.debug || req.flags?.verbose);
// A few internal callers build DaemonRequest directly instead of using the
// public client flag builder. Defend this transport boundary too: credentials
// belong in the auth channel, never in serializable request flags.
const rawFlags = req.flags as
| (NonNullable<typeof req.flags> & { daemonAuthToken?: string })
| undefined;
const { daemonAuthToken: flagAuthToken, ...flags } = rawFlags ?? {};
const requestWithoutAuthFlag = rawFlags ? { ...req, flags } : req;
const settings = resolveClientSettings(
requestWithoutAuthFlag,
options.authToken ?? flagAuthToken,
);
const requestTimeoutMs = resolveCommandRequestTimeoutMs(
resolveCommandTimeoutPolicy(requestWithoutAuthFlag.command),
requestWithoutAuthFlag,
);
const daemon = await withDiagnosticTimer(
'daemon_startup',
async () => await ensureDaemon(settings),
{ requestId, session: req.session },
);
const info = daemon.info;
const preparedRemoteRequest = await runProtectedLeaseWork({
heartbeat: buildUploadLeaseHeartbeat(info, settings, requestWithoutAuthFlag),
task: (signal) => prepareRemoteRequestArtifacts(requestWithoutAuthFlag, info, signal),
});
writeInstallInProgressNotice(requestWithoutAuthFlag.command);
const request = buildTransportRequest(
requestWithoutAuthFlag,
preparedRemoteRequest,
info.token,
requestId,
debug,
);
emitDiagnostic({
level: 'info',
phase: 'daemon_request_prepare',
data: {
requestId,
command: requestWithoutAuthFlag.command,
session: requestWithoutAuthFlag.session,
},
});
return await performDaemonRequestWithCleanup(
requestWithoutAuthFlag,
daemon,
settings,
async () => {
const response = await withDiagnosticTimer(
'daemon_request',
async () =>
await sendRequest(
info,
request,
settings.transportPreference,
settings.paths,
requestTimeoutMs,
options.onProgress ? { onProgress: options.onProgress } : undefined,
),
{ requestId, command: req.command },
);
return withActiveSessionAddressHint(
withRepairSessionAddressHintIfOwned(response, settings),
requestWithoutAuthFlag,
settings,
);
},
);
}
function buildTransportRequest(
request: Omit<DaemonRequest, 'token'>,
preparedRemoteRequest: Awaited<ReturnType<typeof prepareRemoteRequestArtifacts>>,
token: string,
requestId: string,
debug: boolean,
): DaemonRequest {
return {
...request,
positionals: preparedRemoteRequest.positionals,
flags: preparedRemoteRequest.flags,
token,
meta: buildTransportRequestMeta(request, preparedRemoteRequest, requestId, debug),
};
}
function buildTransportRequestMeta(
request: Omit<DaemonRequest, 'token'>,
preparedRemoteRequest: Awaited<ReturnType<typeof prepareRemoteRequestArtifacts>>,
requestId: string,
debug: boolean,
): NonNullable<DaemonRequest['meta']> {
const meta = request.meta ?? {};
return {
...meta,
requestId,
debug,
...buildRequestScopeMeta(meta, request.flags),
...buildRemoteArtifactMeta(preparedRemoteRequest),
};
}
function buildRequestScopeMeta(
meta: NonNullable<DaemonRequest['meta']>,
flags: DaemonRequest['flags'],
): Pick<
NonNullable<DaemonRequest['meta']>,
| 'includeCost'
| 'cwd'
| 'sessionExplicit'
| 'tenantId'
| 'runId'
| 'leaseId'
| 'sessionIsolation'
| 'lockPolicy'
| 'lockPlatform'
> {
return {
includeCost: meta.includeCost,
cwd: meta.cwd,
sessionExplicit: meta.sessionExplicit,
tenantId: meta.tenantId ?? flags?.tenant,
runId: meta.runId ?? flags?.runId,
leaseId: meta.leaseId ?? flags?.leaseId,
sessionIsolation: meta.sessionIsolation ?? flags?.sessionIsolation,
lockPolicy: meta.lockPolicy,
lockPlatform: meta.lockPlatform,
};
}
function buildRemoteArtifactMeta(
preparedRemoteRequest: Awaited<ReturnType<typeof prepareRemoteRequestArtifacts>>,
): Pick<
NonNullable<DaemonRequest['meta']>,
'uploadedArtifactId' | 'clientArtifactPaths' | 'installSource'
> {
return {
...(preparedRemoteRequest.uploadedArtifactId
? { uploadedArtifactId: preparedRemoteRequest.uploadedArtifactId }
: {}),
...(preparedRemoteRequest.clientArtifactPaths
? { clientArtifactPaths: preparedRemoteRequest.clientArtifactPaths }
: {}),
...(preparedRemoteRequest.installSource
? { installSource: preparedRemoteRequest.installSource }
: {}),
};
}
/**
* ADR 0012 decision 6 (BLOCKER 2, third follow-up): runs `send` and ALWAYS
* runs cleanup afterward, using cleanup's result (not `send`'s raw result) as
* the response the caller actually receives — cleanup can discover a
* shutdown-time repair-commit failure the request itself never knew about (a
* one-shot repair that completed with no divergence returns SUCCESS
* immediately; the actual commit is deferred to daemon teardown, which
* `cleanupDaemonAfterRequest` triggers and inspects). A caught-and-rethrown
* error (rather than a `return` inside `finally`, which oxlint's
* `no-unsafe-finally` rejects and which would also make a thrown `send`
* failure silently swallowed by a later `return`) keeps cleanup running
* unconditionally while a thrown failure still propagates normally afterward.
*/
async function performDaemonRequestWithCleanup(
req: Omit<DaemonRequest, 'token'>,
daemon: EnsuredDaemon,
settings: DaemonClientSettings,
send: () => Promise<DaemonResponse>,
): Promise<DaemonResponse> {
let response: DaemonResponse | undefined;
let requestFailed = false;
let requestError: unknown;
try {
response = await send();
} catch (error) {
requestFailed = true;
requestError = error;
}
const finalResponse = await cleanupDaemonAfterRequest(req, daemon, settings, response);
if (requestFailed) throw requestError;
if (!finalResponse) {
// Unreachable in practice: `requestFailed` is false here, so `response`
// was successfully set above, and `cleanupDaemonAfterRequest` always
// returns a response (unchanged or overridden) when given one.
throw new AppError('COMMAND_FAILED', 'Daemon request produced no response after cleanup');
}
return finalResponse;
}
/**
* ADR 0012 decision 6 (Fix 1): the owned ephemeral state dir this daemon was
* started at is otherwise unaddressable by a later invocation — hint it here,
* only when the daemon is actually being kept alive for it
* (`settings.ownedStateDir` means `daemon.startedByClient` is also true).
*/
function withRepairSessionAddressHintIfOwned(
response: DaemonResponse,
settings: DaemonClientSettings,
): DaemonResponse {
if (response.ok || !settings.ownedStateDir || !isHeldRepairDivergence(response)) {
return response;
}
return attachRepairSessionAddressHint(response, settings.paths.baseDir);
}
/**
* ADR 0016 counterpart to `withRepairSessionAddressHintIfOwned` — but unlike
* that one, NOT gated on `settings.ownedStateDir`. An owned ephemeral state
* dir is unaddressable by a later invocation either way, so it's included
* when owned; an explicit `--state-dir`/`AGENT_DEVICE_STATE_DIR` caller
* already knows their own dir, so it's omitted then. But the session's own
* name is cwd-qualified and, per #1394, `session list` cannot rediscover it
* either — so `--session` is still worth hinting even at an explicit state
* dir, which is why this runs for every active-session response regardless
* of `ownedStateDir` (`attachActiveSessionAddressHint` itself decides what,
* if anything, is worth attaching).
*/
function withActiveSessionAddressHint(
response: DaemonResponse,
req: Omit<DaemonRequest, 'token'>,
settings: DaemonClientSettings,
): DaemonResponse {
if (!response.ok || !isActiveReplaySessionResponse(req, response)) {
return response;
}
return attachActiveSessionAddressHint(
response,
settings.ownedStateDir ? settings.paths.baseDir : undefined,
);
}
/**
* The cadence a long client-side phase beats on before it has learned the lease's own window.
*
* The first beat answers with the window the daemon just renewed, and from then on the phase beats a
* third of that window. This constant only covers the gap until that answer lands, and the phase
* when the caller overrides it.
*/
const LEASE_HEARTBEAT_INTERVAL_MS = 20_000;
/**
* The floor for a window-derived cadence.
*
* A lease admitted with the registry's minimum five-second window beats every 1.6s at one third of
* its window; the floor keeps a misreported or pathologically short window from turning the beat
* into a request loop against the daemon it is trying to stay admitted to.
*/
const MIN_LEASE_BEAT_INTERVAL_MS = 1_000;
/** Why a beat stopped protecting the lease: the lease is gone, so nothing else is worth waiting for. */
const LOST_LEASE_BEAT_REASONS: ReadonlySet<unknown> = new Set([
'LEASE_NOT_FOUND',
'LEASE_EXPIRED',
'LEASE_REVOKED',
'LEASE_SESSION_MISMATCH',
]);
/**
* Why a beat stopped protecting the lease even though the lease may live on: this client's request
* will never be the one that renews it.
*
* A beat refused for a missing or mismatched owner scope is a fact about the request, not the
* lease, so every successor is refused identically. Surviving it would only spend the upload against
* a lease that stops renewing — the #2946 failure with extra steps.
*/
const UNRENEWABLE_LEASE_BEAT_REASONS: ReadonlySet<unknown> = new Set([
'LEASE_SCOPE_REQUIRED',
'LEASE_SCOPE_MISMATCH',
]);
/**
* Whether a beat failed for a reason every successor will repeat: the lease is gone, or the daemon
* refused a fact baked into the beat itself. A beat's scope and ttl never change across the phase,
* so an `INVALID_ARGS` refusal — an out-of-range ttl, an unusable lease id — is terminal without
* waiting out the window it can no longer renew.
*/
function isTerminalLeaseBeatError(error: unknown): boolean {
return (
error instanceof AppError &&
(LOST_LEASE_BEAT_REASONS.has(error.details?.reason) ||
UNRENEWABLE_LEASE_BEAT_REASONS.has(error.details?.reason) ||
error.code === 'INVALID_ARGS')
);
}
/**
* Runs one client-side phase under a lease it does not own the clock of.
*
* A lease renews when a request is admitted, and the daemon protects a lease while ADMITTED work
* runs on it (#2509, ADR 0007). An artifact upload is the mirror image: it happens on the caller's
* side, before the install request that will consume it is admitted, so nothing renews the lease
* while it runs and a large enough artifact expired the lease that was paying for the device it was
* being uploaded to (#2946).
*
* `heartbeat` is the caller's transport decision; `undefined` means there is no lease to protect and
* the phase runs untouched. The first beat is fired immediately rather than one interval in, so a
* lease shorter than that interval is renewed before it can lapse — and a lease already gone is
* found before any bytes move. Each beat answers with the window it just renewed, and the next one
* is armed for a third of that window from the beat that landed: beats never overlap, and a slow
* one delays its successor instead of suppressing every beat after it.
*
* A beat that fails for a reason that says nothing about this lease is reported and survived — one
* lost request must not fail an upload that a later beat will cover. A beat that finds the lease
* gone, or finds this client can never renew it, ends the phase with that error and aborts the
* signal the phase runs under: the device is no longer ours (or was never reachable through this
* request), and the only honest outcome is to say so before the bytes finish.
*/
export async function runProtectedLeaseWork<T>(
options: Readonly<{
heartbeat: (() => Promise<unknown>) | undefined;
intervalMs?: number;
task: (signal: AbortSignal) => Promise<T>;
}>,
): Promise<T> {
const { heartbeat } = options;
if (!heartbeat) return await options.task(new AbortController().signal);
const fallbackIntervalMs = options.intervalMs ?? LEASE_HEARTBEAT_INTERVAL_MS;
const control = new AbortController();
let intervalMs = fallbackIntervalMs;
let timer: ReturnType<typeof setTimeout> | undefined;
let stopped = false;
let inFlight: Promise<void> | undefined;
let terminalError: unknown;
let reportTerminal: ((error: unknown) => void) | undefined;
const terminal = new Promise<never>((_, reject) => {
reportTerminal = reject;
});
const runBeat = (): void => {
inFlight = (async () => {
try {
const renewed = leaseWindowFromHeartbeatResponse(await heartbeat());
if (renewed !== undefined) {
intervalMs = Math.max(MIN_LEASE_BEAT_INTERVAL_MS, Math.floor(renewed / 3));
}
} catch (error) {
if (isTerminalLeaseBeatError(error)) {
terminalError = error;
// The upload is the only thing still consuming this phase's time, and it is pointed at a
// device this client can no longer renew. Stop it rather than finish bytes nobody owns.
control.abort();
reportTerminal?.(error);
return;
}
emitDiagnostic({
level: 'warn',
phase: 'lease_heartbeat_failed',
data: { message: error instanceof Error ? error.message : String(error) },
});
}
// A beat that lands after the phase settled must not arm a successor: nothing is left to
// protect, and a beat without a phase to stop it would renew the lease forever.
if (!stopped) timer = setTimeout(runBeat, intervalMs);
})();
};
// Armed before the phase starts, not one interval in: a beat is what proves the lease the upload
// is spending its time on is still alive.
timer = setTimeout(runBeat, 0);
// A beat already in flight when the phase settles can still report a lost lease; the caller reads
// it from `terminalError`, so nothing may be left racing on this rejection by then.
void terminal.catch(() => undefined);
const phase = await captureOutcome(
// The async boundary also turns a synchronous throw from the phase into a rejection, so the
// timer below is always cleared.
(async () => await Promise.race([options.task(control.signal), terminal]))(),
);
stopped = true;
if (timer) clearTimeout(timer);
await inFlight;
// A beat that ended the protection outranks a phase that settled meanwhile, from either side: the
// device is no longer ours, and the lease error is the reason the phase was not worth finishing.
if (terminalError !== undefined) throw terminalError;
if (!phase.ok) throw phase.error;
return phase.value;
}
/**
* The inactivity window a beat just renewed, read from the lease its response carries.
*
* `heartbeatLease` answers with the lease, whose `expiresAt - heartbeatAt` is exactly the window it
* extended — the same pair `leaseOwnTtlMs` renews on. Anything unrecognizable leaves the caller on
* the fallback cadence rather than guessing one.
*/
function leaseWindowFromHeartbeatResponse(response: unknown): number | undefined {
const lease = (
response as Readonly<{ data?: Readonly<{ lease?: Readonly<Record<string, unknown>> }> }>
)?.data?.lease;
const expiresAt = lease?.expiresAt;
const heartbeatAt = lease?.heartbeatAt;
if (typeof expiresAt !== 'number' || typeof heartbeatAt !== 'number') return undefined;
return expiresAt > heartbeatAt ? expiresAt - heartbeatAt : undefined;
}
type Outcome<T> = { ok: true; value: T } | { ok: false; error: unknown };
async function captureOutcome<T>(promise: Promise<T>): Promise<Outcome<T>> {
try {
return { ok: true, value: await promise };
} catch (error) {
return { ok: false, error };
}
}
/**
* The beat that keeps a remote lease alive across a long client-side phase.
*
* `send` is the caller's transport. The beat goes over it directly rather than through the client's
* `leases.heartbeat`, because the client would come back through the upload path it protects.
*/
export function createLeaseRenewalBeat(
leaseScope: LeaseScope,
context: Readonly<{
session: string;
sessionIsolation?: NonNullable<DaemonRequest['meta']>['sessionIsolation'];
token: string;
send: (request: DaemonRequest) => Promise<unknown>;
}>,
): () => Promise<unknown> {
return async () =>
await context.send(
buildLeaseHeartbeatRequest(leaseScope, {
session: context.session,
sessionIsolation: context.sessionIsolation,
requestId: createRequestId(),
token: context.token,
}),
);
}
/**
* The request one beat sends: the command's lease scope, its own id, and nothing else.
*
* It is a fresh request rather than the install rewritten, so nothing about the upload — its source,
* its positional, its own request id — can be mistaken for the lease's state. The scope rides along
* as the command named it, so a beat renews for whatever window that command asked for, and for the
* lease's own window when it named none, which is the ordinary case for an install. Each beat gets a
* fresh id because a beat that times out is canceled under its own, and a shared id would let a later
* beat inherit an earlier cancellation.
*/
export function buildLeaseHeartbeatRequest(
leaseScope: LeaseScope,
context: Readonly<{
session: string;
sessionIsolation?: NonNullable<DaemonRequest['meta']>['sessionIsolation'];
requestId: string;
token: string;
}>,
): DaemonRequest {
return {
command: INTERNAL_COMMANDS.leaseHeartbeat,
positionals: [],
session: context.session,
token: context.token,
meta: {
...leaseScopeToRequestMeta(leaseScope),
sessionIsolation: context.sessionIsolation,
requestId: context.requestId,
},
};
}
/** The lease a request is running under, when it names one. */
export function leaseScopeForHeartbeat(
request: Pick<DaemonRequest, 'flags' | 'meta'>,
): LeaseScope | undefined {
const scope = leaseScopeFromRequest(request);
return scope.leaseId ? scope : undefined;
}
/**
* The beat that renews a remote lease across an artifact upload, or `undefined` when there is no
* lease to protect: only a remote daemon uploads, so only one can be waiting on a billed device, and
* a command that names no lease has nothing to renew.
*
* Exported for its own coverage: `sendToDaemon` calls it once per upload, and the beat cadence is
* far too slow for an end-to-end test to reach it at real transport speed.
*/
export function buildUploadLeaseHeartbeat(
info: EnsuredDaemon['info'],
settings: DaemonClientSettings,
request: Omit<DaemonRequest, 'token'>,
): (() => Promise<unknown>) | undefined {
if (!isRemoteDaemon(info)) return undefined;
const leaseScope = leaseScopeForHeartbeat(request);
if (!leaseScope) return undefined;
const timeoutMs = resolveCommandRequestTimeoutMs(
resolveCommandTimeoutPolicy(INTERNAL_COMMANDS.leaseHeartbeat),
{ positionals: [] },
);
return createLeaseRenewalBeat(leaseScope, {
session: request.session,
sessionIsolation: request.meta?.sessionIsolation,
token: info.token,
send: async (beat) =>
await sendRequest(info, beat, settings.transportPreference, settings.paths, timeoutMs),
});
}
function writeInstallInProgressNotice(command: string | undefined): void {
if (!isInstallLikeCommand(command) || process.stderr.isTTY !== true || process.env.CI) return;
process.stderr.write(
command === PUBLIC_COMMANDS.reinstall ? 'Reinstalling...\n' : 'Installing...\n',
);
}
function isInstallLikeCommand(command: string | undefined): boolean {
return (
command === PUBLIC_COMMANDS.install ||
command === PUBLIC_COMMANDS.reinstall ||
command === INTERNAL_COMMANDS.installSource
);
}