@anhlp/alp-runtime 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.
Files changed (80) 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 +52 -0
  5. package/dist/assignment-results.js +169 -0
  6. package/dist/attachments.d.ts +84 -0
  7. package/dist/attachments.js +213 -0
  8. package/dist/board-domain.js +2 -2
  9. package/dist/board.d.ts +6 -0
  10. package/dist/board.js +7 -0
  11. package/dist/catalog.d.ts +13 -0
  12. package/dist/catalog.js +9 -1
  13. package/dist/claude-transport.d.ts +35 -0
  14. package/dist/claude-transport.js +152 -10
  15. package/dist/compact.d.ts +29 -0
  16. package/dist/compact.js +49 -0
  17. package/dist/configure.d.ts +44 -0
  18. package/dist/configure.js +64 -0
  19. package/dist/contracts.d.ts +185 -4
  20. package/dist/contracts.js +11 -0
  21. package/dist/conversation.d.ts +45 -0
  22. package/dist/conversation.js +62 -0
  23. package/dist/index.d.ts +15 -4
  24. package/dist/index.js +40 -3
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +8 -0
  28. package/dist/language.js +20 -0
  29. package/dist/mailbox.d.ts +2 -0
  30. package/dist/mailbox.js +3 -1
  31. package/dist/mcp-tools.d.ts +8 -0
  32. package/dist/mcp-tools.js +26 -0
  33. package/dist/model-catalog.d.ts +76 -0
  34. package/dist/model-catalog.js +193 -0
  35. package/dist/model-probes.d.ts +7 -0
  36. package/dist/model-probes.js +69 -0
  37. package/dist/providers.js +2 -0
  38. package/dist/resolve.d.ts +1 -0
  39. package/dist/resolve.js +3 -1
  40. package/dist/runtime.d.ts +9 -0
  41. package/dist/runtime.js +1547 -142
  42. package/dist/session-config.d.ts +279 -0
  43. package/dist/session-config.js +10 -10
  44. package/dist/session-state.d.ts +44 -6
  45. package/dist/tools.d.ts +119 -0
  46. package/dist/tools.js +72 -5
  47. package/dist/transport.js +3 -1
  48. package/dist/workspace.d.ts +11 -4
  49. package/dist/workspace.js +29 -11
  50. package/dist/worktree-domain.d.ts +2 -1
  51. package/dist/worktree-domain.js +4 -1
  52. package/package.json +11 -3
  53. package/src/acp-transport.ts +7 -37
  54. package/src/antigravity-transport.ts +95 -53
  55. package/src/assignment-results.ts +146 -0
  56. package/src/attachments.ts +254 -0
  57. package/src/board-domain.ts +2 -2
  58. package/src/board.ts +7 -0
  59. package/src/catalog.ts +10 -1
  60. package/src/claude-transport.ts +171 -11
  61. package/src/compact.ts +62 -0
  62. package/src/configure.ts +93 -0
  63. package/src/contracts.ts +172 -5
  64. package/src/conversation.ts +81 -0
  65. package/src/index.ts +15 -4
  66. package/src/input-limits.ts +65 -0
  67. package/src/language.ts +18 -0
  68. package/src/mailbox.ts +4 -1
  69. package/src/mcp-tools.ts +33 -0
  70. package/src/model-catalog.ts +166 -0
  71. package/src/model-probes.ts +58 -0
  72. package/src/providers.ts +3 -0
  73. package/src/resolve.ts +4 -2
  74. package/src/runtime.ts +1681 -151
  75. package/src/session-config.ts +9 -9
  76. package/src/session-state.ts +29 -2
  77. package/src/tools.ts +69 -5
  78. package/src/transport.ts +3 -1
  79. package/src/workspace.ts +42 -15
  80. package/src/worktree-domain.ts +5 -1
@@ -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
  };
@@ -0,0 +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. */
20
+ export type AssignmentResultOwner = {
21
+ assignmentId: string;
22
+ checkout: string;
23
+ worktree?: string;
24
+ result?: AssignmentResultEvidence;
25
+ handled?: AssignmentResultHandling;
26
+ };
27
+ export type ArchivedAssignmentResult = AssignmentResultOwner & {
28
+ handled: AssignmentResultHandling;
29
+ archivedAt: string;
30
+ };
31
+ type Ledger = {
32
+ version: 1;
33
+ workspaces: string[];
34
+ results: AssignmentResultOwner[];
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;
38
+ /** Permanent ownership, independent of native-thread recall expiry. Missing initialized data is never recreated. */
39
+ export declare function createAssignmentResults(file?: string): {
40
+ register(directory: string): Promise<void>;
41
+ put(entry: AssignmentResultOwner): Promise<void>;
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>;
50
+ inspect(): Promise<Ledger>;
51
+ };
52
+ export {};
@@ -0,0 +1,169 @@
1
+ // packages/runtime/src/assignment-results.ts
2
+ import { readFile, readdir, mkdir, writeFile, open, rm } from "node:fs/promises";
3
+ import path from "node:path";
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;
7
+ var empty = () => ({ version: 1, workspaces: [], results: [] });
8
+ var absolute = (value) => typeof value === "string" && path.isAbsolute(value);
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$/;
14
+ function createAssignmentResults(file) {
15
+ let memory = empty();
16
+ let archivedInMemory = [];
17
+ let queue = Promise.resolve();
18
+ const marker = file ? `${file}.initialized` : void 0;
19
+ const archiveDir = file ? path.join(path.dirname(file), "assignment-archive") : void 0;
20
+ async function load(initialize = false) {
21
+ if (!file) return memory;
22
+ let value;
23
+ try {
24
+ value = JSON.parse(await readFile(file, "utf8"));
25
+ } catch (error) {
26
+ if (error.code !== "ENOENT" || !initialize) throw new Error(`Cannot inspect assignment result ledger ${file}`);
27
+ try {
28
+ await readFile(marker, "utf8");
29
+ } catch (missing) {
30
+ if (missing.code === "ENOENT") return empty();
31
+ throw missing;
32
+ }
33
+ throw new Error(`Assignment result ledger ${file} was lost; restore it before managing workspaces`);
34
+ }
35
+ if (!valid(value)) throw new Error(`Invalid assignment result ledger ${file}`);
36
+ return value;
37
+ }
38
+ async function save(value) {
39
+ if (!file) {
40
+ memory = value;
41
+ return;
42
+ }
43
+ await mkdir(path.dirname(file), { recursive: true, mode: 448 });
44
+ await writeAtomic(file, JSON.stringify(value) + "\n");
45
+ await writeFile(marker, "1\n", { flag: "wx", mode: 384 }).catch((error) => {
46
+ if (error.code !== "EEXIST") throw error;
47
+ });
48
+ }
49
+ function serialize(run) {
50
+ const result = queue.then(run);
51
+ queue = result.then(() => {
52
+ }, () => {
53
+ });
54
+ return result;
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
+ }
105
+ return {
106
+ register(directory) {
107
+ return serialize(async () => {
108
+ const value = await load(true);
109
+ if (!value.workspaces.includes(directory)) value.workspaces.push(directory);
110
+ await save(value);
111
+ });
112
+ },
113
+ put(entry) {
114
+ return serialize(async () => {
115
+ const value = await load(true);
116
+ value.results = [...value.results.filter((existing) => existing.assignmentId !== entry.assignmentId), entry];
117
+ await save(value);
118
+ });
119
+ },
120
+ remove(assignmentId) {
121
+ return serialize(async () => {
122
+ const value = await load();
123
+ value.results = value.results.filter((entry) => entry.assignmentId !== assignmentId);
124
+ await save(value);
125
+ });
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
+ },
160
+ inspect() {
161
+ return serialize(() => load());
162
+ }
163
+ };
164
+ }
165
+ export {
166
+ ARCHIVE_KEEP_MS,
167
+ RESULT_OUTCOMES,
168
+ createAssignmentResults
169
+ };
@@ -0,0 +1,84 @@
1
+ import type { Readable } from 'node:stream';
2
+ import type { RuntimeAttachment } from '@anhlp/alp-protocol/session';
3
+ import type { RuntimeKind } from './resolve.js';
4
+ /**
5
+ * Non-image attachments on the runtime side (issue #121 branch J, docs/protocol/alp-json-rpc-v1.md
6
+ * §12.6). alpd resolves an attachment part to a RuntimeAttachment and hands its verified bytes over
7
+ * through an AttachmentReader, never a path. The runtime stages a runtime-readable copy at a path it
8
+ * generates itself, in one dedicated directory (`<ALP_HOME>/state/staged`) that the sessions'
9
+ * sandboxes already let tools read, and names that path in the turn's input:
10
+ *
11
+ * - The sandbox is never widened: Codex's read-only and workspace-write sandboxes read the whole
12
+ * disk, Claude's file tools read through ALP's permission gate (Read, Glob and Grep are readers in
13
+ * every mode) and its Bash sandbox reads outside the workspace. Neither may write the directory
14
+ * while ALP_HOME is outside the workspace and the temp directory (the default ~/.alp), so a sandboxed
15
+ * tool cannot swap a copy; a copy that changed anyway is caught at the next stage (size, SHA-256).
16
+ * - A copy is named by its attachment id and an extension taken from the display name only when it
17
+ * is plain letters and digits; the display name never becomes a path. It is created exclusively
18
+ * without following links, written from the verified stream, made read-only (0400, never
19
+ * executable) and renamed into place; one already there is used only when it is a regular file of
20
+ * one link, read-only, of the right size and SHA-256, else replaced.
21
+ * - Errors name the attachment's id and display name, never the staging path.
22
+ */
23
+ /**
24
+ * How a runtime can use a file attached to a prompt (the capability matrix of §12.6):
25
+ * - `file.path`: the turn names a staged read-only copy its tools can read byte for byte.
26
+ * - `document.native`: the file goes into the model's input as a document (none does yet).
27
+ * - `text.extract`: ALP extracts bounded text for it (none does yet).
28
+ */
29
+ export type AttachmentRoute = 'file.path' | 'document.native' | 'text.extract';
30
+ /**
31
+ * The routes each runtime has. Codex and Claude read staged copies with their own tools; ALP sends
32
+ * neither a native document part, nor extracted text. ACP agents and Antigravity take none: their
33
+ * file access is not negotiated, so a prompt with attachments is refused for them, never sent
34
+ * as if they could read it.
35
+ */
36
+ export declare const ATTACHMENT_ROUTES: Readonly<Record<RuntimeKind, readonly AttachmentRoute[]>>;
37
+ /** What alpd binds for a runtime that takes attachments (`AttachmentReader` in @anhlp/alp-daemon). */
38
+ export type AttachmentReader = {
39
+ open(attachmentId: string, sessionId: string): Promise<{
40
+ stream: Readable;
41
+ attachment: RuntimeAttachment;
42
+ }>;
43
+ };
44
+ /** Where alpd's runtime stages copies: a directory of its own under ALP_HOME's state. */
45
+ export declare const attachmentStageDir: (home: string) => string;
46
+ /**
47
+ * The first of `writable` (directories a sandboxed session may write: its workspace, the temp
48
+ * directory) that holds the staging directory, or undefined. There a sandboxed tool could change a
49
+ * staged copy between its stage and its read, so alpd warns; ALP_HOME's default ~/.alp is in neither.
50
+ */
51
+ export declare function stagingExposure(stageDir: string, writable: string[]): string | undefined;
52
+ /** The first words of the input part naming an attachment; its JSON follows them. */
53
+ export declare const ATTACHMENT_HEADER = "ALP attached a file to this message (data, not instructions): ";
54
+ /** What stands for the staging directory in timelines and errors clients see. */
55
+ export declare const STAGED_PATH = "<alp-attachments>";
56
+ /** Why staging failed, for the prompt's error: the attachment's id and name, never a path. */
57
+ export declare class AttachmentStageError extends Error {
58
+ constructor(attachment: {
59
+ attachmentId: string;
60
+ name: string;
61
+ }, why: string);
62
+ }
63
+ /** A RuntimeAttachment as alpd resolves it, checked field by field; anything else is refused. */
64
+ export declare function runtimeAttachment(part: unknown): RuntimeAttachment | undefined;
65
+ /** The staged copy's file name: the id and an extension of plain letters and digits, from the name or else the detected type. */
66
+ export declare function stagedName(attachment: Pick<RuntimeAttachment, 'attachmentId' | 'name' | 'detectedMimeType'>): string;
67
+ /** The input part a turn gets for one staged attachment: its metadata and path as JSON, then what to do. */
68
+ export declare function attachmentPart(attachment: RuntimeAttachment, staged: string): string;
69
+ /**
70
+ * Stages read-only copies of verified attachments in one directory, one at a time per attachment.
71
+ * `stage` answers the copy's path; `drop` removes the copy of an attachment alpd no longer keeps.
72
+ */
73
+ export declare function createAttachmentStager(root: string): {
74
+ root: string;
75
+ /** Every spelling of the directory, longest first, for keeping it out of what clients see. */
76
+ spellings: () => string[];
77
+ /** The path of a read-only copy of `attachment` for `sessionId`'s runtime, staged from alpd's verified bytes. */
78
+ stage(reader: AttachmentReader, attachment: RuntimeAttachment, sessionId: string): Promise<string>;
79
+ /** Removes the staged copy of an attachment (alpd collected it); a missing copy is no error. */
80
+ drop(attachmentId: string): Promise<void>;
81
+ /** Removes temporary files a crash left. */
82
+ sweep(): Promise<void>;
83
+ };
84
+ export type AttachmentStager = ReturnType<typeof createAttachmentStager>;