@anhlp/alp-runtime 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.
Files changed (67) hide show
  1. package/dist/acp-transport.js +5 -36
  2. package/dist/antigravity-transport.d.ts +17 -0
  3. package/dist/antigravity-transport.js +82 -58
  4. package/dist/assignment-results.d.ts +34 -0
  5. package/dist/assignment-results.js +94 -2
  6. package/dist/board-domain.js +2 -2
  7. package/dist/board.d.ts +6 -0
  8. package/dist/board.js +7 -0
  9. package/dist/catalog.d.ts +13 -0
  10. package/dist/catalog.js +9 -1
  11. package/dist/claude-transport.d.ts +7 -0
  12. package/dist/claude-transport.js +65 -6
  13. package/dist/compact.d.ts +29 -0
  14. package/dist/compact.js +49 -0
  15. package/dist/configure.d.ts +1 -1
  16. package/dist/configure.js +2 -2
  17. package/dist/contracts.d.ts +25 -1
  18. package/dist/index.d.ts +9 -2
  19. package/dist/index.js +30 -2
  20. package/dist/input-limits.d.ts +25 -0
  21. package/dist/input-limits.js +48 -0
  22. package/dist/language.d.ts +8 -0
  23. package/dist/language.js +20 -0
  24. package/dist/mcp-tools.d.ts +8 -0
  25. package/dist/mcp-tools.js +26 -0
  26. package/dist/model-catalog.d.ts +76 -0
  27. package/dist/model-catalog.js +193 -0
  28. package/dist/model-probes.d.ts +7 -0
  29. package/dist/model-probes.js +69 -0
  30. package/dist/providers.js +2 -0
  31. package/dist/resolve.d.ts +1 -0
  32. package/dist/resolve.js +3 -1
  33. package/dist/runtime.d.ts +3 -1
  34. package/dist/runtime.js +605 -45
  35. package/dist/session-config.d.ts +174 -0
  36. package/dist/session-config.js +9 -9
  37. package/dist/session-state.d.ts +23 -1
  38. package/dist/tools.d.ts +82 -0
  39. package/dist/tools.js +53 -5
  40. package/dist/transport.js +3 -1
  41. package/dist/workspace.d.ts +11 -4
  42. package/dist/workspace.js +29 -11
  43. package/package.json +3 -3
  44. package/src/acp-transport.ts +7 -37
  45. package/src/antigravity-transport.ts +95 -53
  46. package/src/assignment-results.ts +85 -3
  47. package/src/board-domain.ts +2 -2
  48. package/src/board.ts +7 -0
  49. package/src/catalog.ts +10 -1
  50. package/src/claude-transport.ts +71 -6
  51. package/src/compact.ts +62 -0
  52. package/src/configure.ts +3 -3
  53. package/src/contracts.ts +22 -1
  54. package/src/index.ts +9 -2
  55. package/src/input-limits.ts +65 -0
  56. package/src/language.ts +18 -0
  57. package/src/mcp-tools.ts +33 -0
  58. package/src/model-catalog.ts +166 -0
  59. package/src/model-probes.ts +58 -0
  60. package/src/providers.ts +3 -0
  61. package/src/resolve.ts +4 -2
  62. package/src/runtime.ts +650 -46
  63. package/src/session-config.ts +8 -8
  64. package/src/session-state.ts +15 -1
  65. package/src/tools.ts +53 -5
  66. package/src/transport.ts +3 -1
  67. package/src/workspace.ts +42 -15
@@ -9,40 +9,8 @@ import path from "node:path";
9
9
  import { createInterface } from "node:readline";
10
10
  import { commandDecision, unwrapShell } from "@anhlp/alp-core/permissions";
11
11
  import { launchCommand } from "@anhlp/alp-core/providers";
12
+ import { bridgeCommand } from "@anhlp/alp-core/bridges";
12
13
  import { acpText, acpToolDetail } from "./tool-detail.js";
13
- var BRIDGE = `
14
- const net = require('node:net');
15
- const readline = require('node:readline');
16
- const socket = net.connect(process.env.ALP_BRIDGE_SOCKET);
17
- const waiting = new Map();
18
- let sequence = 0;
19
- let buffer = '';
20
- socket.setEncoding('utf8');
21
- socket.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
22
- socket.on('data', data => {
23
- buffer += data;
24
- for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
25
- const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
26
- try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
27
- }
28
- });
29
- socket.on('close', () => process.exit(0));
30
- socket.on('error', () => process.exit(1));
31
- const ask = message => new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
32
- const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
33
- readline.createInterface({ input: process.stdin }).on('line', async line => {
34
- let message; try { message = JSON.parse(line); } catch { return; }
35
- if (message.id === undefined || message.id === null) return;
36
- try {
37
- 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' } } });
38
- if (message.method === 'ping') return send({ id: message.id, result: {} });
39
- if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
40
- 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 }); }
41
- send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
42
- } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
43
- });
44
- process.stdin.on('end', () => process.exit(0));
45
- `;
46
14
  var READERS = ["read", "search", "think", "fetch"];
47
15
  function acpPermission(toolCall, tools) {
48
16
  const raw = toolCall?.rawInput;
@@ -73,7 +41,7 @@ function acpWhat(request) {
73
41
  return `${request.kind === "other" ? "use" : request.kind} ${request.title ? `\`${request.title.slice(0, 300)}\`` : "a tool"}${request.paths.length ? ` (${request.paths.slice(0, 5).join(", ")})` : ""}`;
74
42
  }
75
43
  function acpEnv(provider, base) {
76
- const env = { ...base, ...provider.env };
44
+ const env = { ...base, ...provider.env, ...base.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: base.ALP_AGENT_SESSION } : {} };
77
45
  if (provider.command.split(/[\\/]/).pop().replace(/\.exe$/i, "").toLowerCase() !== "opencode") return env;
78
46
  let config = {};
79
47
  try {
@@ -137,7 +105,7 @@ var AcpTransport = class {
137
105
  if (/\.(cmd|bat|ps1)$/i.test(this.provider.command)) throw new Error(`${this.provider.label}: the command must be a native executable, not a shell launcher`);
138
106
  const env = acpEnv(this.provider, this.env);
139
107
  const launch = launchCommand(this.provider.command, this.provider.args, env);
140
- const child = spawn(launch.command, launch.args, { cwd: this.cwd, env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
108
+ const child = spawn(launch.command, launch.args, { cwd: this.cwd, env: launch.env ? { ...env, ...launch.env } : env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
141
109
  this.child = child;
142
110
  this.exit = new Promise((resolve) => {
143
111
  child.once("close", () => resolve());
@@ -402,7 +370,8 @@ ${this.config.developerInstructions}` });
402
370
  this.bridge = { server, socket, token, connections };
403
371
  }
404
372
  const electron = process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [];
405
- return { name: "alp", command: process.execPath, args: ["-e", BRIDGE], env: [{ name: "ALP_BRIDGE_SOCKET", value: this.bridge.socket }, { name: "ALP_BRIDGE_TOKEN", value: this.bridge.token }, ...electron] };
373
+ const bridge = bridgeCommand("acp");
374
+ return { name: "alp", command: bridge.command, args: bridge.args, env: [{ name: "ALP_BRIDGE_SOCKET", value: this.bridge.socket }, { name: "ALP_BRIDGE_TOKEN", value: this.bridge.token }, ...electron] };
406
375
  }
407
376
  serveBridge(connection, token) {
408
377
  let trusted = false;
@@ -23,6 +23,20 @@ export type AntigravityProvider = {
23
23
  };
24
24
  type Listener = (method: string, params: any) => void;
25
25
  type RequestHandler = (method: string, params: any) => Promise<unknown>;
26
+ /**
27
+ * The agy flags for an ALP mode. Headless agy cannot ask the user, so a tool its
28
+ * permission mode does not allow is denied: both limited modes fail closed.
29
+ * - read-only: agy's default request-review policy; built-in reads and search run,
30
+ * READ_ONLY_COMMANDS run; edits and every other command are denied.
31
+ * - workspace-write: edits accepted and commands run in agy's terminal sandbox,
32
+ * which keeps writes in the workspace; a bypass of the sandbox is denied.
33
+ * - full-access: every tool runs without asking.
34
+ * Both limited modes trust the working directory (otherwise agy denies even its
35
+ * reads and edits there) and allow ALP's own MCP server, which carries alp_*.
36
+ */
37
+ export declare function antigravityModeArgs(sandbox: unknown, cwd: string): string[];
38
+ /** What each mode lets an Antigravity agent do, for its instructions. */
39
+ export declare function antigravityModeText(sandbox: unknown): string;
26
40
  export declare function encodePrompt(text: string): string;
27
41
  /**
28
42
  * AntigravityTransport runs the Antigravity CLI (agy) over its stream-json protocol.
@@ -48,6 +62,7 @@ export declare class AntigravityTransport {
48
62
  private messageText;
49
63
  private messages;
50
64
  private instructionsSent;
65
+ private modeNote?;
51
66
  private tools;
52
67
  private bridge?;
53
68
  private readyPromise?;
@@ -76,6 +91,8 @@ export declare class AntigravityTransport {
76
91
  private serveBridge;
77
92
  private toolCall;
78
93
  private emit;
94
+ /** agy exits on SIGINT. Ignore that expected exit; the next prompt resumes its conversation in a fresh process. */
95
+ private stopProcess;
79
96
  private fail;
80
97
  close(): Promise<void>;
81
98
  }
@@ -1,7 +1,7 @@
1
1
  // packages/runtime/src/antigravity-transport.ts
2
2
  import { spawn, execFile } from "node:child_process";
3
3
  import { randomBytes, randomUUID } from "node:crypto";
4
- import { rmSync } from "node:fs";
4
+ import { realpathSync, rmSync } from "node:fs";
5
5
  import { mkdir, open, readFile, rename, writeFile, unlink } from "node:fs/promises";
6
6
  import net from "node:net";
7
7
  import os from "node:os";
@@ -9,40 +9,34 @@ import path from "node:path";
9
9
  import { createInterface } from "node:readline";
10
10
  import { openMcpTools } from "./mcp-tools.js";
11
11
  import { antigravityToolDetail } from "./tool-detail.js";
12
- var BRIDGE = `// ALP Antigravity bridge v1
13
-
14
- const net = require('node:net');
15
- const readline = require('node:readline');
16
- const socket = process.env.ALP_BRIDGE_SOCKET ? net.connect(process.env.ALP_BRIDGE_SOCKET) : null;
17
- const waiting = new Map();
18
- let sequence = 0;
19
- let buffer = '';
20
- socket?.setEncoding('utf8');
21
- socket?.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
22
- socket?.on('data', data => {
23
- buffer += data;
24
- for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
25
- const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
26
- try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
27
- }
28
- });
29
- socket?.on('close', () => process.exit(0));
30
- socket?.on('error', () => process.exit(1));
31
- 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'); });
32
- const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
33
- readline.createInterface({ input: process.stdin }).on('line', async line => {
34
- let message; try { message = JSON.parse(line); } catch { return; }
35
- if (message.id === undefined || message.id === null) return;
12
+ import { bridgeCommand, isBridgeArgs } from "@anhlp/alp-core/bridges";
13
+ var MODES = ["read-only", "workspace-write", "full-access"];
14
+ var READ_ONLY_COMMANDS = ["pwd", "ls", "cat", "head", "tail", "wc", "grep"];
15
+ var EDIT_TOOLS = /* @__PURE__ */ new Set(["write_file", "write_to_file", "replace_file_content", "multi_replace_file_content", "sed_file", "notebook_edit"]);
16
+ var modeOf = (sandbox) => sandbox === "danger-full-access" ? "full-access" : String(sandbox);
17
+ function antigravityModeArgs(sandbox, cwd) {
18
+ const mode = modeOf(sandbox);
19
+ if (mode === "full-access") return ["--dangerously-skip-permissions"];
20
+ if (!MODES.includes(mode)) throw new Error(`Antigravity does not support mode '${String(sandbox)}'`);
21
+ let real = cwd;
36
22
  try {
37
- 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' } } });
38
- if (message.method === 'ping') return send({ id: message.id, result: {} });
39
- if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
40
- 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 }); }
41
- send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
42
- } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
43
- });
44
- process.stdin.on('end', () => process.exit(0));
45
- `;
23
+ real = realpathSync(cwd);
24
+ } catch {
25
+ }
26
+ const settings = {
27
+ toolPermission: mode === "workspace-write" ? "proceed-in-sandbox" : "request-review",
28
+ enableTerminalSandbox: true,
29
+ trustedWorkspaces: [.../* @__PURE__ */ new Set([cwd, real])],
30
+ permissions: { allow: ["mcp(alp/*)", ...mode === "read-only" ? READ_ONLY_COMMANDS.map((command) => `command(${command})`) : []] }
31
+ };
32
+ return [...mode === "workspace-write" ? ["--mode", "accept-edits"] : [], "--sandbox", "--settings", JSON.stringify(settings)];
33
+ }
34
+ function antigravityModeText(sandbox) {
35
+ const mode = modeOf(sandbox);
36
+ if (mode === "read-only") return "agy enforces read-only: its own file reading and search tools work, and ALP's tools; it allows only the terminal commands pwd, ls, cat, head, tail, wc and grep, with no redirection or chaining, and denies every file edit and other command. A denied tool ends your turn, so do not attempt one: report work that needs changes to your requester.";
37
+ if (mode === "workspace-write") return "agy accepts file edits and runs terminal commands in its sandbox, which writes only inside your workspace; anything outside the workspace or the sandbox is denied, and a denied tool ends your turn. Report work that needs more to your requester.";
38
+ return "Antigravity runs with full access: every tool runs without asking.";
39
+ }
46
40
  function encodePrompt(text) {
47
41
  return `${JSON.stringify({ event: "user", message: { content: text } })}
48
42
  `;
@@ -71,6 +65,7 @@ var AntigravityTransport = class {
71
65
  messageText = /* @__PURE__ */ new Map();
72
66
  messages = 0;
73
67
  instructionsSent = false;
68
+ modeNote;
74
69
  tools = [];
75
70
  bridge;
76
71
  readyPromise;
@@ -98,7 +93,7 @@ var AntigravityTransport = class {
98
93
  async request(method, params) {
99
94
  if (this.closed) throw new Error("Runtime is closed");
100
95
  if (method === "thread/start" || method === "thread/resume") {
101
- if (params.sandbox !== "full-access" && params.sandbox !== "danger-full-access") throw new Error("Antigravity currently supports only full-access");
96
+ antigravityModeArgs(params.sandbox, params.cwd || this.cwd);
102
97
  this.config = params;
103
98
  this.tools = params.dynamicTools ?? [];
104
99
  try {
@@ -134,6 +129,12 @@ var AntigravityTransport = class {
134
129
  this.messageText.clear();
135
130
  const parts = (params.input ?? []).filter((part) => typeof part?.text === "string").map((part) => part.text);
136
131
  let promptText = parts.join("\n\n");
132
+ if (this.modeNote) {
133
+ promptText = `${this.modeNote}
134
+
135
+ ${promptText}`;
136
+ this.modeNote = void 0;
137
+ }
137
138
  if (!this.instructionsSent && this.config?.developerInstructions) {
138
139
  promptText = `Instructions from ALP, which runs you. Follow them for this whole session.
139
140
 
@@ -157,31 +158,19 @@ ${promptText}`;
157
158
  if (method === "turn/interrupt") {
158
159
  if (this.child && this.activeTurn) {
159
160
  const turnId = this.activeTurn;
160
- const child = this.child;
161
- this.child = void 0;
162
- this.lines?.close();
163
- const kill = (signal) => {
164
- if (process.platform !== "win32" && child.pid) {
165
- try {
166
- process.kill(-child.pid, signal);
167
- } catch {
168
- child.kill(signal);
169
- }
170
- } else child.kill(signal);
171
- };
172
- kill("SIGINT");
173
- const timer = setTimeout(() => kill("SIGKILL"), 1500);
174
- try {
175
- await this.exit;
176
- } finally {
177
- clearTimeout(timer);
178
- }
161
+ await this.stopProcess();
179
162
  this.endTurn(turnId, "interrupted");
180
163
  }
181
164
  return {};
182
165
  }
183
166
  if (method === "session/configure" || method === "thread/delete") {
184
- if (method === "session/configure" && params.sandbox && params.sandbox !== "full-access") throw new Error("Antigravity currently supports only full-access");
167
+ if (method === "session/configure" && params.sandbox && this.config && modeOf(params.sandbox) !== modeOf(this.config.sandbox)) {
168
+ antigravityModeArgs(params.sandbox, this.config.cwd || this.cwd);
169
+ if (this.activeTurn) throw new Error("Antigravity changes mode between turns only");
170
+ this.config = { ...this.config, sandbox: params.sandbox };
171
+ this.modeNote = `ALP changed your permission mode to ${modeOf(params.sandbox)}. ${antigravityModeText(params.sandbox)}`;
172
+ await this.stopProcess();
173
+ }
185
174
  return {};
186
175
  }
187
176
  throw new Error(`Antigravity does not support '${method}'`);
@@ -201,7 +190,7 @@ ${promptText}`;
201
190
  "--add-dir",
202
191
  params.cwd || this.cwd,
203
192
  "--disable-slash-commands",
204
- "--dangerously-skip-permissions"
193
+ ...antigravityModeArgs(params.sandbox, params.cwd || this.cwd)
205
194
  ];
206
195
  if (params.model) {
207
196
  args.push("--model", params.model);
@@ -213,6 +202,8 @@ ${promptText}`;
213
202
  ...this.env,
214
203
  ...this.provider?.env ?? {},
215
204
  ...params.env ?? {},
205
+ // Provider or session env never sheds the agent mark (t-ca1f).
206
+ ...this.env.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: this.env.ALP_AGENT_SESSION } : {},
216
207
  // Session credentials are inherited by this agy's MCP child only, never persisted.
217
208
  ALP_BRIDGE_SOCKET: this.bridge?.socket ?? "",
218
209
  ALP_BRIDGE_TOKEN: this.bridge?.token ?? ""
@@ -352,6 +343,9 @@ ${promptText}`;
352
343
  }
353
344
  });
354
345
  } else if (step.state === "DONE" || step.state === "ERROR") {
346
+ if (step.state === "DONE" && modeOf(this.config?.sandbox) === "read-only" && (EDIT_TOOLS.has(toolName) || EDIT_TOOLS.has(step.tool_info?.name))) {
347
+ step = { ...step, state: "ERROR", tool_info: { ...step.tool_info, output: void 0, error: { message: `Antigravity denied ${toolName} in read-only mode` } } };
348
+ }
355
349
  const output = typeof step.tool_info?.output === "string" ? step.tool_info.output : step.tool_info?.error?.message || "";
356
350
  this.emit("item/completed", {
357
351
  threadId: this.conversationId,
@@ -381,6 +375,11 @@ ${promptText}`;
381
375
  const isInterrupted = result.error === "interrupted";
382
376
  this.endTurn(turnId, isInterrupted ? "interrupted" : "failed", result.error);
383
377
  } else {
378
+ const denied = Array.isArray(result.denied_actions) ? result.denied_actions.map((action) => String(action?.display_name || action?.action || "")).filter(Boolean) : [];
379
+ if (denied.length) {
380
+ const text = `Antigravity denied ${[...new Set(denied)].join(", ")} in ${modeOf(this.config?.sandbox)} mode and ended the turn.`;
381
+ this.emit("item/completed", { threadId: this.conversationId, item: { type: "agentMessage", id: `agy-denied-${turnId}`, text } });
382
+ }
384
383
  this.endTurn(turnId, "completed");
385
384
  }
386
385
  }
@@ -449,10 +448,10 @@ ${promptText}`;
449
448
  }
450
449
  config.mcpServers ??= {};
451
450
  const existing = config.mcpServers.alp;
452
- if (existing && !existing.args?.some((arg) => typeof arg === "string" && arg.startsWith("// ALP Antigravity bridge v1"))) {
451
+ if (existing && !isBridgeArgs("antigravity", existing.args, existing.command)) {
453
452
  throw new Error("Antigravity already has an MCP server named alp; rename it before using ALP");
454
453
  }
455
- const launcher = { command: process.execPath, args: ["-e", BRIDGE], ...process.versions.electron ? { env: { ELECTRON_RUN_AS_NODE: "1" } } : {} };
454
+ const launcher = { ...bridgeCommand("antigravity"), ...process.versions.electron ? { env: { ELECTRON_RUN_AS_NODE: "1" } } : {} };
456
455
  if (JSON.stringify(existing) === JSON.stringify(launcher)) return;
457
456
  config.mcpServers.alp = launcher;
458
457
  await writeFile(temporary, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
@@ -554,6 +553,29 @@ ${promptText}`;
554
553
  emit(method, params) {
555
554
  for (const listener of this.listeners) listener(method, params);
556
555
  }
556
+ /** agy exits on SIGINT. Ignore that expected exit; the next prompt resumes its conversation in a fresh process. */
557
+ async stopProcess() {
558
+ const child = this.child;
559
+ if (!child) return;
560
+ this.child = void 0;
561
+ this.lines?.close();
562
+ const kill = (signal) => {
563
+ if (process.platform !== "win32" && child.pid) {
564
+ try {
565
+ process.kill(-child.pid, signal);
566
+ } catch {
567
+ child.kill(signal);
568
+ }
569
+ } else child.kill(signal);
570
+ };
571
+ kill("SIGINT");
572
+ const timer = setTimeout(() => kill("SIGKILL"), 1500);
573
+ try {
574
+ await this.exit;
575
+ } finally {
576
+ clearTimeout(timer);
577
+ }
578
+ }
557
579
  fail(error) {
558
580
  if (this.closed) return;
559
581
  for (const listener of this.failures) listener(error);
@@ -615,5 +637,7 @@ ${promptText}`;
615
637
  };
616
638
  export {
617
639
  AntigravityTransport,
640
+ antigravityModeArgs,
641
+ antigravityModeText,
618
642
  encodePrompt
619
643
  };
@@ -1,18 +1,52 @@
1
+ /** What a finished writer outside a worktree left in its checkout, kept until its requester handles it (recall entries expire, this does not). */
2
+ export type AssignmentResultEvidence = {
3
+ agent: string;
4
+ status: string;
5
+ finishedAt: string;
6
+ project: string;
7
+ requesters: string[];
8
+ taskId?: string;
9
+ brief: string;
10
+ summary: string;
11
+ };
12
+ export declare const RESULT_OUTCOMES: readonly ["applied", "discarded", "acknowledged"];
13
+ export type AssignmentResultHandling = {
14
+ outcome: typeof RESULT_OUTCOMES[number];
15
+ by: string;
16
+ at: string;
17
+ note?: string;
18
+ };
19
+ /** No `handled`: produced (or still running), and the removal guard refuses its paths. `handled`: the guard lets them go; archiving removes it from the ledger. */
1
20
  export type AssignmentResultOwner = {
2
21
  assignmentId: string;
3
22
  checkout: string;
4
23
  worktree?: string;
24
+ result?: AssignmentResultEvidence;
25
+ handled?: AssignmentResultHandling;
26
+ };
27
+ export type ArchivedAssignmentResult = AssignmentResultOwner & {
28
+ handled: AssignmentResultHandling;
29
+ archivedAt: string;
5
30
  };
6
31
  type Ledger = {
7
32
  version: 1;
8
33
  workspaces: string[];
9
34
  results: AssignmentResultOwner[];
10
35
  };
36
+ /** Archived results stay this long after the month they were archived in ends; ledger entries never expire. */
37
+ export declare const ARCHIVE_KEEP_MS: number;
11
38
  /** Permanent ownership, independent of native-thread recall expiry. Missing initialized data is never recreated. */
12
39
  export declare function createAssignmentResults(file?: string): {
13
40
  register(directory: string): Promise<void>;
14
41
  put(entry: AssignmentResultOwner): Promise<void>;
15
42
  remove(assignmentId: string): Promise<void>;
43
+ /**
44
+ * Records how a produced result was handled, then archives every handled entry and drops it from the ledger.
45
+ * The mark is saved first: from then on the guard lets the checkout go, while the ledger still holds the evidence.
46
+ */
47
+ resolve(assignmentId: string, handled: AssignmentResultHandling): Promise<ArchivedAssignmentResult>;
48
+ /** The newest archived record of an assignment, if its archive month is still kept. */
49
+ archived(assignmentId: string): Promise<ArchivedAssignmentResult | undefined>;
16
50
  inspect(): Promise<Ledger>;
17
51
  };
18
52
  export {};
@@ -1,14 +1,22 @@
1
1
  // packages/runtime/src/assignment-results.ts
2
- import { readFile, mkdir, writeFile } from "node:fs/promises";
2
+ import { readFile, readdir, mkdir, writeFile, open, rm } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { writeAtomic } from "@anhlp/alp-core/atomic";
5
+ var RESULT_OUTCOMES = ["applied", "discarded", "acknowledged"];
6
+ var ARCHIVE_KEEP_MS = 365 * 24 * 60 * 60 * 1e3;
5
7
  var empty = () => ({ version: 1, workspaces: [], results: [] });
6
8
  var absolute = (value) => typeof value === "string" && path.isAbsolute(value);
7
- var valid = (value) => 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)));
9
+ var text = (value) => typeof value === "string";
10
+ var evidence = (value) => value === void 0 || !!value && typeof value === "object" && !Array.isArray(value) && [value.agent, value.status, value.finishedAt, value.project, value.brief, value.summary].every(text) && Array.isArray(value.requesters) && value.requesters.every(text) && (value.taskId === void 0 || text(value.taskId));
11
+ var handling = (value) => value === void 0 || !!value && typeof value === "object" && !Array.isArray(value) && RESULT_OUTCOMES.includes(value.outcome) && text(value.by) && text(value.at) && (value.note === void 0 || text(value.note));
12
+ var valid = (value) => 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)) && evidence(entry.result) && handling(entry.handled));
13
+ var MONTH = /^(\d{4})-(\d{2})\.jsonl$/;
8
14
  function createAssignmentResults(file) {
9
15
  let memory = empty();
16
+ let archivedInMemory = [];
10
17
  let queue = Promise.resolve();
11
18
  const marker = file ? `${file}.initialized` : void 0;
19
+ const archiveDir = file ? path.join(path.dirname(file), "assignment-archive") : void 0;
12
20
  async function load(initialize = false) {
13
21
  if (!file) return memory;
14
22
  let value;
@@ -45,6 +53,55 @@ function createAssignmentResults(file) {
45
53
  });
46
54
  return result;
47
55
  }
56
+ async function append(record) {
57
+ if (!archiveDir) {
58
+ archivedInMemory.push(record);
59
+ return;
60
+ }
61
+ await mkdir(archiveDir, { recursive: true, mode: 448 });
62
+ const handle = await open(path.join(archiveDir, `${record.archivedAt.slice(0, 7)}.jsonl`), "a+", 384);
63
+ try {
64
+ const { size } = await handle.stat();
65
+ const last = Buffer.alloc(1);
66
+ const torn = size > 0 && (await handle.read(last, 0, 1, size - 1)).bytesRead === 1 && last[0] !== 10;
67
+ await handle.appendFile(`${torn ? "\n" : ""}${JSON.stringify(record)}
68
+ `);
69
+ await handle.sync();
70
+ } finally {
71
+ await handle.close();
72
+ }
73
+ }
74
+ async function archived() {
75
+ if (!archiveDir) return archivedInMemory;
76
+ let names;
77
+ try {
78
+ names = (await readdir(archiveDir)).filter((name) => MONTH.test(name)).sort();
79
+ } catch (error) {
80
+ if (error.code === "ENOENT") return [];
81
+ throw error;
82
+ }
83
+ const records = [];
84
+ for (const name of names) {
85
+ for (const line of (await readFile(path.join(archiveDir, name), "utf8")).split("\n")) {
86
+ try {
87
+ const record = JSON.parse(line);
88
+ if (typeof record?.assignmentId === "string") records.push(record);
89
+ } catch {
90
+ }
91
+ }
92
+ }
93
+ return records;
94
+ }
95
+ async function prune(now) {
96
+ if (!archiveDir) {
97
+ archivedInMemory = archivedInMemory.filter((record) => now - Date.parse(record.archivedAt) < ARCHIVE_KEEP_MS);
98
+ return;
99
+ }
100
+ for (const name of await readdir(archiveDir).catch(() => [])) {
101
+ const month = MONTH.exec(name);
102
+ if (month && now - Date.UTC(Number(month[1]), Number(month[2])) > ARCHIVE_KEEP_MS) await rm(path.join(archiveDir, name), { force: true });
103
+ }
104
+ }
48
105
  return {
49
106
  register(directory) {
50
107
  return serialize(async () => {
@@ -67,11 +124,46 @@ function createAssignmentResults(file) {
67
124
  await save(value);
68
125
  });
69
126
  },
127
+ /**
128
+ * Records how a produced result was handled, then archives every handled entry and drops it from the ledger.
129
+ * The mark is saved first: from then on the guard lets the checkout go, while the ledger still holds the evidence.
130
+ */
131
+ resolve(assignmentId, handled) {
132
+ return serialize(async () => {
133
+ if (!handling(handled)) throw new Error("Invalid result handling");
134
+ const value = await load();
135
+ const entry = value.results.find((owner) => owner.assignmentId === assignmentId);
136
+ if (!entry) throw new Error(`No retained assignment result ${assignmentId}`);
137
+ if (!entry.handled) {
138
+ entry.handled = handled;
139
+ await save(value);
140
+ }
141
+ const now = Date.now();
142
+ const records = [];
143
+ for (const owner of value.results) {
144
+ if (!owner.handled) continue;
145
+ const record = { ...owner, handled: owner.handled, archivedAt: new Date(now).toISOString() };
146
+ await append(record);
147
+ records.push(record);
148
+ }
149
+ value.results = value.results.filter((owner) => !owner.handled);
150
+ await save(value);
151
+ await prune(now).catch(() => {
152
+ });
153
+ return records.find((record) => record.assignmentId === assignmentId);
154
+ });
155
+ },
156
+ /** The newest archived record of an assignment, if its archive month is still kept. */
157
+ archived(assignmentId) {
158
+ return serialize(async () => (await archived()).filter((record) => record.assignmentId === assignmentId).at(-1));
159
+ },
70
160
  inspect() {
71
161
  return serialize(() => load());
72
162
  }
73
163
  };
74
164
  }
75
165
  export {
166
+ ARCHIVE_KEEP_MS,
167
+ RESULT_OUTCOMES,
76
168
  createAssignmentResults
77
169
  };
@@ -117,8 +117,8 @@ function createBoardDomain({ options, sessions, boards, loadedBoards, rootOf, li
117
117
  return toolResult(true, { pinned: pin.id, kind: pin.kind, ...paths ? { paths } : {}, ...task ? { task } : {} });
118
118
  }
119
119
  async function boardTool(session, args) {
120
- if (!plainObject(args, ["kinds", "limit"]) || args.kinds !== void 0 && (!Array.isArray(args.kinds) || !args.kinds.every((kind) => PIN_KINDS.includes(kind))) || args.limit !== void 0 && (!Number.isSafeInteger(args.limit) || args.limit < 1)) {
121
- return toolResult(false, { error: "kinds lists claim, decision or finding; limit is a positive integer" });
120
+ if (!plainObject(args, ["kinds", "limit"]) || args.kinds !== void 0 && (!Array.isArray(args.kinds) || args.kinds.length > PIN_KINDS.length || !args.kinds.every((kind) => PIN_KINDS.includes(kind))) || args.limit !== void 0 && (!Number.isSafeInteger(args.limit) || args.limit < 1)) {
121
+ return toolResult(false, { error: `kinds lists at most ${PIN_KINDS.length} of claim, decision and finding; limit is a positive integer` });
122
122
  }
123
123
  const kinds = args.kinds ?? [...PIN_KINDS];
124
124
  const pins = (await boardOf(session.mapping.agent.projectRoot)).filter((pin) => live(pin) && kinds.includes(pin.kind));
package/dist/board.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { InputLimits } from './input-limits.js';
1
2
  /**
2
3
  * The project board (plans/reference/ALPD.md §18): one group channel per project that every
3
4
  * agent working on it shares, across trees. Agents pin claims (paths they are changing),
@@ -10,6 +11,11 @@ import type { Pin } from '@anhlp/alp-protocol/dto';
10
11
  export type { PinKind, Pin } from '@anhlp/alp-protocol/dto';
11
12
  export declare const PIN_BODY_CHARS = 2000;
12
13
  export declare const PIN_PATHS = 50;
14
+ /** One claimed path; macOS's PATH_MAX. Each segment of a path is one more realpath call. */
15
+ export declare const PIN_PATH_CHARS = 1024;
16
+ /** alp_pin's paths and alp_board's kinds, checked before any schema walks them. */
17
+ export declare const PIN_PATHS_INPUT: InputLimits;
18
+ export declare const BOARD_KINDS_INPUT: InputLimits;
13
19
  /** Decisions and findings kept per project; live claims are always kept. */
14
20
  export declare const BOARD_KEEP = 200;
15
21
  /** Normalized project-relative paths, or absolute paths in a declared external write root. */
package/dist/board.js CHANGED
@@ -4,6 +4,9 @@ import { realpathSync } from "node:fs";
4
4
  var PIN_KINDS = ["claim", "decision", "finding"];
5
5
  var PIN_BODY_CHARS = 2e3;
6
6
  var PIN_PATHS = 50;
7
+ var PIN_PATH_CHARS = 1024;
8
+ var PIN_PATHS_INPUT = { bytes: PIN_PATHS * (3 * PIN_PATH_CHARS + 3), items: PIN_PATHS, depth: 1, string: PIN_PATH_CHARS };
9
+ var BOARD_KINDS_INPUT = { bytes: 64, items: PIN_KINDS.length, depth: 1, string: 16 };
7
10
  var BOARD_KEEP = 200;
8
11
  var DIGEST_CHARS = 3e3;
9
12
  function canonicalPath(file) {
@@ -23,6 +26,7 @@ function normalizePaths(paths, project, roots = [project]) {
23
26
  const normalized = [];
24
27
  for (const entry of paths) {
25
28
  if (typeof entry !== "string" || !entry.trim()) return "paths must be nonempty strings";
29
+ if (entry.length > PIN_PATH_CHARS) return `paths must be at most ${PIN_PATH_CHARS} characters each`;
26
30
  const absolute = canonicalPath(path.resolve(project, entry.trim()));
27
31
  if (!roots.some((root) => containsPath(canonicalPath(root), absolute))) return `${entry} is outside the project or declared write root`;
28
32
  const relative = path.relative(canonicalPath(project), absolute).split(path.sep).join("/");
@@ -58,9 +62,12 @@ function renderBoard(pins, limit = DIGEST_CHARS) {
58
62
  }
59
63
  export {
60
64
  BOARD_KEEP,
65
+ BOARD_KINDS_INPUT,
61
66
  PIN_BODY_CHARS,
62
67
  PIN_KINDS,
63
68
  PIN_PATHS,
69
+ PIN_PATHS_INPUT,
70
+ PIN_PATH_CHARS,
64
71
  live,
65
72
  normalizePaths,
66
73
  overlapping,
package/dist/catalog.d.ts CHANGED
@@ -15,6 +15,17 @@ export declare const thinkingOptions: {
15
15
  id: string;
16
16
  label: string;
17
17
  }[];
18
+ export type CatalogEntry = {
19
+ runtime: 'codex' | 'claude' | 'antigravity';
20
+ id: string;
21
+ label: string;
22
+ description: string;
23
+ efforts: string[];
24
+ effort?: string;
25
+ source?: 'live' | 'fallback' | 'static';
26
+ };
27
+ /** The rows every consumer reads: core MODELS at start, replaced in place by the live catalog (model-catalog.ts). */
28
+ export declare const entries: CatalogEntry[];
18
29
  export declare const models: {
19
30
  defaultThinkingOptionId?: string | undefined;
20
31
  id: string;
@@ -25,6 +36,8 @@ export declare const models: {
25
36
  label: string;
26
37
  }[];
27
38
  }[];
39
+ /** Replaces the catalog in place so every module holding `models`/`entries` sees the new rows. */
40
+ export declare function applyCatalog(next: CatalogEntry[]): void;
28
41
  export declare function thinkingOptionsFor(runtime: 'codex' | 'claude' | 'antigravity', nativeModel: string): {
29
42
  id: string;
30
43
  label: string;
package/dist/catalog.js CHANGED
@@ -19,7 +19,13 @@ var model = (runtime, id, label, description, modelThinkingOptions, defaultThink
19
19
  thinkingOptions: modelThinkingOptions,
20
20
  ...defaultThinkingOptionId ? { defaultThinkingOptionId } : {}
21
21
  });
22
- var models = MODELS.map((entry) => model(entry.runtime, entry.id, entry.label, entry.description, options(entry.efforts), entry.effort));
22
+ var toModel = (entry) => model(entry.runtime, entry.id, entry.label, entry.description, options(entry.efforts), entry.effort);
23
+ var entries = MODELS.map((entry) => ({ ...entry, source: "static" }));
24
+ var models = entries.map(toModel);
25
+ function applyCatalog(next) {
26
+ entries.splice(0, entries.length, ...next);
27
+ models.splice(0, models.length, ...next.map(toModel));
28
+ }
23
29
  function thinkingOptionsFor(runtime, nativeModel) {
24
30
  return models.find((candidate) => candidate.id === `${runtime}:${nativeModel}`)?.thinkingOptions ?? thinkingOptions;
25
31
  }
@@ -29,6 +35,8 @@ export {
29
35
  DEFAULT_MODEL,
30
36
  ORACLE_MODELS,
31
37
  ORACLE_THINKING,
38
+ applyCatalog,
39
+ entries,
32
40
  models,
33
41
  modes,
34
42
  thinkingOptions,
@@ -169,6 +169,13 @@ export declare class ClaudeTransport {
169
169
  };
170
170
  }>;
171
171
  initialize(): Promise<void>;
172
+ /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
173
+ probeModels(signal?: AbortSignal): Promise<{
174
+ id: string;
175
+ label: string;
176
+ description: string;
177
+ efforts: string[] | undefined;
178
+ }[]>;
172
179
  /** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
173
180
  private probeUsage;
174
181
  onNotification(listener: Listener): () => boolean;