@anhlp/alp-runtime 0.0.0-beta.2 → 0.0.1-beta.10

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 (97) hide show
  1. package/dist/acp-transport.js +7 -36
  2. package/dist/antigravity-transport.d.ts +27 -2
  3. package/dist/antigravity-transport.js +104 -58
  4. package/dist/assignment-results.d.ts +55 -0
  5. package/dist/assignment-results.js +181 -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 +11 -2
  13. package/dist/claude-transport.d.ts +80 -0
  14. package/dist/claude-transport.js +271 -23
  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 +216 -7
  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 +18 -5
  24. package/dist/index.js +48 -4
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +10 -0
  28. package/dist/language.js +26 -0
  29. package/dist/live.d.ts +2 -2
  30. package/dist/live.js +7 -2
  31. package/dist/mailbox.d.ts +2 -0
  32. package/dist/mailbox.js +3 -1
  33. package/dist/mcp-tools.d.ts +8 -0
  34. package/dist/mcp-tools.js +26 -0
  35. package/dist/model-catalog.d.ts +162 -0
  36. package/dist/model-catalog.js +338 -0
  37. package/dist/model-probes.d.ts +7 -0
  38. package/dist/model-probes.js +69 -0
  39. package/dist/providers.js +2 -0
  40. package/dist/recall.d.ts +2 -2
  41. package/dist/recall.js +4 -3
  42. package/dist/resolve.d.ts +2 -0
  43. package/dist/resolve.js +9 -5
  44. package/dist/runtime-context.d.ts +1 -1
  45. package/dist/runtime-context.js +1 -1
  46. package/dist/runtime.d.ts +9 -0
  47. package/dist/runtime.js +2078 -269
  48. package/dist/session-config.d.ts +378 -6
  49. package/dist/session-config.js +19 -15
  50. package/dist/session-state.d.ts +54 -7
  51. package/dist/skill-resources.d.ts +30 -0
  52. package/dist/skill-resources.js +55 -0
  53. package/dist/tool-detail.js +4 -1
  54. package/dist/tools.d.ts +154 -1
  55. package/dist/tools.js +99 -11
  56. package/dist/transport.js +3 -1
  57. package/dist/workspace.d.ts +31 -5
  58. package/dist/workspace.js +92 -11
  59. package/dist/worktree-domain.d.ts +2 -1
  60. package/dist/worktree-domain.js +4 -1
  61. package/dist/write-error.d.ts +2 -0
  62. package/dist/write-error.js +10 -0
  63. package/package.json +12 -4
  64. package/src/acp-transport.ts +10 -37
  65. package/src/antigravity-transport.ts +128 -55
  66. package/src/assignment-results.ts +154 -0
  67. package/src/attachments.ts +254 -0
  68. package/src/board-domain.ts +2 -2
  69. package/src/board.ts +7 -0
  70. package/src/catalog.ts +13 -2
  71. package/src/claude-transport.ts +333 -23
  72. package/src/compact.ts +62 -0
  73. package/src/configure.ts +93 -0
  74. package/src/contracts.ts +199 -8
  75. package/src/conversation.ts +81 -0
  76. package/src/index.ts +18 -5
  77. package/src/input-limits.ts +65 -0
  78. package/src/language.ts +28 -0
  79. package/src/live.ts +7 -3
  80. package/src/mailbox.ts +4 -1
  81. package/src/mcp-tools.ts +33 -0
  82. package/src/model-catalog.ts +316 -0
  83. package/src/model-probes.ts +58 -0
  84. package/src/providers.ts +3 -0
  85. package/src/recall.ts +4 -3
  86. package/src/resolve.ts +15 -7
  87. package/src/runtime-context.ts +2 -2
  88. package/src/runtime.ts +2253 -264
  89. package/src/session-config.ts +25 -14
  90. package/src/session-state.ts +39 -3
  91. package/src/skill-resources.ts +73 -0
  92. package/src/tool-detail.ts +4 -1
  93. package/src/tools.ts +97 -10
  94. package/src/transport.ts +3 -1
  95. package/src/workspace.ts +124 -18
  96. package/src/worktree-domain.ts +5 -1
  97. package/src/write-error.ts +4 -0
@@ -9,40 +9,9 @@ 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
- `;
14
+ import { feedAcpSession } from "./model-catalog.js";
46
15
  var READERS = ["read", "search", "think", "fetch"];
47
16
  function acpPermission(toolCall, tools) {
48
17
  const raw = toolCall?.rawInput;
@@ -73,7 +42,7 @@ function acpWhat(request) {
73
42
  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
43
  }
75
44
  function acpEnv(provider, base) {
76
- const env = { ...base, ...provider.env };
45
+ const env = { ...base, ...provider.env, ...base.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: base.ALP_AGENT_SESSION } : {} };
77
46
  if (provider.command.split(/[\\/]/).pop().replace(/\.exe$/i, "").toLowerCase() !== "opencode") return env;
78
47
  let config = {};
79
48
  try {
@@ -137,7 +106,7 @@ var AcpTransport = class {
137
106
  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
107
  const env = acpEnv(this.provider, this.env);
139
108
  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"] });
109
+ const child = spawn(launch.command, launch.args, { cwd: this.cwd, env: launch.env ? { ...env, ...launch.env } : env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
141
110
  this.child = child;
142
111
  this.exit = new Promise((resolve) => {
143
112
  child.once("close", () => resolve());
@@ -190,6 +159,7 @@ var AcpTransport = class {
190
159
  } else {
191
160
  const result = await this.call("session/new", { cwd: params.cwd, mcpServers }, 12e4);
192
161
  this.sessionId = result.sessionId;
162
+ feedAcpSession(this.provider.id, result);
193
163
  await this.chooseModel(result.models, result.configOptions);
194
164
  }
195
165
  return { thread: { id: this.sessionId, turns: [] }, cwd: params.cwd, model: params.model, reasoningEffort: params.thinking };
@@ -402,7 +372,8 @@ ${this.config.developerInstructions}` });
402
372
  this.bridge = { server, socket, token, connections };
403
373
  }
404
374
  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] };
375
+ const bridge = bridgeCommand("acp");
376
+ 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
377
  }
407
378
  serveBridge(connection, token) {
408
379
  let trusted = false;
@@ -18,11 +18,31 @@ export type AntigravityProvider = {
18
18
  description?: string;
19
19
  }>;
20
20
  enabled?: boolean;
21
- /** Explicit opt-in: read-only is a prompt constraint, never a native sandbox. */
22
- readOnlyMode?: 'instructions' | 'reject';
23
21
  };
24
22
  type Listener = (method: string, params: any) => void;
25
23
  type RequestHandler = (method: string, params: any) => Promise<unknown>;
24
+ /**
25
+ * Whether read-only allows a terminal command line, by ALP's own reading of the allowlist:
26
+ * one allowed command with no shell syntax. Unknown input is refused.
27
+ */
28
+ export declare function antigravityReadOnlyCommandAllowed(commandLine: unknown): boolean;
29
+ /**
30
+ * The agy flags for an ALP mode. Headless agy cannot ask the user, so a tool its
31
+ * permission mode does not allow is denied: both limited modes fail closed.
32
+ * - read-only: agy's default request-review policy; built-in reads and search run,
33
+ * READ_ONLY_COMMANDS run; edits and every other command are denied.
34
+ * - workspace-write: edits accepted and commands run in agy's terminal sandbox,
35
+ * which keeps writes in the workspace; a bypass of the sandbox is denied.
36
+ * - full-access: every tool runs without asking.
37
+ * Both limited modes trust the working directory (otherwise agy denies even its
38
+ * reads and edits there) and allow ALP's own MCP server, which carries alp_*.
39
+ */
40
+ export declare function antigravityModeArgs(sandbox: unknown, cwd: string): string[];
41
+ /** Efforts `agy --effort` takes (agy --help: low|medium|high|xhigh|max); others leave agy's default. */
42
+ export declare const AGY_EFFORTS: string[];
43
+ export declare function antigravityEffortArgs(thinking: unknown): string[];
44
+ /** What each mode lets an Antigravity agent do, for its instructions. */
45
+ export declare function antigravityModeText(sandbox: unknown): string;
26
46
  export declare function encodePrompt(text: string): string;
27
47
  /**
28
48
  * AntigravityTransport runs the Antigravity CLI (agy) over its stream-json protocol.
@@ -48,6 +68,7 @@ export declare class AntigravityTransport {
48
68
  private messageText;
49
69
  private messages;
50
70
  private instructionsSent;
71
+ private modeNote?;
51
72
  private tools;
52
73
  private bridge?;
53
74
  private readyPromise?;
@@ -65,6 +86,8 @@ export declare class AntigravityTransport {
65
86
  private startProcess;
66
87
  private receiveLine;
67
88
  private handleStepUpdate;
89
+ /** Whether read-only refuses this tool step: an edit, or a terminal command outside the allowlist. */
90
+ private readOnlyRefuses;
68
91
  private handleResult;
69
92
  private endTurn;
70
93
  private openBridge;
@@ -76,6 +99,8 @@ export declare class AntigravityTransport {
76
99
  private serveBridge;
77
100
  private toolCall;
78
101
  private emit;
102
+ /** agy exits on SIGINT. Ignore that expected exit; the next prompt resumes its conversation in a fresh process. */
103
+ private stopProcess;
79
104
  private fail;
80
105
  close(): Promise<void>;
81
106
  }
@@ -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,45 @@ 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"];
15
+ var SHELL_SYNTAX = /[;&|<>`$(){}\\\n\r]/;
16
+ function antigravityReadOnlyCommandAllowed(commandLine) {
17
+ if (typeof commandLine !== "string" || SHELL_SYNTAX.test(commandLine)) return false;
18
+ const [command] = commandLine.trim().split(/\s+/);
19
+ return READ_ONLY_COMMANDS.includes(command);
20
+ }
21
+ var COMMAND_TOOLS = /* @__PURE__ */ new Set(["run_command"]);
22
+ var EDIT_TOOLS = /* @__PURE__ */ new Set(["write_file", "write_to_file", "replace_file_content", "multi_replace_file_content", "sed_file", "notebook_edit"]);
23
+ var modeOf = (sandbox) => sandbox === "danger-full-access" ? "full-access" : String(sandbox);
24
+ function antigravityModeArgs(sandbox, cwd) {
25
+ const mode = modeOf(sandbox);
26
+ if (mode === "full-access") return ["--dangerously-skip-permissions"];
27
+ if (!MODES.includes(mode)) throw new Error(`Antigravity does not support mode '${String(sandbox)}'`);
28
+ let real = cwd;
36
29
  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
- `;
30
+ real = realpathSync(cwd);
31
+ } catch {
32
+ }
33
+ const settings = {
34
+ toolPermission: mode === "workspace-write" ? "proceed-in-sandbox" : "request-review",
35
+ enableTerminalSandbox: true,
36
+ trustedWorkspaces: [.../* @__PURE__ */ new Set([cwd, real])],
37
+ permissions: { allow: ["mcp(alp/*)", ...mode === "read-only" ? READ_ONLY_COMMANDS.map((command) => `command(${command})`) : []] }
38
+ };
39
+ return [...mode === "workspace-write" ? ["--mode", "accept-edits"] : [], "--sandbox", "--settings", JSON.stringify(settings)];
40
+ }
41
+ var AGY_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
42
+ function antigravityEffortArgs(thinking) {
43
+ return typeof thinking === "string" && AGY_EFFORTS.includes(thinking) ? ["--effort", thinking] : [];
44
+ }
45
+ function antigravityModeText(sandbox) {
46
+ const mode = modeOf(sandbox);
47
+ 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 command pwd, with no redirection or chaining (read files with its own tools), 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.";
48
+ 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.";
49
+ return "Antigravity runs with full access: every tool runs without asking.";
50
+ }
46
51
  function encodePrompt(text) {
47
52
  return `${JSON.stringify({ event: "user", message: { content: text } })}
48
53
  `;
@@ -71,6 +76,7 @@ var AntigravityTransport = class {
71
76
  messageText = /* @__PURE__ */ new Map();
72
77
  messages = 0;
73
78
  instructionsSent = false;
79
+ modeNote;
74
80
  tools = [];
75
81
  bridge;
76
82
  readyPromise;
@@ -98,7 +104,7 @@ var AntigravityTransport = class {
98
104
  async request(method, params) {
99
105
  if (this.closed) throw new Error("Runtime is closed");
100
106
  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");
107
+ antigravityModeArgs(params.sandbox, params.cwd || this.cwd);
102
108
  this.config = params;
103
109
  this.tools = params.dynamicTools ?? [];
104
110
  try {
@@ -134,6 +140,12 @@ var AntigravityTransport = class {
134
140
  this.messageText.clear();
135
141
  const parts = (params.input ?? []).filter((part) => typeof part?.text === "string").map((part) => part.text);
136
142
  let promptText = parts.join("\n\n");
143
+ if (this.modeNote) {
144
+ promptText = `${this.modeNote}
145
+
146
+ ${promptText}`;
147
+ this.modeNote = void 0;
148
+ }
137
149
  if (!this.instructionsSent && this.config?.developerInstructions) {
138
150
  promptText = `Instructions from ALP, which runs you. Follow them for this whole session.
139
151
 
@@ -157,31 +169,19 @@ ${promptText}`;
157
169
  if (method === "turn/interrupt") {
158
170
  if (this.child && this.activeTurn) {
159
171
  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
- }
172
+ await this.stopProcess();
179
173
  this.endTurn(turnId, "interrupted");
180
174
  }
181
175
  return {};
182
176
  }
183
177
  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");
178
+ if (method === "session/configure" && params.sandbox && this.config && modeOf(params.sandbox) !== modeOf(this.config.sandbox)) {
179
+ antigravityModeArgs(params.sandbox, this.config.cwd || this.cwd);
180
+ if (this.activeTurn) throw new Error("Antigravity changes mode between turns only");
181
+ this.config = { ...this.config, sandbox: params.sandbox };
182
+ this.modeNote = `ALP changed your permission mode to ${modeOf(params.sandbox)}. ${antigravityModeText(params.sandbox)}`;
183
+ await this.stopProcess();
184
+ }
185
185
  return {};
186
186
  }
187
187
  throw new Error(`Antigravity does not support '${method}'`);
@@ -201,11 +201,12 @@ ${promptText}`;
201
201
  "--add-dir",
202
202
  params.cwd || this.cwd,
203
203
  "--disable-slash-commands",
204
- "--dangerously-skip-permissions"
204
+ ...antigravityModeArgs(params.sandbox, params.cwd || this.cwd)
205
205
  ];
206
206
  if (params.model) {
207
207
  args.push("--model", params.model);
208
208
  }
209
+ args.push(...antigravityEffortArgs(params.thinking));
209
210
  if (params.threadId) {
210
211
  args.push("--conversation", params.threadId);
211
212
  }
@@ -213,6 +214,8 @@ ${promptText}`;
213
214
  ...this.env,
214
215
  ...this.provider?.env ?? {},
215
216
  ...params.env ?? {},
217
+ // Provider or session env never sheds the agent mark (t-ca1f).
218
+ ...this.env.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: this.env.ALP_AGENT_SESSION } : {},
216
219
  // Session credentials are inherited by this agy's MCP child only, never persisted.
217
220
  ALP_BRIDGE_SOCKET: this.bridge?.socket ?? "",
218
221
  ALP_BRIDGE_TOKEN: this.bridge?.token ?? ""
@@ -352,6 +355,9 @@ ${promptText}`;
352
355
  }
353
356
  });
354
357
  } else if (step.state === "DONE" || step.state === "ERROR") {
358
+ if (step.state === "DONE" && modeOf(this.config?.sandbox) === "read-only" && this.readOnlyRefuses(toolName, step.tool_info)) {
359
+ step = { ...step, state: "ERROR", tool_info: { ...step.tool_info, output: void 0, error: { message: `Antigravity denied ${typed.tool} in read-only mode` } } };
360
+ }
355
361
  const output = typeof step.tool_info?.output === "string" ? step.tool_info.output : step.tool_info?.error?.message || "";
356
362
  this.emit("item/completed", {
357
363
  threadId: this.conversationId,
@@ -370,6 +376,13 @@ ${promptText}`;
370
376
  }
371
377
  }
372
378
  }
379
+ /** Whether read-only refuses this tool step: an edit, or a terminal command outside the allowlist. */
380
+ readOnlyRefuses(toolName, info) {
381
+ const name = typeof info?.name === "string" && info.name ? info.name : toolName;
382
+ if (EDIT_TOOLS.has(toolName) || EDIT_TOOLS.has(name)) return true;
383
+ if (COMMAND_TOOLS.has(toolName) || COMMAND_TOOLS.has(name)) return !antigravityReadOnlyCommandAllowed(info?.parameters?.CommandLine);
384
+ return false;
385
+ }
373
386
  handleResult(result) {
374
387
  if (!this.activeTurn) return;
375
388
  const turnId = this.activeTurn;
@@ -381,6 +394,11 @@ ${promptText}`;
381
394
  const isInterrupted = result.error === "interrupted";
382
395
  this.endTurn(turnId, isInterrupted ? "interrupted" : "failed", result.error);
383
396
  } else {
397
+ const denied = Array.isArray(result.denied_actions) ? result.denied_actions.map((action) => String(action?.display_name || action?.action || "")).filter(Boolean) : [];
398
+ if (denied.length) {
399
+ const text = `Antigravity denied ${[...new Set(denied)].join(", ")} in ${modeOf(this.config?.sandbox)} mode and ended the turn.`;
400
+ this.emit("item/completed", { threadId: this.conversationId, item: { type: "agentMessage", id: `agy-denied-${turnId}`, text } });
401
+ }
384
402
  this.endTurn(turnId, "completed");
385
403
  }
386
404
  }
@@ -449,10 +467,10 @@ ${promptText}`;
449
467
  }
450
468
  config.mcpServers ??= {};
451
469
  const existing = config.mcpServers.alp;
452
- if (existing && !existing.args?.some((arg) => typeof arg === "string" && arg.startsWith("// ALP Antigravity bridge v1"))) {
470
+ if (existing && !isBridgeArgs("antigravity", existing.args, existing.command)) {
453
471
  throw new Error("Antigravity already has an MCP server named alp; rename it before using ALP");
454
472
  }
455
- const launcher = { command: process.execPath, args: ["-e", BRIDGE], ...process.versions.electron ? { env: { ELECTRON_RUN_AS_NODE: "1" } } : {} };
473
+ const launcher = { ...bridgeCommand("antigravity"), ...process.versions.electron ? { env: { ELECTRON_RUN_AS_NODE: "1" } } : {} };
456
474
  if (JSON.stringify(existing) === JSON.stringify(launcher)) return;
457
475
  config.mcpServers.alp = launcher;
458
476
  await writeFile(temporary, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
@@ -554,6 +572,29 @@ ${promptText}`;
554
572
  emit(method, params) {
555
573
  for (const listener of this.listeners) listener(method, params);
556
574
  }
575
+ /** agy exits on SIGINT. Ignore that expected exit; the next prompt resumes its conversation in a fresh process. */
576
+ async stopProcess() {
577
+ const child = this.child;
578
+ if (!child) return;
579
+ this.child = void 0;
580
+ this.lines?.close();
581
+ const kill = (signal) => {
582
+ if (process.platform !== "win32" && child.pid) {
583
+ try {
584
+ process.kill(-child.pid, signal);
585
+ } catch {
586
+ child.kill(signal);
587
+ }
588
+ } else child.kill(signal);
589
+ };
590
+ kill("SIGINT");
591
+ const timer = setTimeout(() => kill("SIGKILL"), 1500);
592
+ try {
593
+ await this.exit;
594
+ } finally {
595
+ clearTimeout(timer);
596
+ }
597
+ }
557
598
  fail(error) {
558
599
  if (this.closed) return;
559
600
  for (const listener of this.failures) listener(error);
@@ -614,6 +655,11 @@ ${promptText}`;
614
655
  }
615
656
  };
616
657
  export {
658
+ AGY_EFFORTS,
617
659
  AntigravityTransport,
660
+ antigravityEffortArgs,
661
+ antigravityModeArgs,
662
+ antigravityModeText,
663
+ antigravityReadOnlyCommandAllowed,
618
664
  encodePrompt
619
665
  };
@@ -0,0 +1,55 @@
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
+ /**
39
+ * Permanent ownership, independent of native-thread recall expiry. Missing initialized data is never recreated.
40
+ * A failed write still fails its caller; `onError` hears of it too, so a full disk is seen at once.
41
+ */
42
+ export declare function createAssignmentResults(file?: string, onError?: (error: unknown) => void): {
43
+ register(directory: string): Promise<void>;
44
+ put(entry: AssignmentResultOwner): Promise<void>;
45
+ remove(assignmentId: string): Promise<void>;
46
+ /**
47
+ * Records how a produced result was handled, then archives every handled entry and drops it from the ledger.
48
+ * The mark is saved first: from then on the guard lets the checkout go, while the ledger still holds the evidence.
49
+ */
50
+ resolve(assignmentId: string, handled: AssignmentResultHandling): Promise<ArchivedAssignmentResult>;
51
+ /** The newest archived record of an assignment, if its archive month is still kept. */
52
+ archived(assignmentId: string): Promise<ArchivedAssignmentResult | undefined>;
53
+ inspect(): Promise<Ledger>;
54
+ };
55
+ export {};
@@ -0,0 +1,181 @@
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
+ import { tell } from "./write-error.js";
6
+ var RESULT_OUTCOMES = ["applied", "discarded", "acknowledged"];
7
+ var ARCHIVE_KEEP_MS = 365 * 24 * 60 * 60 * 1e3;
8
+ var empty = () => ({ version: 1, workspaces: [], results: [] });
9
+ var absolute = (value) => typeof value === "string" && path.isAbsolute(value);
10
+ var text = (value) => typeof value === "string";
11
+ 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));
12
+ 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));
13
+ 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));
14
+ var MONTH = /^(\d{4})-(\d{2})\.jsonl$/;
15
+ function createAssignmentResults(file, onError = () => {
16
+ }) {
17
+ let memory = empty();
18
+ let archivedInMemory = [];
19
+ let queue = Promise.resolve();
20
+ const marker = file ? `${file}.initialized` : void 0;
21
+ const archiveDir = file ? path.join(path.dirname(file), "assignment-archive") : void 0;
22
+ async function load(initialize = false) {
23
+ if (!file) return memory;
24
+ let value;
25
+ try {
26
+ value = JSON.parse(await readFile(file, "utf8"));
27
+ } catch (error) {
28
+ if (error.code !== "ENOENT" || !initialize) throw new Error(`Cannot inspect assignment result ledger ${file}`);
29
+ try {
30
+ await readFile(marker, "utf8");
31
+ } catch (missing) {
32
+ if (missing.code === "ENOENT") return empty();
33
+ throw missing;
34
+ }
35
+ throw new Error(`Assignment result ledger ${file} was lost; restore it before managing workspaces`);
36
+ }
37
+ if (!valid(value)) throw new Error(`Invalid assignment result ledger ${file}`);
38
+ return value;
39
+ }
40
+ async function save(value) {
41
+ if (!file) {
42
+ memory = value;
43
+ return;
44
+ }
45
+ try {
46
+ await mkdir(path.dirname(file), { recursive: true, mode: 448 });
47
+ await writeAtomic(file, JSON.stringify(value) + "\n");
48
+ await writeFile(marker, "1\n", { flag: "wx", mode: 384 }).catch((error) => {
49
+ if (error.code !== "EEXIST") throw error;
50
+ });
51
+ } catch (error) {
52
+ tell(onError, error);
53
+ throw error;
54
+ }
55
+ }
56
+ function serialize(run) {
57
+ const result = queue.then(run);
58
+ queue = result.then(() => {
59
+ }, () => {
60
+ });
61
+ return result;
62
+ }
63
+ async function append(record) {
64
+ if (!archiveDir) {
65
+ archivedInMemory.push(record);
66
+ return;
67
+ }
68
+ try {
69
+ await mkdir(archiveDir, { recursive: true, mode: 448 });
70
+ const handle = await open(path.join(archiveDir, `${record.archivedAt.slice(0, 7)}.jsonl`), "a+", 384);
71
+ try {
72
+ const { size } = await handle.stat();
73
+ const last = Buffer.alloc(1);
74
+ const torn = size > 0 && (await handle.read(last, 0, 1, size - 1)).bytesRead === 1 && last[0] !== 10;
75
+ await handle.appendFile(`${torn ? "\n" : ""}${JSON.stringify(record)}
76
+ `);
77
+ await handle.sync();
78
+ } finally {
79
+ await handle.close();
80
+ }
81
+ } catch (error) {
82
+ tell(onError, error);
83
+ throw error;
84
+ }
85
+ }
86
+ async function archived() {
87
+ if (!archiveDir) return archivedInMemory;
88
+ let names;
89
+ try {
90
+ names = (await readdir(archiveDir)).filter((name) => MONTH.test(name)).sort();
91
+ } catch (error) {
92
+ if (error.code === "ENOENT") return [];
93
+ throw error;
94
+ }
95
+ const records = [];
96
+ for (const name of names) {
97
+ for (const line of (await readFile(path.join(archiveDir, name), "utf8")).split("\n")) {
98
+ try {
99
+ const record = JSON.parse(line);
100
+ if (typeof record?.assignmentId === "string") records.push(record);
101
+ } catch {
102
+ }
103
+ }
104
+ }
105
+ return records;
106
+ }
107
+ async function prune(now) {
108
+ if (!archiveDir) {
109
+ archivedInMemory = archivedInMemory.filter((record) => now - Date.parse(record.archivedAt) < ARCHIVE_KEEP_MS);
110
+ return;
111
+ }
112
+ for (const name of await readdir(archiveDir).catch(() => [])) {
113
+ const month = MONTH.exec(name);
114
+ if (month && now - Date.UTC(Number(month[1]), Number(month[2])) > ARCHIVE_KEEP_MS) await rm(path.join(archiveDir, name), { force: true });
115
+ }
116
+ }
117
+ return {
118
+ register(directory) {
119
+ return serialize(async () => {
120
+ const value = await load(true);
121
+ if (!value.workspaces.includes(directory)) value.workspaces.push(directory);
122
+ await save(value);
123
+ });
124
+ },
125
+ put(entry) {
126
+ return serialize(async () => {
127
+ const value = await load(true);
128
+ value.results = [...value.results.filter((existing) => existing.assignmentId !== entry.assignmentId), entry];
129
+ await save(value);
130
+ });
131
+ },
132
+ remove(assignmentId) {
133
+ return serialize(async () => {
134
+ const value = await load();
135
+ value.results = value.results.filter((entry) => entry.assignmentId !== assignmentId);
136
+ await save(value);
137
+ });
138
+ },
139
+ /**
140
+ * Records how a produced result was handled, then archives every handled entry and drops it from the ledger.
141
+ * The mark is saved first: from then on the guard lets the checkout go, while the ledger still holds the evidence.
142
+ */
143
+ resolve(assignmentId, handled) {
144
+ return serialize(async () => {
145
+ if (!handling(handled)) throw new Error("Invalid result handling");
146
+ const value = await load();
147
+ const entry = value.results.find((owner) => owner.assignmentId === assignmentId);
148
+ if (!entry) throw new Error(`No retained assignment result ${assignmentId}`);
149
+ if (!entry.handled) {
150
+ entry.handled = handled;
151
+ await save(value);
152
+ }
153
+ const now = Date.now();
154
+ const records = [];
155
+ for (const owner of value.results) {
156
+ if (!owner.handled) continue;
157
+ const record = { ...owner, handled: owner.handled, archivedAt: new Date(now).toISOString() };
158
+ await append(record);
159
+ records.push(record);
160
+ }
161
+ value.results = value.results.filter((owner) => !owner.handled);
162
+ await save(value);
163
+ await prune(now).catch(() => {
164
+ });
165
+ return records.find((record) => record.assignmentId === assignmentId);
166
+ });
167
+ },
168
+ /** The newest archived record of an assignment, if its archive month is still kept. */
169
+ archived(assignmentId) {
170
+ return serialize(async () => (await archived()).filter((record) => record.assignmentId === assignmentId).at(-1));
171
+ },
172
+ inspect() {
173
+ return serialize(() => load());
174
+ }
175
+ };
176
+ }
177
+ export {
178
+ ARCHIVE_KEEP_MS,
179
+ RESULT_OUTCOMES,
180
+ createAssignmentResults
181
+ };