Repository navigation
Expand file tree
/
Copy pathdaemon-client-ensuring.ts
More file actions
100 lines (96 loc) · 4 KB
/
Copy pathdaemon-client-ensuring.ts
File metadata and controls
100 lines (96 loc) · 4 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
import { AppError } from '@agent-device/kernel/errors';
import type { DaemonIdentity, EnsureDaemonOptions } from '@agent-device/contracts/client';
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
import type { sendToDaemon } from './daemon-client.ts';
type DaemonTransport = typeof sendToDaemon;
export type EnsuringTransportOptions = {
/**
* Called when ensuring replaced a daemon: an `incompatible` one that held no work, or an
* `unreachable` one that answered nothing.
*/
onReplaced?: (replaced: {
stateDir: string;
previous: DaemonIdentity;
reason: 'incompatible' | 'unreachable';
}) => void;
};
/**
* Makes a transport explicit about the daemon: the first request that needs a local daemon calls
* `ensureDaemon`, and every request then attaches to what it left. The CLI and MCP use this, so
* neither starts a daemon implicitly or replaces one that holds another client's work.
*
* Ensuring waits for the first request rather than the first call, so a command that never reaches
* the daemon starts none. A remote connection, and a one-shot replay on its own private daemon, pass
* through untouched: neither has a shared local daemon to ensure.
*
* A request that attaches to a daemon that has since gone ensures it again and runs once more; it
* never reached a daemon, so nothing can run twice.
*/
export function withEnsuredDaemon(
transport: DaemonTransport,
options: EnsuringTransportOptions = {},
): DaemonTransport {
const ensured = new Map<string, Promise<unknown>>();
return async (req, context) => {
// Loaded on the first request: the lifecycle module is not part of what every CLI start pays for.
const { resolveEnsurableDaemon } = await import('./daemon-client-lifecycle.ts');
const target = resolveEnsurableDaemon(req);
if (!target) return await transport(req, context);
const stateDir = resolveDaemonPaths(
target.stateDir ?? process.env.AGENT_DEVICE_STATE_DIR,
).baseDir;
// A caller that has already given up starts nothing: attaching refuses before any connection.
if (context?.signal?.aborted) {
return await transport(req, { ...context, daemonLifecycle: 'attach' });
}
// Settled promises are not kept: a failed ensure is retried by the next request, and a daemon
// that went away is ensured again.
const ensure = async (): Promise<{ relied: Promise<unknown> }> => {
let pending = ensured.get(stateDir);
if (!pending) {
const started = ensureLocalDaemon(target, stateDir, options);
pending = started;
ensured.set(stateDir, started);
started.catch(() => {
if (ensured.get(stateDir) === started) ensured.delete(stateDir);
});
}
await pending;
return { relied: pending };
};
const { relied } = await ensure();
const attach = async () => await transport(req, { ...context, daemonLifecycle: 'attach' });
try {
return await attach();
} catch (error) {
// The daemon this invocation ensured is gone (idle reap, a crash, another client's stop).
// An attach that finds none sent nothing, so ensuring again and sending once is safe.
if (!(error instanceof AppError) || error.details?.reason !== 'daemon-not-running')
throw error;
// Only the promise this attach relied on is dropped: a concurrent request may already have
// replaced it with a fresh one.
if (ensured.get(stateDir) === relied) ensured.delete(stateDir);
await ensure();
return await attach();
}
};
}
async function ensureLocalDaemon(
target: EnsureDaemonOptions,
stateDir: string,
options: EnsuringTransportOptions,
): Promise<void> {
const { ensureDaemon } = await import('./daemon-client-ensure.ts');
await ensureDaemon({
...target,
onStart: (reason, previous) => {
if (previous) {
options.onReplaced?.({
stateDir,
previous,
reason: reason === 'incompatible' ? 'incompatible' : 'unreachable',
});
}
},
});
}