@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
@@ -8,7 +8,9 @@ import path from 'node:path';
8
8
  import { createInterface } from 'node:readline';
9
9
  import { commandDecision, unwrapShell, type PermissionProfile } from '@anhlp/alp-core/permissions';
10
10
  import { launchCommand } from '@anhlp/alp-core/providers';
11
+ import { bridgeCommand } from '@anhlp/alp-core/bridges';
11
12
  import { acpText, acpToolDetail, type AcpCall } from './tool-detail.js';
13
+ import { feedAcpSession } from './model-catalog.js';
12
14
 
13
15
  /**
14
16
  * ACP agents (ALPD §46): a generic transport for any agent that speaks the Agent Client
@@ -40,39 +42,6 @@ type RequestHandler = (method: string, params: any) => Promise<unknown>;
40
42
  export type AcpPermission = { kind: string; title: string; command?: string; paths: string[]; alpTool: boolean };
41
43
 
42
44
  /** The MCP server ALP's tools reach an ACP agent through; it speaks MCP on stdio and forwards calls to the socket. */
43
- const BRIDGE = `
44
- const net = require('node:net');
45
- const readline = require('node:readline');
46
- const socket = net.connect(process.env.ALP_BRIDGE_SOCKET);
47
- const waiting = new Map();
48
- let sequence = 0;
49
- let buffer = '';
50
- socket.setEncoding('utf8');
51
- socket.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
52
- socket.on('data', data => {
53
- buffer += data;
54
- for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
55
- const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
56
- try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
57
- }
58
- });
59
- socket.on('close', () => process.exit(0));
60
- socket.on('error', () => process.exit(1));
61
- const ask = message => new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
62
- const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
63
- readline.createInterface({ input: process.stdin }).on('line', async line => {
64
- let message; try { message = JSON.parse(line); } catch { return; }
65
- if (message.id === undefined || message.id === null) return;
66
- try {
67
- 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' } } });
68
- if (message.method === 'ping') return send({ id: message.id, result: {} });
69
- if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
70
- 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 }); }
71
- send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
72
- } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
73
- });
74
- process.stdin.on('end', () => process.exit(0));
75
- `;
76
45
 
77
46
  const READERS = ['read', 'search', 'think', 'fetch'];
78
47
 
@@ -126,7 +95,8 @@ export function acpWhat(request: AcpPermission) {
126
95
  * user passed in OPENCODE_CONFIG_CONTENT, and ALP answers each by the mode.
127
96
  */
128
97
  export function acpEnv(provider: Pick<AcpProvider, 'command' | 'env'>, base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
129
- const env = { ...base, ...provider.env };
98
+ // Provider env never sheds the agent mark (t-ca1f).
99
+ const env: NodeJS.ProcessEnv = { ...base, ...provider.env, ...(base.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: base.ALP_AGENT_SESSION } : {}) };
130
100
  if (provider.command.split(/[\\/]/).pop()!.replace(/\.exe$/i, '').toLowerCase() !== 'opencode') return env;
131
101
  let config: any = {};
132
102
  try { config = JSON.parse(env.OPENCODE_CONFIG_CONTENT ?? '{}') ?? {}; } catch {}
@@ -188,8 +158,8 @@ export class AcpTransport {
188
158
  async initialize() {
189
159
  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`);
190
160
  const env = acpEnv(this.provider, this.env);
191
- const launch = launchCommand(this.provider.command, this.provider.args, env);
192
- const child = spawn(launch.command, launch.args, { cwd: this.cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
161
+ const launch: { command: string; args: string[]; env?: Record<string, string> } = launchCommand(this.provider.command, this.provider.args, env);
162
+ const child = spawn(launch.command, launch.args, { cwd: this.cwd, env: launch.env ? { ...env, ...launch.env } : env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
193
163
  this.child = child;
194
164
  this.exit = new Promise(resolve => { child.once('close', () => resolve()); child.once('error', () => resolve()); });
195
165
  child.stderr.on('data', () => {});
@@ -228,6 +198,8 @@ export class AcpTransport {
228
198
  } else {
229
199
  const result = await this.call('session/new', { cwd: params.cwd, mcpServers }, 120_000);
230
200
  this.sessionId = result.sessionId;
201
+ // The first real session tells the catalog which models this provider offers (t-d0b0).
202
+ feedAcpSession(this.provider.id, result);
231
203
  await this.chooseModel(result.models, result.configOptions);
232
204
  }
233
205
  return { thread: { id: this.sessionId, turns: [] }, cwd: params.cwd, model: params.model, reasoningEffort: params.thinking };
@@ -431,7 +403,8 @@ export class AcpTransport {
431
403
  }
432
404
  // Under Paseo, alpd runs on Electron's binary, which is node only with ELECTRON_RUN_AS_NODE; the agent may not pass its own environment on.
433
405
  const electron = process.versions.electron ? [{ name: 'ELECTRON_RUN_AS_NODE', value: '1' }] : [];
434
- 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] };
406
+ const bridge = bridgeCommand('acp');
407
+ 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] };
435
408
  }
436
409
 
437
410
  private serveBridge(connection: net.Socket, token: string) {
@@ -1,6 +1,6 @@
1
1
  import { spawn, execFile, type ChildProcessWithoutNullStreams } from 'node:child_process';
2
2
  import { randomBytes, randomUUID } from 'node:crypto';
3
- import { rmSync } from 'node:fs';
3
+ import { realpathSync, rmSync } from 'node:fs';
4
4
  import { mkdir, open, readFile, rename, writeFile, unlink } from 'node:fs/promises';
5
5
  import net from 'node:net';
6
6
  import os from 'node:os';
@@ -8,6 +8,7 @@ import path from 'node:path';
8
8
  import { createInterface, type Interface } from 'node:readline';
9
9
  import { openMcpTools } from './mcp-tools.js';
10
10
  import { antigravityToolDetail } from './tool-detail.js';
11
+ import { bridgeCommand, isBridgeArgs } from '@anhlp/alp-core/bridges';
11
12
 
12
13
  /**
13
14
  * Antigravity provider definition for ALP.
@@ -21,48 +22,81 @@ export type AntigravityProvider = {
21
22
  models?: Array<{ id: string; label?: string; description?: string }>;
22
23
  additionalModels?: Array<{ id: string; label?: string; description?: string }>;
23
24
  enabled?: boolean;
24
- /** Explicit opt-in: read-only is a prompt constraint, never a native sandbox. */
25
- readOnlyMode?: 'instructions' | 'reject';
26
25
  };
27
26
 
28
27
  type Listener = (method: string, params: any) => void;
29
28
  type RequestHandler = (method: string, params: any) => Promise<unknown>;
30
29
 
31
30
  /** The MCP server ALP's tools reach an Antigravity agent through via local socket. */
32
- const BRIDGE = `// ALP Antigravity bridge v1
33
-
34
- const net = require('node:net');
35
- const readline = require('node:readline');
36
- const socket = process.env.ALP_BRIDGE_SOCKET ? net.connect(process.env.ALP_BRIDGE_SOCKET) : null;
37
- const waiting = new Map();
38
- let sequence = 0;
39
- let buffer = '';
40
- socket?.setEncoding('utf8');
41
- socket?.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
42
- socket?.on('data', data => {
43
- buffer += data;
44
- for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
45
- const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
46
- try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
47
- }
48
- });
49
- socket?.on('close', () => process.exit(0));
50
- socket?.on('error', () => process.exit(1));
51
- 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'); });
52
- const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
53
- readline.createInterface({ input: process.stdin }).on('line', async line => {
54
- let message; try { message = JSON.parse(line); } catch { return; }
55
- if (message.id === undefined || message.id === null) return;
56
- try {
57
- 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' } } });
58
- if (message.method === 'ping') return send({ id: message.id, result: {} });
59
- if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
60
- 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 }); }
61
- send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
62
- } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
63
- });
64
- process.stdin.on('end', () => process.exit(0));
65
- `;
31
+
32
+ const MODES = ['read-only', 'workspace-write', 'full-access'];
33
+ /**
34
+ * Commands read-only allows. agy matches an allow rule by command prefix and denies
35
+ * redirection, chaining and substitution itself (checked with agy 1.4.10), so each
36
+ * entry must have no flag that writes: git is left out (`git log --output`, and
37
+ * `git status` refreshes the index), as are rg (`--pre`) and find (`-delete`).
38
+ * A prefix rule cannot check a path or a flag, so no command that reads file contents
39
+ * is allowed: cat, head, grep and wc read files outside the workspace, and tail -f or a
40
+ * read of a FIFO hangs the turn. ls is left out too: a prefix rule cannot keep its path
41
+ * argument inside the workspace (`ls /`, `ls ~/.ssh`). agy's own file reading, listing and
42
+ * search tools remain.
43
+ */
44
+ const READ_ONLY_COMMANDS = ['pwd'];
45
+ /** Shell syntax that makes a command line more than one allowed command. */
46
+ const SHELL_SYNTAX = /[;&|<>`$(){}\\\n\r]/;
47
+ /**
48
+ * Whether read-only allows a terminal command line, by ALP's own reading of the allowlist:
49
+ * one allowed command with no shell syntax. Unknown input is refused.
50
+ */
51
+ export function antigravityReadOnlyCommandAllowed(commandLine: unknown): boolean {
52
+ if (typeof commandLine !== 'string' || SHELL_SYNTAX.test(commandLine)) return false;
53
+ const [command] = commandLine.trim().split(/\s+/);
54
+ return READ_ONLY_COMMANDS.includes(command);
55
+ }
56
+ const COMMAND_TOOLS = new Set(['run_command']);
57
+ /** agy's file-editing tools, which read-only always denies. */
58
+ const EDIT_TOOLS = new Set(['write_file', 'write_to_file', 'replace_file_content', 'multi_replace_file_content', 'sed_file', 'notebook_edit']);
59
+ const modeOf = (sandbox: unknown) => sandbox === 'danger-full-access' ? 'full-access' : String(sandbox);
60
+
61
+ /**
62
+ * The agy flags for an ALP mode. Headless agy cannot ask the user, so a tool its
63
+ * permission mode does not allow is denied: both limited modes fail closed.
64
+ * - read-only: agy's default request-review policy; built-in reads and search run,
65
+ * READ_ONLY_COMMANDS run; edits and every other command are denied.
66
+ * - workspace-write: edits accepted and commands run in agy's terminal sandbox,
67
+ * which keeps writes in the workspace; a bypass of the sandbox is denied.
68
+ * - full-access: every tool runs without asking.
69
+ * Both limited modes trust the working directory (otherwise agy denies even its
70
+ * reads and edits there) and allow ALP's own MCP server, which carries alp_*.
71
+ */
72
+ export function antigravityModeArgs(sandbox: unknown, cwd: string): string[] {
73
+ const mode = modeOf(sandbox);
74
+ if (mode === 'full-access') return ['--dangerously-skip-permissions'];
75
+ if (!MODES.includes(mode)) throw new Error(`Antigravity does not support mode '${String(sandbox)}'`);
76
+ let real = cwd;
77
+ try { real = realpathSync(cwd); } catch {}
78
+ const settings = {
79
+ toolPermission: mode === 'workspace-write' ? 'proceed-in-sandbox' : 'request-review',
80
+ enableTerminalSandbox: true,
81
+ trustedWorkspaces: [...new Set([cwd, real])],
82
+ permissions: { allow: ['mcp(alp/*)', ...(mode === 'read-only' ? READ_ONLY_COMMANDS.map(command => `command(${command})`) : [])] },
83
+ };
84
+ return [...(mode === 'workspace-write' ? ['--mode', 'accept-edits'] : []), '--sandbox', '--settings', JSON.stringify(settings)];
85
+ }
86
+
87
+ /** Efforts `agy --effort` takes (agy --help: low|medium|high|xhigh|max); others leave agy's default. */
88
+ export const AGY_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
89
+ export function antigravityEffortArgs(thinking: unknown): string[] {
90
+ return typeof thinking === 'string' && AGY_EFFORTS.includes(thinking) ? ['--effort', thinking] : [];
91
+ }
92
+
93
+ /** What each mode lets an Antigravity agent do, for its instructions. */
94
+ export function antigravityModeText(sandbox: unknown): string {
95
+ const mode = modeOf(sandbox);
96
+ 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.';
97
+ 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.';
98
+ return 'Antigravity runs with full access: every tool runs without asking.';
99
+ }
66
100
 
67
101
  export function encodePrompt(text: string): string {
68
102
  return `${JSON.stringify({ event: 'user', message: { content: text } })}\n`;
@@ -88,6 +122,7 @@ export class AntigravityTransport {
88
122
  private messageText = new Map<string, string>();
89
123
  private messages = 0;
90
124
  private instructionsSent = false;
125
+ private modeNote?: string;
91
126
  private tools: Array<{ name: string; description: string; inputSchema?: unknown }> = [];
92
127
  private bridge?: { server: net.Server; socket: string; token: string; connections: Set<net.Socket> };
93
128
  private readyPromise?: Promise<void>;
@@ -128,7 +163,7 @@ export class AntigravityTransport {
128
163
  if (this.closed) throw new Error('Runtime is closed');
129
164
 
130
165
  if (method === 'thread/start' || method === 'thread/resume') {
131
- if (params.sandbox !== 'full-access' && params.sandbox !== 'danger-full-access') throw new Error('Antigravity currently supports only full-access');
166
+ antigravityModeArgs(params.sandbox, params.cwd || this.cwd);
132
167
  this.config = params;
133
168
  this.tools = params.dynamicTools ?? [];
134
169
 
@@ -166,6 +201,10 @@ export class AntigravityTransport {
166
201
  .map((part: any) => part.text);
167
202
  let promptText = parts.join('\n\n');
168
203
 
204
+ if (this.modeNote) {
205
+ promptText = `${this.modeNote}\n\n${promptText}`;
206
+ this.modeNote = undefined;
207
+ }
169
208
  if (!this.instructionsSent && this.config?.developerInstructions) {
170
209
  promptText = `Instructions from ALP, which runs you. Follow them for this whole session.\n\n${this.config.developerInstructions}\n\n${promptText}`;
171
210
  this.instructionsSent = true;
@@ -189,26 +228,21 @@ export class AntigravityTransport {
189
228
  if (method === 'turn/interrupt') {
190
229
  if (this.child && this.activeTurn) {
191
230
  const turnId = this.activeTurn;
192
- const child = this.child;
193
- // agy exits on SIGINT. Ignore that expected exit, then resume its
194
- // conversation in a fresh process when the next prompt arrives.
195
- this.child = undefined;
196
- this.lines?.close();
197
- const kill = (signal: NodeJS.Signals) => {
198
- if (process.platform !== 'win32' && child.pid) {
199
- try { process.kill(-child.pid, signal); } catch { child.kill(signal); }
200
- } else child.kill(signal);
201
- };
202
- kill('SIGINT');
203
- const timer = setTimeout(() => kill('SIGKILL'), 1500);
204
- try { await this.exit; } finally { clearTimeout(timer); }
231
+ await this.stopProcess();
205
232
  this.endTurn(turnId, 'interrupted');
206
233
  }
207
234
  return {};
208
235
  }
209
236
 
210
237
  if (method === 'session/configure' || method === 'thread/delete') {
211
- if (method === 'session/configure' && params.sandbox && params.sandbox !== 'full-access') throw new Error('Antigravity currently supports only full-access');
238
+ if (method === 'session/configure' && params.sandbox && this.config && modeOf(params.sandbox) !== modeOf(this.config.sandbox)) {
239
+ antigravityModeArgs(params.sandbox, this.config.cwd || this.cwd);
240
+ if (this.activeTurn) throw new Error('Antigravity changes mode between turns only');
241
+ // agy takes its mode at launch: the next turn resumes the conversation in a process with the new one.
242
+ this.config = { ...this.config, sandbox: params.sandbox };
243
+ this.modeNote = `ALP changed your permission mode to ${modeOf(params.sandbox)}. ${antigravityModeText(params.sandbox)}`;
244
+ await this.stopProcess();
245
+ }
212
246
  return {};
213
247
  }
214
248
 
@@ -231,12 +265,13 @@ export class AntigravityTransport {
231
265
  '--add-dir',
232
266
  params.cwd || this.cwd,
233
267
  '--disable-slash-commands',
234
- '--dangerously-skip-permissions',
268
+ ...antigravityModeArgs(params.sandbox, params.cwd || this.cwd),
235
269
  ];
236
270
 
237
271
  if (params.model) {
238
272
  args.push('--model', params.model);
239
273
  }
274
+ args.push(...antigravityEffortArgs(params.thinking));
240
275
 
241
276
  if (params.threadId) {
242
277
  args.push('--conversation', params.threadId);
@@ -246,6 +281,8 @@ export class AntigravityTransport {
246
281
  ...this.env,
247
282
  ...(this.provider?.env ?? {}),
248
283
  ...(params.env ?? {}),
284
+ // Provider or session env never sheds the agent mark (t-ca1f).
285
+ ...(this.env.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: this.env.ALP_AGENT_SESSION } : {}),
249
286
  // Session credentials are inherited by this agy's MCP child only, never persisted.
250
287
  ALP_BRIDGE_SOCKET: this.bridge?.socket ?? '',
251
288
  ALP_BRIDGE_TOKEN: this.bridge?.token ?? '',
@@ -403,6 +440,12 @@ export class AntigravityTransport {
403
440
  },
404
441
  });
405
442
  } else if (step.state === 'DONE' || step.state === 'ERROR') {
443
+ // agy 1.4.10 sometimes marks a tool step it denied DONE, with no error and nothing run. ALP's own
444
+ // record is authoritative: read-only denies every edit and every command outside its allowlist,
445
+ // so never report one as done, whatever agy says.
446
+ if (step.state === 'DONE' && modeOf(this.config?.sandbox) === 'read-only' && this.readOnlyRefuses(toolName, step.tool_info)) {
447
+ step = { ...step, state: 'ERROR', tool_info: { ...step.tool_info, output: undefined, error: { message: `Antigravity denied ${typed.tool} in read-only mode` } } };
448
+ }
406
449
  const output = typeof step.tool_info?.output === 'string'
407
450
  ? step.tool_info.output
408
451
  : step.tool_info?.error?.message || '';
@@ -424,6 +467,14 @@ export class AntigravityTransport {
424
467
  }
425
468
  }
426
469
 
470
+ /** Whether read-only refuses this tool step: an edit, or a terminal command outside the allowlist. */
471
+ private readOnlyRefuses(toolName: string, info: any): boolean {
472
+ const name = typeof info?.name === 'string' && info.name ? info.name : toolName;
473
+ if (EDIT_TOOLS.has(toolName) || EDIT_TOOLS.has(name)) return true;
474
+ if (COMMAND_TOOLS.has(toolName) || COMMAND_TOOLS.has(name)) return !antigravityReadOnlyCommandAllowed(info?.parameters?.CommandLine);
475
+ return false;
476
+ }
477
+
427
478
  private handleResult(result: any): void {
428
479
  if (!this.activeTurn) return;
429
480
  const turnId = this.activeTurn;
@@ -433,6 +484,12 @@ export class AntigravityTransport {
433
484
  const isInterrupted = result.error === 'interrupted';
434
485
  this.endTurn(turnId, isInterrupted ? 'interrupted' : 'failed', result.error);
435
486
  } else {
487
+ // Headless agy cannot ask, so it denies a tool the mode does not allow and ends the turn, often with no answer: say so.
488
+ const denied = Array.isArray(result.denied_actions) ? result.denied_actions.map((action: any) => String(action?.display_name || action?.action || '')).filter(Boolean) : [];
489
+ if (denied.length) {
490
+ const text = `Antigravity denied ${[...new Set(denied)].join(', ')} in ${modeOf(this.config?.sandbox)} mode and ended the turn.`;
491
+ this.emit('item/completed', { threadId: this.conversationId, item: { type: 'agentMessage', id: `agy-denied-${turnId}`, text } });
492
+ }
436
493
  this.endTurn(turnId, 'completed');
437
494
  }
438
495
  }
@@ -509,10 +566,10 @@ export class AntigravityTransport {
509
566
  }
510
567
  config.mcpServers ??= {};
511
568
  const existing = config.mcpServers.alp;
512
- if (existing && !existing.args?.some((arg: unknown) => typeof arg === 'string' && arg.startsWith('// ALP Antigravity bridge v1'))) {
569
+ if (existing && !isBridgeArgs('antigravity', existing.args, existing.command)) {
513
570
  throw new Error('Antigravity already has an MCP server named alp; rename it before using ALP');
514
571
  }
515
- const launcher = { command: process.execPath, args: ['-e', BRIDGE], ...(process.versions.electron ? { env: { ELECTRON_RUN_AS_NODE: '1' } } : {}) };
572
+ const launcher = { ...bridgeCommand('antigravity'), ...(process.versions.electron ? { env: { ELECTRON_RUN_AS_NODE: '1' } } : {}) };
516
573
  if (JSON.stringify(existing) === JSON.stringify(launcher)) return;
517
574
  config.mcpServers.alp = launcher;
518
575
  await writeFile(temporary, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
@@ -612,6 +669,22 @@ export class AntigravityTransport {
612
669
  for (const listener of this.listeners) listener(method, params);
613
670
  }
614
671
 
672
+ /** agy exits on SIGINT. Ignore that expected exit; the next prompt resumes its conversation in a fresh process. */
673
+ private async stopProcess(): Promise<void> {
674
+ const child = this.child;
675
+ if (!child) return;
676
+ this.child = undefined;
677
+ this.lines?.close();
678
+ const kill = (signal: NodeJS.Signals) => {
679
+ if (process.platform !== 'win32' && child.pid) {
680
+ try { process.kill(-child.pid, signal); } catch { child.kill(signal); }
681
+ } else child.kill(signal);
682
+ };
683
+ kill('SIGINT');
684
+ const timer = setTimeout(() => kill('SIGKILL'), 1500);
685
+ try { await this.exit; } finally { clearTimeout(timer); }
686
+ }
687
+
615
688
  private fail(error: Error): void {
616
689
  if (this.closed) return;
617
690
  for (const listener of this.failures) listener(error);
@@ -0,0 +1,154 @@
1
+ import { readFile, readdir, mkdir, writeFile, open, rm } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { writeAtomic } from '@anhlp/alp-core/atomic';
4
+ import { tell } from './write-error.js';
5
+
6
+ /** What a finished writer outside a worktree left in its checkout, kept until its requester handles it (recall entries expire, this does not). */
7
+ export type AssignmentResultEvidence = { agent: string; status: string; finishedAt: string; project: string; requesters: string[]; taskId?: string; brief: string; summary: string };
8
+ export const RESULT_OUTCOMES = ['applied', 'discarded', 'acknowledged'] as const;
9
+ export type AssignmentResultHandling = { outcome: typeof RESULT_OUTCOMES[number]; by: string; at: string; note?: string };
10
+ /** 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. */
11
+ export type AssignmentResultOwner = { assignmentId: string; checkout: string; worktree?: string; result?: AssignmentResultEvidence; handled?: AssignmentResultHandling };
12
+ export type ArchivedAssignmentResult = AssignmentResultOwner & { handled: AssignmentResultHandling; archivedAt: string };
13
+ type Ledger = { version: 1; workspaces: string[]; results: AssignmentResultOwner[] };
14
+ /** Archived results stay this long after the month they were archived in ends; ledger entries never expire. */
15
+ export const ARCHIVE_KEEP_MS = 365 * 24 * 60 * 60 * 1000;
16
+ const empty = (): Ledger => ({ version: 1, workspaces: [], results: [] });
17
+ const absolute = (value: unknown): value is string => typeof value === 'string' && path.isAbsolute(value);
18
+ const text = (value: unknown): value is string => typeof value === 'string';
19
+ const evidence = (value: any) => value === undefined || (!!value && typeof value === 'object' && !Array.isArray(value) &&
20
+ [value.agent, value.status, value.finishedAt, value.project, value.brief, value.summary].every(text) &&
21
+ Array.isArray(value.requesters) && value.requesters.every(text) && (value.taskId === undefined || text(value.taskId)));
22
+ const handling = (value: any) => value === undefined || (!!value && typeof value === 'object' && !Array.isArray(value) &&
23
+ RESULT_OUTCOMES.includes(value.outcome) && text(value.by) && text(value.at) && (value.note === undefined || text(value.note)));
24
+ const valid = (value: any): value is Ledger => value?.version === 1 && Array.isArray(value.workspaces) && value.workspaces.every(absolute) &&
25
+ Array.isArray(value.results) && value.results.every((entry: any) => entry && typeof entry.assignmentId === 'string' && absolute(entry.checkout) && (entry.worktree === undefined || absolute(entry.worktree)) &&
26
+ evidence(entry.result) && handling(entry.handled));
27
+ const MONTH = /^(\d{4})-(\d{2})\.jsonl$/;
28
+
29
+ /**
30
+ * Permanent ownership, independent of native-thread recall expiry. Missing initialized data is never recreated.
31
+ * A failed write still fails its caller; `onError` hears of it too, so a full disk is seen at once.
32
+ */
33
+ export function createAssignmentResults(file?: string, onError: (error: unknown) => void = () => {}) {
34
+ let memory = empty();
35
+ let archivedInMemory: ArchivedAssignmentResult[] = [];
36
+ let queue = Promise.resolve();
37
+ const marker = file ? `${file}.initialized` : undefined;
38
+ // One JSON line per handled result, in a file per month of archiving.
39
+ const archiveDir = file ? path.join(path.dirname(file), 'assignment-archive') : undefined;
40
+ async function load(initialize = false): Promise<Ledger> {
41
+ if (!file) return memory;
42
+ let value: unknown;
43
+ try { value = JSON.parse(await readFile(file, 'utf8')); }
44
+ catch (error) {
45
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || !initialize) throw new Error(`Cannot inspect assignment result ledger ${file}`);
46
+ try { await readFile(marker!, 'utf8'); }
47
+ catch (missing) {
48
+ if ((missing as NodeJS.ErrnoException).code === 'ENOENT') return empty();
49
+ throw missing;
50
+ }
51
+ throw new Error(`Assignment result ledger ${file} was lost; restore it before managing workspaces`);
52
+ }
53
+ if (!valid(value)) throw new Error(`Invalid assignment result ledger ${file}`);
54
+ return value;
55
+ }
56
+ async function save(value: Ledger) {
57
+ if (!file) { memory = value; return; }
58
+ try {
59
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
60
+ await writeAtomic(file, JSON.stringify(value) + '\n');
61
+ // The marker survives a lost ledger; registration must never silently reset ownership.
62
+ await writeFile(marker!, '1\n', { flag: 'wx', mode: 0o600 }).catch(error => { if (error.code !== 'EEXIST') throw error; });
63
+ } catch (error) { tell(onError, error); throw error; }
64
+ }
65
+ function serialize<T>(run: () => Promise<T>): Promise<T> {
66
+ const result = queue.then(run);
67
+ queue = result.then(() => {}, () => {});
68
+ return result;
69
+ }
70
+ /** Appends a record and syncs it before its ledger entry may go; a crash in between archives it again, never loses it. */
71
+ async function append(record: ArchivedAssignmentResult) {
72
+ if (!archiveDir) { archivedInMemory.push(record); return; }
73
+ try {
74
+ await mkdir(archiveDir, { recursive: true, mode: 0o700 });
75
+ const handle = await open(path.join(archiveDir, `${record.archivedAt.slice(0, 7)}.jsonl`), 'a+', 0o600);
76
+ try {
77
+ const { size } = await handle.stat();
78
+ const last = Buffer.alloc(1);
79
+ // A line cut short by a crash must not swallow the next record.
80
+ const torn = size > 0 && (await handle.read(last, 0, 1, size - 1)).bytesRead === 1 && last[0] !== 0x0a;
81
+ await handle.appendFile(`${torn ? '\n' : ''}${JSON.stringify(record)}\n`);
82
+ await handle.sync();
83
+ } finally { await handle.close(); }
84
+ } catch (error) { tell(onError, error); throw error; }
85
+ }
86
+ async function archived(): Promise<ArchivedAssignmentResult[]> {
87
+ if (!archiveDir) return archivedInMemory;
88
+ let names: string[];
89
+ try { names = (await readdir(archiveDir)).filter(name => MONTH.test(name)).sort(); }
90
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
91
+ const records: ArchivedAssignmentResult[] = [];
92
+ for (const name of names) {
93
+ for (const line of (await readFile(path.join(archiveDir, name), 'utf8')).split('\n')) {
94
+ try { const record = JSON.parse(line); if (typeof record?.assignmentId === 'string') records.push(record); } catch {}
95
+ }
96
+ }
97
+ return records;
98
+ }
99
+ /** Deletes the archive months that ended more than ARCHIVE_KEEP_MS ago. */
100
+ async function prune(now: number) {
101
+ if (!archiveDir) { archivedInMemory = archivedInMemory.filter(record => now - Date.parse(record.archivedAt) < ARCHIVE_KEEP_MS); return; }
102
+ for (const name of await readdir(archiveDir).catch(() => [] as string[])) {
103
+ const month = MONTH.exec(name);
104
+ if (month && now - Date.UTC(Number(month[1]), Number(month[2])) > ARCHIVE_KEEP_MS) await rm(path.join(archiveDir, name), { force: true });
105
+ }
106
+ }
107
+ return {
108
+ register(directory: string) { return serialize(async () => {
109
+ const value = await load(true);
110
+ if (!value.workspaces.includes(directory)) value.workspaces.push(directory);
111
+ await save(value);
112
+ }); },
113
+ put(entry: AssignmentResultOwner) { return serialize(async () => {
114
+ // Initial assignment activity can establish the index, but never certify old workspaces.
115
+ const value = await load(true);
116
+ value.results = [...value.results.filter(existing => existing.assignmentId !== entry.assignmentId), entry];
117
+ await save(value);
118
+ }); },
119
+ remove(assignmentId: string) { return serialize(async () => {
120
+ const value = await load();
121
+ value.results = value.results.filter(entry => entry.assignmentId !== assignmentId);
122
+ await save(value);
123
+ }); },
124
+ /**
125
+ * Records how a produced result was handled, then archives every handled entry and drops it from the ledger.
126
+ * The mark is saved first: from then on the guard lets the checkout go, while the ledger still holds the evidence.
127
+ */
128
+ resolve(assignmentId: string, handled: AssignmentResultHandling) { return serialize(async () => {
129
+ if (!handling(handled)) throw new Error('Invalid result handling');
130
+ const value = await load();
131
+ const entry = value.results.find(owner => owner.assignmentId === assignmentId);
132
+ if (!entry) throw new Error(`No retained assignment result ${assignmentId}`);
133
+ if (!entry.handled) {
134
+ entry.handled = handled;
135
+ await save(value);
136
+ }
137
+ const now = Date.now();
138
+ const records: ArchivedAssignmentResult[] = [];
139
+ for (const owner of value.results) {
140
+ if (!owner.handled) continue;
141
+ const record = { ...owner, handled: owner.handled, archivedAt: new Date(now).toISOString() };
142
+ await append(record);
143
+ records.push(record);
144
+ }
145
+ value.results = value.results.filter(owner => !owner.handled);
146
+ await save(value);
147
+ await prune(now).catch(() => {});
148
+ return records.find(record => record.assignmentId === assignmentId)!;
149
+ }); },
150
+ /** The newest archived record of an assignment, if its archive month is still kept. */
151
+ archived(assignmentId: string) { return serialize(async () => (await archived()).filter(record => record.assignmentId === assignmentId).at(-1)); },
152
+ inspect() { return serialize(() => load()); },
153
+ };
154
+ }