@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,406 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
3
|
+
import * as nodeFs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createInterface } from 'node:readline/promises';
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
8
|
+
import { parseArgs } from 'node:util';
|
|
9
|
+
import { bundleInfo, samePath } from '@anhlp/alp-core/packaged';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* `alp update` (t-1807): installs a release of the ALP bundle from GitHub Releases beside the running
|
|
13
|
+
* one (<app>/<version>, see @anhlp/alp-core/packaged) and points <app>/current at it, after checking
|
|
14
|
+
* the archive against the release's SHA256SUMS and, when `gh` is installed, its build provenance.
|
|
15
|
+
* The project template upgrade that `alp update` used to run is `alp update-template`.
|
|
16
|
+
*
|
|
17
|
+
* Everything that touches the network, the filesystem or child processes comes in through `deps`
|
|
18
|
+
* so the tests can drive each step.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export const DEFAULT_REPO = 'phucanh08/alp';
|
|
22
|
+
export const SIGNER_WORKFLOW = '.github/workflows/release-binaries.yml';
|
|
23
|
+
export const NPM_PACKAGE = '@anhlp/alp';
|
|
24
|
+
const TEMPLATE_HINT = 'did you mean `alp update-template`? (`alp update` now updates ALP itself; the project template upgrade is `alp update-template [directory]`)';
|
|
25
|
+
|
|
26
|
+
const OPTIONS = { check: { type: 'boolean' }, yes: { type: 'boolean', short: 'y' }, version: { type: 'string' }, 'base-url': { type: 'string' }, help: { type: 'boolean', short: 'h' } };
|
|
27
|
+
|
|
28
|
+
export const UPDATE_USAGE = `Usage: alp update [--check] [--yes] [--version X] [--base-url URL]
|
|
29
|
+
Installs the latest ALP release (or release X) from GitHub Releases beside this one and switches to it, after checking
|
|
30
|
+
it against SHA256SUMS and, when gh is installed, its build provenance. --check only reports.
|
|
31
|
+
ALP_UPDATE_BASE_URL (as --base-url, an https:// or file:// mirror) and ALP_INSTALL_REPO (owner/name) override the source.
|
|
32
|
+
The project template upgrade is \`alp update-template [directory]\`.`;
|
|
33
|
+
|
|
34
|
+
/** The release platform of this process: darwin-arm64, linux-x64, windows-x64. @param {string} platform @param {string} arch */
|
|
35
|
+
export function releasePlatform(platform = process.platform, arch = process.arch) {
|
|
36
|
+
const osName = { darwin: 'darwin', linux: 'linux', win32: 'windows' }[platform];
|
|
37
|
+
const archName = { x64: 'x64', arm64: 'arm64' }[arch];
|
|
38
|
+
if (!osName || !archName || (osName === 'windows' && archName !== 'x64')) throw new Error(`ALP publishes no build for ${platform}-${arch}`);
|
|
39
|
+
return `${osName}-${archName}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The archive extension of a release platform. @param {string} platform */
|
|
43
|
+
export const archiveExtension = platform => platform.startsWith('windows-') ? '.zip' : '.tar.gz';
|
|
44
|
+
|
|
45
|
+
/** Parses SHA256SUMS into [{ sha256, name }]. @param {string} text */
|
|
46
|
+
export function parseSums(text) {
|
|
47
|
+
const entries = [];
|
|
48
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
49
|
+
const line = raw.trim();
|
|
50
|
+
if (!line) continue;
|
|
51
|
+
const match = /^([0-9a-fA-F]{64}) [ *]?(.+)$/.exec(line);
|
|
52
|
+
if (!match) throw new Error(`Malformed SHA256SUMS line: ${JSON.stringify(line)}`);
|
|
53
|
+
entries.push({ sha256: match[1].toLowerCase(), name: match[2].trim() });
|
|
54
|
+
}
|
|
55
|
+
return entries;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The archive for `platform` in SHA256SUMS: alp-<version>-<platform>.<ext>, for `version` when given.
|
|
60
|
+
* @param {string} sumsText @param {string} platform @param {string} [version]
|
|
61
|
+
* @returns {{ name: string, sha256: string, version: string }}
|
|
62
|
+
*/
|
|
63
|
+
export function selectAsset(sumsText, platform, version) {
|
|
64
|
+
const suffix = `-${platform}${archiveExtension(platform)}`;
|
|
65
|
+
const matches = parseSums(sumsText).filter(({ name }) => name.endsWith(suffix) && /^alp-[0-9]/.test(name) && (!version || name === `alp-${version}${suffix}`));
|
|
66
|
+
if (matches.length === 0) throw new Error(`This release has no ALP build for ${platform}${version ? ` at version ${version}` : ''}`);
|
|
67
|
+
if (matches.length > 1) throw new Error(`SHA256SUMS lists more than one ${platform} archive: ${matches.map(m => m.name).join(', ')}`);
|
|
68
|
+
const [match] = matches;
|
|
69
|
+
if (/[^0-9A-Za-z.+_-]/.test(match.name)) throw new Error(`Unexpected archive name in SHA256SUMS: ${match.name}`);
|
|
70
|
+
return { ...match, version: match.name.slice('alp-'.length, -suffix.length) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export const sha256 = (/** @type {Uint8Array} */ bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
74
|
+
|
|
75
|
+
/** Refuses an archive whose digest differs from SHA256SUMS. @param {Uint8Array} bytes @param {{ name: string, sha256: string }} asset */
|
|
76
|
+
export function verifyChecksum(bytes, asset) {
|
|
77
|
+
const actual = sha256(bytes);
|
|
78
|
+
if (actual !== asset.sha256) throw new Error(`Checksum mismatch for ${asset.name} (expected ${asset.sha256}, got ${actual}); nothing was replaced`);
|
|
79
|
+
return actual;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Compares dotted versions numerically, prerelease below release. @param {string} a @param {string} b */
|
|
83
|
+
export function compareVersions(a, b) {
|
|
84
|
+
const split = (/** @type {string} */ v) => {
|
|
85
|
+
// Build metadata (+b) does not order versions.
|
|
86
|
+
const [core, pre] = v.replace(/^v/, '').replace(/\+.*$/s, '').split(/-(.*)/s);
|
|
87
|
+
if (!/^\d+(\.\d+)*$/.test(core)) throw new Error(`Invalid version: ${JSON.stringify(v)}`);
|
|
88
|
+
return { core: core.split('.').map(Number), pre };
|
|
89
|
+
};
|
|
90
|
+
const x = split(a), y = split(b);
|
|
91
|
+
for (let i = 0; i < Math.max(x.core.length, y.core.length); i++) {
|
|
92
|
+
const d = (x.core[i] ?? 0) - (y.core[i] ?? 0);
|
|
93
|
+
if (d) return Math.sign(d);
|
|
94
|
+
}
|
|
95
|
+
if (x.pre === y.pre) return 0;
|
|
96
|
+
if (x.pre === undefined) return 1;
|
|
97
|
+
if (y.pre === undefined) return -1;
|
|
98
|
+
return x.pre.localeCompare(y.pre, 'en', { numeric: true });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The base URL that holds SHA256SUMS and the archives. @param {{ repo: string, version?: string, baseUrl?: string }} options */
|
|
102
|
+
export function releaseBaseUrl({ repo, version, baseUrl }) {
|
|
103
|
+
let base = baseUrl;
|
|
104
|
+
if (!base) base = version ? `https://github.com/${repo}/releases/download/v${version}` : `https://github.com/${repo}/releases/latest/download`;
|
|
105
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(base) && (path.isAbsolute(base) || (process.platform === 'win32' && path.win32.isAbsolute(base)))) base = pathToFileURL(base).href;
|
|
106
|
+
base = base.replace(/\/+$/, '');
|
|
107
|
+
const url = new URL(base);
|
|
108
|
+
const loopback = isLoopbackHttp(url);
|
|
109
|
+
if (url.protocol !== 'https:' && url.protocol !== 'file:' && !loopback) throw new Error(`The release mirror must be https:// or file:// (${base})`);
|
|
110
|
+
return base;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The largest file alp update downloads: an archive of the bundle is about 70 MB. */
|
|
114
|
+
export const MAX_DOWNLOAD = 512 * 1024 * 1024;
|
|
115
|
+
|
|
116
|
+
const LOOPBACK = ['127.0.0.1', 'localhost', '[::1]'];
|
|
117
|
+
const isLoopbackHttp = (/** @type {URL} */ url) => url.protocol === 'http:' && LOOPBACK.includes(url.hostname);
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Whether a download may go to `next`: every hop of an https download stays https, since one plain
|
|
121
|
+
* http hop lets a man in the middle replace the archive and SHA256SUMS together. Only a loopback
|
|
122
|
+
* http mirror given explicitly (tests) may use loopback http, besides https.
|
|
123
|
+
* @param {string} start @param {string} next
|
|
124
|
+
*/
|
|
125
|
+
export function allowedHop(start, next) {
|
|
126
|
+
const to = new URL(next);
|
|
127
|
+
if (to.protocol === 'https:') return true;
|
|
128
|
+
return isLoopbackHttp(new URL(start)) && isLoopbackHttp(to);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Downloads `url` (https, loopback http or file) within a time and size limit, following at most 10
|
|
133
|
+
* redirects itself and refusing any hop that `allowedHop` refuses.
|
|
134
|
+
* @param {string} url @param {{ timeoutMs?: number, max?: number, fetch?: typeof globalThis.fetch }} [options]
|
|
135
|
+
*/
|
|
136
|
+
export async function fetchBytes(url, { timeoutMs = 10 * 60_000, max = MAX_DOWNLOAD, fetch: fetchImpl = globalThis.fetch } = {}) {
|
|
137
|
+
if (url.startsWith('file:')) {
|
|
138
|
+
const file = fileURLToPath(url);
|
|
139
|
+
if (nodeFs.statSync(file).size > max) throw new Error(`${url} is larger than ${max} bytes`);
|
|
140
|
+
return new Uint8Array(await nodeFs.promises.readFile(file));
|
|
141
|
+
}
|
|
142
|
+
if (!allowedHop(url, url)) throw new Error(`Refusing to download ${url}: not https`);
|
|
143
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
144
|
+
let current = url;
|
|
145
|
+
let response;
|
|
146
|
+
for (let hop = 0; ; hop++) {
|
|
147
|
+
response = await fetchImpl(current, { redirect: 'manual', signal });
|
|
148
|
+
if (![301, 302, 303, 307, 308].includes(response.status)) break;
|
|
149
|
+
const location = response.headers.get('location');
|
|
150
|
+
await response.body?.cancel().catch(() => {});
|
|
151
|
+
if (!location) throw new Error(`${current} redirected without a location`);
|
|
152
|
+
if (hop >= 10) throw new Error(`${url} redirected more than 10 times`);
|
|
153
|
+
const next = new URL(location, current).href;
|
|
154
|
+
if (!allowedHop(url, next)) throw new Error(`${url} redirected to ${next}, which is not https; refused`);
|
|
155
|
+
current = next;
|
|
156
|
+
}
|
|
157
|
+
if (!response.ok) throw new Error(`Could not download ${current} (HTTP ${response.status})`);
|
|
158
|
+
if (Number(response.headers.get('content-length') ?? 0) > max) throw new Error(`${current} is larger than ${max} bytes`);
|
|
159
|
+
const chunks = [];
|
|
160
|
+
let size = 0;
|
|
161
|
+
for await (const chunk of /** @type {AsyncIterable<Uint8Array>} */ (response.body ?? [])) {
|
|
162
|
+
size += chunk.byteLength;
|
|
163
|
+
if (size > max) throw new Error(`${current} is larger than ${max} bytes`);
|
|
164
|
+
chunks.push(chunk);
|
|
165
|
+
}
|
|
166
|
+
return new Uint8Array(Buffer.concat(chunks));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Whether a program is on PATH. @param {string} name */
|
|
170
|
+
function which(name) {
|
|
171
|
+
const result = spawnSync(process.platform === 'win32' ? 'where' : 'which', [name], { encoding: 'utf8', windowsHide: true });
|
|
172
|
+
return result.status === 0 ? result.stdout.split(/\r?\n/)[0].trim() || undefined : undefined;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Verifies the archive's build provenance with gh. Returns 'verified', or 'unavailable' when gh is
|
|
177
|
+
* absent (ALP_UPDATE_NO_GH=1 treats it as absent); throws when gh reports a failure.
|
|
178
|
+
* @param {string} file @param {{ repo: string, env?: NodeJS.ProcessEnv, run?: typeof spawnSync, find?: typeof which }} options
|
|
179
|
+
*/
|
|
180
|
+
export function verifyProvenance(file, { repo, env = process.env, run = spawnSync, find = which }) {
|
|
181
|
+
if (env.ALP_UPDATE_NO_GH === '1') return 'unavailable';
|
|
182
|
+
const gh = find('gh');
|
|
183
|
+
if (!gh) return 'unavailable';
|
|
184
|
+
const result = run(gh, ['attestation', 'verify', file, '--repo', repo, '--source-ref', 'refs/heads/main', '--signer-workflow', `${repo}/${SIGNER_WORKFLOW}`], { encoding: 'utf8', windowsHide: true });
|
|
185
|
+
if (result.status !== 0) {
|
|
186
|
+
const detail = `${result.stderr ?? ''}${result.stdout ?? ''}`.trim().split(/\r?\n/).slice(-3).join(' ');
|
|
187
|
+
throw new Error(`gh attestation verify refused ${path.basename(file)}${detail ? `: ${detail}` : ''}; nothing was replaced (sign in with gh auth login, or set ALP_UPDATE_NO_GH=1 to rely on the checksum only)`);
|
|
188
|
+
}
|
|
189
|
+
return 'verified';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const TRANSIENT = new Set(['EBUSY', 'EPERM', 'EACCES', 'ENOTEMPTY']);
|
|
193
|
+
const pause = (/** @type {number} */ ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Runs `action`, again after a pause while Windows reports the file busy: a virus scanner holds an
|
|
197
|
+
* executable it just saw run (the staged bundle's --version) for a moment. About 6 s in all.
|
|
198
|
+
* @template T @param {() => T} action @param {(ms: number) => void} [sleep]
|
|
199
|
+
*/
|
|
200
|
+
export function retryBusy(action, sleep = pause, attempts = 25) {
|
|
201
|
+
for (let attempt = 1; ; attempt++) {
|
|
202
|
+
try { return action(); } catch (error) {
|
|
203
|
+
if (attempt >= attempts || !TRANSIENT.has(error?.code)) throw error;
|
|
204
|
+
sleep(Math.min(50 * attempt, 400));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** What to say outside the ALP bundle (an npm install). @param {string[]} positionals */
|
|
210
|
+
export function npmMessage(positionals = []) {
|
|
211
|
+
const lines = [];
|
|
212
|
+
if (positionals.length) lines.push(`alp: ${TEMPLATE_HINT}`);
|
|
213
|
+
lines.push(`This alp was installed with npm; update it with npm:\n npm install -g ${NPM_PACKAGE}@beta\nThen restart alpd when no sessions are running: alp daemon restart\n(The project template upgrade is \`alp update-template [directory]\`.)`);
|
|
214
|
+
return lines.join('\n');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Why this bundle cannot update itself: it was not installed by install.sh / install.ps1. @param {string} root */
|
|
218
|
+
export const notInstalledMessage = root => `alp: ${root} is not an installed ALP (no app/current points at it); install the release with install.sh (Windows: install.ps1), which alp update can then keep up to date:\n curl -fsSL https://github.com/${DEFAULT_REPO}/releases/latest/download/install.sh | sh`;
|
|
219
|
+
|
|
220
|
+
const systemTar = () => process.platform === 'win32' ? path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe') : 'tar';
|
|
221
|
+
|
|
222
|
+
/** Extracts the archive into `directory` and returns the bundle inside it. @param {string} archive @param {string} directory @param {{ name: string }} asset @param {string} platform */
|
|
223
|
+
function extract(archive, directory, asset, platform, run = spawnSync) {
|
|
224
|
+
const windows = platform.startsWith('windows-');
|
|
225
|
+
// tar reads both: GNU/bsd tar for .tar.gz, Windows' bsdtar (tar.exe) for .zip.
|
|
226
|
+
// On Windows, Git's GNU tar (which reads no zip) may come first on PATH: use the system's bsdtar.
|
|
227
|
+
const result = run(systemTar(), [windows ? '-xf' : '-xzf', archive, '-C', directory], { encoding: 'utf8', windowsHide: true });
|
|
228
|
+
if (result.status !== 0) throw new Error(`Could not extract ${asset.name}: ${(result.stderr || result.error?.message || '').trim()}`);
|
|
229
|
+
const root = path.join(directory, asset.name.slice(0, -archiveExtension(platform).length));
|
|
230
|
+
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)`);
|
|
231
|
+
return root;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 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 */
|
|
235
|
+
export function bundleCommand(root, platform = process.platform) {
|
|
236
|
+
const node = platform === 'win32' ? path.join(root, 'node', 'node.exe') : path.join(root, 'node', 'bin', 'node');
|
|
237
|
+
return { command: node, args: [path.join(root, 'lib', 'node_modules', '@anhlp', 'alp-cli', 'dist', 'cli.js')] };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Points `<app>/current` at `<app>/<version>`. Unix: a relative symlink renamed over the old one, in
|
|
242
|
+
* one step. Windows: the junction is replaced (removed, then made again; put back on failure).
|
|
243
|
+
* @param {string} app @param {string} version @param {{ platform?: string, fs?: typeof nodeFs, unique?: () => string }} [options]
|
|
244
|
+
*/
|
|
245
|
+
export function switchCurrent(app, version, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(6).toString('hex') } = {}) {
|
|
246
|
+
const p = platform === 'win32' ? path.win32 : path;
|
|
247
|
+
const current = p.join(app, 'current');
|
|
248
|
+
if (platform !== 'win32') {
|
|
249
|
+
const link = p.join(app, `.current-${unique()}`);
|
|
250
|
+
fs.symlinkSync(version, link);
|
|
251
|
+
try { fs.renameSync(link, current); } catch (error) { try { fs.unlinkSync(link); } catch {} throw error; }
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
let previous;
|
|
255
|
+
try { previous = fs.readlinkSync(current); } catch {}
|
|
256
|
+
if (previous !== undefined) retryBusy(() => fs.unlinkSync(current));
|
|
257
|
+
try { fs.symlinkSync(p.join(app, version), current, 'junction'); } catch (error) {
|
|
258
|
+
if (previous !== undefined) try { fs.symlinkSync(previous, current, 'junction'); } catch {}
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Removes what earlier updates left in `<app>`: versions other than `keep`, and staging directories.
|
|
265
|
+
* A failure (a file still in use on Windows) leaves that entry for the next update. keepAside keeps
|
|
266
|
+
* the copies earlier reinstalls moved aside, which a running alpd may still run from.
|
|
267
|
+
* @param {string} app @param {string[]} keep
|
|
268
|
+
*/
|
|
269
|
+
export function pruneVersions(app, keep, fs = nodeFs, { keepAside = false } = {}) {
|
|
270
|
+
let names;
|
|
271
|
+
try { names = fs.readdirSync(app); } catch { return []; }
|
|
272
|
+
const removed = [];
|
|
273
|
+
for (const name of names) {
|
|
274
|
+
if (name === 'current' || keep.includes(name) || (keepAside && name.startsWith('.alp-old-'))) continue;
|
|
275
|
+
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;
|
|
276
|
+
try { fs.rmSync(path.join(app, name), { recursive: true, force: true }); removed.push(name); } catch {}
|
|
277
|
+
}
|
|
278
|
+
return removed;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Asks a yes/no question on the terminal. @param {string} question */
|
|
282
|
+
async function confirm(question) {
|
|
283
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
284
|
+
try { return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim()); } finally { rl.close(); }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* @typedef {{
|
|
289
|
+
* bundle: import('@anhlp/alp-core/packaged').BundleInfo | undefined, version: string, env: NodeJS.ProcessEnv, platform: string, arch: string,
|
|
290
|
+
* log: (line: string) => void, warn: (line: string) => void, interactive: boolean,
|
|
291
|
+
* fetchBytes: (url: string) => Promise<Uint8Array>, confirm: (question: string) => Promise<boolean>,
|
|
292
|
+
* provenance: (file: string, repo: string) => string, extract: typeof extract,
|
|
293
|
+
* daemon: () => Promise<{ version: string, sessions?: number } | undefined>, restartDaemon: (root: string) => number,
|
|
294
|
+
* runVersion: (root: string) => string,
|
|
295
|
+
* }} UpdateDeps
|
|
296
|
+
*/
|
|
297
|
+
|
|
298
|
+
/** @param {string[]} args @param {Partial<UpdateDeps>} [overrides] @returns {Promise<number>} the exit code */
|
|
299
|
+
export async function selfUpdate(args, overrides = {}) {
|
|
300
|
+
/** @type {UpdateDeps} */
|
|
301
|
+
const deps = {
|
|
302
|
+
bundle: bundleInfo(), version: '0.0.0', env: process.env, platform: process.platform, arch: process.arch,
|
|
303
|
+
log: line => console.log(line), warn: line => console.error(line), interactive: !!(process.stdin.isTTY && process.stdout.isTTY),
|
|
304
|
+
fetchBytes, confirm, extract,
|
|
305
|
+
provenance: (file, repo) => verifyProvenance(file, { repo }),
|
|
306
|
+
daemon: async () => undefined,
|
|
307
|
+
restartDaemon: root => { const run = bundleCommand(root); return spawnSync(run.command, [...run.args, 'daemon', 'restart'], { stdio: 'inherit', windowsHide: true }).status ?? 1; },
|
|
308
|
+
runVersion: root => { const run = bundleCommand(root); return spawnSync(run.command, [...run.args, '--version'], { encoding: 'utf8', windowsHide: true, timeout: 60_000 }).stdout?.trim() ?? ''; },
|
|
309
|
+
...overrides,
|
|
310
|
+
};
|
|
311
|
+
const { bundle } = deps;
|
|
312
|
+
let parsed;
|
|
313
|
+
try {
|
|
314
|
+
parsed = parseArgs({ args, allowPositionals: true, options: OPTIONS, strict: true });
|
|
315
|
+
} catch (error) {
|
|
316
|
+
deps.warn(`alp: ${error.message}`);
|
|
317
|
+
deps.warn(`alp: ${TEMPLATE_HINT}`);
|
|
318
|
+
return bundle ? 1 : 0;
|
|
319
|
+
}
|
|
320
|
+
const { values, positionals } = parsed;
|
|
321
|
+
if (values.help) { deps.log(UPDATE_USAGE); return 0; }
|
|
322
|
+
if (!bundle) { deps.log(npmMessage(positionals)); return 0; }
|
|
323
|
+
if (positionals.length) { deps.warn(`alp: ${TEMPLATE_HINT}`); return 1; }
|
|
324
|
+
if (!bundle.current) { deps.warn(notInstalledMessage(bundle.root)); return 1; }
|
|
325
|
+
|
|
326
|
+
const wanted = values.version?.replace(/^v/, '');
|
|
327
|
+
if (wanted !== undefined && !/^[0-9][0-9A-Za-z.+-]*$/.test(wanted)) throw new Error(`Invalid version: ${values.version}`);
|
|
328
|
+
const repo = deps.env.ALP_INSTALL_REPO || DEFAULT_REPO;
|
|
329
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error(`Invalid ALP_INSTALL_REPO: ${repo}`);
|
|
330
|
+
const base = releaseBaseUrl({ repo, version: wanted, baseUrl: values['base-url'] ?? deps.env.ALP_UPDATE_BASE_URL });
|
|
331
|
+
const platform = releasePlatform(deps.platform, deps.arch);
|
|
332
|
+
|
|
333
|
+
const sums = new TextDecoder().decode(await deps.fetchBytes(`${base}/SHA256SUMS`));
|
|
334
|
+
const asset = selectAsset(sums, platform, wanted);
|
|
335
|
+
const order = compareVersions(asset.version, deps.version);
|
|
336
|
+
if (values.check) {
|
|
337
|
+
if (order === 0) deps.log(`alp ${deps.version} is up to date (${platform})`);
|
|
338
|
+
else if (order < 0 && !wanted) deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}`);
|
|
339
|
+
else deps.log(`alp ${deps.version} → ${asset.version} available (${asset.name}); run: alp update${wanted ? ` --version ${wanted}` : ''}`);
|
|
340
|
+
return 0;
|
|
341
|
+
}
|
|
342
|
+
// An explicit --version of the running version reinstalls it (a repair); without one there is nothing to do.
|
|
343
|
+
if (order === 0 && !wanted) { deps.log(`alp ${deps.version} is up to date (${platform})`); return 0; }
|
|
344
|
+
if (order < 0 && !wanted) { deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}; nothing to do (pass --version ${asset.version} to go back)`); return 0; }
|
|
345
|
+
|
|
346
|
+
const { app, current } = bundle;
|
|
347
|
+
// Windows cannot rename or delete a directory that a running node.exe (this one) comes from.
|
|
348
|
+
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`);
|
|
349
|
+
// The version a running alpd uses keeps its files, like the one this process runs.
|
|
350
|
+
const running = await deps.daemon().catch(() => undefined);
|
|
351
|
+
try { nodeFs.accessSync(app, nodeFs.constants.W_OK); } catch { throw new Error(`${app} is not writable; run alp update with the permissions that installed ALP there`); }
|
|
352
|
+
const target = path.join(app, asset.version);
|
|
353
|
+
|
|
354
|
+
if (!values.yes) {
|
|
355
|
+
if (!deps.interactive) throw new Error(`alp update would install ${target} and switch ${current} to it (${deps.version} → ${asset.version}); pass --yes to do it without a terminal`);
|
|
356
|
+
if (!await deps.confirm(`Install ALP ${asset.version} in ${target} and switch to it (from ${deps.version})?`)) { deps.log('Not updated.'); return 1; }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const work = nodeFs.mkdtempSync(path.join(os.tmpdir(), 'alp-update-'));
|
|
360
|
+
// Unpacked beside the versions, so moving it into place stays on one filesystem.
|
|
361
|
+
const staging = path.join(app, `.alp-update-${randomBytes(6).toString('hex')}`);
|
|
362
|
+
/** @type {string | undefined} the running version, moved aside by a reinstall */
|
|
363
|
+
let aside;
|
|
364
|
+
try {
|
|
365
|
+
deps.log(`Downloading ${asset.name} from ${base}`);
|
|
366
|
+
const bytes = await deps.fetchBytes(`${base}/${asset.name}`);
|
|
367
|
+
verifyChecksum(bytes, asset);
|
|
368
|
+
deps.log(`Checksum verified (${asset.sha256})`);
|
|
369
|
+
const archive = path.join(work, asset.name);
|
|
370
|
+
nodeFs.writeFileSync(archive, bytes);
|
|
371
|
+
const provenance = deps.provenance(archive, repo);
|
|
372
|
+
if (provenance === 'verified') deps.log(`Provenance verified by gh attestation (${repo}, refs/heads/main, release-binaries.yml)`);
|
|
373
|
+
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)');
|
|
374
|
+
nodeFs.mkdirSync(staging);
|
|
375
|
+
const unpacked = deps.extract(archive, staging, asset, platform);
|
|
376
|
+
const manifest = JSON.parse(nodeFs.readFileSync(path.join(unpacked, 'alp-bundle.json'), 'utf8'));
|
|
377
|
+
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`);
|
|
378
|
+
const reported = deps.runVersion(unpacked);
|
|
379
|
+
if (reported !== asset.version) throw new Error(`The downloaded ALP reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was changed`);
|
|
380
|
+
if (nodeFs.existsSync(target)) {
|
|
381
|
+
// A reinstall of the running version moves it aside (its processes keep their files); any other copy is stale.
|
|
382
|
+
if (samePath(target, bundle.root) || running?.version === asset.version) { aside = `.alp-old-${randomBytes(6).toString('hex')}`; retryBusy(() => nodeFs.renameSync(target, path.join(app, aside))); }
|
|
383
|
+
else nodeFs.rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
384
|
+
}
|
|
385
|
+
retryBusy(() => nodeFs.renameSync(unpacked, target));
|
|
386
|
+
switchCurrent(app, asset.version, { platform: deps.platform });
|
|
387
|
+
} finally {
|
|
388
|
+
// A cleanup failure must not hide why the update failed; a leftover staging directory goes with the next update.
|
|
389
|
+
try { nodeFs.rmSync(staging, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
|
|
390
|
+
try { nodeFs.rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
|
|
391
|
+
}
|
|
392
|
+
// The version this process (and maybe alpd) runs stays until the next update.
|
|
393
|
+
pruneVersions(app, [asset.version, path.basename(bundle.root), ...(running?.version ? [running.version] : []), ...(aside ? [aside] : [])], nodeFs, { keepAside: Boolean(running) });
|
|
394
|
+
deps.log(`Updated ALP ${deps.version} → ${asset.version} (${current} → ${target})`);
|
|
395
|
+
|
|
396
|
+
if (running && running.version !== asset.version) {
|
|
397
|
+
const sessions = running.sessions;
|
|
398
|
+
const known = Number.isSafeInteger(sessions);
|
|
399
|
+
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`);
|
|
400
|
+
// Never restart on our own: only an interactive yes with no live session known restarts it.
|
|
401
|
+
if (!values.yes && deps.interactive && known && sessions === 0 && await deps.confirm('Restart alpd now?')) {
|
|
402
|
+
if (deps.restartDaemon(target) !== 0) deps.warn('alp: alp daemon restart failed; run it yourself');
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return 0;
|
|
406
|
+
}
|
package/src/sessions.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import { createInterface } from 'node:readline';
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
5
|
import { ago, duration, renderLog, renderPs } from '@anhlp/alp-client/render';
|
|
6
|
-
import { isTaskId } from '@anhlp/alp-core/tasks';
|
|
6
|
+
import { AGENT_MARKER, isAgentProcess, isTaskId } from '@anhlp/alp-core/tasks';
|
|
7
7
|
import { connect } from '@anhlp/alp-client/index';
|
|
8
8
|
import { UsageError } from './usage.js';
|
|
9
9
|
import { start, running, stop } from './daemon.js';
|
|
@@ -261,6 +261,8 @@ async function answer(args) {
|
|
|
261
261
|
const { values, positionals: [questionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { dismiss: { type: 'boolean' }, reason: { type: 'string' } } });
|
|
262
262
|
const text = words.join(' ').trim();
|
|
263
263
|
if (!questionId || (values.dismiss ? text : !text)) throw new UsageError();
|
|
264
|
+
// An answer speaks for the user: never from a process an ALP agent started (t-ca1f).
|
|
265
|
+
if (isAgentProcess()) throw new Error(`Only the user answers a question; this process runs under an ALP agent (${AGENT_MARKER})`);
|
|
264
266
|
const client = await running();
|
|
265
267
|
const result = await client.request('question.answer', values.dismiss ? { questionId, dismiss: true, reason: values.reason } : { questionId, text }).finally(() => client.close());
|
|
266
268
|
console.log(`${values.dismiss ? 'Dismissed' : 'Answered'} ${result.questionId}`);
|
|
@@ -329,6 +331,17 @@ async function log(args) {
|
|
|
329
331
|
for (const line of renderLog(rootId, entries)) console.log(line);
|
|
330
332
|
}
|
|
331
333
|
|
|
334
|
+
/** The models alpd offers now: the live catalog (t-e5ee); --refresh asks every provider again first. */
|
|
335
|
+
async function models(args) {
|
|
336
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { refresh: { type: 'boolean' }, json: { type: 'boolean' } } });
|
|
337
|
+
if (positionals.length) throw new UsageError();
|
|
338
|
+
const client = await running();
|
|
339
|
+
const catalog = await client.request(values.refresh ? 'catalog.refresh' : 'catalog.get', {}).finally(() => client.close());
|
|
340
|
+
if (values.json) { console.log(JSON.stringify(catalog)); return; }
|
|
341
|
+
for (const [runtime, state] of Object.entries(catalog.providers ?? {})) console.log(`${runtime}: ${state.status}${state.fetchedAt ? ` (${state.fetchedAt})` : ''}${state.error ? ` — ${state.error}` : ''}`);
|
|
342
|
+
for (const model of catalog.models) console.log(`${model.id.padEnd(40)} ${model.label}`);
|
|
343
|
+
}
|
|
344
|
+
|
|
332
345
|
/** The project board every agent on the project shares: live claims, then decisions and findings. */
|
|
333
346
|
|
|
334
347
|
async function board(args) {
|
|
@@ -406,4 +419,12 @@ async function interrupt(args) {
|
|
|
406
419
|
console.log('Interrupted');
|
|
407
420
|
}
|
|
408
421
|
|
|
409
|
-
|
|
422
|
+
/** alp compact <session>: compacts a root's context now, or at its next turn boundary (t-0e56). */
|
|
423
|
+
async function compact(args) {
|
|
424
|
+
if (args.length !== 1) throw new UsageError();
|
|
425
|
+
const client = await running();
|
|
426
|
+
const { status } = await client.request('session.compact', { sessionId: args[0] }).finally(() => client.close());
|
|
427
|
+
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');
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export { printer, answerer, follow, run, ps, attach, send, questions, answer, renderStatus, top, log, board, models, printPauses, pause, resume, recall, interrupt, compact };
|
package/src/tasks.js
CHANGED
|
@@ -5,9 +5,11 @@ import { parseArgs } from 'node:util';
|
|
|
5
5
|
import { exportBeads, importBeads, parseJsonl } from '@anhlp/alp-core/beads';
|
|
6
6
|
import { findFormula, formulaDirs, listFormulas, pourFormula } from '@anhlp/alp-core/formulas';
|
|
7
7
|
import { describeVerification } from '@anhlp/alp-core/verify';
|
|
8
|
+
import { scriptCommand } from '@anhlp/alp-core/packaged';
|
|
8
9
|
import { ago } from '@anhlp/alp-client/render';
|
|
9
10
|
import { parse as toml } from 'smol-toml';
|
|
10
|
-
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';
|
|
11
|
+
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';
|
|
12
|
+
import { AlpError } from '@anhlp/alp-core/errors';
|
|
11
13
|
import { alpHome } from '@anhlp/alp-client/index';
|
|
12
14
|
import { UsageError } from './usage.js';
|
|
13
15
|
|
|
@@ -62,7 +64,8 @@ const gh = (args, { cwd }) => new Promise((resolve, reject) => {
|
|
|
62
64
|
const bin = process.env.ALP_GH_BIN ?? 'gh';
|
|
63
65
|
// Windows cannot exec a script by its shebang (the tests' stand-in for gh); a JavaScript one runs under this Node.
|
|
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 => { stdout += chunk; });
|
|
@@ -182,7 +185,7 @@ async function taskCommand([action, ...args]) {
|
|
|
182
185
|
description: { type: 'string', short: 'd' }, priority: { type: 'string', short: 'p' }, type: { type: 'string', short: 't' },
|
|
183
186
|
label: { ...repeated, short: 'l' }, path: repeated, parent: { type: 'string' }, after: repeated, related: repeated, from: { type: 'string' },
|
|
184
187
|
title: { type: 'string' }, message: { type: 'string', short: 'm' }, reason: { type: 'string' }, unverified: { type: 'string' }, project: { type: 'string' }, json: { type: 'boolean' },
|
|
185
|
-
human: { type: 'string' }, timer: { type: 'string' }, pr: { type: 'string' }, run: { type: 'string' },
|
|
188
|
+
human: { type: 'string' }, timer: { type: 'string' }, pr: { type: 'string' }, run: { type: 'string' }, option: repeated, choice: { type: 'string' },
|
|
186
189
|
} });
|
|
187
190
|
const root = await taskProject(values.project);
|
|
188
191
|
const fields = {
|
|
@@ -218,7 +221,7 @@ async function taskCommand([action, ...args]) {
|
|
|
218
221
|
task = await updateTask(root, positionals[0], { ...fields, ...(values.title !== undefined ? { title: values.title } : {}), note: values.message }, 'user');
|
|
219
222
|
} else if (action === 'close') {
|
|
220
223
|
if (positionals.length !== 1) throw new UsageError();
|
|
221
|
-
task = await closeTask(root, positionals[0], { reason: values.reason, summary: values.message, unverified: values.unverified }, 'user');
|
|
224
|
+
task = await closeTask(root, positionals[0], { reason: values.reason, summary: values.message, unverified: values.unverified, agent: isAgentProcess(), channel: 'cli' }, 'user');
|
|
222
225
|
} else if (action === 'reopen') {
|
|
223
226
|
if (positionals.length !== 1) throw new UsageError();
|
|
224
227
|
task = await reopenTask(root, positionals[0], { note: values.message }, 'user');
|
|
@@ -230,11 +233,22 @@ async function taskCommand([action, ...args]) {
|
|
|
230
233
|
} else if (action === 'gate') {
|
|
231
234
|
const [change, id, gate, ...rest] = positionals;
|
|
232
235
|
const kinds = ['human', 'timer', 'pr', 'run'].filter(kind => values[kind] !== undefined);
|
|
236
|
+
// Only the user decides a human gate: never from a process an ALP agent started (t-ca1f).
|
|
237
|
+
if (['clear', 'reject', 'rm'].includes(change) && id && gate && isAgentProcess()) {
|
|
238
|
+
const { tasks: current } = await loadTasks(root);
|
|
239
|
+
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`);
|
|
240
|
+
}
|
|
233
241
|
if (change === 'add' && id && !gate && kinds.length === 1) {
|
|
234
242
|
const kind = kinds[0];
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
243
|
+
if (values.option && kind !== 'human') throw new UsageError();
|
|
244
|
+
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');
|
|
245
|
+
} else if (change === 'clear' && id && gate && !rest.length && !kinds.length && !values.option) {
|
|
246
|
+
// A decision made here reaches main as mail, as one made in Paseo or ALP web does.
|
|
247
|
+
task = await resolveGate(root, id, gate, { by: 'user', note: values.message, channel: 'cli', ...(values.choice !== undefined ? { choice: values.choice } : {}) });
|
|
248
|
+
} else if (change === 'reject' && id && gate && !rest.length && !kinds.length && !values.option && values.choice === undefined) {
|
|
249
|
+
task = await rejectGate(root, id, gate, { by: 'user', reason: values.message, channel: 'cli' });
|
|
250
|
+
} else if (change === 'rm' && id && gate && !rest.length && !kinds.length && !values.option && values.choice === undefined) {
|
|
251
|
+
task = await resolveGate(root, id, gate, { by: 'user', note: values.message, remove: true, channel: 'cli' });
|
|
238
252
|
} else {
|
|
239
253
|
throw new UsageError();
|
|
240
254
|
}
|
|
@@ -261,7 +275,7 @@ function printTask(task, tasks) {
|
|
|
261
275
|
task.related.length && `related ${task.related.join(', ')}`,
|
|
262
276
|
].filter(Boolean);
|
|
263
277
|
if (relations.length) console.log(` ${relations.join('; ')}`);
|
|
264
|
-
for (const gate of task.gates) console.log(` ${gateOpen(gate) ? '⏸' : '✓'} gate ${describeGate(gate)}${gate.resolved ? ` (cleared by ${gate.resolved.by}${gate.resolved.note ? `: ${gate.resolved.note}` : ''})` : ''}`);
|
|
278
|
+
for (const gate of task.gates) console.log(` ${gateOpen(gate) ? '⏸' : '✓'} 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 ? ' ⚠ changed outside ALP (a task file edit cleared or removed it); reopened for you to decide' : ''}`);
|
|
265
279
|
const inherited = gatesOf(task, tasks).filter(label => label.startsWith('t-'));
|
|
266
280
|
if (task.status !== 'closed' && inherited.length) console.log(` waits on its parent's gates: ${inherited.join('; ')}`);
|
|
267
281
|
if (task.compacted) console.log(` compacted ${task.compacted.at.slice(0, 10)} from ${task.compacted.chars} characters`);
|
package/src/terminal.js
CHANGED
|
@@ -20,12 +20,13 @@ export const TERMINAL_WARNING = (user = os.userInfo().username) => [
|
|
|
20
20
|
|
|
21
21
|
const file = home => path.join(home, 'terminal.json');
|
|
22
22
|
|
|
23
|
-
async function read(home) {
|
|
23
|
+
export async function read(home, platform = process.platform) {
|
|
24
24
|
const info = await lstat(file(home)).catch(() => undefined);
|
|
25
25
|
if (!info) return { exists: false, value: undefined, private: true };
|
|
26
26
|
const own = !process.getuid || info.uid === process.getuid();
|
|
27
|
-
const value = info.isFile() ? await readFile(file(home), 'utf8').then(JSON.parse
|
|
28
|
-
|
|
27
|
+
const value = info.isFile() ? await readFile(file(home), 'utf8').then(JSON.parse).catch(() => undefined) : undefined;
|
|
28
|
+
// Windows has no POSIX group/other mode bits (files report 0o666/0o444).
|
|
29
|
+
return { exists: true, value, private: info.isFile() && own && (platform === 'win32' || !(info.mode & 0o077)) };
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
async function write(home, value) {
|
package/src/usage.js
CHANGED
|
@@ -2,15 +2,20 @@
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
|
|
4
4
|
const USAGE = `Usage:
|
|
5
|
-
alp <init|
|
|
5
|
+
alp <init|update-template> [directory] create a project, or upgrade an older project's ALP template (upgrade is an alias)
|
|
6
|
+
alp update [--check] [--yes] [--version X] update ALP from GitHub Releases (checksum and provenance checked)
|
|
7
|
+
alp --version
|
|
6
8
|
alp setup [directory] [--runtime codex|claude|mix] [--prefer claude|codex]
|
|
7
9
|
[--claude-model M] [--codex-model M] [--claude-supervisor M] [--codex-supervisor M]
|
|
8
10
|
[--claude-oracle M] [--codex-oracle M] write Phở/Cafe's agent profiles to .alp/settings.json
|
|
9
11
|
alp daemon <start|stop|restart>
|
|
10
12
|
alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready
|
|
11
13
|
alp daemon <install|uninstall> run alpd as a login service that restarts after a crash
|
|
14
|
+
alp daemon run [--detach] [--service] run alpd in this process (what services written by 0.0.1-beta.5/6 start)
|
|
12
15
|
alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio
|
|
13
16
|
alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address
|
|
17
|
+
alp web serve [--service|--rotate] [--project DIR] run alp-web in this process (what alp web starts)
|
|
18
|
+
alp bridge <acp|antigravity> the stdio MCP bridge an agent CLI starts to reach alpd (internal)
|
|
14
19
|
alp web rotate give alp web a new token: open pages lose access; prints the new address
|
|
15
20
|
alp web pair [--on|--off] the link that pairs Paseo's app on another device through the relay; --on or --off turns the relay on or off
|
|
16
21
|
alp terminal <allow [--paseo] --yes|deny [--paseo]|status> [--json] remote terminals (a shell as you on this host; a workspace is not a sandbox), off by default
|
|
@@ -44,7 +49,7 @@ const USAGE = `Usage:
|
|
|
44
49
|
alp mcp add <name> [--project [DIR]] (--command C [--arg A]... [--env K=V]... [--cwd D] | --url U [--header K=V]...)
|
|
45
50
|
alp hook add <name> [--project [DIR]] --event E --command C [--blocking] [--timeout SEC] [--match-agent A] [--match-label L]
|
|
46
51
|
alp provider add <id> --command C [--arg A]... [--env K=V]... [--label L] [-d text] [--models a,b] an ACP agent; use id antigravity for native agy
|
|
47
|
-
alp provider edit antigravity --read-only-mode instructions|reject
|
|
52
|
+
alp provider edit antigravity --read-only-mode instructions|reject legacy, no effect: agy enforces every mode itself
|
|
48
53
|
alp <agent|team|skill|mcp|hook|provider> <rm|show> <name> [--project [DIR]] | <cp|mv> <from> <to> [--project [DIR]]
|
|
49
54
|
alp <mcp|hook|provider> test <name> [--project [DIR]] list an MCP server's tools; run a hook once; initialize a provider
|
|
50
55
|
without --project, changes go to your library in ~/.alp; built-in agents and teams are never changed
|
|
@@ -65,13 +70,17 @@ const USAGE = `Usage:
|
|
|
65
70
|
alp verify [--project DIR] [--task ID] [--json] run the project's verify commands; --task records the result
|
|
66
71
|
alp task reopen <id> [-m note]
|
|
67
72
|
alp task dep <add|rm> <id> [--after ID]... [--parent ID] [--related ID]...
|
|
68
|
-
alp task gate add <id> --human "question" | --timer +2h|ISO | --pr N|owner/repo#N | --run N|owner/repo#N
|
|
69
|
-
alp task gate
|
|
73
|
+
alp task gate add <id> --human "question" [--option answer]... | --timer +2h|ISO | --pr N|owner/repo#N | --run N|owner/repo#N
|
|
74
|
+
alp task gate clear <id> <gate> [--choice answer] [-m note] approve; main is told by mail
|
|
75
|
+
alp task gate reject <id> <gate> [-m reason] the gate stays open; main is told by mail
|
|
76
|
+
alp task gate rm <id> <gate> [-m note]
|
|
70
77
|
alp pause [codex|claude] [--now] [-m reason] | alp pause status hold delegation; --now parks running assignments
|
|
71
78
|
alp resume [codex|claude] lift a pause; parked assignments continue
|
|
79
|
+
alp models [--refresh] [--json] the models alpd offers now, from each provider (cached; refreshed every 6 h)
|
|
72
80
|
alp language [name | --reset] the language agents and ALP write to you in; default Vietnamese
|
|
73
81
|
alp recall <assignment|task> [--project DIR] [--json] <question> ask a finished assignment about its work
|
|
74
|
-
alp interrupt <session
|
|
82
|
+
alp interrupt <session>
|
|
83
|
+
alp compact <session>`;
|
|
75
84
|
|
|
76
85
|
class UsageError extends Error {}
|
|
77
86
|
|