@aisac/cli 0.4.0-beta.2 → 0.4.0-beta.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +115 -10
- package/dist/assets/claude/hooks/context-compaction.ts +17 -5
- package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
- package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
- package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
- package/dist/assets/codex-context-compaction.mjs +243 -5
- package/dist/assets/jev-paid-pilot-terminal.mjs +6 -0
- package/dist/claude-compatibility.mjs +26 -25
- package/dist/claude-observation.mjs +2 -1
- package/dist/cli.mjs +584 -35
- package/dist/codex-compatibility.mjs +48 -2
- package/dist/codex-engineering.mjs +165 -0
- package/dist/codex-hooks.mjs +411 -0
- package/dist/codex-permissions.mjs +67 -34
- package/dist/codex-protocol-fingerprint.json +11 -11
- package/dist/engineering-init.mjs +615 -0
- package/dist/engineering-pack.mjs +259 -23
- package/dist/engineering-scan-pins.json +42 -0
- package/dist/engineering-scan-report.mjs +1274 -0
- package/dist/engineering-scan-tools.mjs +1418 -0
- package/dist/engineering-scan.mjs +1265 -0
- package/dist/extensions-catalog.mjs +373 -0
- package/dist/extensions-cli.mjs +492 -0
- package/dist/extensions-preferences.mjs +151 -0
- package/dist/guardrails/continuity.mjs +239 -0
- package/dist/guardrails/format.mjs +111 -0
- package/dist/guardrails/guards.mjs +449 -0
- package/dist/guardrails/patch.mjs +33 -0
- package/dist/guardrails/run.mjs +286 -0
- package/dist/guardrails/shell-words.mjs +206 -0
- package/dist/guardrails-plugin.mjs +207 -0
- package/dist/launch.mjs +278 -34
- package/dist/managed-host.mjs +977 -0
- package/dist/mcp-servers.mjs +192 -0
- package/dist/mcp.mjs +10 -2
- package/dist/monitor.mjs +76 -1
- package/dist/package.json +1 -1
- package/dist/platform.mjs +78 -29
- package/dist/release-manifest-public-keys.json +10 -0
- package/dist/release-manifest.json +328 -0
- package/dist/release-manifest.mjs +817 -0
- package/dist/release-settings.mjs +210 -0
- package/dist/self-update.mjs +1036 -0
- package/dist/state.mjs +25 -1
- package/dist/token-guide.mjs +132 -0
- package/dist/update-actions.mjs +442 -0
- package/package.json +1 -1
|
@@ -0,0 +1,977 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Managed hosts (spec aisac-release-manifest FR5, FR8, FR10; ADR-0056 R4).
|
|
4
|
+
*
|
|
5
|
+
* In `managed` mode the client installs the Claude Code version the signed
|
|
6
|
+
* manifest pins under its own state directory, `<state>/hosts/claude/<version>/`,
|
|
7
|
+
* from the manifest's lock set for this platform (`npm ci`, scripts off, npm's
|
|
8
|
+
* integrity check on every tarball), and never touches the user's own `claude`,
|
|
9
|
+
* `~/.claude` or shell profile. Before every launch the copy must print the
|
|
10
|
+
* pinned version and pass the compatibility resolver as `qualified`; anything
|
|
11
|
+
* else falls back to the user's binary (`system`) for that launch with a closed
|
|
12
|
+
* reason, and the launch goes on as it does today. The decision is a pure
|
|
13
|
+
* function; the actions touch only the state directory.
|
|
14
|
+
*
|
|
15
|
+
* Claude Code's npm package is a wrapper: its `bin/claude.exe` is a placeholder
|
|
16
|
+
* that the package's `postinstall` (`install.cjs`, reviewed for R4) replaces with
|
|
17
|
+
* the native binary of the platform package it depends on. With scripts off the
|
|
18
|
+
* client runs that binary where npm unpacked it,
|
|
19
|
+
* `node_modules/<package>-<platform>/claude`, the same file the script would have
|
|
20
|
+
* hard-linked; nothing of the wrapper runs.
|
|
21
|
+
*/
|
|
22
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
23
|
+
import { constants } from 'node:fs';
|
|
24
|
+
import {
|
|
25
|
+
access,
|
|
26
|
+
mkdir,
|
|
27
|
+
mkdtemp,
|
|
28
|
+
readFile,
|
|
29
|
+
readdir,
|
|
30
|
+
rename,
|
|
31
|
+
rm,
|
|
32
|
+
stat,
|
|
33
|
+
writeFile,
|
|
34
|
+
} from 'node:fs/promises';
|
|
35
|
+
import { tmpdir } from 'node:os';
|
|
36
|
+
import { delimiter, dirname, join } from 'node:path';
|
|
37
|
+
import { resolveClaudeCompatibility } from './claude-compatibility.mjs';
|
|
38
|
+
import { resolveNative } from './platform.mjs';
|
|
39
|
+
import { HOST_PACKAGES, PLATFORMS, SEMVER, compareVersions } from './release-manifest.mjs';
|
|
40
|
+
import { HOST_MODE_ENV, isHostMode } from './release-settings.mjs';
|
|
41
|
+
import { ensurePrivateDirectory } from './state.mjs';
|
|
42
|
+
import { acquireFileLock, findNpm, releaseFileLock, safeEnvironment } from './update-actions.mjs';
|
|
43
|
+
|
|
44
|
+
/** `<state>/hosts/<host>/<version>/`: one directory per installed host version (FR5). */
|
|
45
|
+
export const HOSTS_DIRECTORY = 'hosts';
|
|
46
|
+
/** `<state>/hosts/<host>/.lock`: one installer or collector per host at a time (FR5). */
|
|
47
|
+
export const HOST_LOCK_FILE = '.lock';
|
|
48
|
+
/** `<state>/hosts/<host>/npm-cache`: npm's cache for this host's installs, never the user's (FR5); removed with the versions the collector drops. */
|
|
49
|
+
export const HOST_NPM_CACHE_DIRECTORY = 'npm-cache';
|
|
50
|
+
/** An install in progress lives in `<version>.partial` until it is verified (FR5). */
|
|
51
|
+
export const PARTIAL_SUFFIX = '.partial';
|
|
52
|
+
/** A host install is a few hundred MB; past this the download is given up. */
|
|
53
|
+
export const HOST_INSTALL_TIMEOUT_MS = 15 * 60 * 1000;
|
|
54
|
+
/**
|
|
55
|
+
* A host lock older than this is stale whatever its process says (FR5): longer
|
|
56
|
+
* than the install timeout, so a live install never loses its lock to a second
|
|
57
|
+
* launch or to the collector.
|
|
58
|
+
*/
|
|
59
|
+
export const HOST_LOCK_TTL_MS = 20 * 60 * 1000;
|
|
60
|
+
/**
|
|
61
|
+
* After a failed install the launches of the next hour use `system` without
|
|
62
|
+
* trying again (`managed_host_install_deferred`), so an offline machine does not
|
|
63
|
+
* wait for npm at every launch; `--host managed` and a full setup try at once.
|
|
64
|
+
*/
|
|
65
|
+
export const HOST_INSTALL_RETRY_MS = 60 * 60 * 1000;
|
|
66
|
+
/** `<state>/hosts/<host>/install-failure.json`: the last failed install (version, reason, time). */
|
|
67
|
+
export const HOST_INSTALL_FAILURE_FILE = 'install-failure.json';
|
|
68
|
+
export const HOST_VERSION_TIMEOUT_MS = 15_000;
|
|
69
|
+
/** After the install timeout's SIGTERM, an npm still running is killed after this. */
|
|
70
|
+
export const HOST_KILL_GRACE_MS = 10_000;
|
|
71
|
+
/** `aisac claude --host managed|system`: one launch's host mode (FR5). */
|
|
72
|
+
export const HOST_MODE_FLAG = '--host';
|
|
73
|
+
/** The managed host never updates itself or acts on update notices (FR5). */
|
|
74
|
+
export const MANAGED_HOST_ENV = Object.freeze({ DISABLE_AUTOUPDATER: '1', DISABLE_UPDATES: '1' });
|
|
75
|
+
const HOST_LABELS = Object.freeze({ claude: 'Claude Code', codex: 'Codex' });
|
|
76
|
+
const LOCKFILE_VERSION = 3;
|
|
77
|
+
const MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The closed reason codes this module reports (FR10): why a launch runs the
|
|
81
|
+
* `system` host, or that the managed copy is ready.
|
|
82
|
+
*/
|
|
83
|
+
export const MANAGED_HOST_REASONS = Object.freeze([
|
|
84
|
+
'host_mode_system',
|
|
85
|
+
'host_mode_env',
|
|
86
|
+
'host_mode_flag',
|
|
87
|
+
'managed_hosts_disabled',
|
|
88
|
+
'manifest_unavailable',
|
|
89
|
+
'client_below_host_minimum',
|
|
90
|
+
'managed_host_platform_unsupported',
|
|
91
|
+
'managed_host_lock_missing',
|
|
92
|
+
'managed_host_pending',
|
|
93
|
+
'managed_host_busy',
|
|
94
|
+
'managed_host_install_failed',
|
|
95
|
+
'managed_host_install_deferred',
|
|
96
|
+
'managed_host_pin_broken',
|
|
97
|
+
'managed_host_rejected',
|
|
98
|
+
'managed_host_ready',
|
|
99
|
+
]);
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* @typedef {import('./release-manifest.mjs').ResolvedManifest} ResolvedManifest
|
|
103
|
+
* @typedef {import('./release-manifest.mjs').LockEntry} LockEntry
|
|
104
|
+
* @typedef {import('./release-settings.mjs').ReleaseSettings} ReleaseSettings
|
|
105
|
+
* @typedef {import('./release-settings.mjs').HostMode} HostMode
|
|
106
|
+
* @typedef {import('./claude-compatibility.mjs').ClaudeCompatibility} ClaudeCompatibility
|
|
107
|
+
* @typedef {import('./engineering-pack.mjs').PackLocale} PackLocale
|
|
108
|
+
* @typedef {import('./update-actions.mjs').FileLock} FileLock
|
|
109
|
+
* @typedef {import('./update-actions.mjs').LockOptions} LockOptions
|
|
110
|
+
* @typedef {'claude' | 'codex'} HostName
|
|
111
|
+
* @typedef {(typeof MANAGED_HOST_REASONS)[number]} ManagedHostReason
|
|
112
|
+
* @typedef {{ platform: string, arch: string, musl: boolean, translated: boolean }} PlatformInfo
|
|
113
|
+
* @typedef {{ mode: HostMode, reason: ManagedHostReason | null, pinned: string | null,
|
|
114
|
+
* platform: string | null, lock: Record<string, LockEntry> | null, ignoreScripts: boolean,
|
|
115
|
+
* minimumClient: string | null }} HostDecision
|
|
116
|
+
* @typedef {{ host: HostName, settings: ReleaseSettings, env: NodeJS.ProcessEnv, flag: HostMode | null,
|
|
117
|
+
* manifest: ResolvedManifest | null, clientVersion: string | null, platform: string | null }} HostDecisionInput
|
|
118
|
+
* @typedef {{ version: string, reason: ManagedHostReason, at: string }} InstallFailure
|
|
119
|
+
* @typedef {{ npm: string, cwd: string, cache: string, ignoreScripts: boolean, env: NodeJS.ProcessEnv,
|
|
120
|
+
* timeoutMs?: number, killGraceMs?: number }} NpmCiInput
|
|
121
|
+
* @typedef {{ ok: true, directory: string, executable: string, installed: boolean }
|
|
122
|
+
* | { ok: false, reason: 'managed_host_busy' | 'managed_host_install_failed' | 'managed_host_pin_broken' }} InstallResult
|
|
123
|
+
* @typedef {{ root: string, host: HostName, version: string, platform: string,
|
|
124
|
+
* lock: Record<string, LockEntry>, ignoreScripts: boolean, npm: string | null, env: NodeJS.ProcessEnv,
|
|
125
|
+
* locale?: PackLocale, progress?: (line: string) => void, lockOptions?: LockOptions,
|
|
126
|
+
* deps?: Partial<ManagedHostDependencies> }} InstallInput
|
|
127
|
+
* @typedef {{
|
|
128
|
+
* runNpm: (input: NpmCiInput) => Promise<boolean>,
|
|
129
|
+
* readVersion: (executable: string, env: NodeJS.ProcessEnv) => Promise<string>,
|
|
130
|
+
* compatibility: (executable: string, packageRoot: string) => Promise<ClaudeCompatibility>,
|
|
131
|
+
* resolveNative: (name: string, env: NodeJS.ProcessEnv) => string | null,
|
|
132
|
+
* findNpm: (env: NodeJS.ProcessEnv) => string | null,
|
|
133
|
+
* acquireLock: (path: string, options: LockOptions) => Promise<FileLock>,
|
|
134
|
+
* releaseLock: (path: string) => Promise<void>,
|
|
135
|
+
* install: (input: InstallInput) => Promise<InstallResult>,
|
|
136
|
+
* }} ManagedHostDependencies
|
|
137
|
+
* @typedef {{ mode: HostMode, executable: string | null, version: string | null, pinned: string | null,
|
|
138
|
+
* platform: string | null, reason: ManagedHostReason | null, fallback: ManagedHostReason | null,
|
|
139
|
+
* detail: string | null, compatibility: ClaudeCompatibility | null, installed: boolean,
|
|
140
|
+
* directory: string | null }} HostResolution
|
|
141
|
+
* @typedef {{ host: HostName, root: string, packageRoot: string, manifest: ResolvedManifest | null,
|
|
142
|
+
* settings: ReleaseSettings, env: NodeJS.ProcessEnv, flag: HostMode | null, clientVersion: string | null,
|
|
143
|
+
* platform?: string | null, locale?: PackLocale, progress?: (line: string) => void,
|
|
144
|
+
* deps?: Partial<ManagedHostDependencies> }} ResolveInput
|
|
145
|
+
*/
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The lock-set key for this machine (FR5): `<platform>-<arch>` among the four
|
|
149
|
+
* the manifest carries. A musl Linux has no glibc binary to run, and an x64 node
|
|
150
|
+
* under Rosetta 2 runs the arm64 binary, as Claude Code's own installer does.
|
|
151
|
+
* @param {PlatformInfo} info @returns {string | null}
|
|
152
|
+
*/
|
|
153
|
+
export function platformKey(info) {
|
|
154
|
+
if (info.platform === 'linux' && info.musl) return null;
|
|
155
|
+
const arch =
|
|
156
|
+
info.platform === 'darwin' && info.arch === 'x64' && info.translated ? 'arm64' : info.arch;
|
|
157
|
+
const key = `${info.platform}-${arch}`;
|
|
158
|
+
return PLATFORMS.includes(key) ? key : null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** @returns {PlatformInfo} */
|
|
162
|
+
export function currentPlatform() {
|
|
163
|
+
return {
|
|
164
|
+
platform: process.platform,
|
|
165
|
+
arch: process.arch,
|
|
166
|
+
musl: detectMusl(),
|
|
167
|
+
translated: detectTranslation(),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** @returns {string | null} */
|
|
172
|
+
export function currentPlatformKey() {
|
|
173
|
+
return platformKey(currentPlatform());
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** glibc is reported by the process report; its absence on Linux means musl. */
|
|
177
|
+
function detectMusl() {
|
|
178
|
+
if (process.platform !== 'linux') return false;
|
|
179
|
+
try {
|
|
180
|
+
const report = /** @type {{ header?: { glibcVersionRuntime?: unknown } } | undefined} */ (
|
|
181
|
+
process.report?.getReport()
|
|
182
|
+
);
|
|
183
|
+
return report !== undefined && report.header?.glibcVersionRuntime === undefined;
|
|
184
|
+
} catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Rosetta 2: an x64 node on Apple Silicon reports `x64`. */
|
|
190
|
+
function detectTranslation() {
|
|
191
|
+
if (process.platform !== 'darwin' || process.arch !== 'x64') return false;
|
|
192
|
+
const result = spawnSync('/usr/sbin/sysctl', ['-n', 'sysctl.proc_translated'], {
|
|
193
|
+
encoding: 'utf8',
|
|
194
|
+
timeout: 2_000,
|
|
195
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
196
|
+
});
|
|
197
|
+
return !result.error && String(result.stdout ?? '').trim() === '1';
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Take `--host managed|system` out of a launch's arguments (FR5); everything
|
|
202
|
+
* after `--` belongs to the host.
|
|
203
|
+
* @param {string[]} args
|
|
204
|
+
* @returns {{ hostMode: HostMode | null, args: string[] }}
|
|
205
|
+
*/
|
|
206
|
+
export function takeHostFlag(args) {
|
|
207
|
+
/** @type {string[]} */
|
|
208
|
+
const rest = [];
|
|
209
|
+
/** @type {HostMode | null} */
|
|
210
|
+
let hostMode = null;
|
|
211
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
212
|
+
const argument = args[index];
|
|
213
|
+
if (argument === '--') {
|
|
214
|
+
rest.push(...args.slice(index));
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
if (argument === HOST_MODE_FLAG || argument.startsWith(`${HOST_MODE_FLAG}=`)) {
|
|
218
|
+
const value =
|
|
219
|
+
argument === HOST_MODE_FLAG ? args[++index] : argument.slice(HOST_MODE_FLAG.length + 1);
|
|
220
|
+
if (value === undefined || value === '')
|
|
221
|
+
throw new Error(`option_value_required:${HOST_MODE_FLAG}`);
|
|
222
|
+
if (!isHostMode(value)) throw new Error('invalid_host_mode');
|
|
223
|
+
if (hostMode !== null) throw new Error('host_flag_duplicate');
|
|
224
|
+
hostMode = value;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
rest.push(argument);
|
|
228
|
+
}
|
|
229
|
+
return { hostMode, args: rest };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* The FR5 selection as a function: the launch flag, then `AISAC_HOST_MODE=system`,
|
|
234
|
+
* then the stored setting; `managed` then needs a manifest whose signed switch is
|
|
235
|
+
* on, a supported platform, a client at or above the pin's `minimum_client` and a
|
|
236
|
+
* lock set for this platform. Codex arrives with R5.
|
|
237
|
+
* @param {HostDecisionInput} input @returns {HostDecision}
|
|
238
|
+
*/
|
|
239
|
+
export function decideHostMode(input) {
|
|
240
|
+
const { host, settings, env, flag, manifest, clientVersion, platform } = input;
|
|
241
|
+
/** @type {HostDecision} */
|
|
242
|
+
const system = {
|
|
243
|
+
mode: 'system',
|
|
244
|
+
reason: null,
|
|
245
|
+
pinned: manifest?.manifest?.hosts[host].pinned ?? null,
|
|
246
|
+
platform,
|
|
247
|
+
lock: null,
|
|
248
|
+
ignoreScripts: true,
|
|
249
|
+
minimumClient: null,
|
|
250
|
+
};
|
|
251
|
+
if (flag === 'system') return { ...system, reason: 'host_mode_flag' };
|
|
252
|
+
if (env[HOST_MODE_ENV] === 'system') return { ...system, reason: 'host_mode_env' };
|
|
253
|
+
if ((flag ?? settings.hosts[host]) === 'system') return { ...system, reason: 'host_mode_system' };
|
|
254
|
+
if (host !== 'claude') return { ...system, reason: 'managed_host_pending' };
|
|
255
|
+
const document = manifest?.manifest ?? null;
|
|
256
|
+
if (document === null) return { ...system, reason: 'manifest_unavailable' };
|
|
257
|
+
if (document.features.managed_hosts[host] === false)
|
|
258
|
+
return { ...system, reason: 'managed_hosts_disabled' };
|
|
259
|
+
const entry = document.hosts[host];
|
|
260
|
+
const pinned = entry.pinned;
|
|
261
|
+
if (platform === null) return { ...system, reason: 'managed_host_platform_unsupported' };
|
|
262
|
+
const minimumClient = entry.minimum_client[pinned] ?? null;
|
|
263
|
+
// A client whose own version cannot be read counts as below the minimum (closed).
|
|
264
|
+
if (
|
|
265
|
+
minimumClient !== null &&
|
|
266
|
+
(clientVersion === null || compareVersions(clientVersion, minimumClient) < 0)
|
|
267
|
+
)
|
|
268
|
+
return { ...system, reason: 'client_below_host_minimum', minimumClient };
|
|
269
|
+
const version = entry.versions[pinned];
|
|
270
|
+
const lock = version?.platforms[platform]?.lock ?? null;
|
|
271
|
+
if (version === undefined || lock === null)
|
|
272
|
+
return { ...system, reason: 'managed_host_lock_missing', minimumClient };
|
|
273
|
+
return {
|
|
274
|
+
mode: 'managed',
|
|
275
|
+
reason: null,
|
|
276
|
+
pinned,
|
|
277
|
+
platform,
|
|
278
|
+
lock,
|
|
279
|
+
ignoreScripts: version.ignore_scripts,
|
|
280
|
+
minimumClient,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** @param {string} root @param {HostName} host @param {string} version */
|
|
285
|
+
export function hostDirectory(root, host, version) {
|
|
286
|
+
return join(root, HOSTS_DIRECTORY, host, version);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* The binary the launch runs: the platform package's own file, where npm
|
|
291
|
+
* unpacked it (see the module header).
|
|
292
|
+
* @param {string} directory @param {HostName} host @param {string} platform
|
|
293
|
+
*/
|
|
294
|
+
export function managedExecutable(directory, host, platform) {
|
|
295
|
+
return join(directory, 'node_modules', `${HOST_PACKAGES[host]}-${platform}`, host);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The `package.json` and `package-lock.json` (lockfile v3) that make `npm ci`
|
|
300
|
+
* install exactly the manifest's lock set (FR5): the host package and this
|
|
301
|
+
* platform's package, each with the recorded tarball and integrity. The wrapper's
|
|
302
|
+
* other platform packages are not in the lock, so npm neither resolves nor
|
|
303
|
+
* downloads them. An aliased platform package (Codex) is recorded under its real
|
|
304
|
+
* name, as npm writes aliases.
|
|
305
|
+
* @param {HostName} host @param {string} version @param {Record<string, LockEntry>} lock
|
|
306
|
+
*/
|
|
307
|
+
export function lockfileDocuments(host, version, lock) {
|
|
308
|
+
const packageName = HOST_PACKAGES[host];
|
|
309
|
+
const name = `aisac-managed-${host}`;
|
|
310
|
+
const hostEntry = lock[packageName];
|
|
311
|
+
if (hostEntry === undefined) throw new Error('lock_set_without_host');
|
|
312
|
+
/** @type {Record<string, string>} */
|
|
313
|
+
const optionalDependencies = {};
|
|
314
|
+
/** @type {Record<string, Record<string, unknown>>} */
|
|
315
|
+
const packages = {
|
|
316
|
+
'': { name, version: '0.0.0', dependencies: { [packageName]: version } },
|
|
317
|
+
};
|
|
318
|
+
for (const [key, entry] of Object.entries(lock)) {
|
|
319
|
+
if (key === packageName) continue;
|
|
320
|
+
optionalDependencies[key] =
|
|
321
|
+
entry.name !== undefined && entry.name !== key
|
|
322
|
+
? `npm:${entry.name}@${entry.version}`
|
|
323
|
+
: entry.version;
|
|
324
|
+
packages[`node_modules/${key}`] = {
|
|
325
|
+
...(entry.name !== undefined && entry.name !== key ? { name: entry.name } : {}),
|
|
326
|
+
version: entry.version,
|
|
327
|
+
resolved: entry.resolved,
|
|
328
|
+
integrity: entry.integrity,
|
|
329
|
+
optional: true,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
packages[`node_modules/${packageName}`] = {
|
|
333
|
+
version: hostEntry.version,
|
|
334
|
+
resolved: hostEntry.resolved,
|
|
335
|
+
integrity: hostEntry.integrity,
|
|
336
|
+
hasInstallScript: true,
|
|
337
|
+
optionalDependencies,
|
|
338
|
+
};
|
|
339
|
+
return {
|
|
340
|
+
packageJson: {
|
|
341
|
+
name,
|
|
342
|
+
version: '0.0.0',
|
|
343
|
+
private: true,
|
|
344
|
+
dependencies: { [packageName]: version },
|
|
345
|
+
},
|
|
346
|
+
packageLock: {
|
|
347
|
+
name,
|
|
348
|
+
version: '0.0.0',
|
|
349
|
+
lockfileVersion: LOCKFILE_VERSION,
|
|
350
|
+
requires: true,
|
|
351
|
+
packages,
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** @param {string} version @param {string} output The first line of `--version`. */
|
|
357
|
+
export function versionMatches(output, version) {
|
|
358
|
+
const escaped = version.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
|
|
359
|
+
// A pre-release or build suffix (`-beta.1`, `+build`) is another version.
|
|
360
|
+
return new RegExp(`(?:^|[^0-9.])${escaped}(?:[^0-9.+-]|$)`, 'u').test(output.trim());
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** @param {string} path */
|
|
364
|
+
async function isExecutableFile(path) {
|
|
365
|
+
try {
|
|
366
|
+
if (!(await stat(path)).isFile()) return false;
|
|
367
|
+
await access(path, constants.X_OK);
|
|
368
|
+
return true;
|
|
369
|
+
} catch {
|
|
370
|
+
return false;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** The PATH a host subprocess of the client sees: this node first. @param {NodeJS.ProcessEnv} env */
|
|
375
|
+
function pathWithNode(env) {
|
|
376
|
+
const nodeDirectory = dirname(process.execPath);
|
|
377
|
+
const entries = (env.PATH ?? '').split(delimiter).filter((entry) => entry.length > 0);
|
|
378
|
+
return (entries.includes(nodeDirectory) ? entries : [nodeDirectory, ...entries]).join(delimiter);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* `<binary> --version`, bounded and isolated (a temporary HOME and config
|
|
383
|
+
* directory, as the compatibility probes use), first line (FR5 pin check).
|
|
384
|
+
* @param {string} executable @param {NodeJS.ProcessEnv} env
|
|
385
|
+
* @returns {Promise<string>}
|
|
386
|
+
*/
|
|
387
|
+
export async function managedHostVersion(executable, env) {
|
|
388
|
+
const root = await mkdtemp(join(tmpdir(), 'aisac-host-version-'));
|
|
389
|
+
try {
|
|
390
|
+
const home = join(root, 'home');
|
|
391
|
+
const config = join(root, 'config');
|
|
392
|
+
const cwd = join(root, 'cwd');
|
|
393
|
+
await Promise.all(
|
|
394
|
+
[home, config, cwd].map((directory) => mkdir(directory, { recursive: true, mode: 0o700 })),
|
|
395
|
+
);
|
|
396
|
+
/** @type {NodeJS.ProcessEnv} */
|
|
397
|
+
const environment = {
|
|
398
|
+
PATH: [dirname(process.execPath), '/usr/bin', '/bin'].join(delimiter),
|
|
399
|
+
HOME: home,
|
|
400
|
+
CLAUDE_CONFIG_DIR: config,
|
|
401
|
+
CODEX_HOME: config,
|
|
402
|
+
...MANAGED_HOST_ENV,
|
|
403
|
+
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
|
|
404
|
+
NO_COLOR: '1',
|
|
405
|
+
CI: '1',
|
|
406
|
+
...(env.LANG === undefined ? {} : { LANG: env.LANG }),
|
|
407
|
+
};
|
|
408
|
+
const result = spawnSync(executable, ['--version'], {
|
|
409
|
+
cwd,
|
|
410
|
+
env: environment,
|
|
411
|
+
encoding: 'utf8',
|
|
412
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
413
|
+
timeout: HOST_VERSION_TIMEOUT_MS,
|
|
414
|
+
maxBuffer: MAX_VERSION_OUTPUT_BYTES,
|
|
415
|
+
});
|
|
416
|
+
if (result.error || result.status !== 0) return '';
|
|
417
|
+
return (
|
|
418
|
+
String(result.stdout ?? '')
|
|
419
|
+
.split(/\r?\n/u, 1)[0]
|
|
420
|
+
?.trim() ?? ''
|
|
421
|
+
);
|
|
422
|
+
} finally {
|
|
423
|
+
await rm(root, { recursive: true, force: true }).catch(() => undefined);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* `npm ci` in the staging directory (FR5): scripts off unless the manifest says
|
|
429
|
+
* the version's script was reviewed, no audit or progress noise, the client's
|
|
430
|
+
* own cache. The environment is the deny-listed one every npm subprocess of the
|
|
431
|
+
* client gets; the working directory is private, so no project `.npmrc` is read.
|
|
432
|
+
* @param {NpmCiInput} input @returns {Promise<boolean>}
|
|
433
|
+
*/
|
|
434
|
+
export function runNpmCi(input) {
|
|
435
|
+
return new Promise((resolvePromise) => {
|
|
436
|
+
const child = spawn(
|
|
437
|
+
input.npm,
|
|
438
|
+
[
|
|
439
|
+
'ci',
|
|
440
|
+
...(input.ignoreScripts ? ['--ignore-scripts'] : []),
|
|
441
|
+
'--no-audit',
|
|
442
|
+
'--no-fund',
|
|
443
|
+
'--no-progress',
|
|
444
|
+
'--cache',
|
|
445
|
+
input.cache,
|
|
446
|
+
],
|
|
447
|
+
{
|
|
448
|
+
cwd: input.cwd,
|
|
449
|
+
env: { ...safeEnvironment(input.env), PATH: pathWithNode(input.env) },
|
|
450
|
+
stdio: 'ignore',
|
|
451
|
+
},
|
|
452
|
+
);
|
|
453
|
+
// Own timers, unreferenced: spawn's `timeout` only clears on `exit`, which a
|
|
454
|
+
// failed spawn never emits (see update-actions `installClient`). SIGTERM at the
|
|
455
|
+
// timeout; an npm that ignores it is killed after the grace period and the
|
|
456
|
+
// install fails, so a launch never waits past the timeout.
|
|
457
|
+
let settled = false;
|
|
458
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
459
|
+
let timer = null;
|
|
460
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
461
|
+
let killer = null;
|
|
462
|
+
/** @param {boolean} ok */
|
|
463
|
+
const finish = (ok) => {
|
|
464
|
+
if (settled) return;
|
|
465
|
+
settled = true;
|
|
466
|
+
if (timer !== null) clearTimeout(timer);
|
|
467
|
+
if (killer !== null) clearTimeout(killer);
|
|
468
|
+
resolvePromise(ok);
|
|
469
|
+
};
|
|
470
|
+
timer = setTimeout(() => {
|
|
471
|
+
if (child.exitCode === null) child.kill('SIGTERM');
|
|
472
|
+
killer = setTimeout(() => {
|
|
473
|
+
if (child.exitCode === null) child.kill('SIGKILL');
|
|
474
|
+
finish(false);
|
|
475
|
+
}, input.killGraceMs ?? HOST_KILL_GRACE_MS);
|
|
476
|
+
killer.unref();
|
|
477
|
+
}, input.timeoutMs ?? HOST_INSTALL_TIMEOUT_MS);
|
|
478
|
+
timer.unref();
|
|
479
|
+
child.once('error', () => finish(false));
|
|
480
|
+
child.once('close', (code, signal) => finish(signal === null && code === 0));
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* The last failed install under `<state>/hosts/<host>` (FR5), or null when the
|
|
486
|
+
* file is absent or not what this client writes.
|
|
487
|
+
* @param {string} hostRoot @returns {Promise<InstallFailure | null>}
|
|
488
|
+
*/
|
|
489
|
+
export async function readInstallFailure(hostRoot) {
|
|
490
|
+
let text;
|
|
491
|
+
try {
|
|
492
|
+
text = await readFile(join(hostRoot, HOST_INSTALL_FAILURE_FILE), 'utf8');
|
|
493
|
+
} catch {
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
/** @type {unknown} */
|
|
497
|
+
let value;
|
|
498
|
+
try {
|
|
499
|
+
value = JSON.parse(text);
|
|
500
|
+
} catch {
|
|
501
|
+
return null;
|
|
502
|
+
}
|
|
503
|
+
if (typeof value !== 'object' || value === null) return null;
|
|
504
|
+
const { version, reason, at } = /** @type {Record<string, unknown>} */ (value);
|
|
505
|
+
if (typeof version !== 'string' || !SEMVER.test(version)) return null;
|
|
506
|
+
if (
|
|
507
|
+
typeof reason !== 'string' ||
|
|
508
|
+
!MANAGED_HOST_REASONS.includes(/** @type {ManagedHostReason} */ (reason))
|
|
509
|
+
)
|
|
510
|
+
return null;
|
|
511
|
+
if (typeof at !== 'string' || Number.isNaN(Date.parse(at))) return null;
|
|
512
|
+
return { version, reason: /** @type {ManagedHostReason} */ (reason), at };
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** @param {string} hostRoot @param {InstallFailure} failure */
|
|
516
|
+
async function writeInstallFailure(hostRoot, failure) {
|
|
517
|
+
await writeFile(join(hostRoot, HOST_INSTALL_FAILURE_FILE), `${JSON.stringify(failure)}\n`, {
|
|
518
|
+
mode: 0o600,
|
|
519
|
+
}).catch(() => undefined);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** @param {string} hostRoot */
|
|
523
|
+
async function clearInstallFailure(hostRoot) {
|
|
524
|
+
await rm(join(hostRoot, HOST_INSTALL_FAILURE_FILE), { force: true }).catch(() => undefined);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Whether a failed install defers the next attempt (FR5): the same version, less
|
|
529
|
+
* than `HOST_INSTALL_RETRY_MS` ago by this clock. A time in the future (a clock
|
|
530
|
+
* set back) never defers.
|
|
531
|
+
* @param {InstallFailure | null} failure @param {string} version @param {number} [now]
|
|
532
|
+
*/
|
|
533
|
+
export function installDeferred(failure, version, now = Date.now()) {
|
|
534
|
+
if (failure === null || failure.version !== version) return false;
|
|
535
|
+
const age = now - Date.parse(failure.at);
|
|
536
|
+
return age >= 0 && age < HOST_INSTALL_RETRY_MS;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Install the pinned version when it is not there yet (FR5): under the host
|
|
541
|
+
* lock, into `<version>.partial`, from the generated lock files; the staged
|
|
542
|
+
* binary must print the pinned version before the directory is renamed into
|
|
543
|
+
* place (over a `<version>` directory left without its binary, if any). A copy
|
|
544
|
+
* already on disk is only pin-checked; one that prints another version is
|
|
545
|
+
* removed (`managed_host_pin_broken`). Every failure removes the staging
|
|
546
|
+
* directory, records itself for the backoff and leaves the launch to the
|
|
547
|
+
* `system` host; a success clears the record.
|
|
548
|
+
* @param {InstallInput} input @returns {Promise<InstallResult>}
|
|
549
|
+
*/
|
|
550
|
+
export async function installManagedHost(input) {
|
|
551
|
+
const deps = { ...DEFAULT_DEPENDENCIES, ...input.deps };
|
|
552
|
+
const locale = input.locale ?? 'en';
|
|
553
|
+
/** @type {string} */
|
|
554
|
+
let hostRoot;
|
|
555
|
+
try {
|
|
556
|
+
hostRoot = await ensurePrivateDirectory(join(input.root, HOSTS_DIRECTORY, input.host));
|
|
557
|
+
} catch {
|
|
558
|
+
return { ok: false, reason: 'managed_host_install_failed' };
|
|
559
|
+
}
|
|
560
|
+
const lockPath = join(hostRoot, HOST_LOCK_FILE);
|
|
561
|
+
const lock = await deps.acquireLock(lockPath, {
|
|
562
|
+
ttlMs: HOST_LOCK_TTL_MS,
|
|
563
|
+
...(input.lockOptions ?? {}),
|
|
564
|
+
onWait: () => input.progress?.(hostWaitingLine(input.host, locale)),
|
|
565
|
+
});
|
|
566
|
+
if (!lock.acquired)
|
|
567
|
+
return {
|
|
568
|
+
ok: false,
|
|
569
|
+
reason: lock.holder === null ? 'managed_host_install_failed' : 'managed_host_busy',
|
|
570
|
+
};
|
|
571
|
+
const directory = join(hostRoot, input.version);
|
|
572
|
+
const partial = `${directory}${PARTIAL_SUFFIX}`;
|
|
573
|
+
/** @param {'managed_host_install_failed' | 'managed_host_pin_broken'} reason @returns {Promise<InstallResult>} */
|
|
574
|
+
const failed = async (reason) => {
|
|
575
|
+
await writeInstallFailure(hostRoot, {
|
|
576
|
+
version: input.version,
|
|
577
|
+
reason,
|
|
578
|
+
at: new Date().toISOString(),
|
|
579
|
+
});
|
|
580
|
+
return { ok: false, reason };
|
|
581
|
+
};
|
|
582
|
+
/** @param {boolean} installed @param {string} executable @returns {Promise<InstallResult>} */
|
|
583
|
+
const ready = async (installed, executable) => {
|
|
584
|
+
await clearInstallFailure(hostRoot);
|
|
585
|
+
return { ok: true, directory, executable, installed };
|
|
586
|
+
};
|
|
587
|
+
try {
|
|
588
|
+
const executable = managedExecutable(directory, input.host, input.platform);
|
|
589
|
+
if (await isExecutableFile(executable)) {
|
|
590
|
+
if (versionMatches(await deps.readVersion(executable, input.env), input.version))
|
|
591
|
+
return ready(false, executable);
|
|
592
|
+
await rm(directory, { recursive: true, force: true });
|
|
593
|
+
return { ok: false, reason: 'managed_host_pin_broken' };
|
|
594
|
+
}
|
|
595
|
+
if (input.npm === null) return failed('managed_host_install_failed');
|
|
596
|
+
await rm(partial, { recursive: true, force: true });
|
|
597
|
+
await mkdir(partial, { mode: 0o700 });
|
|
598
|
+
const documents = lockfileDocuments(input.host, input.version, input.lock);
|
|
599
|
+
await writeFile(
|
|
600
|
+
join(partial, 'package.json'),
|
|
601
|
+
`${JSON.stringify(documents.packageJson, null, 2)}\n`,
|
|
602
|
+
{
|
|
603
|
+
mode: 0o600,
|
|
604
|
+
},
|
|
605
|
+
);
|
|
606
|
+
await writeFile(
|
|
607
|
+
join(partial, 'package-lock.json'),
|
|
608
|
+
`${JSON.stringify(documents.packageLock, null, 2)}\n`,
|
|
609
|
+
{ mode: 0o600 },
|
|
610
|
+
);
|
|
611
|
+
const cache = await ensurePrivateDirectory(join(hostRoot, HOST_NPM_CACHE_DIRECTORY));
|
|
612
|
+
input.progress?.(hostInstallingLine(input.host, input.version, locale));
|
|
613
|
+
const installed = await deps.runNpm({
|
|
614
|
+
npm: input.npm,
|
|
615
|
+
cwd: partial,
|
|
616
|
+
cache,
|
|
617
|
+
ignoreScripts: input.ignoreScripts,
|
|
618
|
+
env: input.env,
|
|
619
|
+
});
|
|
620
|
+
const staged = managedExecutable(partial, input.host, input.platform);
|
|
621
|
+
if (!installed || !(await isExecutableFile(staged))) {
|
|
622
|
+
await rm(partial, { recursive: true, force: true });
|
|
623
|
+
return failed('managed_host_install_failed');
|
|
624
|
+
}
|
|
625
|
+
if (!versionMatches(await deps.readVersion(staged, input.env), input.version)) {
|
|
626
|
+
await rm(partial, { recursive: true, force: true });
|
|
627
|
+
return failed('managed_host_pin_broken');
|
|
628
|
+
}
|
|
629
|
+
// A `<version>` directory left without its binary (an interrupted removal)
|
|
630
|
+
// would make the rename fail with ENOTEMPTY at every launch: it goes first.
|
|
631
|
+
await rm(directory, { recursive: true, force: true });
|
|
632
|
+
await rename(partial, directory);
|
|
633
|
+
return ready(true, executable);
|
|
634
|
+
} catch {
|
|
635
|
+
await rm(partial, { recursive: true, force: true }).catch(() => undefined);
|
|
636
|
+
return failed('managed_host_install_failed');
|
|
637
|
+
} finally {
|
|
638
|
+
await deps.releaseLock(lockPath);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** @type {ManagedHostDependencies} */
|
|
643
|
+
const DEFAULT_DEPENDENCIES = {
|
|
644
|
+
runNpm: runNpmCi,
|
|
645
|
+
readVersion: managedHostVersion,
|
|
646
|
+
compatibility: resolveClaudeCompatibility,
|
|
647
|
+
resolveNative: (name, env) => resolveNative(name, env),
|
|
648
|
+
findNpm: (env) => findNpm(env, null),
|
|
649
|
+
acquireLock: (path, options) => acquireFileLock(path, options),
|
|
650
|
+
releaseLock: (path) => releaseFileLock(path),
|
|
651
|
+
install: (input) => installManagedHost(input),
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Remove a managed copy the resolver found inconsistent with its pin check (FR5):
|
|
656
|
+
* under the host lock, only when it is free (an install or a collection in
|
|
657
|
+
* progress keeps the directory; the next install's pin check decides). Never
|
|
658
|
+
* throws.
|
|
659
|
+
* @param {string} root @param {HostName} host @param {string} directory
|
|
660
|
+
* @param {ManagedHostDependencies} deps
|
|
661
|
+
*/
|
|
662
|
+
async function removeManagedCopy(root, host, directory, deps) {
|
|
663
|
+
const lockPath = join(root, HOSTS_DIRECTORY, host, HOST_LOCK_FILE);
|
|
664
|
+
const lock = await deps.acquireLock(lockPath, { ttlMs: HOST_LOCK_TTL_MS, waitMs: 0 });
|
|
665
|
+
if (!lock.acquired) return;
|
|
666
|
+
try {
|
|
667
|
+
await rm(directory, { recursive: true, force: true });
|
|
668
|
+
} catch {
|
|
669
|
+
// Left for the next install's pin check.
|
|
670
|
+
} finally {
|
|
671
|
+
await deps.releaseLock(lockPath);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* The one host resolution every call site uses in place of the PATH lookup
|
|
677
|
+
* (FR5): the decision, the install when due, the pin check and the
|
|
678
|
+
* compatibility resolver on the managed copy, or the user's own binary. Never
|
|
679
|
+
* throws for a managed failure: the launch falls back to `system` with the
|
|
680
|
+
* reason in `fallback`.
|
|
681
|
+
* @param {ResolveInput} input @returns {Promise<HostResolution>}
|
|
682
|
+
*/
|
|
683
|
+
export async function resolveHostExecutable(input) {
|
|
684
|
+
const deps = { ...DEFAULT_DEPENDENCIES, ...input.deps };
|
|
685
|
+
const platform = input.platform === undefined ? currentPlatformKey() : input.platform;
|
|
686
|
+
const decision = decideHostMode({
|
|
687
|
+
host: input.host,
|
|
688
|
+
settings: input.settings,
|
|
689
|
+
env: input.env,
|
|
690
|
+
flag: input.flag,
|
|
691
|
+
manifest: input.manifest,
|
|
692
|
+
clientVersion: input.clientVersion,
|
|
693
|
+
platform,
|
|
694
|
+
});
|
|
695
|
+
/** @param {ManagedHostReason | null} fallback @param {string | null} [detail] @returns {HostResolution} */
|
|
696
|
+
const system = (fallback, detail = null) => ({
|
|
697
|
+
mode: 'system',
|
|
698
|
+
executable: deps.resolveNative(input.host, input.env),
|
|
699
|
+
version: null,
|
|
700
|
+
pinned: decision.pinned,
|
|
701
|
+
platform,
|
|
702
|
+
reason: decision.reason,
|
|
703
|
+
fallback,
|
|
704
|
+
detail,
|
|
705
|
+
compatibility: null,
|
|
706
|
+
installed: false,
|
|
707
|
+
directory: null,
|
|
708
|
+
});
|
|
709
|
+
// A `system` decision the user made (the setting, the environment, the flag)
|
|
710
|
+
// is no fallback; one the manifest or this machine forced on a `managed`
|
|
711
|
+
// request is, and the launch says why (FR5).
|
|
712
|
+
if (decision.mode === 'system')
|
|
713
|
+
return system(
|
|
714
|
+
decision.reason === 'host_mode_system' ||
|
|
715
|
+
decision.reason === 'host_mode_env' ||
|
|
716
|
+
decision.reason === 'host_mode_flag'
|
|
717
|
+
? null
|
|
718
|
+
: decision.reason,
|
|
719
|
+
);
|
|
720
|
+
if (decision.lock === null || decision.pinned === null || platform === null)
|
|
721
|
+
return system('managed_host_lock_missing');
|
|
722
|
+
// A failed install this recent is not retried on an ordinary launch (FR5);
|
|
723
|
+
// `--host managed` and a full setup try at once.
|
|
724
|
+
if (input.flag !== 'managed') {
|
|
725
|
+
const failure = await readInstallFailure(join(input.root, HOSTS_DIRECTORY, input.host));
|
|
726
|
+
if (
|
|
727
|
+
failure !== null &&
|
|
728
|
+
installDeferred(failure, decision.pinned) &&
|
|
729
|
+
!(await isExecutableFile(
|
|
730
|
+
managedExecutable(
|
|
731
|
+
hostDirectory(input.root, input.host, decision.pinned),
|
|
732
|
+
input.host,
|
|
733
|
+
platform,
|
|
734
|
+
),
|
|
735
|
+
))
|
|
736
|
+
)
|
|
737
|
+
return system('managed_host_install_deferred', failure.reason);
|
|
738
|
+
}
|
|
739
|
+
/** @type {InstallResult} */
|
|
740
|
+
let install;
|
|
741
|
+
try {
|
|
742
|
+
install = await deps.install({
|
|
743
|
+
root: input.root,
|
|
744
|
+
host: input.host,
|
|
745
|
+
version: decision.pinned,
|
|
746
|
+
platform,
|
|
747
|
+
lock: decision.lock,
|
|
748
|
+
ignoreScripts: decision.ignoreScripts,
|
|
749
|
+
npm: deps.findNpm(input.env),
|
|
750
|
+
env: input.env,
|
|
751
|
+
...(input.locale === undefined ? {} : { locale: input.locale }),
|
|
752
|
+
...(input.progress === undefined ? {} : { progress: input.progress }),
|
|
753
|
+
deps,
|
|
754
|
+
});
|
|
755
|
+
} catch {
|
|
756
|
+
install = { ok: false, reason: 'managed_host_install_failed' };
|
|
757
|
+
}
|
|
758
|
+
if (!install.ok) return system(install.reason);
|
|
759
|
+
/** @type {ClaudeCompatibility} */
|
|
760
|
+
let compatibility;
|
|
761
|
+
try {
|
|
762
|
+
compatibility = await deps.compatibility(install.executable, input.packageRoot);
|
|
763
|
+
} catch {
|
|
764
|
+
return system('managed_host_rejected', 'host_probe_failed');
|
|
765
|
+
}
|
|
766
|
+
if (compatibility.version !== decision.pinned) {
|
|
767
|
+
// The copy printed the pin but the resolver read another version: it goes, and
|
|
768
|
+
// the failure is recorded so ordinary launches do not download it again for an hour.
|
|
769
|
+
await removeManagedCopy(input.root, input.host, install.directory, deps);
|
|
770
|
+
await writeInstallFailure(join(input.root, HOSTS_DIRECTORY, input.host), {
|
|
771
|
+
version: decision.pinned,
|
|
772
|
+
reason: 'managed_host_pin_broken',
|
|
773
|
+
at: new Date().toISOString(),
|
|
774
|
+
});
|
|
775
|
+
return system('managed_host_pin_broken', compatibility.reason);
|
|
776
|
+
}
|
|
777
|
+
if (compatibility.status !== 'qualified')
|
|
778
|
+
return system('managed_host_rejected', compatibility.reason);
|
|
779
|
+
return {
|
|
780
|
+
mode: 'managed',
|
|
781
|
+
executable: compatibility.executable ?? install.executable,
|
|
782
|
+
version: decision.pinned,
|
|
783
|
+
pinned: decision.pinned,
|
|
784
|
+
platform,
|
|
785
|
+
reason: 'managed_host_ready',
|
|
786
|
+
fallback: null,
|
|
787
|
+
detail: null,
|
|
788
|
+
compatibility,
|
|
789
|
+
installed: install.installed,
|
|
790
|
+
directory: install.directory,
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* The managed host's environment (FR5): the user's own, plus the two switches
|
|
796
|
+
* that stop the host from updating itself, and this node first on PATH so the
|
|
797
|
+
* package's shims resolve. `system` launches get neither.
|
|
798
|
+
* @param {NodeJS.ProcessEnv} env @returns {NodeJS.ProcessEnv}
|
|
799
|
+
*/
|
|
800
|
+
export function managedHostEnvironment(env) {
|
|
801
|
+
return { ...env, ...MANAGED_HOST_ENV, PATH: pathWithNode(env) };
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** The versions installed under `<state>/hosts/<host>`, oldest first. @param {string} root @param {HostName} host */
|
|
805
|
+
export async function installedHostVersions(root, host) {
|
|
806
|
+
let entries;
|
|
807
|
+
try {
|
|
808
|
+
entries = await readdir(join(root, HOSTS_DIRECTORY, host), { withFileTypes: true });
|
|
809
|
+
} catch {
|
|
810
|
+
return [];
|
|
811
|
+
}
|
|
812
|
+
return entries
|
|
813
|
+
.filter((entry) => entry.isDirectory() && SEMVER.test(entry.name))
|
|
814
|
+
.map((entry) => entry.name)
|
|
815
|
+
.sort(compareVersions);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Garbage collection after a successful launch (FR5): keep the versions the
|
|
820
|
+
* manifest still carries lock sets for (the pinned one and the one before) and
|
|
821
|
+
* any version a live launch still runs; remove the rest and every staging
|
|
822
|
+
* directory left behind, and with any removal the host's npm cache (it served
|
|
823
|
+
* those installs; a later install downloads again). Skipped, not waited for, when
|
|
824
|
+
* another process holds the host lock, and skipped when `live` cannot be read or
|
|
825
|
+
* returns null (a live launch still resolving its host could run any version).
|
|
826
|
+
* The live versions and the directory are read under the lock, so a launch that
|
|
827
|
+
* names its version between two reads is never collected against. Never throws.
|
|
828
|
+
* @param {{ root: string, host: HostName, keep: readonly string[],
|
|
829
|
+
* live: () => Promise<readonly string[] | null>, deps?: Partial<ManagedHostDependencies> }} input
|
|
830
|
+
* @returns {Promise<string[]>} the directory names removed
|
|
831
|
+
*/
|
|
832
|
+
export async function collectManagedHosts(input) {
|
|
833
|
+
const deps = { ...DEFAULT_DEPENDENCIES, ...input.deps };
|
|
834
|
+
const hostRoot = join(input.root, HOSTS_DIRECTORY, input.host);
|
|
835
|
+
const lockPath = join(hostRoot, HOST_LOCK_FILE);
|
|
836
|
+
const lock = await deps
|
|
837
|
+
.acquireLock(lockPath, { ttlMs: HOST_LOCK_TTL_MS, waitMs: 0 })
|
|
838
|
+
.catch(() => ({ acquired: false, holder: null }));
|
|
839
|
+
if (!lock.acquired) return [];
|
|
840
|
+
/** @type {string[]} */
|
|
841
|
+
const removed = [];
|
|
842
|
+
try {
|
|
843
|
+
const live = await input.live().catch(() => null);
|
|
844
|
+
if (live === null) return removed;
|
|
845
|
+
let entries;
|
|
846
|
+
try {
|
|
847
|
+
entries = await readdir(hostRoot, { withFileTypes: true });
|
|
848
|
+
} catch {
|
|
849
|
+
return removed;
|
|
850
|
+
}
|
|
851
|
+
for (const entry of entries) {
|
|
852
|
+
if (!entry.isDirectory()) continue;
|
|
853
|
+
const partial = entry.name.endsWith(PARTIAL_SUFFIX);
|
|
854
|
+
const version = partial ? entry.name.slice(0, -PARTIAL_SUFFIX.length) : entry.name;
|
|
855
|
+
if (!SEMVER.test(version)) continue;
|
|
856
|
+
if (!partial && (input.keep.includes(version) || live.includes(version))) continue;
|
|
857
|
+
try {
|
|
858
|
+
await rm(join(hostRoot, entry.name), { recursive: true, force: true });
|
|
859
|
+
removed.push(entry.name);
|
|
860
|
+
} catch {
|
|
861
|
+
// Left for a later collection.
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
if (removed.length > 0) {
|
|
865
|
+
const cache = join(hostRoot, HOST_NPM_CACHE_DIRECTORY);
|
|
866
|
+
const present = await stat(cache).then(
|
|
867
|
+
(info) => info.isDirectory(),
|
|
868
|
+
() => false,
|
|
869
|
+
);
|
|
870
|
+
if (present) {
|
|
871
|
+
await rm(cache, { recursive: true, force: true }).catch(() => undefined);
|
|
872
|
+
removed.push(HOST_NPM_CACHE_DIRECTORY);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
} finally {
|
|
876
|
+
await deps.releaseLock(lockPath);
|
|
877
|
+
}
|
|
878
|
+
return removed;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* The `hosts.managed.<host>` doctor section (FR8): the decision this launch
|
|
883
|
+
* would take and the state of the pinned copy on disk, probed when it is there;
|
|
884
|
+
* nothing is installed.
|
|
885
|
+
* @param {Omit<ResolveInput, 'flag' | 'progress' | 'locale'> & { flag?: HostMode | null }} input
|
|
886
|
+
*/
|
|
887
|
+
export async function describeManagedHost(input) {
|
|
888
|
+
const deps = { ...DEFAULT_DEPENDENCIES, ...input.deps };
|
|
889
|
+
const platform = input.platform === undefined ? currentPlatformKey() : input.platform;
|
|
890
|
+
const decision = decideHostMode({
|
|
891
|
+
host: input.host,
|
|
892
|
+
settings: input.settings,
|
|
893
|
+
env: input.env,
|
|
894
|
+
flag: input.flag ?? null,
|
|
895
|
+
manifest: input.manifest,
|
|
896
|
+
clientVersion: input.clientVersion,
|
|
897
|
+
platform,
|
|
898
|
+
});
|
|
899
|
+
const onDisk = await installedHostVersions(input.root, input.host);
|
|
900
|
+
const failure = await readInstallFailure(join(input.root, HOSTS_DIRECTORY, input.host));
|
|
901
|
+
const base = {
|
|
902
|
+
mode: decision.mode,
|
|
903
|
+
reason: decision.reason,
|
|
904
|
+
pinned: decision.pinned,
|
|
905
|
+
platform,
|
|
906
|
+
installed: decision.pinned !== null && onDisk.includes(decision.pinned),
|
|
907
|
+
on_disk: onDisk,
|
|
908
|
+
install_failure: failure,
|
|
909
|
+
/** @type {'ok' | 'broken' | null} */
|
|
910
|
+
pin_check: null,
|
|
911
|
+
/** @type {string | null} */
|
|
912
|
+
resolver: null,
|
|
913
|
+
/** @type {string | null} */
|
|
914
|
+
resolver_reason: null,
|
|
915
|
+
/** @type {string | null} */
|
|
916
|
+
executable: null,
|
|
917
|
+
};
|
|
918
|
+
if (decision.mode !== 'managed' || platform === null || decision.pinned === null) return base;
|
|
919
|
+
const executable = managedExecutable(
|
|
920
|
+
hostDirectory(input.root, input.host, decision.pinned),
|
|
921
|
+
input.host,
|
|
922
|
+
platform,
|
|
923
|
+
);
|
|
924
|
+
if (!(await isExecutableFile(executable))) return { ...base, installed: false };
|
|
925
|
+
/** @type {ClaudeCompatibility} */
|
|
926
|
+
let compatibility;
|
|
927
|
+
try {
|
|
928
|
+
compatibility = await deps.compatibility(executable, input.packageRoot);
|
|
929
|
+
} catch {
|
|
930
|
+
return { ...base, installed: true, pin_check: 'broken', resolver: 'rejected' };
|
|
931
|
+
}
|
|
932
|
+
const pinOk = compatibility.version === decision.pinned;
|
|
933
|
+
return {
|
|
934
|
+
...base,
|
|
935
|
+
installed: true,
|
|
936
|
+
pin_check: pinOk ? 'ok' : 'broken',
|
|
937
|
+
resolver: compatibility.status,
|
|
938
|
+
resolver_reason: compatibility.reason,
|
|
939
|
+
executable:
|
|
940
|
+
pinOk && compatibility.status === 'qualified'
|
|
941
|
+
? (compatibility.executable ?? executable)
|
|
942
|
+
: null,
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/** @param {HostName} host @param {string} version @param {PackLocale} locale */
|
|
947
|
+
export function hostInstallingLine(host, version, locale) {
|
|
948
|
+
const label = HOST_LABELS[host];
|
|
949
|
+
return locale === 'pt-BR'
|
|
950
|
+
? `aisac: instalando o ${label} ${version} na pasta do aisac (algumas centenas de MB, uma vez).`
|
|
951
|
+
: `aisac: installing ${label} ${version} under the aisac directory (a few hundred MB, once).`;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/** @param {HostName} host @param {PackLocale} locale */
|
|
955
|
+
export function hostWaitingLine(host, locale) {
|
|
956
|
+
const label = HOST_LABELS[host];
|
|
957
|
+
return locale === 'pt-BR'
|
|
958
|
+
? `aisac: outro aisac está instalando o ${label}; aguardando.`
|
|
959
|
+
: `aisac: another aisac is installing ${label}; waiting.`;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* One line on stderr when a managed launch falls back to the user's binary
|
|
964
|
+
* (FR5): the pinned version when the manifest gave one and the closed reason
|
|
965
|
+
* (the fallback, else the decision's), never a path.
|
|
966
|
+
* @param {HostName} host @param {HostResolution} resolution @param {PackLocale} locale
|
|
967
|
+
*/
|
|
968
|
+
export function hostFallbackLine(host, resolution, locale) {
|
|
969
|
+
const label = HOST_LABELS[host];
|
|
970
|
+
const reason = `${resolution.fallback ?? resolution.reason ?? 'managed_host_install_failed'}${
|
|
971
|
+
resolution.detail === null ? '' : `: ${resolution.detail}`
|
|
972
|
+
}`;
|
|
973
|
+
const version = resolution.pinned === null ? '' : ` ${resolution.pinned}`;
|
|
974
|
+
return locale === 'pt-BR'
|
|
975
|
+
? `aisac: ${label} gerenciado${version} indisponível (${reason}); usando o ${host} do sistema nesta sessão.`
|
|
976
|
+
: `aisac: managed ${label}${version} unavailable (${reason}); using the system ${host} for this session.`;
|
|
977
|
+
}
|