@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/dist/projects.js CHANGED
@@ -21,8 +21,9 @@ async function project(command, args) {
21
21
  try {
22
22
  const result = await (command === "upgrade" ? upgradeProject : initProject)(args[0] ?? process.cwd(), { library: alpHome() });
23
23
  console.log(`ALP initialized: ${result.created.length} files created, ${result.preserved.length} existing files preserved.`);
24
- const library = await seedLibrary(alpHome());
24
+ const library = await seedLibrary(alpHome(), { offerRoleSkills: command === "upgrade" });
25
25
  if (library.created.length || library.updated.length) console.log(`Skill library ${alpHome()}: ${library.created.length} files added, ${library.updated.length} unchanged files updated.`);
26
+ 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).`);
26
27
  if (command === "init" && result.updated?.length) console.log(`Template model profiles refreshed: ${result.updated.join(", ")}`);
27
28
  if (command === "upgrade") {
28
29
  console.log(`ALP upgraded: ${result.updated.length} files updated.${result.backup ? ` Backup: ${result.backup}` : ""}`);
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The role subcommands (t-1e02): `alp daemon run`, `alp dashboard serve` and `alp bridge acp|antigravity`
3
+ * run alpd, alp-dashboard and the MCP bridges in this process: they import the same scripts that
4
+ * `node alpd.js` and `node alp-dashboard.js` run. Services and MCP entries written by the single-file
5
+ * executable of 0.0.1-beta.5/6 still name them.
6
+ *
7
+ * The role's module reads its options from process.argv as when run directly, so argv is rewritten
8
+ * to `[runtime, entry, ...args]` before the module loads.
9
+ * @param {'daemon' | 'dashboard' | 'acp'} role
10
+ * @param {string} file the role's script beside this CLI
11
+ * @param {string[]} args
12
+ */
13
+ export function runRole(role: "daemon" | "dashboard" | "acp", file: string, args: string[]): Promise<any>;
14
+ /** alp bridge acp|antigravity: the stdio MCP bridge an agent CLI starts to reach alpd's tools. @param {string[]} args */
15
+ export function bridgeCommand(args: string[]): void;
package/dist/roles.js ADDED
@@ -0,0 +1,16 @@
1
+ // packages/cli/src/roles.js
2
+ import { pathToFileURL } from "node:url";
3
+ import { runBridge } from "@anhlp/alp-core/bridges";
4
+ import { UsageError } from "./usage.js";
5
+ async function runRole(role, file, args) {
6
+ process.argv = [process.argv[0], file, ...args];
7
+ return import(pathToFileURL(file).href);
8
+ }
9
+ function bridgeCommand(args) {
10
+ if (args.length !== 1 || !["acp", "antigravity"].includes(args[0])) throw new UsageError();
11
+ runBridge(args[0]);
12
+ }
13
+ export {
14
+ bridgeCommand,
15
+ runRole
16
+ };
@@ -0,0 +1,2 @@
1
+ /** One-shot continuations of an existing root session; timestamps need an explicit offset. */
2
+ export function scheduleCommand(args: any): Promise<void>;
@@ -0,0 +1,45 @@
1
+ // packages/cli/src/schedules.js
2
+ import path from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { running } from "./daemon.js";
5
+ import { UsageError } from "./usage.js";
6
+ async function scheduleCommand(args) {
7
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
8
+ project: { type: "string" },
9
+ session: { type: "string" },
10
+ at: { type: "string" },
11
+ prompt: { type: "string" },
12
+ status: { type: "string" },
13
+ json: { type: "boolean" }
14
+ } });
15
+ const [action, id, ...extra] = positionals;
16
+ if (!["create", "list", "show", "cancel"].includes(action) || extra.length) throw new UsageError();
17
+ if (action === "show" || action === "cancel" ? !id : !!id) throw new UsageError();
18
+ if (action !== "create" && (values.session || values.at || values.prompt)) throw new UsageError();
19
+ if (action !== "list" && values.status) throw new UsageError();
20
+ if (action === "create" && (!values.session || !values.prompt?.trim() || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(values.at ?? "") || !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)");
21
+ const projectRoot = path.resolve(values.project ?? process.cwd());
22
+ const params = action === "create" ? { projectRoot, sessionId: values.session, dueAt: values.at, prompt: values.prompt } : { projectRoot, ...id ? { id } : {}, ...values.status ? { status: values.status } : {} };
23
+ const client = await running();
24
+ try {
25
+ const result = await client.request(`schedule.${action === "show" ? "get" : action}`, params);
26
+ if (values.json) {
27
+ console.log(JSON.stringify(result));
28
+ return;
29
+ }
30
+ const jobs = result.jobs ?? [result.job];
31
+ if (!jobs.length) console.log("No scheduled continuations");
32
+ for (const job of jobs) {
33
+ console.log(`${job.id} ${job.status} ${job.dueAt} session ${job.sessionId}`);
34
+ console.log(` ${job.prompt}`);
35
+ if (job.attemptedAt) console.log(` attempted ${job.attemptedAt}; attempts ${job.attempts}; late ${job.lateByMs ?? 0} ms`);
36
+ for (const field of ["deliveredAt", "failedAt", "cancelledAt"]) if (job[field]) console.log(` ${field}: ${job[field]}`);
37
+ if (job.lastError) console.log(` ${job.lastError.code ?? "error"}: ${job.lastError.message}`);
38
+ }
39
+ } finally {
40
+ client.close();
41
+ }
42
+ }
43
+ export {
44
+ scheduleCommand
45
+ };
@@ -0,0 +1,151 @@
1
+ /** The release platform of this process: darwin-arm64, linux-x64, windows-x64. @param {string} platform @param {string} arch */
2
+ export function releasePlatform(platform?: string, arch?: string): string;
3
+ /** Parses SHA256SUMS into [{ sha256, name }]. @param {string} text */
4
+ export function parseSums(text: string): {
5
+ sha256: string;
6
+ name: string;
7
+ }[];
8
+ /**
9
+ * The archive for `platform` in SHA256SUMS: alp-<version>-<platform>.<ext>, for `version` when given.
10
+ * @param {string} sumsText @param {string} platform @param {string} [version]
11
+ * @returns {{ name: string, sha256: string, version: string }}
12
+ */
13
+ export function selectAsset(sumsText: string, platform: string, version?: string): {
14
+ name: string;
15
+ sha256: string;
16
+ version: string;
17
+ };
18
+ /** Refuses an archive whose digest differs from SHA256SUMS. @param {Uint8Array} bytes @param {{ name: string, sha256: string }} asset */
19
+ export function verifyChecksum(bytes: Uint8Array, asset: {
20
+ name: string;
21
+ sha256: string;
22
+ }): string;
23
+ /** Compares dotted versions numerically, prerelease below release. @param {string} a @param {string} b */
24
+ export function compareVersions(a: string, b: string): number;
25
+ /** The base URL that holds SHA256SUMS and the archives. @param {{ repo: string, version?: string, baseUrl?: string }} options */
26
+ export function releaseBaseUrl({ repo, version, baseUrl }: {
27
+ repo: string;
28
+ version?: string;
29
+ baseUrl?: string;
30
+ }): string;
31
+ /**
32
+ * Whether a download may go to `next`: every hop of an https download stays https, since one plain
33
+ * http hop lets a man in the middle replace the archive and SHA256SUMS together. Only a loopback
34
+ * http mirror given explicitly (tests) may use loopback http, besides https.
35
+ * @param {string} start @param {string} next
36
+ */
37
+ export function allowedHop(start: string, next: string): boolean;
38
+ /**
39
+ * Downloads `url` (https, loopback http or file) within a time and size limit, following at most 10
40
+ * redirects itself and refusing any hop that `allowedHop` refuses.
41
+ * @param {string} url @param {{ timeoutMs?: number, max?: number, fetch?: typeof globalThis.fetch }} [options]
42
+ */
43
+ export function fetchBytes(url: string, { timeoutMs, max, fetch: fetchImpl }?: {
44
+ timeoutMs?: number;
45
+ max?: number;
46
+ fetch?: typeof globalThis.fetch;
47
+ }): Promise<Uint8Array<ArrayBuffer>>;
48
+ /**
49
+ * Verifies the archive's build provenance with gh. Returns 'verified', or 'unavailable' when gh is
50
+ * absent (ALP_UPDATE_NO_GH=1 treats it as absent); throws when gh reports a failure.
51
+ * @param {string} file @param {{ repo: string, env?: NodeJS.ProcessEnv, run?: typeof spawnSync, find?: typeof which }} options
52
+ */
53
+ export function verifyProvenance(file: string, { repo, env, run, find }: {
54
+ repo: string;
55
+ env?: NodeJS.ProcessEnv;
56
+ run?: typeof spawnSync;
57
+ find?: typeof which;
58
+ }): "unavailable" | "verified";
59
+ /**
60
+ * Runs `action`, again after a pause while Windows reports the file busy: a virus scanner holds an
61
+ * executable it just saw run (the staged bundle's --version) for a moment. About 8 s in all.
62
+ * @template T @param {() => T} action @param {(ms: number) => void} [sleep]
63
+ */
64
+ export function retryBusy<T>(action: () => T, sleep?: (ms: number) => void, attempts?: number): T;
65
+ /** What to say outside the ALP bundle (an npm install). @param {string[]} positionals */
66
+ export function npmMessage(positionals?: string[]): string;
67
+ /** 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 */
68
+ export function bundleCommand(root: string, platform?: string): {
69
+ command: string;
70
+ args: string[];
71
+ };
72
+ /**
73
+ * Points `<app>/current` at `<app>/<version>`. Unix: a relative symlink renamed over the old one, in
74
+ * one step. Windows: the junction is replaced (removed, then made again; put back on failure).
75
+ * @param {string} app @param {string} version @param {{ platform?: string, fs?: typeof nodeFs, unique?: () => string }} [options]
76
+ */
77
+ export function switchCurrent(app: string, version: string, { platform, fs, unique }?: {
78
+ platform?: string;
79
+ fs?: typeof nodeFs;
80
+ unique?: () => string;
81
+ }): void;
82
+ /**
83
+ * Removes what earlier updates left in `<app>`: versions other than `keep`, and staging directories.
84
+ * A failure (a file still in use on Windows) leaves that entry for the next update. keepAside keeps
85
+ * the copies earlier reinstalls moved aside, which a running alpd may still run from.
86
+ * @param {string} app @param {string[]} keep
87
+ */
88
+ export function pruneVersions(app: string, keep: string[], fs?: typeof nodeFs, { keepAside }?: {
89
+ keepAside?: boolean | undefined;
90
+ }): string[];
91
+ /**
92
+ * @typedef {{
93
+ * bundle: import('@anhlp/alp-core/packaged').BundleInfo | undefined, version: string, env: NodeJS.ProcessEnv, platform: string, arch: string,
94
+ * log: (line: string) => void, warn: (line: string) => void, interactive: boolean,
95
+ * fetchBytes: (url: string) => Promise<Uint8Array>, confirm: (question: string) => Promise<boolean>,
96
+ * provenance: (file: string, repo: string) => string, extract: typeof extract,
97
+ * daemon: () => Promise<{ version: string, sessions?: number } | undefined>, restartDaemon: (root: string) => number,
98
+ * runVersion: (root: string) => string, runDaemonVersion: (root: string) => string,
99
+ * }} UpdateDeps
100
+ */
101
+ /** @param {string[]} args @param {Partial<UpdateDeps>} [overrides] @returns {Promise<number>} the exit code */
102
+ export function selfUpdate(args: string[], overrides?: Partial<UpdateDeps>): Promise<number>;
103
+ /**
104
+ * `alp update` (t-1807): installs a release of the ALP bundle from GitHub Releases beside the running
105
+ * one (<app>/<version>, see @anhlp/alp-core/packaged) and points <app>/current at it, after checking
106
+ * the archive against the release's SHA256SUMS and, when `gh` is installed, its build provenance.
107
+ * The project template upgrade that `alp update` used to run is `alp update-template`.
108
+ *
109
+ * Everything that touches the network, the filesystem or child processes comes in through `deps`
110
+ * so the tests can drive each step.
111
+ */
112
+ export const DEFAULT_REPO: "phucanh08/alp";
113
+ export const SIGNER_WORKFLOW: ".github/workflows/release-binaries.yml";
114
+ export const NPM_PACKAGE: "@anhlp/alp";
115
+ export const UPDATE_USAGE: "Usage: alp update [--check] [--yes] [--version X] [--base-url URL]\nInstalls the latest ALP release (or release X) from GitHub Releases beside this one and switches to it, after checking\nit against SHA256SUMS and, when gh is installed, its build provenance. --check only reports.\nALP_UPDATE_BASE_URL (as --base-url, an https:// or file:// mirror) and ALP_INSTALL_REPO (owner/name) override the source.\nThe project template upgrade is `alp update-template [directory]`.";
116
+ export function archiveExtension(platform: string): ".zip" | ".tar.gz";
117
+ export function sha256(bytes: Uint8Array): string;
118
+ /** The largest file alp update downloads: an archive of the bundle is about 70 MB. */
119
+ export const MAX_DOWNLOAD: number;
120
+ export function notInstalledMessage(root: string): string;
121
+ export function systemTar(platform?: string, env?: Record<string, string | undefined>): string;
122
+ export type UpdateDeps = {
123
+ bundle: import("@anhlp/alp-core/packaged").BundleInfo | undefined;
124
+ version: string;
125
+ env: NodeJS.ProcessEnv;
126
+ platform: string;
127
+ arch: string;
128
+ log: (line: string) => void;
129
+ warn: (line: string) => void;
130
+ interactive: boolean;
131
+ fetchBytes: (url: string) => Promise<Uint8Array>;
132
+ confirm: (question: string) => Promise<boolean>;
133
+ provenance: (file: string, repo: string) => string;
134
+ extract: typeof extract;
135
+ daemon: () => Promise<{
136
+ version: string;
137
+ sessions?: number;
138
+ } | undefined>;
139
+ restartDaemon: (root: string) => number;
140
+ runVersion: (root: string) => string;
141
+ runDaemonVersion: (root: string) => string;
142
+ };
143
+ import { spawnSync } from 'node:child_process';
144
+ /** Whether a program is on PATH. @param {string} name */
145
+ declare function which(name: string): string | undefined;
146
+ import * as nodeFs from 'node:fs';
147
+ /** Extracts the archive into `directory` and returns the bundle inside it. @param {string} archive @param {string} directory @param {{ name: string }} asset @param {string} platform */
148
+ declare function extract(archive: string, directory: string, asset: {
149
+ name: string;
150
+ }, platform: string, run?: typeof spawnSync): string;
151
+ export {};
@@ -0,0 +1,422 @@
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 { bundleInfo, NATIVE_DAEMON, samePath } 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 ALP itself; 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
+ Installs the latest ALP release (or release X) from GitHub Releases beside this one and switches to it, 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 build 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 build 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 TRANSIENT = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES", "ENOTEMPTY"]);
141
+ var pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
142
+ function retryBusy(action, sleep = pause, attempts = 25) {
143
+ for (let attempt = 1; ; attempt++) {
144
+ try {
145
+ return action();
146
+ } catch (error) {
147
+ if (attempt >= attempts || !TRANSIENT.has(error?.code)) throw error;
148
+ sleep(Math.min(50 * attempt, 400));
149
+ }
150
+ }
151
+ }
152
+ function npmMessage(positionals = []) {
153
+ const lines = [];
154
+ if (positionals.length) lines.push(`alp: ${TEMPLATE_HINT}`);
155
+ lines.push(`This alp was installed with npm; update it with npm:
156
+ npm install -g ${NPM_PACKAGE}@beta
157
+ Then restart alpd when no sessions are running: alp daemon restart
158
+ (The project template upgrade is \`alp update-template [directory]\`.)`);
159
+ return lines.join("\n");
160
+ }
161
+ var 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:
162
+ curl -fsSL https://github.com/${DEFAULT_REPO}/releases/latest/download/install.sh | sh`;
163
+ var systemTar = (platform = process.platform, env = process.env) => platform === "win32" ? path.win32.join(env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe") : "tar";
164
+ function extract(archive, directory, asset, platform, run = spawnSync) {
165
+ const windows = platform.startsWith("windows-");
166
+ const result = run(systemTar(), [windows ? "-xf" : "-xzf", archive, "-C", directory], { encoding: "utf8", windowsHide: true });
167
+ if (result.status !== 0) throw new Error(`Could not extract ${asset.name}: ${(result.stderr || result.error?.message || "").trim()}`);
168
+ const root = path.join(directory, asset.name.slice(0, -archiveExtension(platform).length));
169
+ 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)`);
170
+ return root;
171
+ }
172
+ function bundleCommand(root, platform = process.platform) {
173
+ const node = platform === "win32" ? path.join(root, "node", "node.exe") : path.join(root, "node", "bin", "node");
174
+ return { command: node, args: [path.join(root, "lib", "node_modules", "@anhlp", "alp-cli", "dist", "cli.js")] };
175
+ }
176
+ function switchCurrent(app, version, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(6).toString("hex") } = {}) {
177
+ const p = platform === "win32" ? path.win32 : path;
178
+ const current = p.join(app, "current");
179
+ if (platform !== "win32") {
180
+ const link = p.join(app, `.current-${unique()}`);
181
+ fs.symlinkSync(version, link);
182
+ try {
183
+ fs.renameSync(link, current);
184
+ } catch (error) {
185
+ try {
186
+ fs.unlinkSync(link);
187
+ } catch {
188
+ }
189
+ throw error;
190
+ }
191
+ return;
192
+ }
193
+ let previous;
194
+ try {
195
+ previous = fs.readlinkSync(current);
196
+ } catch {
197
+ }
198
+ if (previous !== void 0) retryBusy(() => fs.unlinkSync(current));
199
+ try {
200
+ fs.symlinkSync(p.join(app, version), current, "junction");
201
+ } catch (error) {
202
+ if (previous !== void 0) try {
203
+ fs.symlinkSync(previous, current, "junction");
204
+ } catch {
205
+ }
206
+ throw error;
207
+ }
208
+ }
209
+ function pruneVersions(app, keep, fs = nodeFs, { keepAside = false } = {}) {
210
+ let names;
211
+ try {
212
+ names = fs.readdirSync(app);
213
+ } catch {
214
+ return [];
215
+ }
216
+ const removed = [];
217
+ for (const name of names) {
218
+ if (name === "current" || keep.includes(name) || keepAside && name.startsWith(".alp-old-")) continue;
219
+ 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;
220
+ try {
221
+ fs.rmSync(path.join(app, name), { recursive: true, force: true });
222
+ removed.push(name);
223
+ } catch {
224
+ }
225
+ }
226
+ return removed;
227
+ }
228
+ async function confirm(question) {
229
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
230
+ try {
231
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
232
+ } finally {
233
+ rl.close();
234
+ }
235
+ }
236
+ async function selfUpdate(args, overrides = {}) {
237
+ const deps = {
238
+ bundle: bundleInfo(),
239
+ version: "0.0.0",
240
+ env: process.env,
241
+ platform: process.platform,
242
+ arch: process.arch,
243
+ log: (line) => console.log(line),
244
+ warn: (line) => console.error(line),
245
+ interactive: !!(process.stdin.isTTY && process.stdout.isTTY),
246
+ fetchBytes,
247
+ confirm,
248
+ extract,
249
+ provenance: (file, repo2) => verifyProvenance(file, { repo: repo2 }),
250
+ daemon: async () => void 0,
251
+ restartDaemon: (root) => {
252
+ const run = bundleCommand(root);
253
+ return spawnSync(run.command, [...run.args, "daemon", "restart"], { stdio: "inherit", windowsHide: true }).status ?? 1;
254
+ },
255
+ runVersion: (root) => {
256
+ const run = bundleCommand(root);
257
+ return spawnSync(run.command, [...run.args, "--version"], { encoding: "utf8", windowsHide: true, timeout: 6e4 }).stdout?.trim() ?? "";
258
+ },
259
+ // Without BUN_BE_BUN, which would make the native alpd the Bun CLI.
260
+ runDaemonVersion: (root) => spawnSync(path.join(root, "bin", NATIVE_DAEMON), ["--version"], { encoding: "utf8", windowsHide: true, timeout: 6e4, env: Object.fromEntries(Object.entries(process.env).filter(([name]) => name !== "BUN_BE_BUN")) }).stdout?.trim() ?? "",
261
+ ...overrides
262
+ };
263
+ const { bundle } = deps;
264
+ let parsed;
265
+ try {
266
+ parsed = parseArgs({ args, allowPositionals: true, options: OPTIONS, strict: true });
267
+ } catch (error) {
268
+ deps.warn(`alp: ${error.message}`);
269
+ deps.warn(`alp: ${TEMPLATE_HINT}`);
270
+ return bundle ? 1 : 0;
271
+ }
272
+ const { values, positionals } = parsed;
273
+ if (values.help) {
274
+ deps.log(UPDATE_USAGE);
275
+ return 0;
276
+ }
277
+ if (!bundle) {
278
+ deps.log(npmMessage(positionals));
279
+ return 0;
280
+ }
281
+ if (positionals.length) {
282
+ deps.warn(`alp: ${TEMPLATE_HINT}`);
283
+ return 1;
284
+ }
285
+ if (!bundle.current) {
286
+ deps.warn(notInstalledMessage(bundle.root));
287
+ return 1;
288
+ }
289
+ const wanted = values.version?.replace(/^v/, "");
290
+ if (wanted !== void 0 && !/^[0-9][0-9A-Za-z.+-]*$/.test(wanted)) throw new Error(`Invalid version: ${values.version}`);
291
+ const repo = deps.env.ALP_INSTALL_REPO || DEFAULT_REPO;
292
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error(`Invalid ALP_INSTALL_REPO: ${repo}`);
293
+ const base = releaseBaseUrl({ repo, version: wanted, baseUrl: values["base-url"] ?? deps.env.ALP_UPDATE_BASE_URL });
294
+ const platform = releasePlatform(deps.platform, deps.arch);
295
+ const sums = new TextDecoder().decode(await deps.fetchBytes(`${base}/SHA256SUMS`));
296
+ const asset = selectAsset(sums, platform, wanted);
297
+ const order = compareVersions(asset.version, deps.version);
298
+ if (values.check) {
299
+ if (order === 0) deps.log(`alp ${deps.version} is up to date (${platform})`);
300
+ else if (order < 0 && !wanted) deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}`);
301
+ else deps.log(`alp ${deps.version} \u2192 ${asset.version} available (${asset.name}); run: alp update${wanted ? ` --version ${wanted}` : ""}`);
302
+ return 0;
303
+ }
304
+ if (order === 0 && !wanted) {
305
+ deps.log(`alp ${deps.version} is up to date (${platform})`);
306
+ return 0;
307
+ }
308
+ if (order < 0 && !wanted) {
309
+ deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}; nothing to do (pass --version ${asset.version} to go back)`);
310
+ return 0;
311
+ }
312
+ const { app, current } = bundle;
313
+ const running = await deps.daemon().catch(() => void 0);
314
+ try {
315
+ nodeFs.accessSync(app, nodeFs.constants.W_OK);
316
+ } catch {
317
+ throw new Error(`${app} is not writable; run alp update with the permissions that installed ALP there`);
318
+ }
319
+ const target = path.join(app, asset.version);
320
+ if (!values.yes) {
321
+ if (!deps.interactive) throw new Error(`alp update would install ${target} and switch ${current} to it (${deps.version} \u2192 ${asset.version}); pass --yes to do it without a terminal`);
322
+ if (!await deps.confirm(`Install ALP ${asset.version} in ${target} and switch to it (from ${deps.version})?`)) {
323
+ deps.log("Not updated.");
324
+ return 1;
325
+ }
326
+ }
327
+ const work = nodeFs.mkdtempSync(path.join(os.tmpdir(), "alp-update-"));
328
+ const staging = path.join(app, `.alp-update-${randomBytes(6).toString("hex")}`);
329
+ let aside;
330
+ try {
331
+ deps.log(`Downloading ${asset.name} from ${base}`);
332
+ const bytes = await deps.fetchBytes(`${base}/${asset.name}`);
333
+ verifyChecksum(bytes, asset);
334
+ deps.log(`Checksum verified (${asset.sha256})`);
335
+ const archive = path.join(work, asset.name);
336
+ nodeFs.writeFileSync(archive, bytes);
337
+ const provenance = deps.provenance(archive, repo);
338
+ if (provenance === "verified") deps.log(`Provenance verified by gh attestation (${repo}, refs/heads/main, release-binaries.yml)`);
339
+ 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)");
340
+ nodeFs.mkdirSync(staging);
341
+ const unpacked = deps.extract(archive, staging, asset, platform);
342
+ const manifest = JSON.parse(nodeFs.readFileSync(path.join(unpacked, "alp-bundle.json"), "utf8"));
343
+ 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`);
344
+ const reported = deps.runVersion(unpacked);
345
+ if (reported !== asset.version) throw new Error(`The downloaded ALP reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was changed`);
346
+ if (deps.env.ALP_NATIVE_DAEMON !== "0" && nodeFs.existsSync(path.join(unpacked, "bin", NATIVE_DAEMON))) {
347
+ const native = deps.runDaemonVersion(unpacked);
348
+ 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`);
349
+ }
350
+ if (nodeFs.existsSync(target)) {
351
+ if (samePath(target, bundle.root) || running?.version === asset.version) {
352
+ const moved = `.alp-old-${randomBytes(6).toString("hex")}`;
353
+ try {
354
+ retryBusy(() => nodeFs.renameSync(target, path.join(app, moved)));
355
+ } catch (error) {
356
+ 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 });
357
+ }
358
+ aside = moved;
359
+ } else nodeFs.rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
360
+ }
361
+ try {
362
+ retryBusy(() => nodeFs.renameSync(unpacked, target));
363
+ } catch (error) {
364
+ if (aside && !nodeFs.existsSync(target)) {
365
+ try {
366
+ nodeFs.renameSync(path.join(app, aside), target);
367
+ aside = void 0;
368
+ } catch {
369
+ throw new Error(`${error.message}; the running ALP ${asset.version} is in ${path.join(app, aside)}: move it back to ${target}`, { cause: error });
370
+ }
371
+ }
372
+ throw error;
373
+ }
374
+ switchCurrent(app, asset.version, { platform: deps.platform });
375
+ } finally {
376
+ try {
377
+ nodeFs.rmSync(staging, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
378
+ } catch {
379
+ }
380
+ try {
381
+ nodeFs.rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
382
+ } catch {
383
+ }
384
+ }
385
+ pruneVersions(app, [asset.version, path.basename(bundle.root), ...running?.version ? [running.version] : [], ...aside ? [aside] : []], nodeFs, { keepAside: Boolean(running) });
386
+ deps.log(`Updated ALP ${deps.version} \u2192 ${asset.version} (${current} \u2192 ${target})`);
387
+ if (running && running.version !== asset.version) {
388
+ const sessions = running.sessions;
389
+ const known = Number.isSafeInteger(sessions);
390
+ 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`);
391
+ if (!values.yes && deps.interactive && known && sessions === 0 && await deps.confirm("Restart alpd now?")) {
392
+ if (deps.restartDaemon(target) !== 0) deps.warn("alp: alp daemon restart failed; run it yourself");
393
+ }
394
+ }
395
+ return 0;
396
+ }
397
+ export {
398
+ DEFAULT_REPO,
399
+ MAX_DOWNLOAD,
400
+ NPM_PACKAGE,
401
+ SIGNER_WORKFLOW,
402
+ UPDATE_USAGE,
403
+ allowedHop,
404
+ archiveExtension,
405
+ bundleCommand,
406
+ compareVersions,
407
+ fetchBytes,
408
+ notInstalledMessage,
409
+ npmMessage,
410
+ parseSums,
411
+ pruneVersions,
412
+ releaseBaseUrl,
413
+ releasePlatform,
414
+ retryBusy,
415
+ selectAsset,
416
+ selfUpdate,
417
+ sha256,
418
+ switchCurrent,
419
+ systemTar,
420
+ verifyChecksum,
421
+ verifyProvenance
422
+ };