@anhlp/alp-cli 0.0.0-beta.1 → 0.0.1-beta.10

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 (83) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +52 -2
  2. package/dist/acp/agent.d.ts +11 -3
  3. package/dist/acp/agent.js +118 -19
  4. package/dist/acp/main.js +1 -1
  5. package/dist/acp.js +7898 -2238
  6. package/dist/alp-dashboard/THIRD-PARTY-NOTICES.txt +3256 -0
  7. package/dist/alp-dashboard/alp-boundary.json +16 -0
  8. package/dist/alp-dashboard/apple-touch-icon.png +0 -0
  9. package/dist/alp-dashboard/assets/TerminalPanel-D8HE9XBX.js +22 -0
  10. package/dist/alp-dashboard/assets/TerminalPanel-DLuoa74B.css +1 -0
  11. package/dist/alp-dashboard/assets/highlighter-BnicKQ_d.js +18 -0
  12. package/dist/alp-dashboard/assets/index-DwqDSiIi.css +1 -0
  13. package/dist/alp-dashboard/assets/index-YdtH3NBy.js +59 -0
  14. package/dist/alp-dashboard/favicon-attention.svg +6 -0
  15. package/dist/alp-dashboard/favicon-running.svg +6 -0
  16. package/dist/alp-dashboard/favicon.svg +5 -0
  17. package/dist/alp-dashboard/index.html +20 -0
  18. package/dist/alp-dashboard.js +10165 -0
  19. package/dist/alpd.js +39994 -16997
  20. package/dist/backup.js +2 -2
  21. package/dist/build-manifest.json +142 -3
  22. package/dist/cli.js +40 -6
  23. package/dist/daemon.d.ts +3 -3
  24. package/dist/daemon.js +16 -7
  25. package/dist/dashboard-migrate.d.ts +31 -0
  26. package/dist/dashboard-migrate.js +127 -0
  27. package/dist/dashboard-service.d.ts +69 -0
  28. package/dist/dashboard-service.js +141 -0
  29. package/dist/desktop.d.ts +56 -0
  30. package/dist/desktop.js +91 -0
  31. package/dist/interfaces.d.ts +23 -3
  32. package/dist/interfaces.js +277 -41
  33. package/dist/library.d.ts +16 -2
  34. package/dist/library.js +114 -7
  35. package/dist/paths.d.ts +6 -0
  36. package/dist/paths.js +4 -1
  37. package/dist/projects.js +2 -1
  38. package/dist/roles.d.ts +15 -0
  39. package/dist/roles.js +16 -0
  40. package/dist/schedules.d.ts +2 -0
  41. package/dist/schedules.js +45 -0
  42. package/dist/self-update.d.ts +151 -0
  43. package/dist/self-update.js +422 -0
  44. package/dist/sessions.d.ts +9 -2
  45. package/dist/sessions.js +67 -13
  46. package/dist/tasks.js +22 -8
  47. package/dist/terminal-native/README.md +201 -0
  48. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  49. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  50. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  51. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  52. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  53. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  54. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  55. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  56. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  57. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  58. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  59. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  60. package/dist/terminal-native/terminal-owner.c +389 -0
  61. package/dist/terminal.d.ts +13 -0
  62. package/dist/terminal.js +80 -0
  63. package/dist/usage.d.ts +1 -1
  64. package/dist/usage.js +31 -9
  65. package/package.json +11 -4
  66. package/src/acp/agent.ts +111 -20
  67. package/src/backup.js +1 -1
  68. package/src/cli.js +51 -6
  69. package/src/daemon.js +18 -9
  70. package/src/dashboard-migrate.js +152 -0
  71. package/src/dashboard-service.js +192 -0
  72. package/src/desktop.js +122 -0
  73. package/src/interfaces.js +345 -38
  74. package/src/library.js +108 -9
  75. package/src/paths.js +9 -1
  76. package/src/projects.js +3 -1
  77. package/src/roles.js +26 -0
  78. package/src/schedules.js +38 -0
  79. package/src/self-update.js +443 -0
  80. package/src/sessions.js +60 -16
  81. package/src/tasks.js +22 -8
  82. package/src/terminal.js +78 -0
  83. package/src/usage.js +31 -9
package/src/projects.js CHANGED
@@ -22,8 +22,10 @@ async function project(command, args) {
22
22
  try {
23
23
  const result = await (command === 'upgrade' ? upgradeProject : initProject)(args[0] ?? process.cwd(), { library: alpHome() });
24
24
  console.log(`ALP initialized: ${result.created.length} files created, ${result.preserved.length} existing files preserved.`);
25
- const library = await seedLibrary(alpHome());
25
+ // On upgrade an edited role-skills.json is offered the built-in role skills it never was (t-de1a).
26
+ const library = await seedLibrary(alpHome(), { offerRoleSkills: command === 'upgrade' });
26
27
  if (library.created.length || library.updated.length) console.log(`Skill library ${alpHome()}: ${library.created.length} files added, ${library.updated.length} unchanged files updated.`);
28
+ if (library.offered?.length) console.log(`New built-in skills given to roles in your edited role-skills.json: ${library.offered.join(', ')} (remove any you do not want; ALP will not add it again).`);
27
29
  if (command === 'init' && result.updated?.length) console.log(`Template model profiles refreshed: ${result.updated.join(', ')}`);
28
30
  if (command === 'upgrade') {
29
31
  console.log(`ALP upgraded: ${result.updated.length} files updated.${result.backup ? ` Backup: ${result.backup}` : ''}`);
package/src/roles.js ADDED
@@ -0,0 +1,26 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { runBridge } from '@anhlp/alp-core/bridges';
3
+ import { UsageError } from './usage.js';
4
+
5
+ /**
6
+ * The role subcommands (t-1e02): `alp daemon run`, `alp dashboard serve` and `alp bridge acp|antigravity`
7
+ * run alpd, alp-dashboard and the MCP bridges in this process: they import the same scripts that
8
+ * `node alpd.js` and `node alp-dashboard.js` run. Services and MCP entries written by the single-file
9
+ * executable of 0.0.1-beta.5/6 still name them.
10
+ *
11
+ * The role's module reads its options from process.argv as when run directly, so argv is rewritten
12
+ * to `[runtime, entry, ...args]` before the module loads.
13
+ * @param {'daemon' | 'dashboard' | 'acp'} role
14
+ * @param {string} file the role's script beside this CLI
15
+ * @param {string[]} args
16
+ */
17
+ export async function runRole(role, file, args) {
18
+ process.argv = [process.argv[0], file, ...args];
19
+ return import(pathToFileURL(file).href);
20
+ }
21
+
22
+ /** alp bridge acp|antigravity: the stdio MCP bridge an agent CLI starts to reach alpd's tools. @param {string[]} args */
23
+ export function bridgeCommand(args) {
24
+ if (args.length !== 1 || !['acp', 'antigravity'].includes(args[0])) throw new UsageError();
25
+ runBridge(args[0]);
26
+ }
@@ -0,0 +1,38 @@
1
+ import path from 'node:path';
2
+ import { parseArgs } from 'node:util';
3
+ import { running } from './daemon.js';
4
+ import { UsageError } from './usage.js';
5
+
6
+ /** One-shot continuations of an existing root session; timestamps need an explicit offset. */
7
+ export async function scheduleCommand(args) {
8
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
9
+ project: { type: 'string' }, session: { type: 'string' }, at: { type: 'string' },
10
+ prompt: { type: 'string' }, status: { type: 'string' }, json: { type: 'boolean' },
11
+ } });
12
+ const [action, id, ...extra] = positionals;
13
+ if (!['create', 'list', 'show', 'cancel'].includes(action) || extra.length) throw new UsageError();
14
+ if ((action === 'show' || action === 'cancel') ? !id : !!id) throw new UsageError();
15
+ if (action !== 'create' && (values.session || values.at || values.prompt)) throw new UsageError();
16
+ if (action !== 'list' && values.status) throw new UsageError();
17
+ if (action === 'create' && (!values.session || !values.prompt?.trim() ||
18
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(values.at ?? '') ||
19
+ !Number.isFinite(Date.parse(values.at)))) throw new Error('create needs --session, --prompt and --at ISO timestamp with Z or a UTC offset (for example 2026-10-20T16:00:00+07:00)');
20
+ const projectRoot = path.resolve(values.project ?? process.cwd());
21
+ const params = action === 'create'
22
+ ? { projectRoot, sessionId: values.session, dueAt: values.at, prompt: values.prompt }
23
+ : { projectRoot, ...(id ? { id } : {}), ...(values.status ? { status: values.status } : {}) };
24
+ const client = await running();
25
+ try {
26
+ const result = await client.request(`schedule.${action === 'show' ? 'get' : action}`, params);
27
+ if (values.json) { console.log(JSON.stringify(result)); return; }
28
+ const jobs = result.jobs ?? [result.job];
29
+ if (!jobs.length) console.log('No scheduled continuations');
30
+ for (const job of jobs) {
31
+ console.log(`${job.id} ${job.status} ${job.dueAt} session ${job.sessionId}`);
32
+ console.log(` ${job.prompt}`);
33
+ if (job.attemptedAt) console.log(` attempted ${job.attemptedAt}; attempts ${job.attempts}; late ${job.lateByMs ?? 0} ms`);
34
+ for (const field of ['deliveredAt', 'failedAt', 'cancelledAt']) if (job[field]) console.log(` ${field}: ${job[field]}`);
35
+ if (job.lastError) console.log(` ${job.lastError.code ?? 'error'}: ${job.lastError.message}`);
36
+ }
37
+ } finally { client.close(); }
38
+ }
@@ -0,0 +1,443 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { createHash, randomBytes } from 'node:crypto';
3
+ import * as nodeFs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createInterface } from 'node:readline/promises';
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { parseArgs } from 'node:util';
9
+ import { bundleInfo, NATIVE_DAEMON, samePath } from '@anhlp/alp-core/packaged';
10
+
11
+ /**
12
+ * `alp update` (t-1807): installs a release of the ALP bundle from GitHub Releases beside the running
13
+ * one (<app>/<version>, see @anhlp/alp-core/packaged) and points <app>/current at it, after checking
14
+ * the archive against the release's SHA256SUMS and, when `gh` is installed, its build provenance.
15
+ * The project template upgrade that `alp update` used to run is `alp update-template`.
16
+ *
17
+ * Everything that touches the network, the filesystem or child processes comes in through `deps`
18
+ * so the tests can drive each step.
19
+ */
20
+
21
+ export const DEFAULT_REPO = 'phucanh08/alp';
22
+ export const SIGNER_WORKFLOW = '.github/workflows/release-binaries.yml';
23
+ export const NPM_PACKAGE = '@anhlp/alp';
24
+ const TEMPLATE_HINT = 'did you mean `alp update-template`? (`alp update` now updates ALP itself; the project template upgrade is `alp update-template [directory]`)';
25
+
26
+ const OPTIONS = { check: { type: 'boolean' }, yes: { type: 'boolean', short: 'y' }, version: { type: 'string' }, 'base-url': { type: 'string' }, help: { type: 'boolean', short: 'h' } };
27
+
28
+ export const UPDATE_USAGE = `Usage: alp update [--check] [--yes] [--version X] [--base-url URL]
29
+ Installs the latest ALP release (or release X) from GitHub Releases beside this one and switches to it, after checking
30
+ it against SHA256SUMS and, when gh is installed, its build provenance. --check only reports.
31
+ ALP_UPDATE_BASE_URL (as --base-url, an https:// or file:// mirror) and ALP_INSTALL_REPO (owner/name) override the source.
32
+ The project template upgrade is \`alp update-template [directory]\`.`;
33
+
34
+ /** The release platform of this process: darwin-arm64, linux-x64, windows-x64. @param {string} platform @param {string} arch */
35
+ export function releasePlatform(platform = process.platform, arch = process.arch) {
36
+ const osName = { darwin: 'darwin', linux: 'linux', win32: 'windows' }[platform];
37
+ const archName = { x64: 'x64', arm64: 'arm64' }[arch];
38
+ if (!osName || !archName || (osName === 'windows' && archName !== 'x64')) throw new Error(`ALP publishes no build for ${platform}-${arch}`);
39
+ return `${osName}-${archName}`;
40
+ }
41
+
42
+ /** The archive extension of a release platform. @param {string} platform */
43
+ export const archiveExtension = platform => platform.startsWith('windows-') ? '.zip' : '.tar.gz';
44
+
45
+ /** Parses SHA256SUMS into [{ sha256, name }]. @param {string} text */
46
+ export function parseSums(text) {
47
+ const entries = [];
48
+ for (const raw of text.split(/\r?\n/)) {
49
+ const line = raw.trim();
50
+ if (!line) continue;
51
+ const match = /^([0-9a-fA-F]{64}) [ *]?(.+)$/.exec(line);
52
+ if (!match) throw new Error(`Malformed SHA256SUMS line: ${JSON.stringify(line)}`);
53
+ entries.push({ sha256: match[1].toLowerCase(), name: match[2].trim() });
54
+ }
55
+ return entries;
56
+ }
57
+
58
+ /**
59
+ * The archive for `platform` in SHA256SUMS: alp-<version>-<platform>.<ext>, for `version` when given.
60
+ * @param {string} sumsText @param {string} platform @param {string} [version]
61
+ * @returns {{ name: string, sha256: string, version: string }}
62
+ */
63
+ export function selectAsset(sumsText, platform, version) {
64
+ const suffix = `-${platform}${archiveExtension(platform)}`;
65
+ const matches = parseSums(sumsText).filter(({ name }) => name.endsWith(suffix) && /^alp-[0-9]/.test(name) && (!version || name === `alp-${version}${suffix}`));
66
+ if (matches.length === 0) throw new Error(`This release has no ALP build for ${platform}${version ? ` at version ${version}` : ''}`);
67
+ if (matches.length > 1) throw new Error(`SHA256SUMS lists more than one ${platform} archive: ${matches.map(m => m.name).join(', ')}`);
68
+ const [match] = matches;
69
+ if (/[^0-9A-Za-z.+_-]/.test(match.name)) throw new Error(`Unexpected archive name in SHA256SUMS: ${match.name}`);
70
+ return { ...match, version: match.name.slice('alp-'.length, -suffix.length) };
71
+ }
72
+
73
+ export const sha256 = (/** @type {Uint8Array} */ bytes) => createHash('sha256').update(bytes).digest('hex');
74
+
75
+ /** Refuses an archive whose digest differs from SHA256SUMS. @param {Uint8Array} bytes @param {{ name: string, sha256: string }} asset */
76
+ export function verifyChecksum(bytes, asset) {
77
+ const actual = sha256(bytes);
78
+ if (actual !== asset.sha256) throw new Error(`Checksum mismatch for ${asset.name} (expected ${asset.sha256}, got ${actual}); nothing was replaced`);
79
+ return actual;
80
+ }
81
+
82
+ /** Compares dotted versions numerically, prerelease below release. @param {string} a @param {string} b */
83
+ export function compareVersions(a, b) {
84
+ const split = (/** @type {string} */ v) => {
85
+ // Build metadata (+b) does not order versions.
86
+ const [core, pre] = v.replace(/^v/, '').replace(/\+.*$/s, '').split(/-(.*)/s);
87
+ if (!/^\d+(\.\d+)*$/.test(core)) throw new Error(`Invalid version: ${JSON.stringify(v)}`);
88
+ return { core: core.split('.').map(Number), pre };
89
+ };
90
+ const x = split(a), y = split(b);
91
+ for (let i = 0; i < Math.max(x.core.length, y.core.length); i++) {
92
+ const d = (x.core[i] ?? 0) - (y.core[i] ?? 0);
93
+ if (d) return Math.sign(d);
94
+ }
95
+ if (x.pre === y.pre) return 0;
96
+ if (x.pre === undefined) return 1;
97
+ if (y.pre === undefined) return -1;
98
+ return x.pre.localeCompare(y.pre, 'en', { numeric: true });
99
+ }
100
+
101
+ /** The base URL that holds SHA256SUMS and the archives. @param {{ repo: string, version?: string, baseUrl?: string }} options */
102
+ export function releaseBaseUrl({ repo, version, baseUrl }) {
103
+ let base = baseUrl;
104
+ if (!base) base = version ? `https://github.com/${repo}/releases/download/v${version}` : `https://github.com/${repo}/releases/latest/download`;
105
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(base) && (path.isAbsolute(base) || (process.platform === 'win32' && path.win32.isAbsolute(base)))) base = pathToFileURL(base).href;
106
+ base = base.replace(/\/+$/, '');
107
+ const url = new URL(base);
108
+ const loopback = isLoopbackHttp(url);
109
+ if (url.protocol !== 'https:' && url.protocol !== 'file:' && !loopback) throw new Error(`The release mirror must be https:// or file:// (${base})`);
110
+ return base;
111
+ }
112
+
113
+ /** The largest file alp update downloads: an archive of the bundle is about 70 MB. */
114
+ export const MAX_DOWNLOAD = 512 * 1024 * 1024;
115
+
116
+ const LOOPBACK = ['127.0.0.1', 'localhost', '[::1]'];
117
+ const isLoopbackHttp = (/** @type {URL} */ url) => url.protocol === 'http:' && LOOPBACK.includes(url.hostname);
118
+
119
+ /**
120
+ * Whether a download may go to `next`: every hop of an https download stays https, since one plain
121
+ * http hop lets a man in the middle replace the archive and SHA256SUMS together. Only a loopback
122
+ * http mirror given explicitly (tests) may use loopback http, besides https.
123
+ * @param {string} start @param {string} next
124
+ */
125
+ export function allowedHop(start, next) {
126
+ const to = new URL(next);
127
+ if (to.protocol === 'https:') return true;
128
+ return isLoopbackHttp(new URL(start)) && isLoopbackHttp(to);
129
+ }
130
+
131
+ /**
132
+ * Downloads `url` (https, loopback http or file) within a time and size limit, following at most 10
133
+ * redirects itself and refusing any hop that `allowedHop` refuses.
134
+ * @param {string} url @param {{ timeoutMs?: number, max?: number, fetch?: typeof globalThis.fetch }} [options]
135
+ */
136
+ export async function fetchBytes(url, { timeoutMs = 10 * 60_000, max = MAX_DOWNLOAD, fetch: fetchImpl = globalThis.fetch } = {}) {
137
+ if (url.startsWith('file:')) {
138
+ const file = fileURLToPath(url);
139
+ if (nodeFs.statSync(file).size > max) throw new Error(`${url} is larger than ${max} bytes`);
140
+ return new Uint8Array(await nodeFs.promises.readFile(file));
141
+ }
142
+ if (!allowedHop(url, url)) throw new Error(`Refusing to download ${url}: not https`);
143
+ const signal = AbortSignal.timeout(timeoutMs);
144
+ let current = url;
145
+ let response;
146
+ for (let hop = 0; ; hop++) {
147
+ response = await fetchImpl(current, { redirect: 'manual', signal });
148
+ if (![301, 302, 303, 307, 308].includes(response.status)) break;
149
+ const location = response.headers.get('location');
150
+ await response.body?.cancel().catch(() => {});
151
+ if (!location) throw new Error(`${current} redirected without a location`);
152
+ if (hop >= 10) throw new Error(`${url} redirected more than 10 times`);
153
+ const next = new URL(location, current).href;
154
+ if (!allowedHop(url, next)) throw new Error(`${url} redirected to ${next}, which is not https; refused`);
155
+ current = next;
156
+ }
157
+ if (!response.ok) throw new Error(`Could not download ${current} (HTTP ${response.status})`);
158
+ if (Number(response.headers.get('content-length') ?? 0) > max) throw new Error(`${current} is larger than ${max} bytes`);
159
+ const chunks = [];
160
+ let size = 0;
161
+ for await (const chunk of /** @type {AsyncIterable<Uint8Array>} */ (response.body ?? [])) {
162
+ size += chunk.byteLength;
163
+ if (size > max) throw new Error(`${current} is larger than ${max} bytes`);
164
+ chunks.push(chunk);
165
+ }
166
+ return new Uint8Array(Buffer.concat(chunks));
167
+ }
168
+
169
+ /** Whether a program is on PATH. @param {string} name */
170
+ function which(name) {
171
+ const result = spawnSync(process.platform === 'win32' ? 'where' : 'which', [name], { encoding: 'utf8', windowsHide: true });
172
+ return result.status === 0 ? result.stdout.split(/\r?\n/)[0].trim() || undefined : undefined;
173
+ }
174
+
175
+ /**
176
+ * Verifies the archive's build provenance with gh. Returns 'verified', or 'unavailable' when gh is
177
+ * absent (ALP_UPDATE_NO_GH=1 treats it as absent); throws when gh reports a failure.
178
+ * @param {string} file @param {{ repo: string, env?: NodeJS.ProcessEnv, run?: typeof spawnSync, find?: typeof which }} options
179
+ */
180
+ export function verifyProvenance(file, { repo, env = process.env, run = spawnSync, find = which }) {
181
+ if (env.ALP_UPDATE_NO_GH === '1') return 'unavailable';
182
+ const gh = find('gh');
183
+ if (!gh) return 'unavailable';
184
+ const result = run(gh, ['attestation', 'verify', file, '--repo', repo, '--source-ref', 'refs/heads/main', '--signer-workflow', `${repo}/${SIGNER_WORKFLOW}`], { encoding: 'utf8', windowsHide: true });
185
+ if (result.status !== 0) {
186
+ const detail = `${result.stderr ?? ''}${result.stdout ?? ''}`.trim().split(/\r?\n/).slice(-3).join(' ');
187
+ throw new Error(`gh attestation verify refused ${path.basename(file)}${detail ? `: ${detail}` : ''}; nothing was replaced (sign in with gh auth login, or set ALP_UPDATE_NO_GH=1 to rely on the checksum only)`);
188
+ }
189
+ return 'verified';
190
+ }
191
+
192
+ const TRANSIENT = new Set(['EBUSY', 'EPERM', 'EACCES', 'ENOTEMPTY']);
193
+ const pause = (/** @type {number} */ ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
194
+
195
+ /**
196
+ * Runs `action`, again after a pause while Windows reports the file busy: a virus scanner holds an
197
+ * executable it just saw run (the staged bundle's --version) for a moment. About 8 s in all.
198
+ * @template T @param {() => T} action @param {(ms: number) => void} [sleep]
199
+ */
200
+ export function retryBusy(action, sleep = pause, attempts = 25) {
201
+ for (let attempt = 1; ; attempt++) {
202
+ try { return action(); } catch (error) {
203
+ if (attempt >= attempts || !TRANSIENT.has(error?.code)) throw error;
204
+ sleep(Math.min(50 * attempt, 400));
205
+ }
206
+ }
207
+ }
208
+
209
+ /** What to say outside the ALP bundle (an npm install). @param {string[]} positionals */
210
+ export function npmMessage(positionals = []) {
211
+ const lines = [];
212
+ if (positionals.length) lines.push(`alp: ${TEMPLATE_HINT}`);
213
+ lines.push(`This alp was installed with npm; update it with npm:\n npm install -g ${NPM_PACKAGE}@beta\nThen restart alpd when no sessions are running: alp daemon restart\n(The project template upgrade is \`alp update-template [directory]\`.)`);
214
+ return lines.join('\n');
215
+ }
216
+
217
+ /** Why this bundle cannot update itself: it was not installed by install.sh / install.ps1. @param {string} root */
218
+ export const notInstalledMessage = root => `alp: ${root} is not an installed ALP (no app/current points at it); install the release with install.sh (Windows: install.ps1), which alp update can then keep up to date:\n curl -fsSL https://github.com/${DEFAULT_REPO}/releases/latest/download/install.sh | sh`;
219
+
220
+ /**
221
+ * tar, as this platform must start it. On Windows it is the system's own bsdtar
222
+ * (%SystemRoot%\System32\tar.exe), never whatever comes first on PATH: under Git Bash that is Git's
223
+ * GNU tar, which reads a drive-letter path such as `D:\a\…\alp.zip` as a remote `host:file`
224
+ * archive and cannot read or write a zip at all. `--force-local` is not an answer: bsdtar rejects it.
225
+ *
226
+ * DUPLICATE, deliberately (t-ffe4.6): `windowsTar` in scripts/spawn-command.mjs is the same
227
+ * knowledge for the repository's own scripts. This package is published, so it cannot import from
228
+ * scripts/, and scripts/ must keep working before anything is built. Change one and change the
229
+ * other; test/integration/spawn-command.test.js asserts the two agree, and refuses any third copy.
230
+ * @param {string} platform @param {Record<string, string | undefined>} env
231
+ */
232
+ export const systemTar = (platform = process.platform, env = process.env) =>
233
+ platform === 'win32' ? path.win32.join(env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe') : 'tar';
234
+
235
+ /** Extracts the archive into `directory` and returns the bundle inside it. @param {string} archive @param {string} directory @param {{ name: string }} asset @param {string} platform */
236
+ function extract(archive, directory, asset, platform, run = spawnSync) {
237
+ const windows = platform.startsWith('windows-');
238
+ // tar reads both: GNU/bsd tar for .tar.gz, Windows' bsdtar (tar.exe) for .zip.
239
+ // On Windows, Git's GNU tar (which reads no zip) may come first on PATH: use the system's bsdtar.
240
+ const result = run(systemTar(), [windows ? '-xf' : '-xzf', archive, '-C', directory], { encoding: 'utf8', windowsHide: true });
241
+ if (result.status !== 0) throw new Error(`Could not extract ${asset.name}: ${(result.stderr || result.error?.message || '').trim()}`);
242
+ const root = path.join(directory, asset.name.slice(0, -archiveExtension(platform).length));
243
+ if (!nodeFs.existsSync(path.join(root, 'alp-bundle.json'))) throw new Error(`${asset.name} does not contain an ALP bundle (${path.basename(root)}/alp-bundle.json)`);
244
+ return root;
245
+ }
246
+
247
+ /** The bundle's own Node and CLI: run without its launcher, so Windows needs no shell for alp.cmd. @param {string} root @param {string} platform */
248
+ export function bundleCommand(root, platform = process.platform) {
249
+ const node = platform === 'win32' ? path.join(root, 'node', 'node.exe') : path.join(root, 'node', 'bin', 'node');
250
+ return { command: node, args: [path.join(root, 'lib', 'node_modules', '@anhlp', 'alp-cli', 'dist', 'cli.js')] };
251
+ }
252
+
253
+ /**
254
+ * Points `<app>/current` at `<app>/<version>`. Unix: a relative symlink renamed over the old one, in
255
+ * one step. Windows: the junction is replaced (removed, then made again; put back on failure).
256
+ * @param {string} app @param {string} version @param {{ platform?: string, fs?: typeof nodeFs, unique?: () => string }} [options]
257
+ */
258
+ export function switchCurrent(app, version, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(6).toString('hex') } = {}) {
259
+ const p = platform === 'win32' ? path.win32 : path;
260
+ const current = p.join(app, 'current');
261
+ if (platform !== 'win32') {
262
+ const link = p.join(app, `.current-${unique()}`);
263
+ fs.symlinkSync(version, link);
264
+ try { fs.renameSync(link, current); } catch (error) { try { fs.unlinkSync(link); } catch {} throw error; }
265
+ return;
266
+ }
267
+ let previous;
268
+ try { previous = fs.readlinkSync(current); } catch {}
269
+ if (previous !== undefined) retryBusy(() => fs.unlinkSync(current));
270
+ try { fs.symlinkSync(p.join(app, version), current, 'junction'); } catch (error) {
271
+ if (previous !== undefined) try { fs.symlinkSync(previous, current, 'junction'); } catch {}
272
+ throw error;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Removes what earlier updates left in `<app>`: versions other than `keep`, and staging directories.
278
+ * A failure (a file still in use on Windows) leaves that entry for the next update. keepAside keeps
279
+ * the copies earlier reinstalls moved aside, which a running alpd may still run from.
280
+ * @param {string} app @param {string[]} keep
281
+ */
282
+ export function pruneVersions(app, keep, fs = nodeFs, { keepAside = false } = {}) {
283
+ let names;
284
+ try { names = fs.readdirSync(app); } catch { return []; }
285
+ const removed = [];
286
+ for (const name of names) {
287
+ if (name === 'current' || keep.includes(name) || (keepAside && name.startsWith('.alp-old-'))) continue;
288
+ if (!/^[0-9][0-9A-Za-z.+-]*$/.test(name) && !/^\.alp-(update|old)-[0-9A-Za-z]+$/.test(name) && !/^\.current-[0-9a-f]+$/.test(name)) continue;
289
+ try { fs.rmSync(path.join(app, name), { recursive: true, force: true }); removed.push(name); } catch {}
290
+ }
291
+ return removed;
292
+ }
293
+
294
+ /** Asks a yes/no question on the terminal. @param {string} question */
295
+ async function confirm(question) {
296
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
297
+ try { return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim()); } finally { rl.close(); }
298
+ }
299
+
300
+ /**
301
+ * @typedef {{
302
+ * bundle: import('@anhlp/alp-core/packaged').BundleInfo | undefined, version: string, env: NodeJS.ProcessEnv, platform: string, arch: string,
303
+ * log: (line: string) => void, warn: (line: string) => void, interactive: boolean,
304
+ * fetchBytes: (url: string) => Promise<Uint8Array>, confirm: (question: string) => Promise<boolean>,
305
+ * provenance: (file: string, repo: string) => string, extract: typeof extract,
306
+ * daemon: () => Promise<{ version: string, sessions?: number } | undefined>, restartDaemon: (root: string) => number,
307
+ * runVersion: (root: string) => string, runDaemonVersion: (root: string) => string,
308
+ * }} UpdateDeps
309
+ */
310
+
311
+ /** @param {string[]} args @param {Partial<UpdateDeps>} [overrides] @returns {Promise<number>} the exit code */
312
+ export async function selfUpdate(args, overrides = {}) {
313
+ /** @type {UpdateDeps} */
314
+ const deps = {
315
+ bundle: bundleInfo(), version: '0.0.0', env: process.env, platform: process.platform, arch: process.arch,
316
+ log: line => console.log(line), warn: line => console.error(line), interactive: !!(process.stdin.isTTY && process.stdout.isTTY),
317
+ fetchBytes, confirm, extract,
318
+ provenance: (file, repo) => verifyProvenance(file, { repo }),
319
+ daemon: async () => undefined,
320
+ restartDaemon: root => { const run = bundleCommand(root); return spawnSync(run.command, [...run.args, 'daemon', 'restart'], { stdio: 'inherit', windowsHide: true }).status ?? 1; },
321
+ runVersion: root => { const run = bundleCommand(root); return spawnSync(run.command, [...run.args, '--version'], { encoding: 'utf8', windowsHide: true, timeout: 60_000 }).stdout?.trim() ?? ''; },
322
+ // Without BUN_BE_BUN, which would make the native alpd the Bun CLI.
323
+ runDaemonVersion: root => spawnSync(path.join(root, 'bin', NATIVE_DAEMON), ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 60_000, env: Object.fromEntries(Object.entries(process.env).filter(([name]) => name !== 'BUN_BE_BUN')) }).stdout?.trim() ?? '',
324
+ ...overrides,
325
+ };
326
+ const { bundle } = deps;
327
+ let parsed;
328
+ try {
329
+ parsed = parseArgs({ args, allowPositionals: true, options: OPTIONS, strict: true });
330
+ } catch (error) {
331
+ deps.warn(`alp: ${error.message}`);
332
+ deps.warn(`alp: ${TEMPLATE_HINT}`);
333
+ return bundle ? 1 : 0;
334
+ }
335
+ const { values, positionals } = parsed;
336
+ if (values.help) { deps.log(UPDATE_USAGE); return 0; }
337
+ if (!bundle) { deps.log(npmMessage(positionals)); return 0; }
338
+ if (positionals.length) { deps.warn(`alp: ${TEMPLATE_HINT}`); return 1; }
339
+ if (!bundle.current) { deps.warn(notInstalledMessage(bundle.root)); return 1; }
340
+
341
+ const wanted = values.version?.replace(/^v/, '');
342
+ if (wanted !== undefined && !/^[0-9][0-9A-Za-z.+-]*$/.test(wanted)) throw new Error(`Invalid version: ${values.version}`);
343
+ const repo = deps.env.ALP_INSTALL_REPO || DEFAULT_REPO;
344
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error(`Invalid ALP_INSTALL_REPO: ${repo}`);
345
+ const base = releaseBaseUrl({ repo, version: wanted, baseUrl: values['base-url'] ?? deps.env.ALP_UPDATE_BASE_URL });
346
+ const platform = releasePlatform(deps.platform, deps.arch);
347
+
348
+ const sums = new TextDecoder().decode(await deps.fetchBytes(`${base}/SHA256SUMS`));
349
+ const asset = selectAsset(sums, platform, wanted);
350
+ const order = compareVersions(asset.version, deps.version);
351
+ if (values.check) {
352
+ if (order === 0) deps.log(`alp ${deps.version} is up to date (${platform})`);
353
+ else if (order < 0 && !wanted) deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}`);
354
+ else deps.log(`alp ${deps.version} → ${asset.version} available (${asset.name}); run: alp update${wanted ? ` --version ${wanted}` : ''}`);
355
+ return 0;
356
+ }
357
+ // An explicit --version of the running version reinstalls it (a repair); without one there is nothing to do.
358
+ if (order === 0 && !wanted) { deps.log(`alp ${deps.version} is up to date (${platform})`); return 0; }
359
+ if (order < 0 && !wanted) { deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}; nothing to do (pass --version ${asset.version} to go back)`); return 0; }
360
+
361
+ const { app, current } = bundle;
362
+ // A reinstall of the running version moves its directory aside instead of replacing it in place,
363
+ // on Windows too: Windows renames a directory that holds a running executable. Only a process
364
+ // whose working directory is inside the tree, or a handle opened without delete sharing, refuses
365
+ // the move (t-5294.7, board finding p-bcd9c956) — that failure is reported below, not predicted.
366
+ // The version a running alpd uses keeps its files, like the one this process runs.
367
+ const running = await deps.daemon().catch(() => undefined);
368
+ try { nodeFs.accessSync(app, nodeFs.constants.W_OK); } catch { throw new Error(`${app} is not writable; run alp update with the permissions that installed ALP there`); }
369
+ const target = path.join(app, asset.version);
370
+
371
+ if (!values.yes) {
372
+ if (!deps.interactive) throw new Error(`alp update would install ${target} and switch ${current} to it (${deps.version} → ${asset.version}); pass --yes to do it without a terminal`);
373
+ if (!await deps.confirm(`Install ALP ${asset.version} in ${target} and switch to it (from ${deps.version})?`)) { deps.log('Not updated.'); return 1; }
374
+ }
375
+
376
+ const work = nodeFs.mkdtempSync(path.join(os.tmpdir(), 'alp-update-'));
377
+ // Unpacked beside the versions, so moving it into place stays on one filesystem.
378
+ const staging = path.join(app, `.alp-update-${randomBytes(6).toString('hex')}`);
379
+ /** @type {string | undefined} the running version, moved aside by a reinstall */
380
+ let aside;
381
+ try {
382
+ deps.log(`Downloading ${asset.name} from ${base}`);
383
+ const bytes = await deps.fetchBytes(`${base}/${asset.name}`);
384
+ verifyChecksum(bytes, asset);
385
+ deps.log(`Checksum verified (${asset.sha256})`);
386
+ const archive = path.join(work, asset.name);
387
+ nodeFs.writeFileSync(archive, bytes);
388
+ const provenance = deps.provenance(archive, repo);
389
+ if (provenance === 'verified') deps.log(`Provenance verified by gh attestation (${repo}, refs/heads/main, release-binaries.yml)`);
390
+ else deps.warn('alp: warning: gh is not available, so only the SHA256SUMS checksum was verified, not the build provenance (install gh to verify it)');
391
+ nodeFs.mkdirSync(staging);
392
+ const unpacked = deps.extract(archive, staging, asset, platform);
393
+ const manifest = JSON.parse(nodeFs.readFileSync(path.join(unpacked, 'alp-bundle.json'), 'utf8'));
394
+ if (manifest.version !== asset.version || (manifest.platform && manifest.platform !== platform)) throw new Error(`${asset.name} holds ALP ${manifest.version} for ${manifest.platform}, not ${asset.version} for ${platform}; nothing was changed`);
395
+ const reported = deps.runVersion(unpacked);
396
+ if (reported !== asset.version) throw new Error(`The downloaded ALP reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was changed`);
397
+ // The native alpd (t-81b0.9) must run on this machine too: an old CPU, glibc or a quarantined file would
398
+ // otherwise leave alp without a daemon after the switch.
399
+ if (deps.env.ALP_NATIVE_DAEMON !== '0' && nodeFs.existsSync(path.join(unpacked, 'bin', NATIVE_DAEMON))) {
400
+ const native = deps.runDaemonVersion(unpacked);
401
+ if (native !== asset.version) throw new Error(`The downloaded ALP's native alpd (bin/${NATIVE_DAEMON}) reports version ${JSON.stringify(native)}, not ${asset.version}, so it cannot run here; nothing was changed. To update with alpd on the bundled Node, set ALP_NATIVE_DAEMON=0 for this update and keep it set`);
402
+ }
403
+ if (nodeFs.existsSync(target)) {
404
+ // A reinstall of the running version moves it aside (its processes keep their files); any other copy is stale.
405
+ if (samePath(target, bundle.root) || running?.version === asset.version) {
406
+ const moved = `.alp-old-${randomBytes(6).toString('hex')}`;
407
+ try { retryBusy(() => nodeFs.renameSync(target, path.join(app, moved))); } catch (error) {
408
+ // Nothing has been replaced yet. Say what really holds the directory, so nobody looks for
409
+ // a Windows rule that does not exist (t-5294.7).
410
+ throw new Error(`Could not move ${target} aside to reinstall ALP ${asset.version}: ${error.message}. Something holds that directory: a process whose working directory is inside it, or a file handle opened without delete sharing. Stop alpd (alp daemon stop), leave that directory in any shell, and run alp update again`, { cause: error });
411
+ }
412
+ aside = moved;
413
+ }
414
+ else nodeFs.rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
415
+ }
416
+ try { retryBusy(() => nodeFs.renameSync(unpacked, target)); } catch (error) {
417
+ // The running version goes back where it was, so app/current still points at files (t-1f14).
418
+ if (aside && !nodeFs.existsSync(target)) {
419
+ try { nodeFs.renameSync(path.join(app, aside), target); aside = undefined; } catch { throw new Error(`${error.message}; the running ALP ${asset.version} is in ${path.join(app, aside)}: move it back to ${target}`, { cause: error }); }
420
+ }
421
+ throw error;
422
+ }
423
+ switchCurrent(app, asset.version, { platform: deps.platform });
424
+ } finally {
425
+ // A cleanup failure must not hide why the update failed; a leftover staging directory goes with the next update.
426
+ try { nodeFs.rmSync(staging, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
427
+ try { nodeFs.rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
428
+ }
429
+ // The version this process (and maybe alpd) runs stays until the next update.
430
+ pruneVersions(app, [asset.version, path.basename(bundle.root), ...(running?.version ? [running.version] : []), ...(aside ? [aside] : [])], nodeFs, { keepAside: Boolean(running) });
431
+ deps.log(`Updated ALP ${deps.version} → ${asset.version} (${current} → ${target})`);
432
+
433
+ if (running && running.version !== asset.version) {
434
+ const sessions = running.sessions;
435
+ const known = Number.isSafeInteger(sessions);
436
+ deps.log(`alpd ${running.version} is still running${!known ? ' (its live sessions could not be read)' : sessions ? ` with ${sessions} live session${sessions === 1 ? '' : 's'}` : ''}; it runs the new version after: alp daemon restart`);
437
+ // Never restart on our own: only an interactive yes with no live session known restarts it.
438
+ if (!values.yes && deps.interactive && known && sessions === 0 && await deps.confirm('Restart alpd now?')) {
439
+ if (deps.restartDaemon(target) !== 0) deps.warn('alp: alp daemon restart failed; run it yourself');
440
+ }
441
+ }
442
+ return 0;
443
+ }