@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.
Files changed (47) hide show
  1. package/README.md +115 -10
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +243 -5
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +6 -0
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +584 -35
  11. package/dist/codex-compatibility.mjs +48 -2
  12. package/dist/codex-engineering.mjs +165 -0
  13. package/dist/codex-hooks.mjs +411 -0
  14. package/dist/codex-permissions.mjs +67 -34
  15. package/dist/codex-protocol-fingerprint.json +11 -11
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +259 -23
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/extensions-catalog.mjs +373 -0
  23. package/dist/extensions-cli.mjs +492 -0
  24. package/dist/extensions-preferences.mjs +151 -0
  25. package/dist/guardrails/continuity.mjs +239 -0
  26. package/dist/guardrails/format.mjs +111 -0
  27. package/dist/guardrails/guards.mjs +449 -0
  28. package/dist/guardrails/patch.mjs +33 -0
  29. package/dist/guardrails/run.mjs +286 -0
  30. package/dist/guardrails/shell-words.mjs +206 -0
  31. package/dist/guardrails-plugin.mjs +207 -0
  32. package/dist/launch.mjs +278 -34
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/mcp-servers.mjs +192 -0
  35. package/dist/mcp.mjs +10 -2
  36. package/dist/monitor.mjs +76 -1
  37. package/dist/package.json +1 -1
  38. package/dist/platform.mjs +78 -29
  39. package/dist/release-manifest-public-keys.json +10 -0
  40. package/dist/release-manifest.json +328 -0
  41. package/dist/release-manifest.mjs +817 -0
  42. package/dist/release-settings.mjs +210 -0
  43. package/dist/self-update.mjs +1036 -0
  44. package/dist/state.mjs +25 -1
  45. package/dist/token-guide.mjs +132 -0
  46. package/dist/update-actions.mjs +442 -0
  47. package/package.json +1 -1
package/dist/state.mjs CHANGED
@@ -272,11 +272,22 @@ export async function readConfig(rootOverride) {
272
272
  * @param {unknown} value
273
273
  */
274
274
  export async function atomicJson(path, value) {
275
+ await atomicBytes(path, Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8'));
276
+ }
277
+
278
+ /**
279
+ * Replace one owned file with exact bytes (`0600`), atomically. The existing
280
+ * file is left intact if the temporary write fails. Used for documents whose
281
+ * bytes are signed and must be kept as received (the release manifest cache).
282
+ * @param {string} path
283
+ * @param {Uint8Array} bytes
284
+ */
285
+ export async function atomicBytes(path, bytes) {
275
286
  await assertSafePath(dirname(path), false);
276
287
  await assertSafePath(path);
277
288
  const temp = `${path}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
278
289
  try {
279
- await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
290
+ await writeFile(temp, bytes, { mode: 0o600, flag: 'wx' });
280
291
  await chmod(temp, 0o600);
281
292
  await rename(temp, path);
282
293
  } catch (error) {
@@ -285,6 +296,19 @@ export async function atomicJson(path, value) {
285
296
  }
286
297
  }
287
298
 
299
+ /**
300
+ * Create, or confirm, one private subdirectory (`0700`, owned, no symlinked
301
+ * ancestor) under an owned state root.
302
+ * @param {string} path
303
+ */
304
+ export async function ensurePrivateDirectory(path) {
305
+ await assertSafePath(path);
306
+ await mkdir(path, { recursive: true, mode: 0o700 });
307
+ await chmod(path, 0o700);
308
+ await assertSafePath(path, false);
309
+ return path;
310
+ }
311
+
288
312
  /** @param {string} token */
289
313
  export async function tokenDigest(token) {
290
314
  return createHash('sha256').update(token, 'utf8').digest('hex');
@@ -0,0 +1,132 @@
1
+ // Step-by-step guidance for obtaining an AI Brain PAT during `aisac setup`.
2
+ // Spec aibrain-subscriber-beta § Setup step 3: guide users to the existing
3
+ // dashboard token flow instead of failing with a bare error code. The text
4
+ // never contains the token or any account data; the URL is the endpoint origin.
5
+
6
+ const DEFAULT_DASHBOARD = 'https://mcp.ai-brain.aisac.cloud';
7
+
8
+ /** @typedef {'pt-BR' | 'en'} GuideLocale */
9
+
10
+ /** Setup failures that mean "you need a (different) token", mapped to a reason key. */
11
+ const TOKEN_FAILURES = Object.freeze({
12
+ empty_token: 'empty',
13
+ token_file_required_in_noninteractive_mode: 'noninteractive',
14
+ 'provider_free_probe_failed:mcp_auth_denied': 'denied',
15
+ 'provider_free_probe_failed:mcp_paid_plan_required': 'unlicensed',
16
+ });
17
+
18
+ /**
19
+ * Setup failures that are not about the token but have one usual cause worth
20
+ * naming. `INVALID_INPUT` from the probe is almost always a system clock that
21
+ * is ahead of the server (the server rejects `observed_at` more than 30 s in
22
+ * the future); WSL2 drifts after a sleep.
23
+ */
24
+ const SETUP_HINTS = Object.freeze({
25
+ 'provider_free_probe_failed:mcp_invalid_input': 'clock',
26
+ });
27
+
28
+ const TEXT = Object.freeze({
29
+ 'pt-BR': {
30
+ intro: 'O aisac precisa de um token pessoal (PAT) do seu AI Brain.',
31
+ missing: 'Não tem um? Gere em um minuto:',
32
+ login: (/** @type {string} */ url) =>
33
+ ` 1. Abra ${url} e entre com o MESMO e-mail usado na compra\n (chega um código de 6 dígitos). A licença fica vinculada a esse e-mail.`,
34
+ label:
35
+ ' 2. No painel, dê um rótulo (ex.: meu-mac) e escolha o agente\n (Anthropic para Claude Code, OpenAI para Codex). Isso só organiza a atribuição.',
36
+ generate: ' 3. Clique em "Gerar token" e copie na hora: ele aparece uma única vez.',
37
+ pasteHere: ' 4. Cole abaixo em "AI Brain PAT". A digitação fica oculta.',
38
+ rerun: ' 4. Rode `aisac setup` de novo e cole o token em "AI Brain PAT" (fica oculto).',
39
+ safety:
40
+ 'Nunca coloque o token em argumento de comando, arquivo do repositório ou perfil do shell.',
41
+ support: 'Se o e-mail da compra não entrar ou não tiver a licença, fale com o suporte AISAC.',
42
+ reasons: {
43
+ empty: 'Nenhum token foi informado.',
44
+ noninteractive:
45
+ 'Sem um terminal interativo, o token precisa vir de `--token-file` (um arquivo privado, modo 600).',
46
+ denied:
47
+ 'O AI Brain recusou este token: ele está incompleto, foi revogado ou não existe. Gere um novo.',
48
+ unlicensed:
49
+ 'Este token pertence a uma conta sem a licença. Gere o token entrando com o e-mail usado na compra.',
50
+ },
51
+ hints: {
52
+ clock:
53
+ 'O AI Brain recusou a sondagem como entrada inválida (INVALID_INPUT). Causa mais comum: o relógio do sistema está adiantado em relação ao servidor; no WSL2 isso acontece depois de suspender o computador. Acerte o relógio (ex.: `sudo hwclock -s` ou reinicie o WSL) e rode `aisac setup` de novo. O token não precisa mudar.',
54
+ },
55
+ },
56
+ en: {
57
+ intro: 'aisac needs a personal access token (PAT) from your AI Brain.',
58
+ missing: "Don't have one? Create it in a minute:",
59
+ login: (/** @type {string} */ url) =>
60
+ ` 1. Open ${url} and sign in with the SAME email you used to buy\n (a 6-digit code arrives by email). The license is tied to that email.`,
61
+ label:
62
+ ' 2. In the dashboard, enter a label (e.g. my-mac) and pick the agent\n (Anthropic for Claude Code, OpenAI for Codex). It only organizes attribution.',
63
+ generate: ' 3. Click "Gerar token" and copy it right away: it is shown only once.',
64
+ pasteHere: ' 4. Paste it below at "AI Brain PAT". Typing stays hidden.',
65
+ rerun: ' 4. Run `aisac setup` again and paste the token at "AI Brain PAT" (hidden).',
66
+ safety: 'Never put the token in command arguments, a repository file or a shell profile.',
67
+ support: 'If the purchase email cannot sign in or has no license, contact AISAC support.',
68
+ reasons: {
69
+ empty: 'No token was entered.',
70
+ noninteractive:
71
+ 'Without an interactive terminal the token must come from `--token-file` (a private file, mode 600).',
72
+ denied:
73
+ 'AI Brain rejected this token: it is incomplete, revoked or unknown. Create a new one.',
74
+ unlicensed:
75
+ 'This token belongs to an account without the license. Create the token signed in with the purchase email.',
76
+ },
77
+ hints: {
78
+ clock:
79
+ 'AI Brain rejected the probe as invalid input (INVALID_INPUT). Most common cause: the system clock is ahead of the server; on WSL2 this happens after the computer sleeps. Fix the clock (e.g. `sudo hwclock -s` or restart WSL) and run `aisac setup` again. The token does not need to change.',
80
+ },
81
+ },
82
+ });
83
+
84
+ /** The dashboard origin derived from an https endpoint, else the production dashboard. @param {string} endpoint */
85
+ export function dashboardUrl(endpoint) {
86
+ try {
87
+ const url = new URL(endpoint);
88
+ return url.protocol === 'https:' ? url.origin : DEFAULT_DASHBOARD;
89
+ } catch {
90
+ return DEFAULT_DASHBOARD;
91
+ }
92
+ }
93
+
94
+ /** @param {GuideLocale} locale @param {string} endpoint @param {'prompt' | 'rerun'} step */
95
+ function steps(locale, endpoint, step) {
96
+ const text = TEXT[locale];
97
+ return [
98
+ text.intro,
99
+ text.missing,
100
+ text.login(dashboardUrl(endpoint)),
101
+ text.label,
102
+ text.generate,
103
+ step === 'prompt' ? text.pasteHere : text.rerun,
104
+ text.safety,
105
+ ].join('\n');
106
+ }
107
+
108
+ /** Guidance printed right before the masked PAT prompt. @param {GuideLocale} locale @param {string} endpoint */
109
+ export function tokenPromptGuide(locale, endpoint) {
110
+ return steps(locale, endpoint, 'prompt');
111
+ }
112
+
113
+ /**
114
+ * One-paragraph hint for a setup failure with a usual non-token cause, or null.
115
+ * @param {string} code @param {GuideLocale} locale
116
+ */
117
+ export function setupFailureHint(code, locale) {
118
+ const hint = /** @type {Record<string, keyof typeof TEXT.en.hints>} */ (SETUP_HINTS)[code];
119
+ return hint === undefined ? null : TEXT[locale].hints[hint];
120
+ }
121
+
122
+ /**
123
+ * Guidance for a setup failure caused by a missing, rejected or unlicensed token,
124
+ * or null when the failure has another cause.
125
+ * @param {string} code @param {GuideLocale} locale @param {string} endpoint
126
+ */
127
+ export function tokenFailureGuide(code, locale, endpoint) {
128
+ const reason = /** @type {Record<string, keyof typeof TEXT.en.reasons>} */ (TOKEN_FAILURES)[code];
129
+ if (reason === undefined) return null;
130
+ const text = TEXT[locale];
131
+ return [text.reasons[reason], '', steps(locale, endpoint, 'rerun'), text.support].join('\n');
132
+ }
@@ -0,0 +1,442 @@
1
+ // @ts-check
2
+ /**
3
+ * Self-update actions (spec aisac-release-manifest FR6; ADR-0056 R3): the npm
4
+ * prefix that owns the running client, the writability probe, the private
5
+ * directory npm runs in, the update lock, the npm subprocesses (registry read,
6
+ * install), the installed-version read, the re-exec and the npm lookup. No
7
+ * decision lives here: `self-update.mjs` decides and calls these.
8
+ */
9
+ import { spawn, spawnSync } from 'node:child_process';
10
+ import { accessSync, constants, statSync } from 'node:fs';
11
+ import { link, lstat, open, rename, unlink, writeFile } from 'node:fs/promises';
12
+ import { constants as osConstants } from 'node:os';
13
+ import { basename, dirname, join, resolve } from 'node:path';
14
+ import { stdin } from 'node:process';
15
+ import { processAlive } from './engineering-pack.mjs';
16
+ import { resolveNative } from './platform.mjs';
17
+ import { ensurePrivateDirectory } from './state.mjs';
18
+ import { CLIENT_PACKAGES, RELEASE_STATE_DIRECTORY } from './release-manifest.mjs';
19
+
20
+ /** Set by the parent on re-exec; the child then skips the update step (FR6). */
21
+ export const REEXEC_ENV = 'AISAC_REEXEC';
22
+ /** `<state>/release/update.lock`: one installer at a time, no host launch under one (FR6). */
23
+ export const UPDATE_LOCK_FILE = 'update.lock';
24
+ /** `<state>/release/npm`: where every npm subprocess runs, never the user's directory (FR6). */
25
+ export const NPM_WORKING_DIRECTORY = 'npm';
26
+ /** How long a launch waits for another launcher's update before it refuses to start a host. */
27
+ export const LOCK_WAIT_MS = 2 * 60 * 1000;
28
+ /** A lock older than this is stale whatever its process says (pid reuse). */
29
+ const LOCK_TTL_MS = 15 * 60 * 1000;
30
+ const LOCK_POLL_MS = 250;
31
+ export const INSTALL_TIMEOUT_MS = 5 * 60 * 1000;
32
+ const VIEW_TIMEOUT_MS = 60_000;
33
+ const VERSION_TIMEOUT_MS = 15_000;
34
+ const MAX_RECORD_BYTES = 4 * 1024;
35
+ export const SRI_SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/u;
36
+ const VERSION_OUTPUT = /^(?:aisac|aibrain) (\S+)$/u;
37
+ const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/u;
38
+
39
+ /**
40
+ * @typedef {{ prefix: string, modulesDirectory: string, packageName: string, cliPath: string }} InstallPrefix
41
+ * @typedef {{ npm: string, prefix: InstallPrefix, packageName: string, version: string,
42
+ * env: NodeJS.ProcessEnv, cwd: string }} InstallInput
43
+ * @typedef {{ status: 'ok', integrity: string } | { status: 'unavailable' }} RegistryIntegrity
44
+ * @typedef {{ acquired: true, holder: number } | { acquired: false, holder: number | null }} UpdateLock
45
+ * @typedef {UpdateLock} FileLock
46
+ * @typedef {{ pid: number, at: string }} LockRecord
47
+ * @typedef {{ now?: () => Date, alive?: (pid: number) => boolean, sleep?: (ms: number) => Promise<void>,
48
+ * onWait?: (holder: number) => void, ttlMs?: number, waitMs?: number }} LockOptions
49
+ */
50
+
51
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
52
+ export function isRecord(value) {
53
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
54
+ }
55
+
56
+ /** @param {unknown} value @returns {value is string} */
57
+ export function isInstant(value) {
58
+ return typeof value === 'string' && ISO_INSTANT.test(value);
59
+ }
60
+
61
+ /**
62
+ * The environment a subprocess sees: never the provider keys or a token file.
63
+ * The account token is not in the environment to begin with. A deny-list, not an
64
+ * allow-list: the user's own `~/.npmrc` may expand `${NPM_TOKEN}` for a private
65
+ * registry, and npm fails outright when the variable is missing; the control
66
+ * against a hostile `.npmrc` is the working directory, never the user's.
67
+ * @param {NodeJS.ProcessEnv} env
68
+ */
69
+ export function safeEnvironment(env) {
70
+ /** @type {NodeJS.ProcessEnv} */
71
+ const copy = { ...env };
72
+ delete copy.JEV_API_KEY;
73
+ delete copy.TYPESAFE_API_KEY;
74
+ delete copy.AIBRAIN_TOKEN_FILE;
75
+ return copy;
76
+ }
77
+
78
+ /**
79
+ * The npm prefix that owns the running client, derived from the code's own
80
+ * path: `<prefix>/lib/node_modules/<package>/dist` (the Linux and macOS global
81
+ * layout, FR6). Anything else (a repository checkout, another layout) is
82
+ * unknown, and the client then only prints the command.
83
+ * @param {string} packageRoot The `dist` directory the running `cli.mjs` lives in.
84
+ * @returns {InstallPrefix | null}
85
+ */
86
+ export function installPrefix(packageRoot) {
87
+ const dist = resolve(packageRoot);
88
+ if (basename(dist) !== 'dist') return null;
89
+ let cursor = dirname(dist);
90
+ const segments = [basename(cursor)];
91
+ cursor = dirname(cursor);
92
+ if (basename(cursor).startsWith('@')) {
93
+ segments.unshift(basename(cursor));
94
+ cursor = dirname(cursor);
95
+ }
96
+ const packageName = segments.join('/');
97
+ if (!CLIENT_PACKAGES.includes(packageName)) return null;
98
+ if (basename(cursor) !== 'node_modules') return null;
99
+ const modulesDirectory = cursor;
100
+ cursor = dirname(cursor);
101
+ if (basename(cursor) !== 'lib') return null;
102
+ return { prefix: dirname(cursor), modulesDirectory, packageName, cliPath: join(dist, 'cli.mjs') };
103
+ }
104
+
105
+ /**
106
+ * Whether this user can write into the prefix: an exclusive temporary file in
107
+ * each directory npm writes (`lib/node_modules` for the package, `bin` for the
108
+ * executable link), removed at once. Never `sudo` (FR6).
109
+ * @param {string[]} directories
110
+ */
111
+ export async function prefixWritable(...directories) {
112
+ for (const directory of directories) if (!(await writableDirectory(directory))) return false;
113
+ return directories.length > 0;
114
+ }
115
+
116
+ /** @param {string} directory */
117
+ async function writableDirectory(directory) {
118
+ const probe = join(
119
+ directory,
120
+ `.aisac-update-probe-${process.pid}-${Math.random().toString(16).slice(2)}`,
121
+ );
122
+ /** @type {import('node:fs/promises').FileHandle | undefined} */
123
+ let handle;
124
+ try {
125
+ handle = await open(probe, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
126
+ return true;
127
+ } catch {
128
+ return false;
129
+ } finally {
130
+ await handle?.close().catch(() => undefined);
131
+ await unlink(probe).catch(() => undefined);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * A private state document of bounded size: regular, owned, opened without
137
+ * following symlinks. Null when missing or not ours.
138
+ * @param {string} path @returns {Promise<unknown>}
139
+ */
140
+ export async function readOwnedJson(path) {
141
+ /** @type {import('node:fs/promises').FileHandle | undefined} */
142
+ let handle;
143
+ try {
144
+ const link = await lstat(path);
145
+ if (!link.isFile() || link.size > MAX_RECORD_BYTES) return null;
146
+ if (typeof process.getuid === 'function' && link.uid !== process.getuid()) return null;
147
+ handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
148
+ return JSON.parse(await handle.readFile('utf8'));
149
+ } catch {
150
+ return null;
151
+ } finally {
152
+ await handle?.close().catch(() => undefined);
153
+ }
154
+ }
155
+
156
+ /** @param {string} root The private directory where npm runs (see `registryIntegrity`). */
157
+ export async function npmWorkingDirectory(root) {
158
+ return ensurePrivateDirectory(join(root, RELEASE_STATE_DIRECTORY, NPM_WORKING_DIRECTORY));
159
+ }
160
+
161
+ /** @param {unknown} value @returns {{ pid: number, at: string } | null} */
162
+ function lockRecord(value) {
163
+ if (!isRecord(value) || value.schemaVersion !== 1 || !isInstant(value.at)) return null;
164
+ if (!Number.isSafeInteger(value.pid) || /** @type {number} */ (value.pid) <= 0) return null;
165
+ return { pid: /** @type {number} */ (value.pid), at: value.at };
166
+ }
167
+
168
+ /**
169
+ * The update lock (FR6): one installer at a time, and no host launch while an
170
+ * install runs, since a launch has no marker of its own until its host starts.
171
+ * Created atomically (write, then `link`), it names its holder; a lock whose
172
+ * process is gone, or older than the TTL, is stale and removed. A live lock is
173
+ * waited on, up to `LOCK_WAIT_MS`. `acquired: false` with a holder means the
174
+ * wait ran out; with none, the lock could not be used at all and the caller
175
+ * goes on without it.
176
+ * @param {string} root @param {LockOptions} [options] @returns {Promise<UpdateLock>}
177
+ */
178
+ export async function acquireUpdateLock(root, options = {}) {
179
+ /** @type {string} */
180
+ let directory;
181
+ try {
182
+ directory = await ensurePrivateDirectory(join(root, RELEASE_STATE_DIRECTORY));
183
+ } catch {
184
+ return { acquired: false, holder: null };
185
+ }
186
+ return acquireFileLock(join(directory, UPDATE_LOCK_FILE), options);
187
+ }
188
+
189
+ /** Remove the update lock when this process holds it. Never throws. @param {string} root */
190
+ export async function releaseUpdateLock(root) {
191
+ await releaseFileLock(join(root, RELEASE_STATE_DIRECTORY, UPDATE_LOCK_FILE));
192
+ }
193
+
194
+ /**
195
+ * One exclusive lock file (the update lock above, the per-host install lock of
196
+ * R4): created atomically (write, then `link`), naming its holder; stale when
197
+ * its process is gone or it is older than `ttlMs`; waited on up to `waitMs`.
198
+ * @param {string} path @param {LockOptions} [options] @returns {Promise<FileLock>}
199
+ */
200
+ export async function acquireFileLock(path, options = {}) {
201
+ const now = options.now ?? (() => new Date());
202
+ const alive = options.alive ?? processAlive;
203
+ const ttl = options.ttlMs ?? LOCK_TTL_MS;
204
+ const wait = options.waitMs ?? LOCK_WAIT_MS;
205
+ const sleep =
206
+ options.sleep ??
207
+ /** @type {(ms: number) => Promise<void>} */ (
208
+ (ms) =>
209
+ new Promise((done) => {
210
+ setTimeout(() => done(), ms);
211
+ })
212
+ );
213
+ const started = now().getTime();
214
+ let waiting = false;
215
+ let broken = 0;
216
+ for (;;) {
217
+ const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}`;
218
+ try {
219
+ await writeFile(
220
+ temp,
221
+ `${JSON.stringify({ schemaVersion: 1, pid: process.pid, at: now().toISOString() })}\n`,
222
+ { mode: 0o600, flag: 'wx' },
223
+ );
224
+ await link(temp, path);
225
+ await unlink(temp).catch(() => undefined);
226
+ return { acquired: true, holder: process.pid };
227
+ } catch (error) {
228
+ await unlink(temp).catch(() => undefined);
229
+ if (!isRecord(error) || error.code !== 'EEXIST') return { acquired: false, holder: null };
230
+ }
231
+ const lock = lockRecord(await readOwnedJson(path));
232
+ if (lock === null || !alive(lock.pid) || now().getTime() - Date.parse(lock.at) > ttl) {
233
+ broken += 1;
234
+ if (broken > 3) return { acquired: false, holder: null };
235
+ await breakStaleLock(path, lock);
236
+ continue;
237
+ }
238
+ if (now().getTime() - started >= wait) return { acquired: false, holder: lock.pid };
239
+ if (!waiting) {
240
+ waiting = true;
241
+ options.onWait?.(lock.pid);
242
+ }
243
+ await sleep(LOCK_POLL_MS);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Remove a lock judged stale without removing one another waiter took in the
249
+ * meantime: the file is renamed aside (atomic), the record it holds is compared
250
+ * with the stale one, and a record that differs (a fresh holder) is put back under
251
+ * its name by `link`. Two waiters that read the same stale record can therefore not
252
+ * both end up holding the lock. Never throws.
253
+ * @param {string} path @param {LockRecord | null} stale
254
+ * @returns {Promise<boolean>} whether the stale lock was removed
255
+ */
256
+ export async function breakStaleLock(path, stale) {
257
+ const aside = `${path}.stale.${process.pid}.${Math.random().toString(16).slice(2)}`;
258
+ try {
259
+ await rename(path, aside);
260
+ } catch {
261
+ return false;
262
+ }
263
+ const current = lockRecord(await readOwnedJson(aside));
264
+ const same =
265
+ (current === null && stale === null) ||
266
+ (current !== null && stale !== null && current.pid === stale.pid && current.at === stale.at);
267
+ if (!same) {
268
+ // A holder that took the lock after our read: its lock goes back (EEXIST means a
269
+ // third process already created a new one; the moved record then goes, and that
270
+ // holder's release finds nothing of its own to remove).
271
+ await link(aside, path).catch(() => undefined);
272
+ }
273
+ await unlink(aside).catch(() => undefined);
274
+ return same;
275
+ }
276
+
277
+ /** Remove a lock file when this process holds it. Never throws. @param {string} path */
278
+ export async function releaseFileLock(path) {
279
+ const lock = lockRecord(await readOwnedJson(path));
280
+ if (lock !== null && lock.pid === process.pid) await unlink(path).catch(() => undefined);
281
+ }
282
+
283
+ /**
284
+ * `npm view <package>@<version> dist.integrity` with the same npm (FR6): `ok`
285
+ * with the SRI line, `unavailable` when npm fails or prints anything else.
286
+ * Every npm subprocess runs in `cwd`, the client's private `<state>/release/npm`:
287
+ * npm reads a project-level `.npmrc` from its working directory and expands
288
+ * `${VAR}` from the environment in it, so the user's own directory (a cloned
289
+ * repository, say) must never be where npm runs.
290
+ * @param {string} npm @param {string} packageName @param {string} version
291
+ * @param {NodeJS.ProcessEnv} env @param {string} cwd
292
+ * @returns {RegistryIntegrity}
293
+ */
294
+ export function registryIntegrity(npm, packageName, version, env, cwd) {
295
+ const result = spawnSync(npm, ['view', `${packageName}@${version}`, 'dist.integrity'], {
296
+ cwd,
297
+ env: safeEnvironment(env),
298
+ encoding: 'utf8',
299
+ stdio: ['ignore', 'pipe', 'pipe'],
300
+ timeout: VIEW_TIMEOUT_MS,
301
+ });
302
+ if (result.error || result.status !== 0) return { status: 'unavailable' };
303
+ const line =
304
+ String(result.stdout ?? '')
305
+ .trim()
306
+ .split(/\r?\n/u)[0]
307
+ ?.trim() ?? '';
308
+ return SRI_SHA512.test(line) ? { status: 'ok', integrity: line } : { status: 'unavailable' };
309
+ }
310
+
311
+ /**
312
+ * `npm install -g --prefix <prefix> --ignore-scripts … <package>@<version>`:
313
+ * the user's own prefix, scripts off, no audit or progress noise (FR6).
314
+ * @param {InstallInput} input @returns {Promise<boolean>}
315
+ */
316
+ export function installClient(input) {
317
+ return new Promise((resolvePromise) => {
318
+ const child = spawn(
319
+ input.npm,
320
+ [
321
+ 'install',
322
+ '-g',
323
+ '--prefix',
324
+ input.prefix.prefix,
325
+ '--ignore-scripts',
326
+ '--no-audit',
327
+ '--no-fund',
328
+ '--no-progress',
329
+ `${input.packageName}@${input.version}`,
330
+ ],
331
+ { cwd: input.cwd, env: safeEnvironment(input.env), stdio: 'ignore' },
332
+ );
333
+ // Own timer, unreferenced: spawn's `timeout` only clears on `exit`, which a
334
+ // failed spawn (npm missing) never emits, and it would then hold the process.
335
+ const timer = setTimeout(() => {
336
+ if (child.exitCode === null) child.kill('SIGTERM');
337
+ }, INSTALL_TIMEOUT_MS);
338
+ timer.unref();
339
+ let settled = false;
340
+ /** @param {boolean} ok */
341
+ const finish = (ok) => {
342
+ if (settled) return;
343
+ settled = true;
344
+ clearTimeout(timer);
345
+ resolvePromise(ok);
346
+ };
347
+ child.once('error', () => finish(false));
348
+ child.once('close', (code, signal) => finish(signal === null && code === 0));
349
+ });
350
+ }
351
+
352
+ /**
353
+ * The version an installed `cli.mjs` reports, through this node (FR6 verify).
354
+ * @param {string} cliPath @param {NodeJS.ProcessEnv} env
355
+ */
356
+ export function installedVersionAt(cliPath, env) {
357
+ const result = spawnSync(process.execPath, [cliPath, '--version'], {
358
+ env: safeEnvironment(env),
359
+ encoding: 'utf8',
360
+ stdio: ['ignore', 'pipe', 'pipe'],
361
+ timeout: VERSION_TIMEOUT_MS,
362
+ });
363
+ if (result.error || result.status !== 0) return null;
364
+ const match = VERSION_OUTPUT.exec(String(result.stdout ?? '').trim());
365
+ return match === null ? null : (match[1] ?? null);
366
+ }
367
+
368
+ /**
369
+ * Run the freshly installed client with the original arguments and
370
+ * `AISAC_REEXEC=<version>`, forwarding the terminal and the signals (FR6).
371
+ * @param {{ cliPath: string, args: string[], version: string, env: NodeJS.ProcessEnv,
372
+ * stdio?: 'inherit' | 'pipe' }} input
373
+ * @returns {Promise<{ code: number, stdout: string }>}
374
+ */
375
+ export function reexecClient(input) {
376
+ return new Promise((resolvePromise) => {
377
+ const stdio = input.stdio ?? 'inherit';
378
+ const child = spawn(process.execPath, [input.cliPath, ...input.args], {
379
+ env: { ...input.env, [REEXEC_ENV]: input.version },
380
+ stdio,
381
+ });
382
+ let stdout = '';
383
+ child.stdout?.on('data', (chunk) => {
384
+ stdout += chunk;
385
+ });
386
+ /** @type {NodeJS.Signals[]} */
387
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
388
+ // In a terminal the foreground process group already delivers SIGINT and
389
+ // SIGHUP to the child; forwarding them would double every Ctrl-C. SIGTERM is
390
+ // addressed to this process alone, so it is passed on. The listeners also
391
+ // keep this process alive until the child exits.
392
+ const terminal = stdin.isTTY === true;
393
+ /** @type {Map<NodeJS.Signals, () => void>} */
394
+ const handlers = new Map(
395
+ signals.map((signal) => [
396
+ signal,
397
+ () => {
398
+ if (child.exitCode === null && (signal === 'SIGTERM' || !terminal)) child.kill(signal);
399
+ },
400
+ ]),
401
+ );
402
+ for (const [signal, handler] of handlers) process.on(signal, handler);
403
+ let settled = false;
404
+ /** @param {number} code */
405
+ const finish = (code) => {
406
+ if (settled) return;
407
+ settled = true;
408
+ for (const [signal, handler] of handlers) process.removeListener(signal, handler);
409
+ resolvePromise({ code, stdout });
410
+ };
411
+ child.once('error', () => finish(1));
412
+ child.once('close', (code, signal) =>
413
+ finish(signal === null ? (code ?? 1) : 128 + (osConstants.signals[signal] ?? 0)),
414
+ );
415
+ });
416
+ }
417
+
418
+ /**
419
+ * The npm that owns the installation (FR6 "the same npm"): the prefix's own
420
+ * `bin/npm` (a version manager's node, say), else the one beside this node,
421
+ * else the first on PATH.
422
+ * @param {NodeJS.ProcessEnv} env @param {InstallPrefix | null} prefix
423
+ */
424
+ export function findNpm(env, prefix) {
425
+ const candidates = [
426
+ prefix === null ? null : join(prefix.prefix, 'bin', 'npm'),
427
+ join(dirname(process.execPath), 'npm'),
428
+ ];
429
+ for (const candidate of candidates)
430
+ if (candidate !== null && isExecutable(candidate)) return candidate;
431
+ return resolveNative('npm', env);
432
+ }
433
+
434
+ /** @param {string} path */
435
+ function isExecutable(path) {
436
+ try {
437
+ accessSync(path, constants.X_OK);
438
+ return statSync(path).isFile();
439
+ } catch {
440
+ return false;
441
+ }
442
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aisac/cli",
3
- "version": "0.4.0-beta.2",
3
+ "version": "0.4.0-beta.21",
4
4
  "private": false,
5
5
  "description": "AISAC client for Claude Code and Codex: AI Brain memory, context management and AISAC Engineering",
6
6
  "license": "UNLICENSED",