@anhlp/alp-core 0.0.1-beta.3 → 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/dist/backup.js +106 -4
- package/dist/bridges.d.ts +27 -0
- package/dist/bridges.js +97 -0
- package/dist/gate-ledger.d.ts +30 -0
- package/dist/gate-ledger.js +99 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/migrations.js +1 -1
- package/dist/models.d.ts +39 -0
- package/dist/models.js +51 -1
- package/dist/packaged.d.ts +96 -0
- package/dist/packaged.js +198 -0
- package/dist/providers.d.ts +3 -1
- package/dist/providers.js +6 -1
- package/dist/task-rows.d.ts +5 -0
- package/dist/task-rows.js +1 -1
- package/dist/tasks.d.ts +22 -4
- package/dist/tasks.js +97 -9
- package/dist/template-path.d.ts +2 -2
- package/dist/template-path.js +5 -0
- package/dist/types.d.ts +1 -0
- package/dist/user-worktree.d.ts +29 -0
- package/dist/user-worktree.js +242 -0
- package/dist/validation.js +19 -4
- package/package.json +18 -2
- package/src/backup.js +106 -5
- package/src/bridges.js +113 -0
- package/src/gate-ledger.js +125 -0
- package/src/index.js +1 -0
- package/src/migrations.js +1 -1
- package/src/models.js +63 -1
- package/src/packaged.js +255 -0
- package/src/providers.js +4 -2
- package/src/task-rows.js +1 -1
- package/src/tasks.d.ts +22 -4
- package/src/tasks.js +126 -10
- package/src/template-path.js +6 -1
- package/src/types.d.ts +1 -0
- package/src/user-worktree.js +259 -0
- package/src/validation.js +22 -4
- package/templates/agents/main/AGENT.md +4 -0
- package/templates/role-skills.json +1 -1
- package/templates/skills/compact/SKILL.md +34 -0
- package/templates/skills/curate/SKILL.md +35 -0
package/dist/backup.js
CHANGED
|
@@ -13,10 +13,15 @@ import { STATE_SCHEMA, assertStateSupported, readStateSchema } from "./state-sch
|
|
|
13
13
|
import { withTaskLock } from "./tasks.js";
|
|
14
14
|
var BACKUP_FORMAT = 1;
|
|
15
15
|
var BACKUP_EXTENSION = ".alpbackup";
|
|
16
|
-
var
|
|
16
|
+
var RESULT_LEDGER = "state/assignment-results.json";
|
|
17
|
+
var RESULT_MARKER = `${RESULT_LEDGER}.initialized`;
|
|
18
|
+
var DESTINATIONS = "worktree-destinations.json";
|
|
19
|
+
var QUARANTINED_DESTINATIONS = "state/worktree-destinations.quarantined.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"];
|
|
17
21
|
var CLEARED_UNITS = ["state/live.json", "state/migration.json"];
|
|
18
22
|
var HOME_UNITS = [
|
|
19
23
|
...STATE_UNITS,
|
|
24
|
+
DESTINATIONS,
|
|
20
25
|
"settings.json",
|
|
21
26
|
"library.json",
|
|
22
27
|
"role-skills.json",
|
|
@@ -378,6 +383,101 @@ async function holdTaskLocks(roots, work) {
|
|
|
378
383
|
clearInterval(touch);
|
|
379
384
|
}
|
|
380
385
|
}
|
|
386
|
+
async function prepareWorkspaceRestore(home, root, units, warnings) {
|
|
387
|
+
const relevant = [RESULT_LEDGER, RESULT_MARKER, DESTINATIONS, "state/sessions", "state/web-workspaces.json"];
|
|
388
|
+
const restorable = units.filter((unit) => unit.path !== QUARANTINED_DESTINATIONS);
|
|
389
|
+
if (!units.some((unit) => relevant.includes(unit.path))) return restorable;
|
|
390
|
+
for (const base of [home, root]) {
|
|
391
|
+
const info = await lstat(path.join(base, "state")).catch((error) => {
|
|
392
|
+
if (error.code === "ENOENT") return void 0;
|
|
393
|
+
throw error;
|
|
394
|
+
});
|
|
395
|
+
if (info && !info.isDirectory()) throw invalid("workspace state must be a real directory");
|
|
396
|
+
}
|
|
397
|
+
const result = restorable.filter((unit) => ![RESULT_LEDGER, RESULT_MARKER, DESTINATIONS, "state/web-workspaces.json"].includes(unit.path));
|
|
398
|
+
async function regular(base, unit, declared) {
|
|
399
|
+
if (declared && declared.kind === "absent") return void 0;
|
|
400
|
+
const file = path.join(base, unit);
|
|
401
|
+
const info = await lstat(file).catch((error) => {
|
|
402
|
+
if (error.code === "ENOENT") return void 0;
|
|
403
|
+
throw error;
|
|
404
|
+
});
|
|
405
|
+
if (!info) {
|
|
406
|
+
if (declared) throw invalid(`${unit} is declared but missing from the backup`);
|
|
407
|
+
return void 0;
|
|
408
|
+
}
|
|
409
|
+
if (!info.isFile()) throw invalid(`${unit} must be a regular file for a workspace restore`);
|
|
410
|
+
return readFile(file, "utf8");
|
|
411
|
+
}
|
|
412
|
+
const incoming = async (unit) => {
|
|
413
|
+
const declared = units.find((entry) => entry.path === unit);
|
|
414
|
+
return declared ? regular(root, unit, declared) : void 0;
|
|
415
|
+
};
|
|
416
|
+
const owners = /* @__PURE__ */ new Map();
|
|
417
|
+
let hasLedger = false;
|
|
418
|
+
for (const text of [await incoming(RESULT_LEDGER), await regular(home, RESULT_LEDGER)]) {
|
|
419
|
+
if (text === void 0) continue;
|
|
420
|
+
let value;
|
|
421
|
+
try {
|
|
422
|
+
value = JSON.parse(text);
|
|
423
|
+
} catch {
|
|
424
|
+
throw invalid("assignment result ledger is not readable JSON; repair it before restoring");
|
|
425
|
+
}
|
|
426
|
+
const absolute = (value2) => typeof value2 === "string" && path.isAbsolute(value2);
|
|
427
|
+
if (value?.version !== 1 || !Array.isArray(value.workspaces) || !value.workspaces.every(absolute) || !Array.isArray(value.results) || !value.results.every((entry) => entry && typeof entry.assignmentId === "string" && absolute(entry.checkout) && (entry.worktree === void 0 || absolute(entry.worktree))))
|
|
428
|
+
throw invalid("assignment result ledger has an unsupported or invalid shape");
|
|
429
|
+
hasLedger = true;
|
|
430
|
+
for (const entry of value.results) {
|
|
431
|
+
const owner = { assignmentId: entry.assignmentId, checkout: entry.checkout, ...entry.worktree === void 0 ? {} : { worktree: entry.worktree } };
|
|
432
|
+
const previous = owners.get(owner.assignmentId);
|
|
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 } });
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const markers = [await incoming(RESULT_MARKER), await regular(home, RESULT_MARKER)];
|
|
441
|
+
if (markers.some((text) => text !== void 0 && text !== "1\n")) throw invalid("assignment result initialized marker is invalid");
|
|
442
|
+
await mkdir(path.join(root, "state"), { recursive: true, mode: 448 });
|
|
443
|
+
if (hasLedger) await writeAtomic(path.join(root, RESULT_LEDGER), JSON.stringify({ version: 1, workspaces: [], results: [...owners.values()] }) + "\n");
|
|
444
|
+
result.push({ path: RESULT_LEDGER, kind: hasLedger ? "file" : "absent" });
|
|
445
|
+
const initialized = markers.some((text) => text !== void 0);
|
|
446
|
+
if (initialized) await writeAtomic(path.join(root, RESULT_MARKER), "1\n");
|
|
447
|
+
result.push({ path: RESULT_MARKER, kind: initialized ? "file" : "absent" });
|
|
448
|
+
const mappings = await incoming(DESTINATIONS);
|
|
449
|
+
if (mappings !== void 0) {
|
|
450
|
+
await writeAtomic(path.join(root, QUARANTINED_DESTINATIONS), mappings);
|
|
451
|
+
result.push({ path: QUARANTINED_DESTINATIONS, kind: "file" });
|
|
452
|
+
}
|
|
453
|
+
result.push({ path: DESTINATIONS, kind: "absent" });
|
|
454
|
+
const registryUnit = "state/web-workspaces.json";
|
|
455
|
+
const registryDeclaration = units.find((unit) => unit.path === registryUnit);
|
|
456
|
+
const registryText = registryDeclaration ? await incoming(registryUnit) : await regular(home, registryUnit);
|
|
457
|
+
if (registryText !== void 0) {
|
|
458
|
+
let registry;
|
|
459
|
+
try {
|
|
460
|
+
registry = JSON.parse(registryText);
|
|
461
|
+
} catch {
|
|
462
|
+
throw invalid("workspace registry is not readable JSON; repair it before restoring");
|
|
463
|
+
}
|
|
464
|
+
const epoch = `restore-${randomBytes(16).toString("hex")}`;
|
|
465
|
+
let revoked = false;
|
|
466
|
+
const revoke = (value) => {
|
|
467
|
+
if (!value || typeof value !== "object") return;
|
|
468
|
+
if (Object.hasOwn(value, "grantEpoch")) {
|
|
469
|
+
value.grantEpoch = epoch;
|
|
470
|
+
revoked = true;
|
|
471
|
+
}
|
|
472
|
+
for (const child of Object.values(value)) revoke(child);
|
|
473
|
+
};
|
|
474
|
+
revoke(registry);
|
|
475
|
+
await writeAtomic(path.join(root, registryUnit), revoked ? JSON.stringify(registry) + "\n" : registryText);
|
|
476
|
+
result.push({ path: registryUnit, kind: "file" });
|
|
477
|
+
} else if (registryDeclaration) result.push({ path: registryUnit, kind: "absent" });
|
|
478
|
+
if (hasLedger || initialized || mappings !== void 0 || await exists(path.join(home, DESTINATIONS))) warnings.push("Workspace restore retains assignment owners but clears checkout birth certification; old targets require an audited migration. Worktree destination mappings are inactive and require explicit host approval; archived mapping evidence is in state/worktree-destinations.quarantined.json. Historical checkout grants remain revoked after reapproval.");
|
|
479
|
+
return result;
|
|
480
|
+
}
|
|
381
481
|
async function restoreBackup({ home, file, projects = true, safety = true, clearLive = true, replaceNewer = false, by = "alp", beforeSwap }) {
|
|
382
482
|
const interrupted = await recoverInterruptedRestore(home);
|
|
383
483
|
try {
|
|
@@ -392,6 +492,7 @@ async function restoreBackup({ home, file, projects = true, safety = true, clear
|
|
|
392
492
|
const warnings = [];
|
|
393
493
|
const areaBase = (area) => area === "home" ? home : header.projects[Number(area.slice(8))].root;
|
|
394
494
|
const directories = [];
|
|
495
|
+
let homeUnits;
|
|
395
496
|
const journal = { version: 1, id, file: path.resolve(file), by, startedAt: (/* @__PURE__ */ new Date()).toISOString(), phase: "staging", units: [], staging: [], created: [], locks: [] };
|
|
396
497
|
const record = () => writeAtomic(journalFile(home), JSON.stringify(journal) + "\n");
|
|
397
498
|
const abandon = async () => {
|
|
@@ -443,6 +544,7 @@ async function restoreBackup({ home, file, projects = true, safety = true, clear
|
|
|
443
544
|
};
|
|
444
545
|
}
|
|
445
546
|
});
|
|
547
|
+
homeUnits = await prepareWorkspaceRestore(home, staging.get("home"), header.units, warnings);
|
|
446
548
|
for (const [directory, mode] of directories.reverse()) if (Number.isSafeInteger(mode)) await chmod(directory, mode & 511 | 448).catch(() => {
|
|
447
549
|
});
|
|
448
550
|
} catch (error) {
|
|
@@ -463,8 +565,8 @@ async function restoreBackup({ home, file, projects = true, safety = true, clear
|
|
|
463
565
|
const plan = [];
|
|
464
566
|
for (const [area, root] of staging) {
|
|
465
567
|
const base = areaBase(area);
|
|
466
|
-
const units = area === "home" ?
|
|
467
|
-
const known = area === "home" ? HOME_UNITS : PROJECT_UNITS;
|
|
568
|
+
const units = area === "home" ? homeUnits : header.projects[Number(area.slice(8))].units;
|
|
569
|
+
const known = area === "home" ? [...HOME_UNITS, QUARANTINED_DESTINATIONS] : PROJECT_UNITS;
|
|
468
570
|
for (const unit of units) {
|
|
469
571
|
if (!known.includes(unit.path)) {
|
|
470
572
|
warnings.push(`${unit.path} is not a unit this ALP restores; left as it is`);
|
|
@@ -489,7 +591,7 @@ async function restoreBackup({ home, file, projects = true, safety = true, clear
|
|
|
489
591
|
let safetyFile;
|
|
490
592
|
if (safety) {
|
|
491
593
|
try {
|
|
492
|
-
safetyFile = await automaticBackup(home, "pre-restore", { units: header.units.map((unit) => unit.path).filter((unit) => HOME_UNITS.includes(unit)), projects: roots, by });
|
|
594
|
+
safetyFile = await automaticBackup(home, "pre-restore", { units: [.../* @__PURE__ */ new Set([...header.units.map((unit) => unit.path), ...homeUnits.map((unit) => unit.path)])].filter((unit) => HOME_UNITS.includes(unit) || unit === QUARANTINED_DESTINATIONS), projects: roots, by });
|
|
493
595
|
} catch (error) {
|
|
494
596
|
await abandon();
|
|
495
597
|
throw new AlpError("RESTORE_SAFETY_BACKUP_FAILED", `could not save the current data before restoring (${error?.message ?? error}); nothing was changed`, { cause: error });
|
|
@@ -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";
|
package/dist/bridges.js
ADDED
|
@@ -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/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -29,6 +29,7 @@ import * as user_settings from "./user-settings.js";
|
|
|
29
29
|
import * as validation from "./validation.js";
|
|
30
30
|
import * as verify from "./verify.js";
|
|
31
31
|
import * as workflow from "./workflow.js";
|
|
32
|
+
import * as user_worktree from "./user-worktree.js";
|
|
32
33
|
export {
|
|
33
34
|
adapter,
|
|
34
35
|
atomic,
|
|
@@ -57,6 +58,7 @@ export {
|
|
|
57
58
|
trust,
|
|
58
59
|
upgrade,
|
|
59
60
|
user_settings,
|
|
61
|
+
user_worktree,
|
|
60
62
|
validation,
|
|
61
63
|
verify,
|
|
62
64
|
workflow
|
package/dist/migrations.js
CHANGED
|
@@ -78,7 +78,7 @@ async function migrateState(home, { by = "alp", migrations = MIGRATIONS, target
|
|
|
78
78
|
throw new AlpError("STATE_MIGRATION_ROLLBACK_FAILED", `state migration ${step.name} failed (${error?.message ?? error}) and putting the state back from ${backup} failed too (${rollback?.message ?? rollback}); the next start tries the migration again. See docs/alp/data-recovery.md`, { cause: error });
|
|
79
79
|
}
|
|
80
80
|
await rm(migrationFile(home), { force: true });
|
|
81
|
-
throw new AlpError("STATE_MIGRATION_FAILED", `state migration ${step.name} (schema ${step.from} \u2192 ${step.to}) failed: ${error?.message ?? error};
|
|
81
|
+
throw new AlpError("STATE_MIGRATION_FAILED", `state migration ${step.name} (schema ${step.from} \u2192 ${step.to}) failed: ${error?.message ?? error}; data was restored from ${backup} with workspace authority checks. See docs/alp/data-recovery.md`, { cause: error });
|
|
82
82
|
}
|
|
83
83
|
await writeStateSchema(home, step.to, by);
|
|
84
84
|
await rm(migrationFile(home), { force: true });
|
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
|
};
|