@anhlp/alp-core 0.0.1-beta.4 → 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/backup.js CHANGED
@@ -17,7 +17,7 @@ var RESULT_LEDGER = "state/assignment-results.json";
17
17
  var RESULT_MARKER = `${RESULT_LEDGER}.initialized`;
18
18
  var DESTINATIONS = "worktree-destinations.json";
19
19
  var QUARANTINED_DESTINATIONS = "state/worktree-destinations.quarantined.json";
20
- var 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"];
20
+ var 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"];
21
21
  var CLEARED_UNITS = ["state/live.json", "state/migration.json"];
22
22
  var HOME_UNITS = [
23
23
  ...STATE_UNITS,
@@ -430,8 +430,11 @@ async function prepareWorkspaceRestore(home, root, units, warnings) {
430
430
  for (const entry of value.results) {
431
431
  const owner = { assignmentId: entry.assignmentId, checkout: entry.checkout, ...entry.worktree === void 0 ? {} : { worktree: entry.worktree } };
432
432
  const previous = owners.get(owner.assignmentId);
433
- if (previous && JSON.stringify(previous) !== JSON.stringify(owner)) throw invalid("assignment result ownership conflicts with current data; reconcile it before restoring");
434
- owners.set(owner.assignmentId, owner);
433
+ const identity = (value2) => JSON.stringify({ assignmentId: value2.assignmentId, checkout: value2.checkout, worktree: value2.worktree });
434
+ if (previous && identity(previous) !== identity(owner)) throw invalid("assignment result ownership conflicts with current data; reconcile it before restoring");
435
+ const evidence = (value2) => !!value2 && typeof value2 === "object" && !Array.isArray(value2) && ["agent", "status", "finishedAt", "project", "brief", "summary"].every((key) => typeof value2[key] === "string") && Array.isArray(value2.requesters) && value2.requesters.every((id) => typeof id === "string") && (value2.taskId === void 0 || typeof value2.taskId === "string");
436
+ const result2 = evidence(entry.result) ? entry.result : previous?.result;
437
+ owners.set(owner.assignmentId, { ...owner, ...result2 === void 0 ? {} : { result: result2 } });
435
438
  }
436
439
  }
437
440
  const markers = [await incoming(RESULT_MARKER), await regular(home, RESULT_MARKER)];
@@ -0,0 +1,27 @@
1
+ /** Runs a bridge in this process, as `node -e` would. @param {string} kind */
2
+ export function runBridge(kind: string): void;
3
+ /**
4
+ * The command an agent CLI runs to start a bridge: `node -e <source>` under Node, the executable's
5
+ * `bridge <kind>` subcommand when packaged.
6
+ * @param {'acp' | 'antigravity'} kind
7
+ * @returns {{ command: string, args: string[] }}
8
+ */
9
+ export function bridgeCommand(kind: "acp" | "antigravity"): {
10
+ command: string;
11
+ args: string[];
12
+ };
13
+ /**
14
+ * Whether an MCP server entry is one of ALP's bridge launchers: the `-e` source, or the ALP
15
+ * executable's `bridge <kind>` (only when its command is named alp, so another server is kept).
16
+ * @param {'acp' | 'antigravity'} kind
17
+ * @param {unknown} args
18
+ * @param {unknown} [command]
19
+ */
20
+ export function isBridgeArgs(kind: "acp" | "antigravity", args: unknown, command?: unknown): boolean;
21
+ /**
22
+ * The stdio MCP bridges an agent CLI starts to reach alpd's tools (ACP agents and Antigravity).
23
+ * Under Node they run as `node -e <source>`; the ALP executable cannot evaluate `-e`, so it runs
24
+ * them as `alp bridge acp|antigravity`, which calls runBridge (t-1e02).
25
+ */
26
+ export const ACP_BRIDGE: "\nconst net = require('node:net');\nconst readline = require('node:readline');\nconst socket = net.connect(process.env.ALP_BRIDGE_SOCKET);\nconst waiting = new Map();\nlet sequence = 0;\nlet buffer = '';\nsocket.setEncoding('utf8');\nsocket.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');\nsocket.on('data', data => {\n buffer += data;\n for (let index; (index = buffer.indexOf('\\n')) >= 0;) {\n const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);\n try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}\n }\n});\nsocket.on('close', () => process.exit(0));\nsocket.on('error', () => process.exit(1));\nconst ask = message => new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });\nconst send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');\nreadline.createInterface({ input: process.stdin }).on('line', async line => {\n let message; try { message = JSON.parse(line); } catch { return; }\n if (message.id === undefined || message.id === null) return;\n try {\n 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' } } });\n if (message.method === 'ping') return send({ id: message.id, result: {} });\n if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }\n 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 }); }\n send({ id: message.id, error: { code: -32601, message: 'Method not found' } });\n } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }\n});\nprocess.stdin.on('end', () => process.exit(0));\n";
27
+ export const ANTIGRAVITY_BRIDGE: "// ALP Antigravity bridge v1\n\nconst net = require('node:net');\nconst readline = require('node:readline');\nconst socket = process.env.ALP_BRIDGE_SOCKET ? net.connect(process.env.ALP_BRIDGE_SOCKET) : null;\nconst waiting = new Map();\nlet sequence = 0;\nlet buffer = '';\nsocket?.setEncoding('utf8');\nsocket?.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');\nsocket?.on('data', data => {\n buffer += data;\n for (let index; (index = buffer.indexOf('\\n')) >= 0;) {\n const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);\n try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}\n }\n});\nsocket?.on('close', () => process.exit(0));\nsocket?.on('error', () => process.exit(1));\nconst 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'); });\nconst send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');\nreadline.createInterface({ input: process.stdin }).on('line', async line => {\n let message; try { message = JSON.parse(line); } catch { return; }\n if (message.id === undefined || message.id === null) return;\n try {\n 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' } } });\n if (message.method === 'ping') return send({ id: message.id, result: {} });\n if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }\n 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 }); }\n send({ id: message.id, error: { code: -32601, message: 'Method not found' } });\n } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }\n});\nprocess.stdin.on('end', () => process.exit(0));\n";
@@ -0,0 +1,97 @@
1
+ // packages/core/src/bridges.js
2
+ import { createRequire } from "node:module";
3
+ import { isExecutableName, isPackaged, isSelf, ROLE_ARGS } from "./packaged.js";
4
+ var ACP_BRIDGE = `
5
+ const net = require('node:net');
6
+ const readline = require('node:readline');
7
+ const socket = net.connect(process.env.ALP_BRIDGE_SOCKET);
8
+ const waiting = new Map();
9
+ let sequence = 0;
10
+ let buffer = '';
11
+ socket.setEncoding('utf8');
12
+ socket.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
13
+ socket.on('data', data => {
14
+ buffer += data;
15
+ for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
16
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
17
+ try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
18
+ }
19
+ });
20
+ socket.on('close', () => process.exit(0));
21
+ socket.on('error', () => process.exit(1));
22
+ const ask = message => new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
23
+ const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
24
+ readline.createInterface({ input: process.stdin }).on('line', async line => {
25
+ let message; try { message = JSON.parse(line); } catch { return; }
26
+ if (message.id === undefined || message.id === null) return;
27
+ try {
28
+ 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' } } });
29
+ if (message.method === 'ping') return send({ id: message.id, result: {} });
30
+ if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
31
+ 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 }); }
32
+ send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
33
+ } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
34
+ });
35
+ process.stdin.on('end', () => process.exit(0));
36
+ `;
37
+ var ANTIGRAVITY_BRIDGE = `// ALP Antigravity bridge v1
38
+
39
+ const net = require('node:net');
40
+ const readline = require('node:readline');
41
+ const socket = process.env.ALP_BRIDGE_SOCKET ? net.connect(process.env.ALP_BRIDGE_SOCKET) : null;
42
+ const waiting = new Map();
43
+ let sequence = 0;
44
+ let buffer = '';
45
+ socket?.setEncoding('utf8');
46
+ socket?.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
47
+ socket?.on('data', data => {
48
+ buffer += data;
49
+ for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
50
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
51
+ try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
52
+ }
53
+ });
54
+ socket?.on('close', () => process.exit(0));
55
+ socket?.on('error', () => process.exit(1));
56
+ 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'); });
57
+ const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
58
+ readline.createInterface({ input: process.stdin }).on('line', async line => {
59
+ let message; try { message = JSON.parse(line); } catch { return; }
60
+ if (message.id === undefined || message.id === null) return;
61
+ try {
62
+ 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' } } });
63
+ if (message.method === 'ping') return send({ id: message.id, result: {} });
64
+ if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
65
+ 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 }); }
66
+ send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
67
+ } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
68
+ });
69
+ process.stdin.on('end', () => process.exit(0));
70
+ `;
71
+ var BRIDGES = { acp: ACP_BRIDGE, antigravity: ANTIGRAVITY_BRIDGE };
72
+ function runBridge(kind) {
73
+ const source = Object.hasOwn(BRIDGES, kind) ? BRIDGES[
74
+ /** @type {'acp' | 'antigravity'} */
75
+ kind
76
+ ] : void 0;
77
+ if (!source) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
78
+ new Function("require", source)(createRequire(import.meta.url));
79
+ }
80
+ function bridgeCommand(kind) {
81
+ if (!Object.hasOwn(BRIDGES, kind)) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
82
+ if (isPackaged()) return { command: process.execPath, args: [...ROLE_ARGS[kind === "acp" ? "bridge-acp" : "bridge-antigravity"]] };
83
+ return { command: process.execPath, args: ["-e", BRIDGES[kind]] };
84
+ }
85
+ function isBridgeArgs(kind, args, command = void 0) {
86
+ if (!Array.isArray(args)) return false;
87
+ const marker = kind === "antigravity" ? "// ALP Antigravity bridge v1" : void 0;
88
+ if (marker && args.some((arg) => typeof arg === "string" && arg.startsWith(marker))) return true;
89
+ return typeof command === "string" && (isExecutableName(command) || isSelf(command)) && args.length === 2 && args[0] === "bridge" && args[1] === kind;
90
+ }
91
+ export {
92
+ ACP_BRIDGE,
93
+ ANTIGRAVITY_BRIDGE,
94
+ bridgeCommand,
95
+ isBridgeArgs,
96
+ runBridge
97
+ };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The project's ledger. A missing one is empty. On read (`strict` false) an unreadable or corrupt
3
+ * one detects nothing and never blocks the task graph; a writer (`strict`) refuses it instead,
4
+ * so it never overwrites entries it could not read.
5
+ */
6
+ export function readLedger(projectRoot: any, { strict }?: {
7
+ strict?: boolean | undefined;
8
+ }): Promise<any>;
9
+ /** 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. */
10
+ export function ledgerAdopt(projectRoot: any, task: any): Promise<void>;
11
+ /**
12
+ * Records that ALP cleared or removed a human gate. Written under the task lock once every check
13
+ * passed and before the task file: should the file write fail, the gate stays open in the file.
14
+ */
15
+ export function ledgerResolve(projectRoot: any, taskId: any, gate: any, { by, channel, removed }: {
16
+ by: any;
17
+ channel: any;
18
+ removed?: boolean | undefined;
19
+ }): Promise<void>;
20
+ /**
21
+ * Reopens, in the loaded tasks, every ledgered human gate the files show cleared or
22
+ * removed without a clear in the ledger, marking it `tampered`.
23
+ */
24
+ export function applyLedger(tasks: any, ledger: any): any;
25
+ /**
26
+ * Drops the entries that no longer guard anything (t-f438): the cleared ones, which applyLedger
27
+ * skips. An open entry stays even for a closed or missing task: status and presence are file
28
+ * state an agent can edit, so only a clear ALP recorded ends an entry. Called from compaction.
29
+ */
30
+ export function ledgerPrune(projectRoot: any): Promise<number>;
@@ -0,0 +1,99 @@
1
+ // packages/core/src/gate-ledger.js
2
+ import { realpathSync } from "node:fs";
3
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import path from "node:path";
6
+ import { alpHome } from "./library.js";
7
+ import { AlpError } from "./errors.js";
8
+ var key = (taskId, gate) => `${taskId}/${gate.id}@${gate.at}`;
9
+ function realRoot(projectRoot) {
10
+ try {
11
+ return realpathSync.native(path.resolve(projectRoot));
12
+ } catch {
13
+ return path.resolve(projectRoot);
14
+ }
15
+ }
16
+ function ledgerFile(projectRoot) {
17
+ const hash = createHash("sha256").update(realRoot(projectRoot)).digest("hex").slice(0, 24);
18
+ return path.join(alpHome(), "gates", `${hash}.json`);
19
+ }
20
+ async function readLedger(projectRoot, { strict = false } = {}) {
21
+ let data;
22
+ try {
23
+ data = JSON.parse(await readFile(ledgerFile(projectRoot), "utf8"));
24
+ } catch (error) {
25
+ if (error.code === "ENOENT") return { gates: {} };
26
+ if (strict) throw new AlpError("GATE_LEDGER_UNREADABLE", `The gate ledger ${ledgerFile(projectRoot)} is unreadable (${error.message}); fix or remove it`);
27
+ return { gates: {} };
28
+ }
29
+ if (data && typeof data === "object" && data.gates && typeof data.gates === "object") return data;
30
+ if (strict) throw new AlpError("GATE_LEDGER_UNREADABLE", `The gate ledger ${ledgerFile(projectRoot)} is not a ledger; fix or remove it`);
31
+ return { gates: {} };
32
+ }
33
+ async function writeLedger(projectRoot, ledger) {
34
+ const file = ledgerFile(projectRoot);
35
+ await mkdir(path.dirname(file), { recursive: true, mode: 448 });
36
+ const temporary = `${file}.${randomUUID().slice(0, 8)}.tmp`;
37
+ await writeFile(temporary, JSON.stringify(ledger, null, 2) + "\n", { mode: 384 });
38
+ await rename(temporary, file);
39
+ }
40
+ async function ledgerAdopt(projectRoot, task) {
41
+ const open = (task.gates ?? []).filter((gate) => gate.kind === "human" && !gate.resolved && typeof gate.at === "string" && /^g\d+$/.test(gate.id));
42
+ if (!open.length) return;
43
+ const ledger = await readLedger(projectRoot, { strict: true });
44
+ const missing = open.filter((gate) => !ledger.gates[key(task.id, gate)]);
45
+ if (!missing.length) return;
46
+ ledger.project = realRoot(projectRoot);
47
+ for (const gate of missing) ledger.gates[key(task.id, gate)] = { opened: gate.at };
48
+ await writeLedger(projectRoot, ledger);
49
+ }
50
+ async function ledgerResolve(projectRoot, taskId, gate, { by, channel, removed = false }) {
51
+ const ledger = await readLedger(projectRoot, { strict: true });
52
+ const entry = ledger.gates[key(taskId, gate)];
53
+ if (!entry) return;
54
+ entry.resolved = { at: (/* @__PURE__ */ new Date()).toISOString(), by, ...channel ? { channel } : {}, ...removed ? { removed: true } : {} };
55
+ await writeLedger(projectRoot, ledger);
56
+ }
57
+ function applyLedger(tasks, ledger) {
58
+ const byId = new Map(tasks.map((task) => [task.id, task]));
59
+ for (const [name, entry] of Object.entries(ledger.gates ?? {})) {
60
+ if (!entry || entry.resolved) continue;
61
+ const match = /^(.+)\/(g\d+)@(.+)$/.exec(name);
62
+ if (!match) continue;
63
+ const [, taskId, gateId, at] = match;
64
+ const task = byId.get(taskId);
65
+ if (!task) continue;
66
+ task.gates = Array.isArray(task.gates) ? task.gates : [];
67
+ const gate = task.gates.find((item) => item.id === gateId);
68
+ if (gate && gate.at === at && gate.kind === "human" && !gate.resolved) continue;
69
+ if (gate) {
70
+ const { resolved, ...open } = gate;
71
+ 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);
72
+ } else {
73
+ task.gates = [...task.gates, { id: gateId, kind: "human", note: "restored: this human gate was removed outside ALP", at, tampered: { removed: true } }];
74
+ }
75
+ if (task.step?.human && task.status === "closed") {
76
+ task.status = "open";
77
+ task.closed = null;
78
+ }
79
+ }
80
+ return tasks;
81
+ }
82
+ async function ledgerPrune(projectRoot) {
83
+ const ledger = await readLedger(projectRoot, { strict: true });
84
+ let dropped = 0;
85
+ for (const [name, entry] of Object.entries(ledger.gates)) {
86
+ if (entry && !entry.resolved) continue;
87
+ delete ledger.gates[name];
88
+ dropped += 1;
89
+ }
90
+ if (dropped) await writeLedger(projectRoot, ledger);
91
+ return dropped;
92
+ }
93
+ export {
94
+ applyLedger,
95
+ ledgerAdopt,
96
+ ledgerPrune,
97
+ ledgerResolve,
98
+ readLedger
99
+ };
package/dist/models.d.ts CHANGED
@@ -1,3 +1,34 @@
1
+ /**
2
+ * Live over static (t-e5ee): a runtime with a live list shows its live models first, in the provider's
3
+ * order, with the provider's label and description; a live model ALP knows keeps ALP's efforts (plus any
4
+ * new ones the provider adds) and ALP's default effort, a new one takes the provider's. Static rows the
5
+ * provider did not report stay as `fallback` (aliases, 1M variants). A runtime without a live list keeps
6
+ * its static rows. MODEL_POLICY applies last.
7
+ * @param {typeof MODELS} base
8
+ * @param {Partial<Record<string, Array<{ id: string, label?: string, description?: string, efforts?: string[], effort?: string }> | undefined>>} live
9
+ * @returns {Array<(typeof MODELS)[number] & { source?: 'live' | 'fallback' | 'static' }>}
10
+ */
11
+ export function mergeCatalog(base: typeof MODELS, live: Partial<Record<string, Array<{
12
+ id: string;
13
+ label?: string;
14
+ description?: string;
15
+ efforts?: string[];
16
+ effort?: string;
17
+ }> | undefined>>): Array<(typeof MODELS)[number] & {
18
+ source?: "live" | "fallback" | "static";
19
+ }>;
20
+ /**
21
+ * The catalog as alpd last saw it, for readers outside alpd (alp setup, the Paseo plugin): static rows
22
+ * when there is no cache or it is unreadable. @param {string | undefined} home
23
+ */
24
+ export function catalogModels(home: string | undefined): {
25
+ runtime: "codex" | "claude" | "antigravity";
26
+ id: string;
27
+ label: string;
28
+ description: string;
29
+ efforts: string[];
30
+ effort?: string;
31
+ }[];
1
32
  /**
2
33
  * @type {Array<{ runtime: 'codex' | 'claude' | 'antigravity', id: string, label: string, description: string, efforts: string[], effort?: string }>}
3
34
  */
@@ -9,3 +40,11 @@ export const MODELS: Array<{
9
40
  efforts: string[];
10
41
  effort?: string;
11
42
  }>;
43
+ /** ALP policy applied over whatever a provider reports. */
44
+ export const MODEL_POLICY: {
45
+ 'codex:gpt-6-astra': {
46
+ efforts: string[];
47
+ effort: string;
48
+ };
49
+ };
50
+ export function catalogCacheFile(home: string): string;
package/dist/models.js CHANGED
@@ -1,4 +1,6 @@
1
1
  // packages/core/src/models.js
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
2
4
  var codexFull = ["low", "medium", "high", "xhigh", "max", "ultra"];
3
5
  var codexStandard = ["low", "medium", "high", "xhigh", "max"];
4
6
  var claudeFull = ["low", "medium", "high", "xhigh", "max", "ultracode"];
@@ -39,6 +41,54 @@ var MODELS = [
39
41
  ["antigravity", "claude-opus-4-6-thinking", "Claude Opus 4.6 Thinking", "Opus 4.6 with thinking via Antigravity.", [], void 0],
40
42
  ["antigravity", "gpt-oss-120b-medium", "GPT-OSS 120B (Medium)", "Open weights model via Antigravity.", [], void 0]
41
43
  ].map(([runtime, id, label, description, efforts, effort]) => ({ runtime, id, label, description, efforts, ...effort ? { effort } : {} }));
44
+ var MODEL_POLICY = {
45
+ // ALP runs GPT-6 Astra at low effort only.
46
+ "codex:gpt-6-astra": { efforts: ["low"], effort: "low" }
47
+ };
48
+ var CATALOG_RUNTIMES = ["codex", "claude", "antigravity"];
49
+ function mergeCatalog(base, live) {
50
+ const out = [];
51
+ for (const runtime of CATALOG_RUNTIMES) {
52
+ const known = base.filter((entry) => entry.runtime === runtime);
53
+ const listed = live?.[runtime];
54
+ const reported = (Array.isArray(listed) ? listed : []).filter((model) => typeof model?.id === "string" && model.id.trim());
55
+ if (!reported.length) {
56
+ out.push(...known);
57
+ continue;
58
+ }
59
+ const seen = /* @__PURE__ */ new Set();
60
+ for (const model of reported) {
61
+ if (seen.has(model.id)) continue;
62
+ seen.add(model.id);
63
+ const prior = known.find((entry) => entry.id === model.id);
64
+ const priorEfforts = prior?.efforts ?? [];
65
+ const efforts = [...priorEfforts, ...(Array.isArray(model.efforts) ? model.efforts : []).filter((effort2) => typeof effort2 === "string" && !priorEfforts.includes(effort2))];
66
+ const effort = prior?.effort ?? (typeof model.effort === "string" && efforts.includes(model.effort) ? model.effort : void 0);
67
+ const text = (value) => typeof value === "string" && value ? value : void 0;
68
+ 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" });
69
+ }
70
+ for (const entry of known) if (!seen.has(entry.id)) out.push({ ...entry, source: "fallback" });
71
+ }
72
+ return out.map((entry) => {
73
+ const policy = MODEL_POLICY[`${entry.runtime}:${entry.id}`];
74
+ return policy ? { ...entry, ...policy } : entry;
75
+ });
76
+ }
77
+ var catalogCacheFile = (home) => path.join(home, "cache", "models.json");
78
+ function catalogModels(home) {
79
+ if (!home) return MODELS;
80
+ try {
81
+ const cached = JSON.parse(readFileSync(catalogCacheFile(home), "utf8"));
82
+ const providers = cached?.providers && typeof cached.providers === "object" ? cached.providers : {};
83
+ return mergeCatalog(MODELS, Object.fromEntries(Object.entries(providers).map(([runtime, state]) => [runtime, Array.isArray(state?.models) ? state.models : void 0])));
84
+ } catch {
85
+ return MODELS;
86
+ }
87
+ }
42
88
  export {
43
- MODELS
89
+ MODELS,
90
+ MODEL_POLICY,
91
+ catalogCacheFile,
92
+ catalogModels,
93
+ mergeCatalog
44
94
  };
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @typedef {{ path: string, sha256: string, size: number }} PackagedAsset
3
+ * @typedef {{ version: string, assets?: Record<string, PackagedAsset>, roles?: Record<string, () => Promise<unknown>>, modules?: Record<string, () => Promise<unknown>> }} PackagedRegistration
4
+ */
5
+ /** Called once by the executable's entry. @param {PackagedRegistration} registration */
6
+ export function registerPackaged(registration: PackagedRegistration): void;
7
+ /** The registration when this process is the ALP executable, else undefined. @returns {PackagedRegistration | undefined} */
8
+ export function packagedInfo(): PackagedRegistration | undefined;
9
+ /** Whether this process is the self-contained ALP executable. */
10
+ export function isPackaged(): boolean;
11
+ /**
12
+ * The command that starts ALP's `role` from this process: the executable's subcommand when packaged,
13
+ * else `script` under this Node, exactly as before.
14
+ * @param {keyof typeof ROLE_ARGS} role
15
+ * @param {{ script: string, args?: string[] }} options
16
+ * @returns {{ command: string, args: string[] }}
17
+ */
18
+ export function selfCommand(role: keyof typeof ROLE_ARGS, { script, args }: {
19
+ script: string;
20
+ args?: string[];
21
+ }): {
22
+ command: string;
23
+ args: string[];
24
+ };
25
+ /**
26
+ * The command that runs an `entry` found on disk (an install record, a service definition, a CLI
27
+ * on PATH): a script runs under `execPath`; an executable runs its own role subcommand.
28
+ * @param {string} entry
29
+ * @param {keyof typeof ROLE_ARGS} role
30
+ * @param {string[]} [args]
31
+ * @param {string} [execPath]
32
+ * @param {{ scriptOnly?: boolean }} [options] scriptOnly: `entry` is always run under execPath (third-party integrations)
33
+ * @returns {{ command: string, args: string[] }}
34
+ */
35
+ export function entryCommand(entry: string, role: keyof typeof ROLE_ARGS, args?: string[], execPath?: string, { scriptOnly }?: {
36
+ scriptOnly?: boolean;
37
+ }): {
38
+ command: string;
39
+ args: string[];
40
+ };
41
+ /**
42
+ * The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows)
43
+ * with this process's runtime. The executable runs it as Bun does when BUN_BE_BUN is set.
44
+ * @param {string} script
45
+ * @param {string[]} [args]
46
+ * @returns {{ command: string, args: string[], env?: Record<string, string> }}
47
+ */
48
+ export function scriptCommand(script: string, args?: string[]): {
49
+ command: string;
50
+ args: string[];
51
+ env?: Record<string, string>;
52
+ };
53
+ /** The ALP executable's path when this process is it, else undefined. */
54
+ export function executablePath(): string | undefined;
55
+ /** Where this process's own entry lives: the executable when packaged, else `script`. @param {string} script */
56
+ export function selfEntry(script: string): string;
57
+ /** The directory the executable's assets are extracted to. @param {string} version @param {NodeJS.ProcessEnv} [env] */
58
+ export function assetCacheDir(version: string, env?: NodeJS.ProcessEnv): string;
59
+ /**
60
+ * The directory holding the executable's embedded assets (templates, the web app, the native
61
+ * terminal helper), extracted once per version to `<ALP_HOME or ~/.alp>/cache/<version>/` and
62
+ * checked against the build's sha256 manifest. Undefined when not packaged: callers then use the
63
+ * files beside their scripts, as before.
64
+ * @param {{ env?: NodeJS.ProcessEnv, info?: PackagedRegistration }} [options]
65
+ * @returns {string | undefined}
66
+ */
67
+ export function assetDir({ env, info }?: {
68
+ env?: NodeJS.ProcessEnv;
69
+ info?: PackagedRegistration;
70
+ }): string | undefined;
71
+ /** Subcommands of the executable that run each ALP role (the npm CLI understands them too). */
72
+ export const ROLE_ARGS: Readonly<{
73
+ daemon: readonly string[];
74
+ web: readonly string[];
75
+ 'bridge-acp': readonly string[];
76
+ 'bridge-antigravity': readonly string[];
77
+ }>;
78
+ /**
79
+ * A string only ALP's executable carries: its generated entry embeds it, so discovery can tell ALP
80
+ * from an unrelated native program that happens to be called `alp` without running it.
81
+ */
82
+ export const EXECUTABLE_MARKER: "alp-standalone-executable:v1:2b6f0c1e";
83
+ export function isExecutableName(file: string): boolean;
84
+ export function isSelf(file: unknown): boolean;
85
+ export function samePath(a: string, b: string): boolean;
86
+ export function isScript(file: string): boolean;
87
+ export type PackagedAsset = {
88
+ path: string;
89
+ sha256: string;
90
+ size: number;
91
+ };
92
+ export type PackagedRegistration = {
93
+ version: string;
94
+ assets?: Record<string, PackagedAsset>;
95
+ roles?: Record<string, () => Promise<unknown>>;
96
+ modules?: Record<string, () => Promise<unknown>>;
97
+ };