@anhlp/alp-cli 0.0.1-beta.4 → 0.0.1-beta.6

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 (66) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +26 -1
  2. package/dist/acp/main.js +1 -1
  3. package/dist/acp.js +267 -92
  4. package/dist/alp-web/THIRD-PARTY-NOTICES.txt +666 -0
  5. package/dist/alp-web/alp-boundary.json +1 -0
  6. package/dist/alp-web/assets/TerminalPanel-CqTsgY-W.js +22 -0
  7. package/dist/alp-web/assets/highlighter-BnicKQ_d.js +18 -0
  8. package/dist/alp-web/assets/index-BMbDUCHW.css +1 -0
  9. package/dist/alp-web/assets/index-B_RFaj2C.js +59 -0
  10. package/dist/alp-web/index.html +2 -2
  11. package/dist/alp-web.js +666 -187
  12. package/dist/alpd.js +10768 -2592
  13. package/dist/backup.js +1 -1
  14. package/dist/build-manifest.json +22 -2
  15. package/dist/cli.js +32 -3
  16. package/dist/daemon.d.ts +1 -1
  17. package/dist/daemon.js +5 -0
  18. package/dist/interfaces.d.ts +13 -1
  19. package/dist/interfaces.js +96 -11
  20. package/dist/paths.d.ts +1 -0
  21. package/dist/paths.js +2 -1
  22. package/dist/roles.d.ts +15 -0
  23. package/dist/roles.js +18 -0
  24. package/dist/self-update.d.ts +152 -0
  25. package/dist/self-update.js +390 -0
  26. package/dist/sessions.d.ts +4 -0
  27. package/dist/sessions.js +22 -1
  28. package/dist/tasks.js +22 -8
  29. package/dist/terminal-native/README.md +201 -0
  30. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  31. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  32. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  33. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  34. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  35. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  36. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  37. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  38. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  39. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  40. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  41. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  42. package/dist/terminal-native/terminal-owner.c +389 -0
  43. package/dist/terminal.d.ts +5 -0
  44. package/dist/terminal.js +4 -3
  45. package/dist/usage.d.ts +1 -1
  46. package/dist/usage.js +14 -5
  47. package/dist/web-service.d.ts +22 -4
  48. package/dist/web-service.js +33 -9
  49. package/package.json +6 -5
  50. package/src/cli.js +38 -4
  51. package/src/daemon.js +3 -0
  52. package/src/interfaces.js +102 -12
  53. package/src/paths.js +3 -1
  54. package/src/roles.js +28 -0
  55. package/src/self-update.js +406 -0
  56. package/src/sessions.js +23 -2
  57. package/src/tasks.js +22 -8
  58. package/src/terminal.js +4 -3
  59. package/src/usage.js +14 -5
  60. package/src/web-service.js +58 -14
  61. package/dist/alp-web/assets/TerminalPanel-PrU2l3u5.js +0 -16
  62. package/dist/alp-web/assets/index-BJdBTDFX.css +0 -1
  63. package/dist/alp-web/assets/index-DpfiPv5s.js +0 -52
  64. package/src/web/grant.js +0 -204
  65. package/src/web/main.js +0 -285
  66. package/src/web/serve.js +0 -144
@@ -0,0 +1,390 @@
1
+ // packages/cli/src/self-update.js
2
+ import { spawnSync } from "node:child_process";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import * as nodeFs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { createInterface } from "node:readline/promises";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { parseArgs } from "node:util";
10
+ import { executablePath } from "@anhlp/alp-core/packaged";
11
+ var DEFAULT_REPO = "phucanh08/alp";
12
+ var SIGNER_WORKFLOW = ".github/workflows/release-binaries.yml";
13
+ var NPM_PACKAGE = "@anhlp/alp";
14
+ var TEMPLATE_HINT = "did you mean `alp update-template`? (`alp update` now updates the ALP executable; the project template upgrade is `alp update-template [directory]`)";
15
+ var OPTIONS = { check: { type: "boolean" }, yes: { type: "boolean", short: "y" }, version: { type: "string" }, "base-url": { type: "string" }, help: { type: "boolean", short: "h" } };
16
+ var UPDATE_USAGE = `Usage: alp update [--check] [--yes] [--version X] [--base-url URL]
17
+ Replaces this ALP executable with the latest release (or release X) from GitHub Releases, after checking
18
+ it against SHA256SUMS and, when gh is installed, its build provenance. --check only reports.
19
+ ALP_UPDATE_BASE_URL (as --base-url, an https:// or file:// mirror) and ALP_INSTALL_REPO (owner/name) override the source.
20
+ The project template upgrade is \`alp update-template [directory]\`.`;
21
+ function releasePlatform(platform = process.platform, arch = process.arch) {
22
+ const osName = { darwin: "darwin", linux: "linux", win32: "windows" }[platform];
23
+ const archName = { x64: "x64", arm64: "arm64" }[arch];
24
+ if (!osName || !archName || osName === "windows" && archName !== "x64") throw new Error(`ALP publishes no executable for ${platform}-${arch}`);
25
+ return `${osName}-${archName}`;
26
+ }
27
+ var archiveExtension = (platform) => platform.startsWith("windows-") ? ".zip" : ".tar.gz";
28
+ function parseSums(text) {
29
+ const entries = [];
30
+ for (const raw of text.split(/\r?\n/)) {
31
+ const line = raw.trim();
32
+ if (!line) continue;
33
+ const match = /^([0-9a-fA-F]{64}) [ *]?(.+)$/.exec(line);
34
+ if (!match) throw new Error(`Malformed SHA256SUMS line: ${JSON.stringify(line)}`);
35
+ entries.push({ sha256: match[1].toLowerCase(), name: match[2].trim() });
36
+ }
37
+ return entries;
38
+ }
39
+ function selectAsset(sumsText, platform, version) {
40
+ const suffix = `-${platform}${archiveExtension(platform)}`;
41
+ const matches = parseSums(sumsText).filter(({ name }) => name.endsWith(suffix) && /^alp-[0-9]/.test(name) && (!version || name === `alp-${version}${suffix}`));
42
+ if (matches.length === 0) throw new Error(`This release has no ALP executable for ${platform}${version ? ` at version ${version}` : ""}`);
43
+ if (matches.length > 1) throw new Error(`SHA256SUMS lists more than one ${platform} archive: ${matches.map((m) => m.name).join(", ")}`);
44
+ const [match] = matches;
45
+ if (/[^0-9A-Za-z.+_-]/.test(match.name)) throw new Error(`Unexpected archive name in SHA256SUMS: ${match.name}`);
46
+ return { ...match, version: match.name.slice("alp-".length, -suffix.length) };
47
+ }
48
+ var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
49
+ function verifyChecksum(bytes, asset) {
50
+ const actual = sha256(bytes);
51
+ if (actual !== asset.sha256) throw new Error(`Checksum mismatch for ${asset.name} (expected ${asset.sha256}, got ${actual}); nothing was replaced`);
52
+ return actual;
53
+ }
54
+ function compareVersions(a, b) {
55
+ const split = (v) => {
56
+ const [core, pre] = v.replace(/^v/, "").replace(/\+.*$/s, "").split(/-(.*)/s);
57
+ if (!/^\d+(\.\d+)*$/.test(core)) throw new Error(`Invalid version: ${JSON.stringify(v)}`);
58
+ return { core: core.split(".").map(Number), pre };
59
+ };
60
+ const x = split(a), y = split(b);
61
+ for (let i = 0; i < Math.max(x.core.length, y.core.length); i++) {
62
+ const d = (x.core[i] ?? 0) - (y.core[i] ?? 0);
63
+ if (d) return Math.sign(d);
64
+ }
65
+ if (x.pre === y.pre) return 0;
66
+ if (x.pre === void 0) return 1;
67
+ if (y.pre === void 0) return -1;
68
+ return x.pre.localeCompare(y.pre, "en", { numeric: true });
69
+ }
70
+ function releaseBaseUrl({ repo, version, baseUrl }) {
71
+ let base = baseUrl;
72
+ if (!base) base = version ? `https://github.com/${repo}/releases/download/v${version}` : `https://github.com/${repo}/releases/latest/download`;
73
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(base) && (path.isAbsolute(base) || process.platform === "win32" && path.win32.isAbsolute(base))) base = pathToFileURL(base).href;
74
+ base = base.replace(/\/+$/, "");
75
+ const url = new URL(base);
76
+ const loopback = isLoopbackHttp(url);
77
+ if (url.protocol !== "https:" && url.protocol !== "file:" && !loopback) throw new Error(`The release mirror must be https:// or file:// (${base})`);
78
+ return base;
79
+ }
80
+ var MAX_DOWNLOAD = 512 * 1024 * 1024;
81
+ var LOOPBACK = ["127.0.0.1", "localhost", "[::1]"];
82
+ var isLoopbackHttp = (url) => url.protocol === "http:" && LOOPBACK.includes(url.hostname);
83
+ function allowedHop(start, next) {
84
+ const to = new URL(next);
85
+ if (to.protocol === "https:") return true;
86
+ return isLoopbackHttp(new URL(start)) && isLoopbackHttp(to);
87
+ }
88
+ async function fetchBytes(url, { timeoutMs = 10 * 6e4, max = MAX_DOWNLOAD, fetch: fetchImpl = globalThis.fetch } = {}) {
89
+ if (url.startsWith("file:")) {
90
+ const file = fileURLToPath(url);
91
+ if (nodeFs.statSync(file).size > max) throw new Error(`${url} is larger than ${max} bytes`);
92
+ return new Uint8Array(await nodeFs.promises.readFile(file));
93
+ }
94
+ if (!allowedHop(url, url)) throw new Error(`Refusing to download ${url}: not https`);
95
+ const signal = AbortSignal.timeout(timeoutMs);
96
+ let current = url;
97
+ let response;
98
+ for (let hop = 0; ; hop++) {
99
+ response = await fetchImpl(current, { redirect: "manual", signal });
100
+ if (![301, 302, 303, 307, 308].includes(response.status)) break;
101
+ const location = response.headers.get("location");
102
+ await response.body?.cancel().catch(() => {
103
+ });
104
+ if (!location) throw new Error(`${current} redirected without a location`);
105
+ if (hop >= 10) throw new Error(`${url} redirected more than 10 times`);
106
+ const next = new URL(location, current).href;
107
+ if (!allowedHop(url, next)) throw new Error(`${url} redirected to ${next}, which is not https; refused`);
108
+ current = next;
109
+ }
110
+ if (!response.ok) throw new Error(`Could not download ${current} (HTTP ${response.status})`);
111
+ if (Number(response.headers.get("content-length") ?? 0) > max) throw new Error(`${current} is larger than ${max} bytes`);
112
+ const chunks = [];
113
+ let size = 0;
114
+ for await (
115
+ const chunk of
116
+ /** @type {AsyncIterable<Uint8Array>} */
117
+ response.body ?? []
118
+ ) {
119
+ size += chunk.byteLength;
120
+ if (size > max) throw new Error(`${current} is larger than ${max} bytes`);
121
+ chunks.push(chunk);
122
+ }
123
+ return new Uint8Array(Buffer.concat(chunks));
124
+ }
125
+ function which(name) {
126
+ const result = spawnSync(process.platform === "win32" ? "where" : "which", [name], { encoding: "utf8", windowsHide: true });
127
+ return result.status === 0 ? result.stdout.split(/\r?\n/)[0].trim() || void 0 : void 0;
128
+ }
129
+ function verifyProvenance(file, { repo, env = process.env, run = spawnSync, find = which }) {
130
+ if (env.ALP_UPDATE_NO_GH === "1") return "unavailable";
131
+ const gh = find("gh");
132
+ if (!gh) return "unavailable";
133
+ const result = run(gh, ["attestation", "verify", file, "--repo", repo, "--source-ref", "refs/heads/main", "--signer-workflow", `${repo}/${SIGNER_WORKFLOW}`], { encoding: "utf8", windowsHide: true });
134
+ if (result.status !== 0) {
135
+ const detail = `${result.stderr ?? ""}${result.stdout ?? ""}`.trim().split(/\r?\n/).slice(-3).join(" ");
136
+ 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)`);
137
+ }
138
+ return "verified";
139
+ }
140
+ var oldPath = (target, platform = process.platform) => {
141
+ const p = platform === "win32" ? path.win32 : path;
142
+ return p.join(p.dirname(target), `${p.basename(target, p.extname(target))}.old${p.extname(target) || ".exe"}`);
143
+ };
144
+ var TRANSIENT = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
145
+ var pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
146
+ function retryBusy(action, sleep = pause, attempts = 25) {
147
+ for (let attempt = 1; ; attempt++) {
148
+ try {
149
+ return action();
150
+ } catch (error) {
151
+ if (attempt >= attempts || !TRANSIENT.has(error?.code)) throw error;
152
+ sleep(Math.min(50 * attempt, 400));
153
+ }
154
+ }
155
+ }
156
+ function replaceExecutable(staged, target, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(4).toString("hex"), sleep = pause } = {}) {
157
+ if (platform !== "win32") {
158
+ fs.renameSync(staged, target);
159
+ return { old: void 0 };
160
+ }
161
+ const old = oldPath(target, platform);
162
+ if (fs.existsSync(old)) {
163
+ try {
164
+ fs.rmSync(old, { force: true });
165
+ } catch {
166
+ const aside = old.replace(/\.exe$/i, `.${unique()}.exe`);
167
+ try {
168
+ fs.renameSync(old, aside);
169
+ } catch (error) {
170
+ throw new Error(`${old} is in use and could not be moved (${error.code ?? error.message}); stop the ALP processes started from it (alp daemon stop) and run alp update again`);
171
+ }
172
+ }
173
+ }
174
+ retryBusy(() => fs.renameSync(target, old), sleep);
175
+ try {
176
+ retryBusy(() => fs.renameSync(staged, target), sleep);
177
+ } catch (error) {
178
+ try {
179
+ retryBusy(() => fs.renameSync(old, target), sleep);
180
+ } catch (restore) {
181
+ throw new Error(`Could not put the new executable at ${target} (${error.code ?? error.message}), and could not move the previous one back (${restore.code ?? restore.message}): rename ${old} to ${target} yourself`);
182
+ }
183
+ throw error;
184
+ }
185
+ return { old };
186
+ }
187
+ function cleanupOldExecutable(target, { platform = process.platform, fs = nodeFs } = {}) {
188
+ if (platform !== "win32") return false;
189
+ const old = path.win32.basename(oldPath(target, platform));
190
+ const stem = old.slice(0, -".exe".length).toLowerCase();
191
+ let names;
192
+ try {
193
+ names = fs.readdirSync(path.win32.dirname(target));
194
+ } catch {
195
+ return false;
196
+ }
197
+ let removed = false;
198
+ for (const name of names) {
199
+ const lower = name.toLowerCase();
200
+ if (lower !== `${stem}.exe` && !(lower.startsWith(`${stem}.`) && /^[0-9a-f]+\.exe$/.test(lower.slice(stem.length + 1)))) continue;
201
+ try {
202
+ fs.rmSync(path.win32.join(path.win32.dirname(target), name), { force: true });
203
+ removed = true;
204
+ } catch {
205
+ }
206
+ }
207
+ return removed;
208
+ }
209
+ function isNpmExecutable(execPath) {
210
+ return /[\\/]node_modules[\\/]@anhlp[\\/]alp-(?:darwin|linux|win32)-(?:arm64|x64)[\\/]bin[\\/]alp(?:\.exe)?$/i.test(execPath ?? "");
211
+ }
212
+ function npmMessage(positionals = []) {
213
+ const lines = [];
214
+ if (positionals.length) lines.push(`alp: ${TEMPLATE_HINT}`);
215
+ lines.push(`This alp was installed with npm; update it with npm:
216
+ npm install -g ${NPM_PACKAGE}@beta
217
+ Then restart alpd when no sessions are running: alp daemon restart
218
+ (The project template upgrade is \`alp update-template [directory]\`.)`);
219
+ return lines.join("\n");
220
+ }
221
+ function extract(archive, directory, asset, platform, run = spawnSync) {
222
+ const windows = platform.startsWith("windows-");
223
+ const tar = process.platform === "win32" ? path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe") : "tar";
224
+ const result = run(tar, [windows ? "-xf" : "-xzf", archive, "-C", directory], { encoding: "utf8", windowsHide: true });
225
+ if (result.status !== 0) throw new Error(`Could not extract ${asset.name}: ${(result.stderr || result.error?.message || "").trim()}`);
226
+ const name = asset.name.slice(0, -archiveExtension(platform).length);
227
+ const binary = path.join(directory, name, windows ? "alp.exe" : "alp");
228
+ if (!nodeFs.existsSync(binary)) throw new Error(`${asset.name} does not contain ${name}/${windows ? "alp.exe" : "alp"}`);
229
+ return binary;
230
+ }
231
+ async function confirm(question) {
232
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
233
+ try {
234
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
235
+ } finally {
236
+ rl.close();
237
+ }
238
+ }
239
+ async function selfUpdate(args, overrides = {}) {
240
+ const deps = {
241
+ packaged: false,
242
+ version: "0.0.0",
243
+ execPath: executablePath() ?? "",
244
+ env: process.env,
245
+ platform: process.platform,
246
+ arch: process.arch,
247
+ log: (line) => console.log(line),
248
+ warn: (line) => console.error(line),
249
+ interactive: !!(process.stdin.isTTY && process.stdout.isTTY),
250
+ fetchBytes,
251
+ confirm,
252
+ extract,
253
+ provenance: (file, repo2) => verifyProvenance(file, { repo: repo2 }),
254
+ daemon: async () => void 0,
255
+ restartDaemon: (binary) => spawnSync(binary, ["daemon", "restart"], { stdio: "inherit", windowsHide: true }).status ?? 1,
256
+ runVersion: (binary) => spawnSync(binary, ["--version"], { encoding: "utf8", windowsHide: true, timeout: 6e4 }).stdout?.trim() ?? "",
257
+ ...overrides
258
+ };
259
+ let parsed;
260
+ try {
261
+ parsed = parseArgs({ args, allowPositionals: true, options: OPTIONS, strict: true });
262
+ } catch (error) {
263
+ deps.warn(`alp: ${error.message}`);
264
+ deps.warn(`alp: ${TEMPLATE_HINT}`);
265
+ return deps.packaged ? 1 : 0;
266
+ }
267
+ const { values, positionals } = parsed;
268
+ if (values.help) {
269
+ deps.log(UPDATE_USAGE);
270
+ return 0;
271
+ }
272
+ if (!deps.packaged || isNpmExecutable(deps.execPath)) {
273
+ deps.log(npmMessage(positionals));
274
+ return 0;
275
+ }
276
+ if (positionals.length) {
277
+ deps.warn(`alp: ${TEMPLATE_HINT}`);
278
+ return 1;
279
+ }
280
+ const wanted = values.version?.replace(/^v/, "");
281
+ if (wanted !== void 0 && !/^[0-9][0-9A-Za-z.+-]*$/.test(wanted)) throw new Error(`Invalid version: ${values.version}`);
282
+ const repo = deps.env.ALP_INSTALL_REPO || DEFAULT_REPO;
283
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error(`Invalid ALP_INSTALL_REPO: ${repo}`);
284
+ const base = releaseBaseUrl({ repo, version: wanted, baseUrl: values["base-url"] ?? deps.env.ALP_UPDATE_BASE_URL });
285
+ const platform = releasePlatform(deps.platform, deps.arch);
286
+ const sums = new TextDecoder().decode(await deps.fetchBytes(`${base}/SHA256SUMS`));
287
+ const asset = selectAsset(sums, platform, wanted);
288
+ const order = compareVersions(asset.version, deps.version);
289
+ if (values.check) {
290
+ if (order === 0) deps.log(`alp ${deps.version} is up to date (${platform})`);
291
+ else if (order < 0 && !wanted) deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}`);
292
+ else deps.log(`alp ${deps.version} \u2192 ${asset.version} available (${asset.name}); run: alp update${wanted ? ` --version ${wanted}` : ""}`);
293
+ return 0;
294
+ }
295
+ if (order === 0 && !wanted) {
296
+ deps.log(`alp ${deps.version} is up to date (${platform})`);
297
+ return 0;
298
+ }
299
+ if (order < 0 && !wanted) {
300
+ deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}; nothing to do (pass --version ${asset.version} to go back)`);
301
+ return 0;
302
+ }
303
+ let target;
304
+ try {
305
+ target = nodeFs.realpathSync(deps.execPath);
306
+ } catch {
307
+ target = deps.execPath;
308
+ }
309
+ const dir = path.dirname(target);
310
+ try {
311
+ nodeFs.accessSync(dir, nodeFs.constants.W_OK);
312
+ } catch {
313
+ throw new Error(`${dir} is not writable; run alp update with the permissions that installed ${target}`);
314
+ }
315
+ if (!values.yes) {
316
+ if (!deps.interactive) throw new Error(`alp update would replace ${target} (${deps.version} \u2192 ${asset.version}); pass --yes to do it without a terminal`);
317
+ if (!await deps.confirm(`Replace ${target} (${deps.version} \u2192 ${asset.version})?`)) {
318
+ deps.log("Not updated.");
319
+ return 1;
320
+ }
321
+ }
322
+ const work = nodeFs.mkdtempSync(path.join(os.tmpdir(), "alp-update-"));
323
+ let staged;
324
+ try {
325
+ deps.log(`Downloading ${asset.name} from ${base}`);
326
+ const bytes = await deps.fetchBytes(`${base}/${asset.name}`);
327
+ verifyChecksum(bytes, asset);
328
+ deps.log(`Checksum verified (${asset.sha256})`);
329
+ const archive = path.join(work, asset.name);
330
+ nodeFs.writeFileSync(archive, bytes);
331
+ const provenance = deps.provenance(archive, repo);
332
+ if (provenance === "verified") deps.log(`Provenance verified by gh attestation (${repo}, refs/heads/main, release-binaries.yml)`);
333
+ 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)");
334
+ const unpacked = path.join(work, "x");
335
+ nodeFs.mkdirSync(unpacked);
336
+ const binary = deps.extract(archive, unpacked, asset, platform);
337
+ staged = path.join(dir, `.alp.update.${randomBytes(6).toString("hex")}${deps.platform === "win32" ? ".exe" : ""}`);
338
+ nodeFs.copyFileSync(binary, staged);
339
+ if (deps.platform !== "win32") nodeFs.chmodSync(staged, 493);
340
+ const reported = deps.runVersion(staged);
341
+ if (reported !== asset.version) throw new Error(`The downloaded executable reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was replaced`);
342
+ replaceExecutable(staged, target, { platform: deps.platform });
343
+ staged = void 0;
344
+ } finally {
345
+ if (staged) try {
346
+ nodeFs.rmSync(staged, { force: true, maxRetries: 10, retryDelay: 100 });
347
+ } catch {
348
+ }
349
+ try {
350
+ nodeFs.rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
351
+ } catch {
352
+ }
353
+ }
354
+ deps.log(`Updated ${target}: ${deps.version} \u2192 ${asset.version}`);
355
+ const running = await deps.daemon().catch(() => void 0);
356
+ if (running && running.version !== asset.version) {
357
+ const sessions = running.sessions;
358
+ const known = Number.isSafeInteger(sessions);
359
+ 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`);
360
+ if (!values.yes && deps.interactive && known && sessions === 0 && await deps.confirm("Restart alpd now?")) {
361
+ if (deps.restartDaemon(target) !== 0) deps.warn("alp: alp daemon restart failed; run it yourself");
362
+ }
363
+ }
364
+ return 0;
365
+ }
366
+ export {
367
+ DEFAULT_REPO,
368
+ MAX_DOWNLOAD,
369
+ NPM_PACKAGE,
370
+ SIGNER_WORKFLOW,
371
+ UPDATE_USAGE,
372
+ allowedHop,
373
+ archiveExtension,
374
+ cleanupOldExecutable,
375
+ compareVersions,
376
+ fetchBytes,
377
+ isNpmExecutable,
378
+ npmMessage,
379
+ oldPath,
380
+ parseSums,
381
+ releaseBaseUrl,
382
+ releasePlatform,
383
+ replaceExecutable,
384
+ retryBusy,
385
+ selectAsset,
386
+ selfUpdate,
387
+ sha256,
388
+ verifyChecksum,
389
+ verifyProvenance
390
+ };
@@ -28,6 +28,8 @@ export function top(args: any): Promise<void>;
28
28
  export function log(args: any): Promise<void>;
29
29
  /** The project board every agent on the project shares: live claims, then decisions and findings. */
30
30
  export function board(args: any): Promise<void>;
31
+ /** The models alpd offers now: the live catalog (t-e5ee); --refresh asks every provider again first. */
32
+ export function models(args: any): Promise<void>;
31
33
  export function printPauses({ all, runtimes, parked }: {
32
34
  all: any;
33
35
  runtimes: any;
@@ -41,3 +43,5 @@ export function resume(args: any): Promise<void>;
41
43
  export function recall(args: any): Promise<void>;
42
44
  /** alp web: opens the web app alpd serves on 127.0.0.1, with the token in the address (ALPD §61). */
43
45
  export function interrupt(args: any): Promise<void>;
46
+ /** alp compact <session>: compacts a root's context now, or at its next turn boundary (t-0e56). */
47
+ export function compact(args: any): Promise<void>;
package/dist/sessions.js CHANGED
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { createInterface } from "node:readline";
5
5
  import { parseArgs } from "node:util";
6
6
  import { ago, duration, renderLog, renderPs } from "@anhlp/alp-client/render";
7
- import { isTaskId } from "@anhlp/alp-core/tasks";
7
+ import { AGENT_MARKER, isAgentProcess, isTaskId } from "@anhlp/alp-core/tasks";
8
8
  import { connect } from "@anhlp/alp-client/index";
9
9
  import { UsageError } from "./usage.js";
10
10
  import { start, running, stop } from "./daemon.js";
@@ -293,6 +293,7 @@ async function answer(args) {
293
293
  const { values, positionals: [questionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { dismiss: { type: "boolean" }, reason: { type: "string" } } });
294
294
  const text = words.join(" ").trim();
295
295
  if (!questionId || (values.dismiss ? text : !text)) throw new UsageError();
296
+ if (isAgentProcess()) throw new Error(`Only the user answers a question; this process runs under an ALP agent (${AGENT_MARKER})`);
296
297
  const client = await running();
297
298
  const result = await client.request("question.answer", values.dismiss ? { questionId, dismiss: true, reason: values.reason } : { questionId, text }).finally(() => client.close());
298
299
  console.log(`${values.dismiss ? "Dismissed" : "Answered"} ${result.questionId}`);
@@ -367,6 +368,18 @@ async function log(args) {
367
368
  }
368
369
  for (const line of renderLog(rootId, entries)) console.log(line);
369
370
  }
371
+ async function models(args) {
372
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { refresh: { type: "boolean" }, json: { type: "boolean" } } });
373
+ if (positionals.length) throw new UsageError();
374
+ const client = await running();
375
+ const catalog = await client.request(values.refresh ? "catalog.refresh" : "catalog.get", {}).finally(() => client.close());
376
+ if (values.json) {
377
+ console.log(JSON.stringify(catalog));
378
+ return;
379
+ }
380
+ for (const [runtime, state] of Object.entries(catalog.providers ?? {})) console.log(`${runtime}: ${state.status}${state.fetchedAt ? ` (${state.fetchedAt})` : ""}${state.error ? ` \u2014 ${state.error}` : ""}`);
381
+ for (const model of catalog.models) console.log(`${model.id.padEnd(40)} ${model.label}`);
382
+ }
370
383
  async function board(args) {
371
384
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: "string" }, json: { type: "boolean" } } });
372
385
  if (positionals.length) throw new UsageError();
@@ -435,14 +448,22 @@ async function interrupt(args) {
435
448
  await client.request("session.interrupt", { sessionId: args[0] }).finally(() => client.close());
436
449
  console.log("Interrupted");
437
450
  }
451
+ async function compact(args) {
452
+ if (args.length !== 1) throw new UsageError();
453
+ const client = await running();
454
+ const { status } = await client.request("session.compact", { sessionId: args[0] }).finally(() => client.close());
455
+ console.log(status === "started" ? "Compacting: main writes a checkpoint, then its context is compacted" : status === "running" ? "A compaction is already running" : "Compaction queued for the next turn boundary");
456
+ }
438
457
  export {
439
458
  answer,
440
459
  answerer,
441
460
  attach,
442
461
  board,
462
+ compact,
443
463
  follow,
444
464
  interrupt,
445
465
  log,
466
+ models,
446
467
  pause,
447
468
  printPauses,
448
469
  printer,
package/dist/tasks.js CHANGED
@@ -6,9 +6,11 @@ import { parseArgs } from "node:util";
6
6
  import { exportBeads, importBeads, parseJsonl } from "@anhlp/alp-core/beads";
7
7
  import { findFormula, formulaDirs, listFormulas, pourFormula } from "@anhlp/alp-core/formulas";
8
8
  import { describeVerification } from "@anhlp/alp-core/verify";
9
+ import { scriptCommand } from "@anhlp/alp-core/packaged";
9
10
  import { ago } from "@anhlp/alp-client/render";
10
11
  import { parse as toml } from "smol-toml";
11
- import { addGate, blockersOf, checkGates, childrenOf, closeTask, compactTasks, createTask, describeGate, gateOpen, epicReport, gatesOf, linkTask, listTasks, loadTasks, readyTasks, reopenTask, resolveGate, summarize, TASKS_DIR, updateTask } from "@anhlp/alp-core/tasks";
12
+ import { addGate, blockersOf, checkGates, childrenOf, closeTask, compactTasks, createTask, describeGate, gateOpen, epicReport, gatesOf, linkTask, listTasks, loadTasks, readyTasks, rejectGate, reopenTask, resolveGate, summarize, TASKS_DIR, updateTask, isAgentProcess, AGENT_MARKER } from "@anhlp/alp-core/tasks";
13
+ import { AlpError } from "@anhlp/alp-core/errors";
12
14
  import { alpHome } from "@anhlp/alp-client/index";
13
15
  import { UsageError } from "./usage.js";
14
16
  var STATUS_MARK = { open: "\u25CB", in_progress: "\u25D0", review: "\u25D1", closed: "\u25CF" };
@@ -62,7 +64,8 @@ async function tasksCommand(args) {
62
64
  var gh = (args, { cwd }) => new Promise((resolve, reject) => {
63
65
  const bin = process.env.ALP_GH_BIN ?? "gh";
64
66
  const script = process.platform === "win32" && /\.[cm]?js$/i.test(bin);
65
- const child = spawn(script ? process.execPath : bin, script ? [bin, ...args] : args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
67
+ const run = script ? scriptCommand(bin, args) : { command: bin, args };
68
+ const child = spawn(run.command, run.args, { cwd, ...run.env ? { env: { ...process.env, ...run.env } } : {}, stdio: ["ignore", "pipe", "pipe"] });
66
69
  let stdout = "";
67
70
  let stderr = "";
68
71
  child.stdout.on("data", (chunk) => {
@@ -227,7 +230,9 @@ async function taskCommand([action, ...args]) {
227
230
  human: { type: "string" },
228
231
  timer: { type: "string" },
229
232
  pr: { type: "string" },
230
- run: { type: "string" }
233
+ run: { type: "string" },
234
+ option: repeated,
235
+ choice: { type: "string" }
231
236
  } });
232
237
  const root = await taskProject(values.project);
233
238
  const fields = {
@@ -266,7 +271,7 @@ async function taskCommand([action, ...args]) {
266
271
  task = await updateTask(root, positionals[0], { ...fields, ...values.title !== void 0 ? { title: values.title } : {}, note: values.message }, "user");
267
272
  } else if (action === "close") {
268
273
  if (positionals.length !== 1) throw new UsageError();
269
- task = await closeTask(root, positionals[0], { reason: values.reason, summary: values.message, unverified: values.unverified }, "user");
274
+ task = await closeTask(root, positionals[0], { reason: values.reason, summary: values.message, unverified: values.unverified, agent: isAgentProcess(), channel: "cli" }, "user");
270
275
  } else if (action === "reopen") {
271
276
  if (positionals.length !== 1) throw new UsageError();
272
277
  task = await reopenTask(root, positionals[0], { note: values.message }, "user");
@@ -278,11 +283,20 @@ async function taskCommand([action, ...args]) {
278
283
  } else if (action === "gate") {
279
284
  const [change, id, gate, ...rest] = positionals;
280
285
  const kinds = ["human", "timer", "pr", "run"].filter((kind) => values[kind] !== void 0);
286
+ if (["clear", "reject", "rm"].includes(change) && id && gate && isAgentProcess()) {
287
+ const { tasks: current } = await loadTasks(root);
288
+ if (current.find((entry) => entry.id === id)?.gates.find((entry) => entry.id === gate)?.kind === "human") throw new AlpError("GATE_USER_ONLY", `Only the user clears a human gate; this process runs under an ALP agent (${AGENT_MARKER}). Ask the user to decide it`);
289
+ }
281
290
  if (change === "add" && id && !gate && kinds.length === 1) {
282
291
  const kind = kinds[0];
283
- task = await addGate(root, id, kind === "human" ? { kind, note: values.human } : kind === "timer" ? { kind, until: values.timer } : { kind: `gh:${kind}`, ref: values[kind] }, "user");
284
- } else if ((change === "clear" || change === "rm") && id && gate && !rest.length && !kinds.length) {
285
- task = await resolveGate(root, id, gate, { by: "user", note: values.message, remove: change === "rm" });
292
+ if (values.option && kind !== "human") throw new UsageError();
293
+ task = await addGate(root, id, kind === "human" ? { kind, note: values.human, ...values.option ? { options: values.option } : {} } : kind === "timer" ? { kind, until: values.timer } : { kind: `gh:${kind}`, ref: values[kind] }, "user");
294
+ } else if (change === "clear" && id && gate && !rest.length && !kinds.length && !values.option) {
295
+ task = await resolveGate(root, id, gate, { by: "user", note: values.message, channel: "cli", ...values.choice !== void 0 ? { choice: values.choice } : {} });
296
+ } else if (change === "reject" && id && gate && !rest.length && !kinds.length && !values.option && values.choice === void 0) {
297
+ task = await rejectGate(root, id, gate, { by: "user", reason: values.message, channel: "cli" });
298
+ } else if (change === "rm" && id && gate && !rest.length && !kinds.length && !values.option && values.choice === void 0) {
299
+ task = await resolveGate(root, id, gate, { by: "user", note: values.message, remove: true, channel: "cli" });
286
300
  } else {
287
301
  throw new UsageError();
288
302
  }
@@ -314,7 +328,7 @@ function printTask(task, tasks) {
314
328
  task.related.length && `related ${task.related.join(", ")}`
315
329
  ].filter(Boolean);
316
330
  if (relations.length) console.log(` ${relations.join("; ")}`);
317
- for (const gate of task.gates) console.log(` ${gateOpen(gate) ? "\u23F8" : "\u2713"} gate ${describeGate(gate)}${gate.resolved ? ` (cleared by ${gate.resolved.by}${gate.resolved.note ? `: ${gate.resolved.note}` : ""})` : ""}`);
331
+ for (const gate of task.gates) console.log(` ${gateOpen(gate) ? "\u23F8" : "\u2713"} gate ${describeGate(gate)}${gate.resolved ? ` (cleared by ${gate.resolved.by}${gate.resolved.choice ? ` with "${gate.resolved.choice}"` : ""}${gate.resolved.channel ? ` in ${gate.resolved.channel}` : ""}${gate.resolved.note ? `: ${gate.resolved.note}` : ""})` : gate.rejected ? ` (rejected by ${gate.rejected.by}${gate.rejected.reason ? `: ${gate.rejected.reason}` : ""})` : ""}${gateOpen(gate) && gate.options ? ` options: ${gate.options.join(" | ")}` : ""}${gate.tampered ? " \u26A0 changed outside ALP (a task file edit cleared or removed it); reopened for you to decide" : ""}`);
318
332
  const inherited = gatesOf(task, tasks).filter((label) => label.startsWith("t-"));
319
333
  if (task.status !== "closed" && inherited.length) console.log(` waits on its parent's gates: ${inherited.join("; ")}`);
320
334
  if (task.compacted) console.log(` compacted ${task.compacted.at.slice(0, 10)} from ${task.compacted.chars} characters`);