Repository navigation
Expand file tree
/
Copy pathdaemon-launch-spec.ts
More file actions
206 lines (191 loc) · 8.82 KB
/
Copy pathdaemon-launch-spec.ts
File metadata and controls
206 lines (191 loc) · 8.82 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
import fs from 'node:fs';
import path from 'node:path';
import { AppError } from '@agent-device/kernel/errors';
import {
DAEMON_SOURCE_ENTRY,
findProjectRoot,
isNewerVersion,
readVersion,
} from '@agent-device/host-kit/version';
import { createTtlMemo } from '@agent-device/kernel/ttl-memo';
import {
computeDaemonCodeSignature,
resolveDaemonCodeOrigin,
} from '@agent-device/host-kit/code-signature';
import type { DaemonInfo } from './daemon-client-metadata.ts';
export type DaemonLaunchSpec = {
root: string;
distPath: string;
distPaths: string[];
srcPath: string;
useSrc: boolean;
};
// Which entry this client launches cannot change under it: a source client
// stays a source client whatever a concurrent build produces, and the paths
// themselves are derived from the project root. So the ~8 existence probes run
// once per process, cleared between tests by the shared process-memo reset.
const launchSpecMemo = createTtlMemo<'local', DaemonLaunchSpec>();
/** Which daemon entry this client would launch, and the root it belongs to. */
export function resolveDaemonLaunchSpec(): DaemonLaunchSpec {
const memoized = launchSpecMemo.get('local');
if (memoized) return memoized;
const root = findProjectRoot();
const distPaths = [
path.join(root, 'dist', 'src', 'internal', 'daemon.js'),
path.join(root, 'dist', 'src', 'daemon.js'),
];
const defaultDistPath = distPaths[0];
if (defaultDistPath === undefined) {
throw new AppError('COMMAND_FAILED', 'Daemon dist path list is empty');
}
const distPath = distPaths.find((candidate) => fs.existsSync(candidate)) ?? defaultDistPath;
const srcPath = path.join(root, DAEMON_SOURCE_ENTRY);
const hasDist = distPaths.some((candidate) => fs.existsSync(candidate));
const hasSrc = fs.existsSync(srcPath);
if (!hasDist && !hasSrc) {
throw new AppError('COMMAND_FAILED', 'Daemon entry not found', { distPaths, srcPath });
}
const runningFromSource = process.execArgv.includes('--experimental-strip-types');
const useSrc = runningFromSource ? hasSrc : !hasDist && hasSrc;
const spec: DaemonLaunchSpec = { root, distPath, distPaths, srcPath, useSrc };
launchSpecMemo.set('local', spec);
return spec;
}
/**
* What this tree would launch a daemon from, and what it can prove about that code.
*
* An installed tree carries no fingerprint at all, on purpose. Its bytes change on
* install and not on edit, and every install of one published version is the same
* artifact, so the version is the whole of the identity it can offer: `size:mtime`
* cannot be a fingerprint of it, because an installer stamps a fresh mtime on every
* file and two installs of identical bytes would then sign differently and replace
* each other's daemon — live session with it (#2458). A source checkout is the tree
* whose code moves under a version that does not, so it keeps a fingerprint.
*/
export type LocalDaemonCodeIdentity =
| { origin: 'installed' }
| { origin: 'checkout'; codeSignature: string };
/**
* This tree's answer, read afresh on every call.
*
* A dist entry is a bundle of ~120 chunks and walks in ~5ms; a source checkout's graph
* — ~1,500 modules once the workspace packages the daemon imports by specifier are
* counted — costs tens of milliseconds and goes through the stat-validated cache
* (`code-signature-cache.ts`), which replays the identical signature from `statSync`
* alone. That cache loads on demand, which is why this is async: only the checkout arm
* can reach it, and a static import would put it and its atomic-publish dependency in
* the startup closure of every client that cannot use it (`eager-closure-budgets.ts`).
*
* Deliberately NOT memoized, unlike the launch spec above: a long-lived client (the
* MCP server) must still notice a daemon rebuilt underneath it, and the cache is what
* makes re-answering that question per request cheap.
*/
export async function resolveLocalDaemonCodeIdentity(): Promise<LocalDaemonCodeIdentity> {
const launchSpec = resolveDaemonLaunchSpec();
const origin = resolveDaemonCodeOrigin(launchSpec.root);
if (origin === 'installed') return { origin };
if (!launchSpec.useSrc) {
return {
origin,
codeSignature: computeDaemonCodeSignature(launchSpec.distPath, launchSpec.root),
};
}
const { resolveCachedDaemonCodeSignature } =
await import('@agent-device/host-kit/code-signature-cache');
return {
origin,
codeSignature: await resolveCachedDaemonCodeSignature(launchSpec.srcPath, launchSpec.root),
};
}
/**
* Why a daemon is not the one this client would use. `transport` means alive but not on the
* transport this client uses: the ladder only ever answers `unreachable` for it, and a caller that
* must not kill a live daemon refines it with `observeLocalDaemon`.
*/
export type DaemonTakeoverCause = 'version' | 'code' | 'transport' | 'unreachable';
/** What to do with the daemon already running on this state directory. */
export type DaemonTakeoverDecision =
| { kind: 'reuse' }
| { kind: 'replace'; reason: string; cause: DaemonTakeoverCause }
| { kind: 'refuseNewer'; daemonVersion: string; clientVersion: string };
/**
* Reuse needs the daemon on the transport this client will route through; refusal needs only
* proof that the daemon is alive, on any transport its metadata advertises. A client whose
* transport preference the daemon does not serve must still see a live newer daemon.
*/
export type DaemonReachability = {
/** Asked last, only once version and code identity leave the decision to it. */
onClientTransport: () => Promise<boolean>;
onAnyAdvertisedTransport: () => Promise<boolean>;
};
/**
* One ladder decides reuse, replace, or refuse, so a daemon can never be reused and announced as
* replaced, or replaced without a reason to print. The version answers first because it is cheap
* and decides alone for the common pair of installed trees; the code identity
* (`resolveCodeIdentityMismatch`) answers next and unreachability last.
*
* A live daemon NEWER than this client is neither reused nor replaced: it was started by a
* newer install that may still own live sessions, and an older binary that a package manager
* hoisted onto PATH must not kill it under that install. An unreachable newer daemon is dead and
* replaced like any version mismatch.
*/
export async function resolveDaemonTakeover(
info: DaemonInfo,
reachability: DaemonReachability,
): Promise<DaemonTakeoverDecision> {
const clientVersion = readVersion();
if (info.version !== clientVersion) {
if (
info.version &&
isNewerVersion(info.version, clientVersion) &&
(await reachability.onAnyAdvertisedTransport())
) {
return { kind: 'refuseNewer', daemonVersion: info.version, clientVersion };
}
return {
kind: 'replace',
reason: `version mismatch (client v${clientVersion})`,
cause: 'version',
};
}
const localIdentity = await resolveLocalDaemonCodeIdentity();
const codeMismatch = resolveCodeIdentityMismatch(localIdentity, info);
if (codeMismatch) return { kind: 'replace', reason: codeMismatch, cause: 'code' };
if (!(await reachability.onClientTransport())) {
return { kind: 'replace', reason: 'unreachable', cause: 'unreachable' };
}
return { kind: 'reuse' };
}
/**
* Whether the running daemon holds the code this client would launch, given what each
* side can prove about itself.
*
* The bypass is pairwise, not one-sided: it holds only where BOTH sides are installed,
* because that is the only pair whose shared version already fixes the bytes both run.
* One side cannot vouch for the other — an installed client that reused an unreported
* daemon would run whatever a modified checkout beside it chose to publish under this
* version (#2458). A daemon that predates the field is therefore judged by its
* signature, the rule it was reused under until now, which costs a long-lived state
* directory one takeover after an upgrade.
*
* The two trees rarely meet: a checkout keeps its daemon in a worktree-scoped state
* directory and an installed client in the shared one (`@agent-device/daemon-contracts/daemon-resolution`, same
* test). An explicit `--state-dir` is what puts them together, and that is where this
* pair has to hold.
*/
function resolveCodeIdentityMismatch(
local: LocalDaemonCodeIdentity,
info: DaemonInfo,
): string | undefined {
if (local.origin === 'installed') {
return info.codeOrigin === 'installed' ? undefined : describeCodeOriginMismatch(local, info);
}
if (info.codeOrigin === 'installed') return describeCodeOriginMismatch(local, info);
return info.codeSignature === local.codeSignature ? undefined : 'code-signature mismatch';
}
function describeCodeOriginMismatch(
local: LocalDaemonCodeIdentity,
info: DaemonInfo,
): `code origin mismatch (${string}, client ${string})` {
return `code origin mismatch (daemon ${info.codeOrigin ?? 'unreported'}, client ${local.origin})`;
}