@anhlp/alp-core 0.0.1-beta.4 → 0.0.1-beta.5

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/src/backup.js CHANGED
@@ -39,7 +39,7 @@ const RESULT_MARKER = `${RESULT_LEDGER}.initialized`;
39
39
  const DESTINATIONS = 'worktree-destinations.json';
40
40
  // Evidence only: the daemon never loads mapping authority from this path.
41
41
  const QUARANTINED_DESTINATIONS = 'state/worktree-destinations.quarantined.json';
42
- export const STATE_UNITS = [RESULT_LEDGER, RESULT_MARKER, 'state/schema.json', 'state/sessions', 'state/timeline', 'state/receipts', 'state/recall.json', 'state/pause.json', 'state/trust.json', 'state/web-workspaces.json'];
42
+ export const STATE_UNITS = [RESULT_LEDGER, RESULT_MARKER, 'state/assignment-archive', 'state/schema.json', 'state/sessions', 'state/timeline', 'state/receipts', 'state/recall.json', 'state/pause.json', 'state/trust.json', 'state/web-workspaces.json'];
43
43
  /**
44
44
  * Live work (running assignments alpd continues after a restart) and the journal of an
45
45
  * unfinished migration are never backed up: a restore of the state removes them, so restored
@@ -448,8 +448,14 @@ async function prepareWorkspaceRestore(home, root, units, warnings) {
448
448
  for (const entry of value.results) {
449
449
  const owner = { assignmentId: entry.assignmentId, checkout: entry.checkout, ...(entry.worktree === undefined ? {} : { worktree: entry.worktree }) };
450
450
  const previous = owners.get(owner.assignmentId);
451
- if (previous && JSON.stringify(previous) !== JSON.stringify(owner)) throw invalid('assignment result ownership conflicts with current data; reconcile it before restoring');
452
- owners.set(owner.assignmentId, owner);
451
+ const identity = value => JSON.stringify({ assignmentId: value.assignmentId, checkout: value.checkout, worktree: value.worktree });
452
+ if (previous && identity(previous) !== identity(owner)) throw invalid('assignment result ownership conflicts with current data; reconcile it before restoring');
453
+ // Its evidence comes along, the current data's first; how it was handled does not, so a restored result is resolved again.
454
+ const evidence = value => !!value && typeof value === 'object' && !Array.isArray(value) &&
455
+ ['agent', 'status', 'finishedAt', 'project', 'brief', 'summary'].every(key => typeof value[key] === 'string') &&
456
+ Array.isArray(value.requesters) && value.requesters.every(id => typeof id === 'string') && (value.taskId === undefined || typeof value.taskId === 'string');
457
+ const result = evidence(entry.result) ? entry.result : previous?.result;
458
+ owners.set(owner.assignmentId, { ...owner, ...(result === undefined ? {} : { result }) });
453
459
  }
454
460
  }
455
461
  const markers = [await incoming(RESULT_MARKER), await regular(home, RESULT_MARKER)];
package/src/bridges.js ADDED
@@ -0,0 +1,113 @@
1
+ import { createRequire } from 'node:module';
2
+ import { isExecutableName, isPackaged, isSelf, ROLE_ARGS } from './packaged.js';
3
+
4
+ /**
5
+ * The stdio MCP bridges an agent CLI starts to reach alpd's tools (ACP agents and Antigravity).
6
+ * Under Node they run as `node -e <source>`; the ALP executable cannot evaluate `-e`, so it runs
7
+ * them as `alp bridge acp|antigravity`, which calls runBridge (t-1e02).
8
+ */
9
+
10
+ export const ACP_BRIDGE = `
11
+ const net = require('node:net');
12
+ const readline = require('node:readline');
13
+ const socket = net.connect(process.env.ALP_BRIDGE_SOCKET);
14
+ const waiting = new Map();
15
+ let sequence = 0;
16
+ let buffer = '';
17
+ socket.setEncoding('utf8');
18
+ socket.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
19
+ socket.on('data', data => {
20
+ buffer += data;
21
+ for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
22
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
23
+ try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
24
+ }
25
+ });
26
+ socket.on('close', () => process.exit(0));
27
+ socket.on('error', () => process.exit(1));
28
+ const ask = message => new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
29
+ const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
30
+ readline.createInterface({ input: process.stdin }).on('line', async line => {
31
+ let message; try { message = JSON.parse(line); } catch { return; }
32
+ if (message.id === undefined || message.id === null) return;
33
+ try {
34
+ if (message.method === 'initialize') return send({ id: message.id, result: { protocolVersion: (message.params && message.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'alp', version: '1' } } });
35
+ if (message.method === 'ping') return send({ id: message.id, result: {} });
36
+ if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
37
+ if (message.method === 'tools/call') { const reply = await ask({ op: 'call', name: message.params.name, arguments: message.params.arguments || {} }); return send({ id: message.id, result: reply.result }); }
38
+ send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
39
+ } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
40
+ });
41
+ process.stdin.on('end', () => process.exit(0));
42
+ `;
43
+
44
+ export const ANTIGRAVITY_BRIDGE = `// ALP Antigravity bridge v1
45
+
46
+ const net = require('node:net');
47
+ const readline = require('node:readline');
48
+ const socket = process.env.ALP_BRIDGE_SOCKET ? net.connect(process.env.ALP_BRIDGE_SOCKET) : null;
49
+ const waiting = new Map();
50
+ let sequence = 0;
51
+ let buffer = '';
52
+ socket?.setEncoding('utf8');
53
+ socket?.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
54
+ socket?.on('data', data => {
55
+ buffer += data;
56
+ for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
57
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
58
+ try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
59
+ }
60
+ });
61
+ socket?.on('close', () => process.exit(0));
62
+ socket?.on('error', () => process.exit(1));
63
+ const ask = message => !socket ? Promise.resolve({ tools: [], result: { content: [{ type: 'text', text: 'No ALP session' }], isError: true } }) : new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
64
+ const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
65
+ readline.createInterface({ input: process.stdin }).on('line', async line => {
66
+ let message; try { message = JSON.parse(line); } catch { return; }
67
+ if (message.id === undefined || message.id === null) return;
68
+ try {
69
+ if (message.method === 'initialize') return send({ id: message.id, result: { protocolVersion: (message.params && message.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'alp', version: '1' } } });
70
+ if (message.method === 'ping') return send({ id: message.id, result: {} });
71
+ if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
72
+ if (message.method === 'tools/call') { const reply = await ask({ op: 'call', name: message.params.name, arguments: message.params.arguments || {} }); return send({ id: message.id, result: reply.result }); }
73
+ send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
74
+ } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
75
+ });
76
+ process.stdin.on('end', () => process.exit(0));
77
+ `;
78
+
79
+ const BRIDGES = { acp: ACP_BRIDGE, antigravity: ANTIGRAVITY_BRIDGE };
80
+
81
+ /** Runs a bridge in this process, as `node -e` would. @param {string} kind */
82
+ export function runBridge(kind) {
83
+ const source = Object.hasOwn(BRIDGES, kind) ? BRIDGES[/** @type {'acp' | 'antigravity'} */ (kind)] : undefined;
84
+ if (!source) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
85
+ // eslint-disable-next-line no-new-func
86
+ new Function('require', source)(createRequire(import.meta.url));
87
+ }
88
+
89
+ /**
90
+ * The command an agent CLI runs to start a bridge: `node -e <source>` under Node, the executable's
91
+ * `bridge <kind>` subcommand when packaged.
92
+ * @param {'acp' | 'antigravity'} kind
93
+ * @returns {{ command: string, args: string[] }}
94
+ */
95
+ export function bridgeCommand(kind) {
96
+ if (!Object.hasOwn(BRIDGES, kind)) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
97
+ if (isPackaged()) return { command: process.execPath, args: [...ROLE_ARGS[kind === 'acp' ? 'bridge-acp' : 'bridge-antigravity']] };
98
+ return { command: process.execPath, args: ['-e', BRIDGES[kind]] };
99
+ }
100
+
101
+ /**
102
+ * Whether an MCP server entry is one of ALP's bridge launchers: the `-e` source, or the ALP
103
+ * executable's `bridge <kind>` (only when its command is named alp, so another server is kept).
104
+ * @param {'acp' | 'antigravity'} kind
105
+ * @param {unknown} args
106
+ * @param {unknown} [command]
107
+ */
108
+ export function isBridgeArgs(kind, args, command = undefined) {
109
+ if (!Array.isArray(args)) return false;
110
+ const marker = kind === 'antigravity' ? '// ALP Antigravity bridge v1' : undefined;
111
+ if (marker && args.some(arg => typeof arg === 'string' && arg.startsWith(marker))) return true;
112
+ return typeof command === 'string' && (isExecutableName(command) || isSelf(command)) && args.length === 2 && args[0] === 'bridge' && args[1] === kind;
113
+ }
@@ -0,0 +1,125 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import path from 'node:path';
5
+ import { alpHome } from './library.js';
6
+ import { AlpError } from './errors.js';
7
+
8
+ /**
9
+ * A record of the human gates ALP opened and the clears ALP itself made, kept in
10
+ * $ALP_HOME, outside the project. The task files in .alp/tasks are plain files an
11
+ * agent can edit; when one shows a ledgered human gate cleared or gone without a
12
+ * clear here, loadTasks reopens it and marks it `tampered`.
13
+ *
14
+ * This detects an edit of the task file only. It is not a security boundary: an
15
+ * agent running as the same OS user can edit this file too (t-ca1f residual risk).
16
+ * Human gates from before the ledger enter it the next time ALP writes their task.
17
+ */
18
+
19
+ const key = (taskId, gate) => `${taskId}/${gate.id}@${gate.at}`;
20
+
21
+ /** One project's ledger, by its real path: /tmp and /private/tmp are the same project. */
22
+ function realRoot(projectRoot) {
23
+ try { return realpathSync.native(path.resolve(projectRoot)); } catch { return path.resolve(projectRoot); }
24
+ }
25
+
26
+ function ledgerFile(projectRoot) {
27
+ const hash = createHash('sha256').update(realRoot(projectRoot)).digest('hex').slice(0, 24);
28
+ return path.join(alpHome(), 'gates', `${hash}.json`);
29
+ }
30
+
31
+ /**
32
+ * The project's ledger. A missing one is empty. On read (`strict` false) an unreadable or corrupt
33
+ * one detects nothing and never blocks the task graph; a writer (`strict`) refuses it instead,
34
+ * so it never overwrites entries it could not read.
35
+ */
36
+ export async function readLedger(projectRoot, { strict = false } = {}) {
37
+ let data;
38
+ try {
39
+ data = JSON.parse(await readFile(ledgerFile(projectRoot), 'utf8'));
40
+ } catch (error) {
41
+ if (error.code === 'ENOENT') return { gates: {} };
42
+ if (strict) throw new AlpError('GATE_LEDGER_UNREADABLE', `The gate ledger ${ledgerFile(projectRoot)} is unreadable (${error.message}); fix or remove it`);
43
+ return { gates: {} };
44
+ }
45
+ if (data && typeof data === 'object' && data.gates && typeof data.gates === 'object') return data;
46
+ if (strict) throw new AlpError('GATE_LEDGER_UNREADABLE', `The gate ledger ${ledgerFile(projectRoot)} is not a ledger; fix or remove it`);
47
+ return { gates: {} };
48
+ }
49
+
50
+ async function writeLedger(projectRoot, ledger) {
51
+ const file = ledgerFile(projectRoot);
52
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
53
+ const temporary = `${file}.${randomUUID().slice(0, 8)}.tmp`;
54
+ await writeFile(temporary, JSON.stringify(ledger, null, 2) + '\n', { mode: 0o600 });
55
+ await rename(temporary, file);
56
+ }
57
+
58
+ /** Records the open human gates of a task ALP just wrote (addGate, a formula's human step, a beads import) that it does not hold yet. */
59
+ export async function ledgerAdopt(projectRoot, task) {
60
+ const open = (task.gates ?? []).filter(gate => gate.kind === 'human' && !gate.resolved && typeof gate.at === 'string' && /^g\d+$/.test(gate.id));
61
+ if (!open.length) return;
62
+ const ledger = await readLedger(projectRoot, { strict: true });
63
+ const missing = open.filter(gate => !ledger.gates[key(task.id, gate)]);
64
+ if (!missing.length) return;
65
+ ledger.project = realRoot(projectRoot);
66
+ for (const gate of missing) ledger.gates[key(task.id, gate)] = { opened: gate.at };
67
+ await writeLedger(projectRoot, ledger);
68
+ }
69
+
70
+ /**
71
+ * Records that ALP cleared or removed a human gate. Written under the task lock once every check
72
+ * passed and before the task file: should the file write fail, the gate stays open in the file.
73
+ */
74
+ export async function ledgerResolve(projectRoot, taskId, gate, { by, channel, removed = false }) {
75
+ const ledger = await readLedger(projectRoot, { strict: true });
76
+ const entry = ledger.gates[key(taskId, gate)];
77
+ if (!entry) return;
78
+ entry.resolved = { at: new Date().toISOString(), by, ...(channel ? { channel } : {}), ...(removed ? { removed: true } : {}) };
79
+ await writeLedger(projectRoot, ledger);
80
+ }
81
+
82
+ /**
83
+ * Reopens, in the loaded tasks, every ledgered human gate the files show cleared or
84
+ * removed without a clear in the ledger, marking it `tampered`.
85
+ */
86
+ export function applyLedger(tasks, ledger) {
87
+ const byId = new Map(tasks.map(task => [task.id, task]));
88
+ for (const [name, entry] of Object.entries(ledger.gates ?? {})) {
89
+ if (!entry || entry.resolved) continue;
90
+ const match = /^(.+)\/(g\d+)@(.+)$/.exec(name);
91
+ if (!match) continue;
92
+ const [, taskId, gateId, at] = match;
93
+ const task = byId.get(taskId);
94
+ if (!task) continue;
95
+ task.gates = Array.isArray(task.gates) ? task.gates : [];
96
+ const gate = task.gates.find(item => item.id === gateId);
97
+ if (gate && gate.at === at && gate.kind === 'human' && !gate.resolved) continue;
98
+ if (gate) {
99
+ const { resolved, ...open } = gate;
100
+ task.gates = task.gates.map(item => item === gate ? { ...open, kind: 'human', at, ...(open.note ? {} : { note: 'restored: this human gate was changed outside ALP' }), tampered: { at: resolved?.at ?? null, by: resolved?.by ?? null } } : item);
101
+ } else {
102
+ task.gates = [...task.gates, { id: gateId, kind: 'human', note: 'restored: this human gate was removed outside ALP', at, tampered: { removed: true } }];
103
+ }
104
+ // A step closed by the forged approval opens again.
105
+ if (task.step?.human && task.status === 'closed') { task.status = 'open'; task.closed = null; }
106
+ }
107
+ return tasks;
108
+ }
109
+
110
+ /**
111
+ * Drops the entries that no longer guard anything (t-f438): the cleared ones, which applyLedger
112
+ * skips. An open entry stays even for a closed or missing task: status and presence are file
113
+ * state an agent can edit, so only a clear ALP recorded ends an entry. Called from compaction.
114
+ */
115
+ export async function ledgerPrune(projectRoot) {
116
+ const ledger = await readLedger(projectRoot, { strict: true });
117
+ let dropped = 0;
118
+ for (const [name, entry] of Object.entries(ledger.gates)) {
119
+ if (entry && !entry.resolved) continue;
120
+ delete ledger.gates[name];
121
+ dropped += 1;
122
+ }
123
+ if (dropped) await writeLedger(projectRoot, ledger);
124
+ return dropped;
125
+ }
package/src/models.js CHANGED
@@ -1,4 +1,7 @@
1
- /** Models ALP offers, with the efforts each takes: the runtime's catalog and alp setup read this list. */
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /** Models ALP offers when no provider has answered yet (the live catalog, t-e5ee, merges provider lists over these), with the efforts each takes: the runtime's catalog and alp setup read this list. */
2
5
  const codexFull = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
3
6
  const codexStandard = ['low', 'medium', 'high', 'xhigh', 'max'];
4
7
  const claudeFull = ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'];
@@ -43,3 +46,62 @@ export const MODELS = [
43
46
  ['antigravity', 'claude-opus-4-6-thinking', 'Claude Opus 4.6 Thinking', 'Opus 4.6 with thinking via Antigravity.', [], undefined],
44
47
  ['antigravity', 'gpt-oss-120b-medium', 'GPT-OSS 120B (Medium)', 'Open weights model via Antigravity.', [], undefined],
45
48
  ].map(([runtime, id, label, description, efforts, effort]) => ({ runtime, id, label, description, efforts, ...(effort ? { effort } : {}) }));
49
+
50
+ /** ALP policy applied over whatever a provider reports. */
51
+ export const MODEL_POLICY = {
52
+ // ALP runs GPT-6 Astra at low effort only.
53
+ 'codex:gpt-6-astra': { efforts: ['low'], effort: 'low' },
54
+ };
55
+ const CATALOG_RUNTIMES = ['codex', 'claude', 'antigravity'];
56
+
57
+ /**
58
+ * Live over static (t-e5ee): a runtime with a live list shows its live models first, in the provider's
59
+ * order, with the provider's label and description; a live model ALP knows keeps ALP's efforts (plus any
60
+ * new ones the provider adds) and ALP's default effort, a new one takes the provider's. Static rows the
61
+ * provider did not report stay as `fallback` (aliases, 1M variants). A runtime without a live list keeps
62
+ * its static rows. MODEL_POLICY applies last.
63
+ * @param {typeof MODELS} base
64
+ * @param {Partial<Record<string, Array<{ id: string, label?: string, description?: string, efforts?: string[], effort?: string }> | undefined>>} live
65
+ * @returns {Array<(typeof MODELS)[number] & { source?: 'live' | 'fallback' | 'static' }>}
66
+ */
67
+ export function mergeCatalog(base, live) {
68
+ const out = [];
69
+ for (const runtime of CATALOG_RUNTIMES) {
70
+ const known = base.filter(entry => entry.runtime === runtime);
71
+ const listed = live?.[runtime];
72
+ const reported = (Array.isArray(listed) ? listed : []).filter(model => typeof model?.id === 'string' && model.id.trim());
73
+ if (!reported.length) { out.push(...known); continue; }
74
+ const seen = new Set();
75
+ for (const model of reported) {
76
+ if (seen.has(model.id)) continue;
77
+ seen.add(model.id);
78
+ const prior = known.find(entry => entry.id === model.id);
79
+ const priorEfforts = prior?.efforts ?? [];
80
+ const efforts = [...priorEfforts, ...(Array.isArray(model.efforts) ? model.efforts : []).filter(effort => typeof effort === 'string' && !priorEfforts.includes(effort))];
81
+ const effort = prior?.effort ?? (typeof model.effort === 'string' && efforts.includes(model.effort) ? model.effort : undefined);
82
+ const text = value => typeof value === 'string' && value ? value : undefined;
83
+ out.push({ runtime, id: model.id, label: text(model.label) ?? prior?.label ?? model.id, description: text(model.description) ?? prior?.description ?? '', efforts, ...(effort ? { effort } : {}), source: 'live' });
84
+ }
85
+ for (const entry of known) if (!seen.has(entry.id)) out.push({ ...entry, source: 'fallback' });
86
+ }
87
+ return out.map(entry => {
88
+ const policy = MODEL_POLICY[`${entry.runtime}:${entry.id}`];
89
+ return policy ? { ...entry, ...policy } : entry;
90
+ });
91
+ }
92
+
93
+ /** Where alpd caches the live catalog: ALP_HOME/cache/models.json. @param {string} home */
94
+ export const catalogCacheFile = home => path.join(home, 'cache', 'models.json');
95
+
96
+ /**
97
+ * The catalog as alpd last saw it, for readers outside alpd (alp setup, the Paseo plugin): static rows
98
+ * when there is no cache or it is unreadable. @param {string | undefined} home
99
+ */
100
+ export function catalogModels(home) {
101
+ if (!home) return MODELS;
102
+ try {
103
+ const cached = JSON.parse(readFileSync(catalogCacheFile(home), 'utf8'));
104
+ const providers = cached?.providers && typeof cached.providers === 'object' ? cached.providers : {};
105
+ return mergeCatalog(MODELS, Object.fromEntries(Object.entries(providers).map(([runtime, state]) => [runtime, Array.isArray(state?.models) ? state.models : undefined])));
106
+ } catch { return MODELS; }
107
+ }
@@ -0,0 +1,255 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ /**
7
+ * ALP runs either as npm scripts under Node (`node cli.js`, `node alpd.js`) or as one self-contained
8
+ * executable (`alp`, built with `bun build --compile`, t-1e02). In the executable, `process.execPath`
9
+ * is ALP itself: it cannot run a script path, and `-e code` is not evaluated. Every place that starts
10
+ * another ALP process asks this module for the command instead of spawning `process.execPath`.
11
+ *
12
+ * The executable's entry registers itself before importing anything else; the registration lives
13
+ * on globalThis because alpd.js and the CLI each inline their own copy of this module.
14
+ */
15
+
16
+ const KEY = Symbol.for('alp.packaged');
17
+
18
+ /** Subcommands of the executable that run each ALP role (the npm CLI understands them too). */
19
+ export const ROLE_ARGS = Object.freeze({
20
+ daemon: Object.freeze(['daemon', 'run']),
21
+ web: Object.freeze(['web', 'serve']),
22
+ 'bridge-acp': Object.freeze(['bridge', 'acp']),
23
+ 'bridge-antigravity': Object.freeze(['bridge', 'antigravity']),
24
+ });
25
+
26
+ /**
27
+ * @typedef {{ path: string, sha256: string, size: number }} PackagedAsset
28
+ * @typedef {{ version: string, assets?: Record<string, PackagedAsset>, roles?: Record<string, () => Promise<unknown>> }} PackagedRegistration
29
+ */
30
+
31
+ /** Called once by the executable's entry. @param {PackagedRegistration} registration */
32
+ export function registerPackaged(registration) {
33
+ if (!registration || typeof registration.version !== 'string') throw new TypeError('registerPackaged needs a version');
34
+ // assetDir rides along so dependency-free adapters (native-terminal.js) can reach the cache via globalThis alone.
35
+ Object.defineProperty(globalThis, KEY, { value: Object.freeze({ ...registration, assetDir: () => assetDir() }), configurable: true, enumerable: false, writable: false });
36
+ }
37
+
38
+ /** The registration when this process is the ALP executable, else undefined. @returns {PackagedRegistration | undefined} */
39
+ export function packagedInfo() { return /** @type {any} */ (globalThis)[KEY]; }
40
+
41
+ /** Whether this process is the self-contained ALP executable. */
42
+ export function isPackaged() { return packagedInfo() !== undefined; }
43
+
44
+ /**
45
+ * A string only ALP's executable carries: its generated entry embeds it, so discovery can tell ALP
46
+ * from an unrelated native program that happens to be called `alp` without running it.
47
+ */
48
+ export const EXECUTABLE_MARKER = 'alp-standalone-executable:v1:2b6f0c1e';
49
+
50
+ /** Whether `file` is named like the ALP executable (alp, alp.exe). @param {string} file */
51
+ export const isExecutableName = file => /^alp(\.exe)?$/i.test(file.split(/[\\/]/).pop() ?? '');
52
+
53
+ /** Whether `file` is this process's own ALP executable, whatever it is called (alp-darwin-arm64, a rename). @param {unknown} file */
54
+ export const isSelf = file => isPackaged() && typeof file === 'string' && samePath(file, process.execPath);
55
+
56
+ /** The canonical form of a path: symlinks resolved when it exists, case-folded where the filesystem usually is. @param {string} file */
57
+ const canonical = file => {
58
+ let resolved = path.resolve(file);
59
+ try { resolved = realpathSync.native(resolved); } catch {}
60
+ return process.platform === 'darwin' || process.platform === 'win32' ? resolved.toLowerCase() : resolved;
61
+ };
62
+
63
+ /** Whether two paths name the same file (a symlink such as ~/.alp/bin/alp, or a differently cased path on macOS/Windows). @param {string} a @param {string} b */
64
+ export const samePath = (a, b) => canonical(a) === canonical(b);
65
+
66
+ /** A file path that names a JavaScript entry rather than an executable. @param {string} file */
67
+ export const isScript = file => /\.[cm]?js$/i.test(file);
68
+
69
+ /** The role's argument prefix. @param {keyof typeof ROLE_ARGS} role */
70
+ function roleArgs(role) {
71
+ const args = ROLE_ARGS[role];
72
+ if (!args) throw new TypeError(`Unknown ALP role: ${role}`);
73
+ return [...args];
74
+ }
75
+
76
+ /**
77
+ * The command that starts ALP's `role` from this process: the executable's subcommand when packaged,
78
+ * else `script` under this Node, exactly as before.
79
+ * @param {keyof typeof ROLE_ARGS} role
80
+ * @param {{ script: string, args?: string[] }} options
81
+ * @returns {{ command: string, args: string[] }}
82
+ */
83
+ export function selfCommand(role, { script, args = [] }) {
84
+ if (isPackaged()) return { command: process.execPath, args: [...roleArgs(role), ...args] };
85
+ return { command: process.execPath, args: [script, ...args] };
86
+ }
87
+
88
+ /**
89
+ * The command that runs an `entry` found on disk (an install record, a service definition, a CLI
90
+ * on PATH): a script runs under `execPath`; an executable runs its own role subcommand.
91
+ * @param {string} entry
92
+ * @param {keyof typeof ROLE_ARGS} role
93
+ * @param {string[]} [args]
94
+ * @param {string} [execPath]
95
+ * @param {{ scriptOnly?: boolean }} [options] scriptOnly: `entry` is always run under execPath (third-party integrations)
96
+ * @returns {{ command: string, args: string[] }}
97
+ */
98
+ export function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
99
+ // Only a file named alp/alp.exe, or this very executable under any name, is native; anything else
100
+ // (alpd.js, alpd.ts, a launcher) is a script.
101
+ if (scriptOnly || isScript(entry) || !(isExecutableName(entry) || isSelf(entry))) {
102
+ // The executable cannot run a script itself; a script entry then needs a real Node.
103
+ if (isPackaged() && execPath === process.execPath) return { command: 'node', args: [entry, ...args] };
104
+ return { command: execPath, args: [entry, ...args] };
105
+ }
106
+ return { command: entry, args: [...roleArgs(role), ...args] };
107
+ }
108
+
109
+ /**
110
+ * The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows)
111
+ * with this process's runtime. The executable runs it as Bun does when BUN_BE_BUN is set.
112
+ * @param {string} script
113
+ * @param {string[]} [args]
114
+ * @returns {{ command: string, args: string[], env?: Record<string, string> }}
115
+ */
116
+ export function scriptCommand(script, args = []) {
117
+ if (isPackaged()) return { command: process.execPath, args: [script, ...args], env: { BUN_BE_BUN: '1' } };
118
+ return { command: process.execPath, args: [script, ...args] };
119
+ }
120
+
121
+ /** The ALP executable's path when this process is it, else undefined. */
122
+ export function executablePath() { return isPackaged() ? process.execPath : undefined; }
123
+
124
+ /** Where this process's own entry lives: the executable when packaged, else `script`. @param {string} script */
125
+ export function selfEntry(script) { return isPackaged() ? process.execPath : script; }
126
+
127
+ const sha256 = (/** @type {Buffer} */ bytes) => createHash('sha256').update(bytes).digest('hex');
128
+ const MARKER = '.alp-assets.json';
129
+
130
+ /** The directory the executable's assets are extracted to. @param {string} version @param {NodeJS.ProcessEnv} [env] */
131
+ export function assetCacheDir(version, env = process.env) {
132
+ if (!/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version)) throw new TypeError(`Invalid ALP version for the asset cache: ${JSON.stringify(version)}`);
133
+ const home = env.ALP_HOME ? path.resolve(env.ALP_HOME) : path.join(os.homedir(), '.alp');
134
+ return path.join(home, 'cache', version);
135
+ }
136
+
137
+ /** The manifest digest the marker records, so a changed build never reuses an older extraction. @param {Record<string, PackagedAsset>} assets */
138
+ const manifestDigest = assets => sha256(Buffer.from(JSON.stringify(Object.keys(assets).sort().map(name => [name, assets[name].sha256, assets[name].size]))));
139
+
140
+ /** Rejects names that would leave the cache directory. @param {string} name */
141
+ function assertAssetName(name) {
142
+ if (!name || path.isAbsolute(name) || name.split(/[\\/]/).some(part => part === '..' || part === '' || part === '.') || name === MARKER) throw new Error(`Invalid packaged asset name: ${JSON.stringify(name)}`);
143
+ }
144
+
145
+ /** A private directory we own, not a symlink. @param {string} directory */
146
+ function assertPrivate(directory) {
147
+ const info = lstatSync(directory);
148
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache is not a directory: ${directory}`);
149
+ if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)) throw new Error(`ALP asset cache must be private to the current user (0700): ${directory}`);
150
+ }
151
+
152
+ /** The cache parent (<ALP_HOME>/cache): a real directory of ours that nobody else may write into. @param {string} directory */
153
+ function assertParent(directory) {
154
+ const info = lstatSync(directory);
155
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache parent is not a directory: ${directory}`);
156
+ if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0)) throw new Error(`ALP asset cache parent must belong to the current user and not be group- or world-writable: ${directory}`);
157
+ }
158
+
159
+ /** Whether `directory` holds exactly this manifest's extraction: every file's size and sha256 match. */
160
+ function extracted(/** @type {string} */ directory, /** @type {string} */ digest, /** @type {Record<string, PackagedAsset>} */ assets) {
161
+ try {
162
+ if (JSON.parse(readFileSync(path.join(directory, MARKER), 'utf8')).digest !== digest) return false;
163
+ return Object.entries(assets).every(([name, asset]) => {
164
+ const file = path.join(directory, name);
165
+ const info = lstatSync(file);
166
+ return info.isFile() && info.size === asset.size && sha256(readFileSync(file)) === asset.sha256;
167
+ });
168
+ } catch { return false; }
169
+ }
170
+
171
+ const STAGING = /^(.+)\.tmp-(\d+)-(\d+)$/;
172
+ const STALE_MS = 60 * 60 * 1000;
173
+ const SWEEP_MIN_MS = 10 * 60 * 1000;
174
+
175
+ /** Removes staging directories another process left behind (it crashed, or was killed mid-extraction). @param {string} parent */
176
+ function sweepStaging(parent) {
177
+ let names;
178
+ try { names = readdirSync(parent); } catch { return; }
179
+ for (const name of names) {
180
+ const match = STAGING.exec(name);
181
+ if (!match) continue;
182
+ const pid = Number(match[2]);
183
+ if (pid === process.pid) continue;
184
+ const age = Date.now() - Number(match[3]);
185
+ // Another pid namespace (a bind-mounted ALP_HOME) may hold a live extractor this one cannot see,
186
+ // so even a dead-looking pid's staging is kept for a few minutes; past an hour nothing is running.
187
+ if (age < SWEEP_MIN_MS) continue;
188
+ let alive = false;
189
+ try { process.kill(pid, 0); alive = true; } catch (error) { alive = /** @type {any} */ (error)?.code === 'EPERM'; }
190
+ if (alive && age < STALE_MS) continue;
191
+ try { rmSync(path.join(parent, name), { recursive: true, force: true }); } catch {}
192
+ }
193
+ }
194
+
195
+ /**
196
+ * The directory holding the executable's embedded assets (templates, the web app, the native
197
+ * terminal helper), extracted once per version to `<ALP_HOME or ~/.alp>/cache/<version>/` and
198
+ * checked against the build's sha256 manifest. Undefined when not packaged: callers then use the
199
+ * files beside their scripts, as before.
200
+ * @param {{ env?: NodeJS.ProcessEnv, info?: PackagedRegistration }} [options]
201
+ * @returns {string | undefined}
202
+ */
203
+ export function assetDir({ env = process.env, info = packagedInfo() } = {}) {
204
+ if (!info) return undefined;
205
+ const assets = info.assets ?? {};
206
+ const directory = assetCacheDir(info.version, env);
207
+ const digest = manifestDigest(assets);
208
+ // Checked once per process and directory; later calls (every template read) reuse the answer.
209
+ const key = `${directory}\0${digest}`;
210
+ if (verified.has(key) && existsSync(path.join(directory, MARKER))) return directory;
211
+ const result = extract(directory, digest, assets, info.version);
212
+ verified.add(key);
213
+ return result;
214
+ }
215
+
216
+ const verified = new Set();
217
+
218
+ /** @param {string} directory @param {string} digest @param {Record<string, PackagedAsset>} assets @param {string} version */
219
+ function extract(directory, digest, assets, version) {
220
+ const parent = path.dirname(directory);
221
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
222
+ assertParent(parent);
223
+ sweepStaging(parent);
224
+ if (existsSync(directory)) {
225
+ assertPrivate(directory);
226
+ if (extracted(directory, digest, assets)) return directory;
227
+ }
228
+ const staging = `${directory}.tmp-${process.pid}-${Date.now()}`;
229
+ mkdirSync(staging, { mode: 0o700 });
230
+ try {
231
+ for (const [name, asset] of Object.entries(assets)) {
232
+ assertAssetName(name);
233
+ const bytes = readFileSync(asset.path);
234
+ if (bytes.length !== asset.size || sha256(bytes) !== asset.sha256) throw new Error(`Packaged asset ${name} does not match its manifest`);
235
+ const target = path.join(staging, name);
236
+ mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
237
+ writeFileSync(target, bytes, { mode: 0o600 });
238
+ if (/(^|\/)terminal-owner(\.exe)?$/.test(name)) chmodSync(target, 0o700);
239
+ }
240
+ writeFileSync(path.join(staging, MARKER), JSON.stringify({ version, digest }), { mode: 0o600 });
241
+ // Another ALP process may have finished the same extraction first; its copy is equivalent.
242
+ if (existsSync(directory)) {
243
+ assertPrivate(directory);
244
+ if (extracted(directory, digest, assets)) { rmSync(staging, { recursive: true, force: true }); return directory; }
245
+ rmSync(directory, { recursive: true, force: true });
246
+ }
247
+ renameSync(staging, directory);
248
+ if (!extracted(directory, digest, assets)) throw new Error(`ALP asset cache ${directory} is incomplete after extraction`);
249
+ } catch (error) {
250
+ rmSync(staging, { recursive: true, force: true });
251
+ if (existsSync(directory) && extracted(directory, digest, assets)) return directory;
252
+ throw error;
253
+ }
254
+ return directory;
255
+ }
package/src/providers.js CHANGED
@@ -3,6 +3,7 @@ import { readdir, readFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { AlpError } from './errors.js';
5
5
  import { settingsKeys, unknownMessage } from './validation.js';
6
+ import { isPackaged, scriptCommand } from './packaged.js';
6
7
 
7
8
  /**
8
9
  * ACP providers (ALPD §46): agents that speak the Agent Client Protocol, such as Gemini
@@ -100,7 +101,8 @@ export function acpModel(model) {
100
101
  * native executable it calls, or the Node script, under this Node. A bare name with an .exe or
101
102
  * .com on PATH, any other command, and every command elsewhere are returned as they are.
102
103
  * @param {string} command @param {string[]} [args] @param {Record<string, string | undefined>} [env]
103
- * @returns {{ command: string, args: string[] }}
104
+ * In the ALP executable a Node script runs with the executable as its Bun runtime, via `env` to add.
105
+ * @returns {{ command: string, args: string[], env?: Record<string, string> }}
104
106
  */
105
107
  export function launchCommand(command, args = [], env = process.env) {
106
108
  if (process.platform !== 'win32' || /[\\/]/.test(command) || path.extname(command)) return { command, args };
@@ -113,7 +115,7 @@ export function launchCommand(command, args = [], env = process.env) {
113
115
  // for a Node script. Anything else (a hand-written batch file) stays refused by spawn, as before.
114
116
  const text = readFileSync(shim, 'utf8');
115
117
  const script = /"%_prog%"((?:\s+[^\s"]+)*)\s+"%~?dp0%\\?([^"]+)"\s+%\*/i.exec(text);
116
- if (script) return { command: process.execPath, args: [...script[1].split(/\s+/).filter(Boolean), path.join(directory, script[2]), ...args] };
118
+ if (script) { const flags = script[1].split(/\s+/).filter(Boolean); const run = scriptCommand(path.join(directory, script[2]), args); return { command: run.command, args: isPackaged() ? run.args : [...flags, ...run.args], ...(run.env ? { env: run.env } : {}) }; }
117
119
  const native = /^\s*"%~?dp0%\\?([^"]+\.(?:exe|com))"\s+%\*/im.exec(text);
118
120
  if (native) return { command: path.join(directory, native[1]), args };
119
121
  break;
package/src/task-rows.js CHANGED
@@ -20,7 +20,7 @@ export async function taskRows(projectRoot) {
20
20
  }
21
21
  const rows = tasks.map(task => {
22
22
  const row = summarize(task, tasks);
23
- const approvals = task.status === 'closed' ? [] : task.gates.filter(gate => gate.kind === 'human' && !gate.resolved).map(gate => ({ gate: gate.id, note: gate.note ?? '' }));
23
+ const approvals = task.status === 'closed' ? [] : task.gates.filter(gate => gate.kind === 'human' && !gate.resolved).map(gate => ({ gate: gate.id, note: gate.note ?? '', ...(gate.options?.length ? { options: gate.options } : {}), ...(gate.rejected ? { rejected: { at: gate.rejected.at, ...(gate.rejected.reason ? { reason: gate.rejected.reason } : {}) } } : {}) }));
24
24
  const waits = task.status === 'closed' ? [] : gatesOf(task, tasks);
25
25
  return {
26
26
  id: task.id, title: task.title, type: task.type, priority: task.priority, status: task.status, rev: task.rev,