@anhlp/alp-cli 0.0.1-beta.3 → 0.0.1-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD-PARTY-NOTICES.txt +51 -1
- package/dist/acp/main.js +1 -1
- package/dist/acp.js +300 -92
- package/dist/alp-web/THIRD-PARTY-NOTICES.txt +3256 -0
- package/dist/alp-web/alp-boundary.json +16 -0
- package/dist/alp-web/apple-touch-icon.png +0 -0
- package/dist/alp-web/assets/TerminalPanel-CqTsgY-W.js +22 -0
- package/dist/alp-web/assets/TerminalPanel-DLuoa74B.css +1 -0
- package/dist/alp-web/assets/highlighter-BnicKQ_d.js +18 -0
- package/dist/alp-web/assets/index-BMbDUCHW.css +1 -0
- package/dist/alp-web/assets/index-B_RFaj2C.js +59 -0
- package/dist/alp-web/favicon-attention.svg +6 -0
- package/dist/alp-web/favicon-running.svg +6 -0
- package/dist/alp-web/favicon.svg +5 -0
- package/dist/alp-web/index.html +20 -0
- package/dist/alp-web.js +10119 -0
- package/dist/alpd.js +30333 -15153
- package/dist/backup.js +2 -2
- package/dist/build-manifest.json +120 -2
- package/dist/cli.js +34 -3
- package/dist/daemon.d.ts +1 -1
- package/dist/daemon.js +5 -0
- package/dist/interfaces.d.ts +22 -2
- package/dist/interfaces.js +182 -37
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +2 -1
- package/dist/roles.d.ts +15 -0
- package/dist/roles.js +18 -0
- package/dist/schedules.d.ts +2 -0
- package/dist/schedules.js +45 -0
- package/dist/self-update.d.ts +152 -0
- package/dist/self-update.js +390 -0
- package/dist/sessions.d.ts +7 -1
- package/dist/sessions.js +44 -12
- 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 +13 -0
- package/dist/terminal.js +80 -0
- package/dist/usage.d.ts +1 -1
- package/dist/usage.js +22 -7
- package/dist/web-service.d.ts +56 -0
- package/dist/web-service.js +143 -0
- package/package.json +11 -4
- package/src/backup.js +1 -1
- package/src/cli.js +40 -4
- package/src/daemon.js +3 -0
- package/src/interfaces.js +227 -32
- package/src/paths.js +3 -1
- package/src/roles.js +28 -0
- package/src/schedules.js +38 -0
- package/src/self-update.js +406 -0
- package/src/sessions.js +44 -13
- package/src/tasks.js +22 -8
- package/src/terminal.js +78 -0
- package/src/usage.js +22 -7
- package/src/web-service.js +187 -0
|
@@ -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 { executablePath } from '@anhlp/alp-core/packaged';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* `alp update` (t-1e02 P3): replaces the ALP executable with a release from GitHub Releases, after
|
|
13
|
+
* checking the archive against the release's SHA256SUMS and, when `gh` is installed, its build
|
|
14
|
+
* provenance. The project template upgrade that `alp update` used to run is `alp update-template`.
|
|
15
|
+
*
|
|
16
|
+
* Everything that touches the network, the filesystem or child processes comes in through `deps`
|
|
17
|
+
* so the tests can drive each step.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_REPO = 'phucanh08/alp';
|
|
21
|
+
export const SIGNER_WORKFLOW = '.github/workflows/release-binaries.yml';
|
|
22
|
+
export const NPM_PACKAGE = '@anhlp/alp';
|
|
23
|
+
const TEMPLATE_HINT = 'did you mean `alp update-template`? (`alp update` now updates the ALP executable; the project template upgrade is `alp update-template [directory]`)';
|
|
24
|
+
|
|
25
|
+
const OPTIONS = { check: { type: 'boolean' }, yes: { type: 'boolean', short: 'y' }, version: { type: 'string' }, 'base-url': { type: 'string' }, help: { type: 'boolean', short: 'h' } };
|
|
26
|
+
|
|
27
|
+
export const UPDATE_USAGE = `Usage: alp update [--check] [--yes] [--version X] [--base-url URL]
|
|
28
|
+
Replaces this ALP executable with the latest release (or release X) from GitHub Releases, after checking
|
|
29
|
+
it against SHA256SUMS and, when gh is installed, its build provenance. --check only reports.
|
|
30
|
+
ALP_UPDATE_BASE_URL (as --base-url, an https:// or file:// mirror) and ALP_INSTALL_REPO (owner/name) override the source.
|
|
31
|
+
The project template upgrade is \`alp update-template [directory]\`.`;
|
|
32
|
+
|
|
33
|
+
/** The release platform of this process: darwin-arm64, linux-x64, windows-x64. @param {string} platform @param {string} arch */
|
|
34
|
+
export function releasePlatform(platform = process.platform, arch = process.arch) {
|
|
35
|
+
const osName = { darwin: 'darwin', linux: 'linux', win32: 'windows' }[platform];
|
|
36
|
+
const archName = { x64: 'x64', arm64: 'arm64' }[arch];
|
|
37
|
+
if (!osName || !archName || (osName === 'windows' && archName !== 'x64')) throw new Error(`ALP publishes no executable for ${platform}-${arch}`);
|
|
38
|
+
return `${osName}-${archName}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The archive extension of a release platform. @param {string} platform */
|
|
42
|
+
export const archiveExtension = platform => platform.startsWith('windows-') ? '.zip' : '.tar.gz';
|
|
43
|
+
|
|
44
|
+
/** Parses SHA256SUMS into [{ sha256, name }]. @param {string} text */
|
|
45
|
+
export function parseSums(text) {
|
|
46
|
+
const entries = [];
|
|
47
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
48
|
+
const line = raw.trim();
|
|
49
|
+
if (!line) continue;
|
|
50
|
+
const match = /^([0-9a-fA-F]{64}) [ *]?(.+)$/.exec(line);
|
|
51
|
+
if (!match) throw new Error(`Malformed SHA256SUMS line: ${JSON.stringify(line)}`);
|
|
52
|
+
entries.push({ sha256: match[1].toLowerCase(), name: match[2].trim() });
|
|
53
|
+
}
|
|
54
|
+
return entries;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The archive for `platform` in SHA256SUMS: alp-<version>-<platform>.<ext>, for `version` when given.
|
|
59
|
+
* @param {string} sumsText @param {string} platform @param {string} [version]
|
|
60
|
+
* @returns {{ name: string, sha256: string, version: string }}
|
|
61
|
+
*/
|
|
62
|
+
export function selectAsset(sumsText, platform, version) {
|
|
63
|
+
const suffix = `-${platform}${archiveExtension(platform)}`;
|
|
64
|
+
const matches = parseSums(sumsText).filter(({ name }) => name.endsWith(suffix) && /^alp-[0-9]/.test(name) && (!version || name === `alp-${version}${suffix}`));
|
|
65
|
+
if (matches.length === 0) throw new Error(`This release has no ALP executable for ${platform}${version ? ` at version ${version}` : ''}`);
|
|
66
|
+
if (matches.length > 1) throw new Error(`SHA256SUMS lists more than one ${platform} archive: ${matches.map(m => m.name).join(', ')}`);
|
|
67
|
+
const [match] = matches;
|
|
68
|
+
if (/[^0-9A-Za-z.+_-]/.test(match.name)) throw new Error(`Unexpected archive name in SHA256SUMS: ${match.name}`);
|
|
69
|
+
return { ...match, version: match.name.slice('alp-'.length, -suffix.length) };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export const sha256 = (/** @type {Uint8Array} */ bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
73
|
+
|
|
74
|
+
/** Refuses an archive whose digest differs from SHA256SUMS. @param {Uint8Array} bytes @param {{ name: string, sha256: string }} asset */
|
|
75
|
+
export function verifyChecksum(bytes, asset) {
|
|
76
|
+
const actual = sha256(bytes);
|
|
77
|
+
if (actual !== asset.sha256) throw new Error(`Checksum mismatch for ${asset.name} (expected ${asset.sha256}, got ${actual}); nothing was replaced`);
|
|
78
|
+
return actual;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Compares dotted versions numerically, prerelease below release. @param {string} a @param {string} b */
|
|
82
|
+
export function compareVersions(a, b) {
|
|
83
|
+
const split = (/** @type {string} */ v) => {
|
|
84
|
+
// Build metadata (+b) does not order versions.
|
|
85
|
+
const [core, pre] = v.replace(/^v/, '').replace(/\+.*$/s, '').split(/-(.*)/s);
|
|
86
|
+
if (!/^\d+(\.\d+)*$/.test(core)) throw new Error(`Invalid version: ${JSON.stringify(v)}`);
|
|
87
|
+
return { core: core.split('.').map(Number), pre };
|
|
88
|
+
};
|
|
89
|
+
const x = split(a), y = split(b);
|
|
90
|
+
for (let i = 0; i < Math.max(x.core.length, y.core.length); i++) {
|
|
91
|
+
const d = (x.core[i] ?? 0) - (y.core[i] ?? 0);
|
|
92
|
+
if (d) return Math.sign(d);
|
|
93
|
+
}
|
|
94
|
+
if (x.pre === y.pre) return 0;
|
|
95
|
+
if (x.pre === undefined) return 1;
|
|
96
|
+
if (y.pre === undefined) return -1;
|
|
97
|
+
return x.pre.localeCompare(y.pre, 'en', { numeric: true });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The base URL that holds SHA256SUMS and the archives. @param {{ repo: string, version?: string, baseUrl?: string }} options */
|
|
101
|
+
export function releaseBaseUrl({ repo, version, baseUrl }) {
|
|
102
|
+
let base = baseUrl;
|
|
103
|
+
if (!base) base = version ? `https://github.com/${repo}/releases/download/v${version}` : `https://github.com/${repo}/releases/latest/download`;
|
|
104
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(base) && (path.isAbsolute(base) || (process.platform === 'win32' && path.win32.isAbsolute(base)))) base = pathToFileURL(base).href;
|
|
105
|
+
base = base.replace(/\/+$/, '');
|
|
106
|
+
const url = new URL(base);
|
|
107
|
+
const loopback = isLoopbackHttp(url);
|
|
108
|
+
if (url.protocol !== 'https:' && url.protocol !== 'file:' && !loopback) throw new Error(`The release mirror must be https:// or file:// (${base})`);
|
|
109
|
+
return base;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The largest file alp update downloads: the executable is about 100 MB. */
|
|
113
|
+
export const MAX_DOWNLOAD = 512 * 1024 * 1024;
|
|
114
|
+
|
|
115
|
+
const LOOPBACK = ['127.0.0.1', 'localhost', '[::1]'];
|
|
116
|
+
const isLoopbackHttp = (/** @type {URL} */ url) => url.protocol === 'http:' && LOOPBACK.includes(url.hostname);
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Whether a download may go to `next`: every hop of an https download stays https, since one plain
|
|
120
|
+
* http hop lets a man in the middle replace the archive and SHA256SUMS together. Only a loopback
|
|
121
|
+
* http mirror given explicitly (tests) may use loopback http, besides https.
|
|
122
|
+
* @param {string} start @param {string} next
|
|
123
|
+
*/
|
|
124
|
+
export function allowedHop(start, next) {
|
|
125
|
+
const to = new URL(next);
|
|
126
|
+
if (to.protocol === 'https:') return true;
|
|
127
|
+
return isLoopbackHttp(new URL(start)) && isLoopbackHttp(to);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Downloads `url` (https, loopback http or file) within a time and size limit, following at most 10
|
|
132
|
+
* redirects itself and refusing any hop that `allowedHop` refuses.
|
|
133
|
+
* @param {string} url @param {{ timeoutMs?: number, max?: number, fetch?: typeof globalThis.fetch }} [options]
|
|
134
|
+
*/
|
|
135
|
+
export async function fetchBytes(url, { timeoutMs = 10 * 60_000, max = MAX_DOWNLOAD, fetch: fetchImpl = globalThis.fetch } = {}) {
|
|
136
|
+
if (url.startsWith('file:')) {
|
|
137
|
+
const file = fileURLToPath(url);
|
|
138
|
+
if (nodeFs.statSync(file).size > max) throw new Error(`${url} is larger than ${max} bytes`);
|
|
139
|
+
return new Uint8Array(await nodeFs.promises.readFile(file));
|
|
140
|
+
}
|
|
141
|
+
if (!allowedHop(url, url)) throw new Error(`Refusing to download ${url}: not https`);
|
|
142
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
143
|
+
let current = url;
|
|
144
|
+
let response;
|
|
145
|
+
for (let hop = 0; ; hop++) {
|
|
146
|
+
response = await fetchImpl(current, { redirect: 'manual', signal });
|
|
147
|
+
if (![301, 302, 303, 307, 308].includes(response.status)) break;
|
|
148
|
+
const location = response.headers.get('location');
|
|
149
|
+
await response.body?.cancel().catch(() => {});
|
|
150
|
+
if (!location) throw new Error(`${current} redirected without a location`);
|
|
151
|
+
if (hop >= 10) throw new Error(`${url} redirected more than 10 times`);
|
|
152
|
+
const next = new URL(location, current).href;
|
|
153
|
+
if (!allowedHop(url, next)) throw new Error(`${url} redirected to ${next}, which is not https; refused`);
|
|
154
|
+
current = next;
|
|
155
|
+
}
|
|
156
|
+
if (!response.ok) throw new Error(`Could not download ${current} (HTTP ${response.status})`);
|
|
157
|
+
if (Number(response.headers.get('content-length') ?? 0) > max) throw new Error(`${current} is larger than ${max} bytes`);
|
|
158
|
+
const chunks = [];
|
|
159
|
+
let size = 0;
|
|
160
|
+
for await (const chunk of /** @type {AsyncIterable<Uint8Array>} */ (response.body ?? [])) {
|
|
161
|
+
size += chunk.byteLength;
|
|
162
|
+
if (size > max) throw new Error(`${current} is larger than ${max} bytes`);
|
|
163
|
+
chunks.push(chunk);
|
|
164
|
+
}
|
|
165
|
+
return new Uint8Array(Buffer.concat(chunks));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Whether a program is on PATH. @param {string} name */
|
|
169
|
+
function which(name) {
|
|
170
|
+
const result = spawnSync(process.platform === 'win32' ? 'where' : 'which', [name], { encoding: 'utf8', windowsHide: true });
|
|
171
|
+
return result.status === 0 ? result.stdout.split(/\r?\n/)[0].trim() || undefined : undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Verifies the archive's build provenance with gh. Returns 'verified', or 'unavailable' when gh is
|
|
176
|
+
* absent (ALP_UPDATE_NO_GH=1 treats it as absent); throws when gh reports a failure.
|
|
177
|
+
* @param {string} file @param {{ repo: string, env?: NodeJS.ProcessEnv, run?: typeof spawnSync, find?: typeof which }} options
|
|
178
|
+
*/
|
|
179
|
+
export function verifyProvenance(file, { repo, env = process.env, run = spawnSync, find = which }) {
|
|
180
|
+
if (env.ALP_UPDATE_NO_GH === '1') return 'unavailable';
|
|
181
|
+
const gh = find('gh');
|
|
182
|
+
if (!gh) return 'unavailable';
|
|
183
|
+
const result = run(gh, ['attestation', 'verify', file, '--repo', repo, '--source-ref', 'refs/heads/main', '--signer-workflow', `${repo}/${SIGNER_WORKFLOW}`], { encoding: 'utf8', windowsHide: true });
|
|
184
|
+
if (result.status !== 0) {
|
|
185
|
+
const detail = `${result.stderr ?? ''}${result.stdout ?? ''}`.trim().split(/\r?\n/).slice(-3).join(' ');
|
|
186
|
+
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)`);
|
|
187
|
+
}
|
|
188
|
+
return 'verified';
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The previous executable Windows keeps beside the new one until the next start. @param {string} target @param {string} [platform] */
|
|
192
|
+
export const oldPath = (target, platform = process.platform) => {
|
|
193
|
+
const p = platform === 'win32' ? path.win32 : path;
|
|
194
|
+
return p.join(p.dirname(target), `${p.basename(target, p.extname(target))}.old${p.extname(target) || '.exe'}`);
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const TRANSIENT = new Set(['EBUSY', 'EPERM', 'EACCES']);
|
|
198
|
+
const pause = (/** @type {number} */ ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Runs `action`, again after a pause while Windows reports the file busy: a virus scanner holds an
|
|
202
|
+
* executable it just saw run (the staged file's --version) for a moment. About 6 s in all.
|
|
203
|
+
* @template T @param {() => T} action @param {(ms: number) => void} [sleep]
|
|
204
|
+
*/
|
|
205
|
+
export function retryBusy(action, sleep = pause, attempts = 25) {
|
|
206
|
+
for (let attempt = 1; ; attempt++) {
|
|
207
|
+
try { return action(); } catch (error) {
|
|
208
|
+
if (attempt >= attempts || !TRANSIENT.has(error?.code)) throw error;
|
|
209
|
+
sleep(Math.min(50 * attempt, 400));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Puts `staged` in place of `target`. Unix: rename over the running file. Windows: the running
|
|
216
|
+
* alp.exe cannot be overwritten but can be renamed, so it becomes alp.old.exe (deleted on the next
|
|
217
|
+
* start) and the new file takes its name; a failure puts the old one back.
|
|
218
|
+
* @param {string} staged @param {string} target @param {{ platform?: string, fs?: Pick<typeof nodeFs, 'renameSync' | 'rmSync' | 'existsSync'>, unique?: () => string, sleep?: (ms: number) => void }} [options]
|
|
219
|
+
*/
|
|
220
|
+
export function replaceExecutable(staged, target, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(4).toString('hex'), sleep = pause } = {}) {
|
|
221
|
+
if (platform !== 'win32') { fs.renameSync(staged, target); return { old: undefined }; }
|
|
222
|
+
const old = oldPath(target, platform);
|
|
223
|
+
if (fs.existsSync(old)) {
|
|
224
|
+
// A process started from the previous update's file (an alpd not restarted yet) keeps it locked:
|
|
225
|
+
// it cannot be deleted, but it can be moved aside for a later start to delete.
|
|
226
|
+
try { fs.rmSync(old, { force: true }); } catch {
|
|
227
|
+
const aside = old.replace(/\.exe$/i, `.${unique()}.exe`);
|
|
228
|
+
try { fs.renameSync(old, aside); } catch (error) {
|
|
229
|
+
throw new Error(`${old} is in use and could not be moved (${error.code ?? error.message}); stop the ALP processes started from it (alp daemon stop) and run alp update again`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
retryBusy(() => fs.renameSync(target, old), sleep);
|
|
234
|
+
try {
|
|
235
|
+
retryBusy(() => fs.renameSync(staged, target), sleep);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
try { retryBusy(() => fs.renameSync(old, target), sleep); } catch (restore) {
|
|
238
|
+
throw new Error(`Could not put the new executable at ${target} (${error.code ?? error.message}), and could not move the previous one back (${restore.code ?? restore.message}): rename ${old} to ${target} yourself`);
|
|
239
|
+
}
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
return { old };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Deletes the alp.old.exe (and alp.old.<hex>.exe) a Windows update left behind; called on every packaged start. @param {string} target @param {{ platform?: string, fs?: Pick<typeof nodeFs, 'rmSync' | 'readdirSync'> }} [options] */
|
|
246
|
+
export function cleanupOldExecutable(target, { platform = process.platform, fs = nodeFs } = {}) {
|
|
247
|
+
if (platform !== 'win32') return false;
|
|
248
|
+
const old = path.win32.basename(oldPath(target, platform));
|
|
249
|
+
const stem = old.slice(0, -'.exe'.length).toLowerCase();
|
|
250
|
+
let names;
|
|
251
|
+
try { names = fs.readdirSync(path.win32.dirname(target)); } catch { return false; }
|
|
252
|
+
let removed = false;
|
|
253
|
+
// alp.old.exe, and the alp.old.<hex>.exe a locked one was moved aside to.
|
|
254
|
+
for (const name of names) {
|
|
255
|
+
const lower = name.toLowerCase();
|
|
256
|
+
if (lower !== `${stem}.exe` && !(lower.startsWith(`${stem}.`) && /^[0-9a-f]+\.exe$/.test(lower.slice(stem.length + 1)))) continue;
|
|
257
|
+
try { fs.rmSync(path.win32.join(path.win32.dirname(target), name), { force: true }); removed = true; } catch {}
|
|
258
|
+
}
|
|
259
|
+
return removed;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Whether the executable is the one npm installed for @anhlp/alp (t-cd7f): it lives in a platform
|
|
264
|
+
* package, node_modules/@anhlp/alp-<os>-<arch>/bin/. npm owns that file; updating it in place would
|
|
265
|
+
* leave npm's records behind, so npm updates it. @param {string} execPath
|
|
266
|
+
*/
|
|
267
|
+
export function isNpmExecutable(execPath) {
|
|
268
|
+
return /[\\/]node_modules[\\/]@anhlp[\\/]alp-(?:darwin|linux|win32)-(?:arm64|x64)[\\/]bin[\\/]alp(?:\.exe)?$/i.test(execPath ?? '');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** What to say outside the executable (an npm install). @param {string[]} positionals */
|
|
272
|
+
export function npmMessage(positionals = []) {
|
|
273
|
+
const lines = [];
|
|
274
|
+
if (positionals.length) lines.push(`alp: ${TEMPLATE_HINT}`);
|
|
275
|
+
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]\`.)`);
|
|
276
|
+
return lines.join('\n');
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Extracts the archive and returns the executable inside it. @param {string} archive @param {string} directory @param {{ name: string }} asset @param {string} platform */
|
|
280
|
+
function extract(archive, directory, asset, platform, run = spawnSync) {
|
|
281
|
+
const windows = platform.startsWith('windows-');
|
|
282
|
+
// tar reads both: GNU/bsd tar for .tar.gz, Windows' bsdtar (tar.exe) for .zip.
|
|
283
|
+
// On Windows, Git's GNU tar (which reads no zip) may come first on PATH: use the system's bsdtar.
|
|
284
|
+
const tar = process.platform === 'win32' ? path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe') : 'tar';
|
|
285
|
+
const result = run(tar, [windows ? '-xf' : '-xzf', archive, '-C', directory], { encoding: 'utf8', windowsHide: true });
|
|
286
|
+
if (result.status !== 0) throw new Error(`Could not extract ${asset.name}: ${(result.stderr || result.error?.message || '').trim()}`);
|
|
287
|
+
const name = asset.name.slice(0, -archiveExtension(platform).length);
|
|
288
|
+
const binary = path.join(directory, name, windows ? 'alp.exe' : 'alp');
|
|
289
|
+
if (!nodeFs.existsSync(binary)) throw new Error(`${asset.name} does not contain ${name}/${windows ? 'alp.exe' : 'alp'}`);
|
|
290
|
+
return binary;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Asks a yes/no question on the terminal. @param {string} question */
|
|
294
|
+
async function confirm(question) {
|
|
295
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
296
|
+
try { return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim()); } finally { rl.close(); }
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* @typedef {{
|
|
301
|
+
* packaged: boolean, version: string, execPath: string, env: NodeJS.ProcessEnv, platform: string, arch: string,
|
|
302
|
+
* log: (line: string) => void, warn: (line: string) => void, interactive: boolean,
|
|
303
|
+
* fetchBytes: (url: string) => Promise<Uint8Array>, confirm: (question: string) => Promise<boolean>,
|
|
304
|
+
* provenance: (file: string, repo: string) => string, extract: typeof extract,
|
|
305
|
+
* daemon: () => Promise<{ version: string, sessions?: number } | undefined>, restartDaemon: (binary: string) => number,
|
|
306
|
+
* runVersion: (binary: string) => string,
|
|
307
|
+
* }} UpdateDeps
|
|
308
|
+
*/
|
|
309
|
+
|
|
310
|
+
/** @param {string[]} args @param {Partial<UpdateDeps>} [overrides] @returns {Promise<number>} the exit code */
|
|
311
|
+
export async function selfUpdate(args, overrides = {}) {
|
|
312
|
+
/** @type {UpdateDeps} */
|
|
313
|
+
const deps = {
|
|
314
|
+
packaged: false, version: '0.0.0', execPath: executablePath() ?? '', env: process.env, platform: process.platform, arch: process.arch,
|
|
315
|
+
log: line => console.log(line), warn: line => console.error(line), interactive: !!(process.stdin.isTTY && process.stdout.isTTY),
|
|
316
|
+
fetchBytes, confirm, extract,
|
|
317
|
+
provenance: (file, repo) => verifyProvenance(file, { repo }),
|
|
318
|
+
daemon: async () => undefined, restartDaemon: binary => spawnSync(binary, ['daemon', 'restart'], { stdio: 'inherit', windowsHide: true }).status ?? 1,
|
|
319
|
+
runVersion: binary => spawnSync(binary, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 60_000 }).stdout?.trim() ?? '',
|
|
320
|
+
...overrides,
|
|
321
|
+
};
|
|
322
|
+
let parsed;
|
|
323
|
+
try {
|
|
324
|
+
parsed = parseArgs({ args, allowPositionals: true, options: OPTIONS, strict: true });
|
|
325
|
+
} catch (error) {
|
|
326
|
+
deps.warn(`alp: ${error.message}`);
|
|
327
|
+
deps.warn(`alp: ${TEMPLATE_HINT}`);
|
|
328
|
+
return deps.packaged ? 1 : 0;
|
|
329
|
+
}
|
|
330
|
+
const { values, positionals } = parsed;
|
|
331
|
+
if (values.help) { deps.log(UPDATE_USAGE); return 0; }
|
|
332
|
+
if (!deps.packaged || isNpmExecutable(deps.execPath)) { deps.log(npmMessage(positionals)); return 0; }
|
|
333
|
+
if (positionals.length) { deps.warn(`alp: ${TEMPLATE_HINT}`); return 1; }
|
|
334
|
+
|
|
335
|
+
const wanted = values.version?.replace(/^v/, '');
|
|
336
|
+
if (wanted !== undefined && !/^[0-9][0-9A-Za-z.+-]*$/.test(wanted)) throw new Error(`Invalid version: ${values.version}`);
|
|
337
|
+
const repo = deps.env.ALP_INSTALL_REPO || DEFAULT_REPO;
|
|
338
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error(`Invalid ALP_INSTALL_REPO: ${repo}`);
|
|
339
|
+
const base = releaseBaseUrl({ repo, version: wanted, baseUrl: values['base-url'] ?? deps.env.ALP_UPDATE_BASE_URL });
|
|
340
|
+
const platform = releasePlatform(deps.platform, deps.arch);
|
|
341
|
+
|
|
342
|
+
const sums = new TextDecoder().decode(await deps.fetchBytes(`${base}/SHA256SUMS`));
|
|
343
|
+
const asset = selectAsset(sums, platform, wanted);
|
|
344
|
+
const order = compareVersions(asset.version, deps.version);
|
|
345
|
+
if (values.check) {
|
|
346
|
+
if (order === 0) deps.log(`alp ${deps.version} is up to date (${platform})`);
|
|
347
|
+
else if (order < 0 && !wanted) deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}`);
|
|
348
|
+
else deps.log(`alp ${deps.version} → ${asset.version} available (${asset.name}); run: alp update${wanted ? ` --version ${wanted}` : ''}`);
|
|
349
|
+
return 0;
|
|
350
|
+
}
|
|
351
|
+
// An explicit --version of the running version reinstalls it (a repair); without one there is nothing to do.
|
|
352
|
+
if (order === 0 && !wanted) { deps.log(`alp ${deps.version} is up to date (${platform})`); return 0; }
|
|
353
|
+
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; }
|
|
354
|
+
|
|
355
|
+
let target;
|
|
356
|
+
try { target = nodeFs.realpathSync(deps.execPath); } catch { target = deps.execPath; }
|
|
357
|
+
const dir = path.dirname(target);
|
|
358
|
+
try { nodeFs.accessSync(dir, nodeFs.constants.W_OK); } catch { throw new Error(`${dir} is not writable; run alp update with the permissions that installed ${target}`); }
|
|
359
|
+
|
|
360
|
+
if (!values.yes) {
|
|
361
|
+
if (!deps.interactive) throw new Error(`alp update would replace ${target} (${deps.version} → ${asset.version}); pass --yes to do it without a terminal`);
|
|
362
|
+
if (!await deps.confirm(`Replace ${target} (${deps.version} → ${asset.version})?`)) { deps.log('Not updated.'); return 1; }
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const work = nodeFs.mkdtempSync(path.join(os.tmpdir(), 'alp-update-'));
|
|
366
|
+
let staged;
|
|
367
|
+
try {
|
|
368
|
+
deps.log(`Downloading ${asset.name} from ${base}`);
|
|
369
|
+
const bytes = await deps.fetchBytes(`${base}/${asset.name}`);
|
|
370
|
+
verifyChecksum(bytes, asset);
|
|
371
|
+
deps.log(`Checksum verified (${asset.sha256})`);
|
|
372
|
+
const archive = path.join(work, asset.name);
|
|
373
|
+
nodeFs.writeFileSync(archive, bytes);
|
|
374
|
+
const provenance = deps.provenance(archive, repo);
|
|
375
|
+
if (provenance === 'verified') deps.log(`Provenance verified by gh attestation (${repo}, refs/heads/main, release-binaries.yml)`);
|
|
376
|
+
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)');
|
|
377
|
+
const unpacked = path.join(work, 'x');
|
|
378
|
+
nodeFs.mkdirSync(unpacked);
|
|
379
|
+
const binary = deps.extract(archive, unpacked, asset, platform);
|
|
380
|
+
// Stage beside the target so the rename stays on one filesystem; no half-written file is ever alp.
|
|
381
|
+
staged = path.join(dir, `.alp.update.${randomBytes(6).toString('hex')}${deps.platform === 'win32' ? '.exe' : ''}`);
|
|
382
|
+
nodeFs.copyFileSync(binary, staged);
|
|
383
|
+
if (deps.platform !== 'win32') nodeFs.chmodSync(staged, 0o755);
|
|
384
|
+
const reported = deps.runVersion(staged);
|
|
385
|
+
if (reported !== asset.version) throw new Error(`The downloaded executable reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was replaced`);
|
|
386
|
+
replaceExecutable(staged, target, { platform: deps.platform });
|
|
387
|
+
staged = undefined;
|
|
388
|
+
} finally {
|
|
389
|
+
// A cleanup failure must not hide why the update failed; a leftover .alp.update.* is harmless.
|
|
390
|
+
if (staged) try { nodeFs.rmSync(staged, { force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
|
|
391
|
+
try { nodeFs.rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
|
|
392
|
+
}
|
|
393
|
+
deps.log(`Updated ${target}: ${deps.version} → ${asset.version}`);
|
|
394
|
+
|
|
395
|
+
const running = await deps.daemon().catch(() => undefined);
|
|
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';
|
|
@@ -108,7 +108,7 @@ function answerer(client) {
|
|
|
108
108
|
|
|
109
109
|
/** Streams a tree until its root is idle; the first Ctrl-C interrupts it, the second detaches. */
|
|
110
110
|
|
|
111
|
-
function follow(client, rootId, print, { untilIdle, interactive = false }) {
|
|
111
|
+
function follow(client, rootId, print, { untilIdle, interactive = false, targetOnly = false, promptId }) {
|
|
112
112
|
const answering = interactive ? answerer(client) : undefined;
|
|
113
113
|
const done = new Promise((resolve, reject) => {
|
|
114
114
|
let failed = false;
|
|
@@ -121,9 +121,11 @@ function follow(client, rootId, print, { untilIdle, interactive = false }) {
|
|
|
121
121
|
client.request('session.interrupt', { sessionId: rootId }).catch(() => {});
|
|
122
122
|
};
|
|
123
123
|
process.on('SIGINT', onSignal);
|
|
124
|
-
client.onClose(error => { process.off('SIGINT', onSignal); reject(error); });
|
|
124
|
+
client.onClose(error => { process.off('SIGINT', onSignal); answering?.close(); reject(error); });
|
|
125
125
|
let rootEnded = false;
|
|
126
126
|
client.onEvent(envelope => {
|
|
127
|
+
if (targetOnly && envelope.sessionId !== rootId) return;
|
|
128
|
+
if (promptId && envelope.event.type === 'prompt.failed' && envelope.event.clientMessageId !== promptId) return;
|
|
127
129
|
print(envelope);
|
|
128
130
|
answering?.accept(envelope.event);
|
|
129
131
|
const { sessionId, event } = envelope;
|
|
@@ -207,28 +209,36 @@ async function attach(args) {
|
|
|
207
209
|
/** Steers a running root, prompts an idle one, or resumes a closed one; then follows it until idle. */
|
|
208
210
|
|
|
209
211
|
async function send(args) {
|
|
210
|
-
const { values, positionals: [sessionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
|
|
212
|
+
const { values, positionals: [sessionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' }, prompt: { type: 'boolean' } } });
|
|
211
213
|
const text = words.join(' ').trim();
|
|
212
214
|
if (!sessionId || !text) throw new UsageError();
|
|
213
215
|
const client = await connect(await start(), { name: 'alp-cli', version: '1' });
|
|
216
|
+
let subscriptionId;
|
|
214
217
|
try {
|
|
215
218
|
const { session } = await client.request('session.get', { sessionId });
|
|
216
|
-
if (session.parentId) {
|
|
219
|
+
if (session.parentId && !values.prompt) {
|
|
217
220
|
// An assignment gets the text as mail from the user, in its running turn.
|
|
218
221
|
await client.request('session.message', { sessionId, text });
|
|
219
222
|
if (!values.json) console.error(`Sent to ${session.agent} as mail from the user`);
|
|
220
223
|
return;
|
|
221
224
|
}
|
|
222
|
-
const done = follow(client, sessionId, printer(values.json), { untilIdle: true, interactive: !values.json && process.stdin.isTTY });
|
|
223
225
|
const live = session.status === 'idle' || session.status === 'running';
|
|
224
|
-
if (live)
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
226
|
+
if (values.prompt && !live) throw new Error('Explicit prompts require a live session; use default alp send to reopen a root');
|
|
227
|
+
const clientMessageId = randomUUID();
|
|
228
|
+
const done = follow(client, sessionId, printer(values.json), { untilIdle: true, interactive: !values.json && process.stdin.isTTY, targetOnly: !!session.parentId, promptId: clientMessageId });
|
|
229
|
+
if (live) {
|
|
230
|
+
const attached = await client.request('session.attach', { sessionId, replay: false });
|
|
231
|
+
subscriptionId = attached.session.id; // A child attaches its root for observation only.
|
|
232
|
+
} else {
|
|
233
|
+
await client.request('session.create', { sessionId, spec: { cwd: session.projectRoot } });
|
|
234
|
+
subscriptionId = sessionId;
|
|
235
|
+
}
|
|
236
|
+
const steer = !values.prompt && live && !!session.activeTurnId;
|
|
237
|
+
await client.request('session.prompt', { sessionId, clientMessageId, delivery: steer ? 'steer' : 'auto', content: [{ type: 'text', text }] });
|
|
238
|
+
if (!values.json) console.error(values.prompt ? 'Submitted an explicit prompt' : steer ? 'Steered the running turn' : live ? 'Started a turn' : 'Resumed the session');
|
|
229
239
|
if (!await done) process.exitCode = 1;
|
|
230
|
-
await client.request('session.release', { sessionId }).catch(() => {});
|
|
231
240
|
} finally {
|
|
241
|
+
if (subscriptionId) await client.request('session.release', { sessionId: subscriptionId }).catch(() => {});
|
|
232
242
|
client.close();
|
|
233
243
|
}
|
|
234
244
|
}
|
|
@@ -251,6 +261,8 @@ async function answer(args) {
|
|
|
251
261
|
const { values, positionals: [questionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { dismiss: { type: 'boolean' }, reason: { type: 'string' } } });
|
|
252
262
|
const text = words.join(' ').trim();
|
|
253
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})`);
|
|
254
266
|
const client = await running();
|
|
255
267
|
const result = await client.request('question.answer', values.dismiss ? { questionId, dismiss: true, reason: values.reason } : { questionId, text }).finally(() => client.close());
|
|
256
268
|
console.log(`${values.dismiss ? 'Dismissed' : 'Answered'} ${result.questionId}`);
|
|
@@ -319,6 +331,17 @@ async function log(args) {
|
|
|
319
331
|
for (const line of renderLog(rootId, entries)) console.log(line);
|
|
320
332
|
}
|
|
321
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
|
+
|
|
322
345
|
/** The project board every agent on the project shares: live claims, then decisions and findings. */
|
|
323
346
|
|
|
324
347
|
async function board(args) {
|
|
@@ -396,4 +419,12 @@ async function interrupt(args) {
|
|
|
396
419
|
console.log('Interrupted');
|
|
397
420
|
}
|
|
398
421
|
|
|
399
|
-
|
|
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`);
|