@anhlp/alp-cli 0.0.1-beta.4 → 0.0.1-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD-PARTY-NOTICES.txt +26 -1
- package/dist/acp/main.js +1 -1
- package/dist/acp.js +152 -33
- package/dist/alp-web/THIRD-PARTY-NOTICES.txt +666 -0
- package/dist/alp-web/alp-boundary.json +1 -0
- package/dist/alp-web/assets/TerminalPanel-BeMws9CP.js +22 -0
- package/dist/alp-web/assets/highlighter-BnicKQ_d.js +18 -0
- package/dist/alp-web/assets/index-Dl7motn1.js +59 -0
- package/dist/alp-web/assets/index-DwqDSiIi.css +1 -0
- package/dist/alp-web/index.html +2 -2
- package/dist/alp-web.js +529 -172
- package/dist/alpd.js +10623 -2570
- package/dist/backup.js +1 -1
- package/dist/build-manifest.json +22 -2
- package/dist/cli.js +28 -3
- package/dist/daemon.d.ts +1 -1
- package/dist/daemon.js +5 -0
- package/dist/interfaces.d.ts +13 -1
- package/dist/interfaces.js +95 -11
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +2 -1
- package/dist/roles.d.ts +15 -0
- package/dist/roles.js +16 -0
- package/dist/self-update.d.ts +149 -0
- package/dist/self-update.js +399 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +22 -1
- package/dist/tasks.js +22 -8
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal.d.ts +5 -0
- package/dist/terminal.js +4 -3
- package/dist/usage.d.ts +1 -1
- package/dist/usage.js +14 -5
- package/dist/web-service.d.ts +22 -4
- package/dist/web-service.js +32 -8
- package/package.json +6 -5
- package/src/cli.js +35 -4
- package/src/daemon.js +3 -0
- package/src/interfaces.js +101 -12
- package/src/paths.js +3 -1
- package/src/roles.js +26 -0
- package/src/self-update.js +406 -0
- package/src/sessions.js +23 -2
- package/src/tasks.js +22 -8
- package/src/terminal.js +4 -3
- package/src/usage.js +14 -5
- package/src/web-service.js +56 -13
- package/dist/alp-web/assets/TerminalPanel-PrU2l3u5.js +0 -16
- package/dist/alp-web/assets/index-BJdBTDFX.css +0 -1
- package/dist/alp-web/assets/index-DpfiPv5s.js +0 -52
- package/src/web/grant.js +0 -204
- package/src/web/main.js +0 -285
- package/src/web/serve.js +0 -144
|
@@ -0,0 +1,399 @@
|
|
|
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, 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 = () => process.platform === "win32" ? path.join(process.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
|
+
...overrides
|
|
260
|
+
};
|
|
261
|
+
const { bundle } = deps;
|
|
262
|
+
let parsed;
|
|
263
|
+
try {
|
|
264
|
+
parsed = parseArgs({ args, allowPositionals: true, options: OPTIONS, strict: true });
|
|
265
|
+
} catch (error) {
|
|
266
|
+
deps.warn(`alp: ${error.message}`);
|
|
267
|
+
deps.warn(`alp: ${TEMPLATE_HINT}`);
|
|
268
|
+
return bundle ? 1 : 0;
|
|
269
|
+
}
|
|
270
|
+
const { values, positionals } = parsed;
|
|
271
|
+
if (values.help) {
|
|
272
|
+
deps.log(UPDATE_USAGE);
|
|
273
|
+
return 0;
|
|
274
|
+
}
|
|
275
|
+
if (!bundle) {
|
|
276
|
+
deps.log(npmMessage(positionals));
|
|
277
|
+
return 0;
|
|
278
|
+
}
|
|
279
|
+
if (positionals.length) {
|
|
280
|
+
deps.warn(`alp: ${TEMPLATE_HINT}`);
|
|
281
|
+
return 1;
|
|
282
|
+
}
|
|
283
|
+
if (!bundle.current) {
|
|
284
|
+
deps.warn(notInstalledMessage(bundle.root));
|
|
285
|
+
return 1;
|
|
286
|
+
}
|
|
287
|
+
const wanted = values.version?.replace(/^v/, "");
|
|
288
|
+
if (wanted !== void 0 && !/^[0-9][0-9A-Za-z.+-]*$/.test(wanted)) throw new Error(`Invalid version: ${values.version}`);
|
|
289
|
+
const repo = deps.env.ALP_INSTALL_REPO || DEFAULT_REPO;
|
|
290
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error(`Invalid ALP_INSTALL_REPO: ${repo}`);
|
|
291
|
+
const base = releaseBaseUrl({ repo, version: wanted, baseUrl: values["base-url"] ?? deps.env.ALP_UPDATE_BASE_URL });
|
|
292
|
+
const platform = releasePlatform(deps.platform, deps.arch);
|
|
293
|
+
const sums = new TextDecoder().decode(await deps.fetchBytes(`${base}/SHA256SUMS`));
|
|
294
|
+
const asset = selectAsset(sums, platform, wanted);
|
|
295
|
+
const order = compareVersions(asset.version, deps.version);
|
|
296
|
+
if (values.check) {
|
|
297
|
+
if (order === 0) deps.log(`alp ${deps.version} is up to date (${platform})`);
|
|
298
|
+
else if (order < 0 && !wanted) deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}`);
|
|
299
|
+
else deps.log(`alp ${deps.version} \u2192 ${asset.version} available (${asset.name}); run: alp update${wanted ? ` --version ${wanted}` : ""}`);
|
|
300
|
+
return 0;
|
|
301
|
+
}
|
|
302
|
+
if (order === 0 && !wanted) {
|
|
303
|
+
deps.log(`alp ${deps.version} is up to date (${platform})`);
|
|
304
|
+
return 0;
|
|
305
|
+
}
|
|
306
|
+
if (order < 0 && !wanted) {
|
|
307
|
+
deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}; nothing to do (pass --version ${asset.version} to go back)`);
|
|
308
|
+
return 0;
|
|
309
|
+
}
|
|
310
|
+
const { app, current } = bundle;
|
|
311
|
+
if (deps.platform === "win32" && asset.version === path.basename(bundle.root)) throw new Error(`ALP ${asset.version} is the version running now; Windows cannot replace it in place. Close ALP (alp daemon stop) and rerun install.ps1 to repair it`);
|
|
312
|
+
const running = await deps.daemon().catch(() => void 0);
|
|
313
|
+
try {
|
|
314
|
+
nodeFs.accessSync(app, nodeFs.constants.W_OK);
|
|
315
|
+
} catch {
|
|
316
|
+
throw new Error(`${app} is not writable; run alp update with the permissions that installed ALP there`);
|
|
317
|
+
}
|
|
318
|
+
const target = path.join(app, asset.version);
|
|
319
|
+
if (!values.yes) {
|
|
320
|
+
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`);
|
|
321
|
+
if (!await deps.confirm(`Install ALP ${asset.version} in ${target} and switch to it (from ${deps.version})?`)) {
|
|
322
|
+
deps.log("Not updated.");
|
|
323
|
+
return 1;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const work = nodeFs.mkdtempSync(path.join(os.tmpdir(), "alp-update-"));
|
|
327
|
+
const staging = path.join(app, `.alp-update-${randomBytes(6).toString("hex")}`);
|
|
328
|
+
let aside;
|
|
329
|
+
try {
|
|
330
|
+
deps.log(`Downloading ${asset.name} from ${base}`);
|
|
331
|
+
const bytes = await deps.fetchBytes(`${base}/${asset.name}`);
|
|
332
|
+
verifyChecksum(bytes, asset);
|
|
333
|
+
deps.log(`Checksum verified (${asset.sha256})`);
|
|
334
|
+
const archive = path.join(work, asset.name);
|
|
335
|
+
nodeFs.writeFileSync(archive, bytes);
|
|
336
|
+
const provenance = deps.provenance(archive, repo);
|
|
337
|
+
if (provenance === "verified") deps.log(`Provenance verified by gh attestation (${repo}, refs/heads/main, release-binaries.yml)`);
|
|
338
|
+
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)");
|
|
339
|
+
nodeFs.mkdirSync(staging);
|
|
340
|
+
const unpacked = deps.extract(archive, staging, asset, platform);
|
|
341
|
+
const manifest = JSON.parse(nodeFs.readFileSync(path.join(unpacked, "alp-bundle.json"), "utf8"));
|
|
342
|
+
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`);
|
|
343
|
+
const reported = deps.runVersion(unpacked);
|
|
344
|
+
if (reported !== asset.version) throw new Error(`The downloaded ALP reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was changed`);
|
|
345
|
+
if (nodeFs.existsSync(target)) {
|
|
346
|
+
if (samePath(target, bundle.root) || running?.version === asset.version) {
|
|
347
|
+
aside = `.alp-old-${randomBytes(6).toString("hex")}`;
|
|
348
|
+
retryBusy(() => nodeFs.renameSync(target, path.join(app, aside)));
|
|
349
|
+
} else nodeFs.rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
350
|
+
}
|
|
351
|
+
retryBusy(() => nodeFs.renameSync(unpacked, target));
|
|
352
|
+
switchCurrent(app, asset.version, { platform: deps.platform });
|
|
353
|
+
} finally {
|
|
354
|
+
try {
|
|
355
|
+
nodeFs.rmSync(staging, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
356
|
+
} catch {
|
|
357
|
+
}
|
|
358
|
+
try {
|
|
359
|
+
nodeFs.rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
360
|
+
} catch {
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
pruneVersions(app, [asset.version, path.basename(bundle.root), ...running?.version ? [running.version] : [], ...aside ? [aside] : []], nodeFs, { keepAside: Boolean(running) });
|
|
364
|
+
deps.log(`Updated ALP ${deps.version} \u2192 ${asset.version} (${current} \u2192 ${target})`);
|
|
365
|
+
if (running && running.version !== asset.version) {
|
|
366
|
+
const sessions = running.sessions;
|
|
367
|
+
const known = Number.isSafeInteger(sessions);
|
|
368
|
+
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`);
|
|
369
|
+
if (!values.yes && deps.interactive && known && sessions === 0 && await deps.confirm("Restart alpd now?")) {
|
|
370
|
+
if (deps.restartDaemon(target) !== 0) deps.warn("alp: alp daemon restart failed; run it yourself");
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return 0;
|
|
374
|
+
}
|
|
375
|
+
export {
|
|
376
|
+
DEFAULT_REPO,
|
|
377
|
+
MAX_DOWNLOAD,
|
|
378
|
+
NPM_PACKAGE,
|
|
379
|
+
SIGNER_WORKFLOW,
|
|
380
|
+
UPDATE_USAGE,
|
|
381
|
+
allowedHop,
|
|
382
|
+
archiveExtension,
|
|
383
|
+
bundleCommand,
|
|
384
|
+
compareVersions,
|
|
385
|
+
fetchBytes,
|
|
386
|
+
notInstalledMessage,
|
|
387
|
+
npmMessage,
|
|
388
|
+
parseSums,
|
|
389
|
+
pruneVersions,
|
|
390
|
+
releaseBaseUrl,
|
|
391
|
+
releasePlatform,
|
|
392
|
+
retryBusy,
|
|
393
|
+
selectAsset,
|
|
394
|
+
selfUpdate,
|
|
395
|
+
sha256,
|
|
396
|
+
switchCurrent,
|
|
397
|
+
verifyChecksum,
|
|
398
|
+
verifyProvenance
|
|
399
|
+
};
|
package/dist/sessions.d.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
284
|
-
|
|
285
|
-
|
|
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`);
|