@anhlp/alp-runtime 0.0.1-beta.4 → 0.0.1-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/acp-transport.js +5 -36
  2. package/dist/antigravity-transport.d.ts +17 -0
  3. package/dist/antigravity-transport.js +82 -58
  4. package/dist/assignment-results.d.ts +34 -0
  5. package/dist/assignment-results.js +94 -2
  6. package/dist/board-domain.js +2 -2
  7. package/dist/board.d.ts +6 -0
  8. package/dist/board.js +7 -0
  9. package/dist/catalog.d.ts +13 -0
  10. package/dist/catalog.js +9 -1
  11. package/dist/claude-transport.d.ts +7 -0
  12. package/dist/claude-transport.js +65 -6
  13. package/dist/compact.d.ts +29 -0
  14. package/dist/compact.js +49 -0
  15. package/dist/configure.d.ts +1 -1
  16. package/dist/configure.js +2 -2
  17. package/dist/contracts.d.ts +25 -1
  18. package/dist/index.d.ts +9 -2
  19. package/dist/index.js +30 -2
  20. package/dist/input-limits.d.ts +25 -0
  21. package/dist/input-limits.js +48 -0
  22. package/dist/language.d.ts +8 -0
  23. package/dist/language.js +20 -0
  24. package/dist/mcp-tools.d.ts +8 -0
  25. package/dist/mcp-tools.js +26 -0
  26. package/dist/model-catalog.d.ts +76 -0
  27. package/dist/model-catalog.js +193 -0
  28. package/dist/model-probes.d.ts +7 -0
  29. package/dist/model-probes.js +69 -0
  30. package/dist/providers.js +2 -0
  31. package/dist/resolve.d.ts +1 -0
  32. package/dist/resolve.js +3 -1
  33. package/dist/runtime.d.ts +3 -1
  34. package/dist/runtime.js +605 -45
  35. package/dist/session-config.d.ts +174 -0
  36. package/dist/session-config.js +9 -9
  37. package/dist/session-state.d.ts +23 -1
  38. package/dist/tools.d.ts +82 -0
  39. package/dist/tools.js +53 -5
  40. package/dist/transport.js +3 -1
  41. package/dist/workspace.d.ts +11 -4
  42. package/dist/workspace.js +29 -11
  43. package/package.json +3 -3
  44. package/src/acp-transport.ts +7 -37
  45. package/src/antigravity-transport.ts +95 -53
  46. package/src/assignment-results.ts +85 -3
  47. package/src/board-domain.ts +2 -2
  48. package/src/board.ts +7 -0
  49. package/src/catalog.ts +10 -1
  50. package/src/claude-transport.ts +71 -6
  51. package/src/compact.ts +62 -0
  52. package/src/configure.ts +3 -3
  53. package/src/contracts.ts +22 -1
  54. package/src/index.ts +9 -2
  55. package/src/input-limits.ts +65 -0
  56. package/src/language.ts +18 -0
  57. package/src/mcp-tools.ts +33 -0
  58. package/src/model-catalog.ts +166 -0
  59. package/src/model-probes.ts +58 -0
  60. package/src/providers.ts +3 -0
  61. package/src/resolve.ts +4 -2
  62. package/src/runtime.ts +650 -46
  63. package/src/session-config.ts +8 -8
  64. package/src/session-state.ts +15 -1
  65. package/src/tools.ts +53 -5
  66. package/src/transport.ts +3 -1
  67. package/src/workspace.ts +42 -15
@@ -39,10 +39,14 @@ export declare function createWorktree(workdir: string, root: string, id: string
39
39
  commit: string;
40
40
  }): Promise<Worktree>;
41
41
  /**
42
- * Checks out an assignment's existing branch again at its worktree's place, after
43
- * reclaimWorktrees committed and removed it, so the assignment continues there.
42
+ * Continues an assignment in its worktree after a restart. A worktree that is still valid
43
+ * is reused as is, whatever it holds. A directory left without valid git metadata (a crash
44
+ * mid-write) is never deleted: it moves aside to `preserved` and the branch is checked out
45
+ * again at its place.
44
46
  */
45
- export declare function reattachWorktree(worktree: Worktree): Promise<Worktree>;
47
+ export declare function reattachWorktree(worktree: Worktree): Promise<Worktree & {
48
+ preserved?: string;
49
+ }>;
46
50
  /** A digest of a checkout's state: HEAD, its uncommitted changes, and the names of untracked files. */
47
51
  export declare function checkoutFingerprint(checkout: string): Promise<string | undefined>;
48
52
  /**
@@ -79,7 +83,10 @@ export declare function removeWorktree(worktree: Worktree, { deleteBranch }?: {
79
83
  }): Promise<void>;
80
84
  /**
81
85
  * After a crash: commits work left in worktrees under `root` to their branches and
82
- * removes the directories. Returns the branches that were kept.
86
+ * removes the directories. Returns the branches that were kept. A directory is removed
87
+ * only once everything in it is committed to its own `alp/<name>` branch; any other one
88
+ * (invalid git metadata, a failed commit, another branch checked out, a detached HEAD)
89
+ * stays untouched, so recovery reuses or preserves it and nothing uncommitted is lost.
83
90
  */
84
91
  export declare function reclaimWorktrees(root: string): Promise<string[]>;
85
92
  /**
package/dist/workspace.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // packages/runtime/src/workspace.ts
2
2
  import { spawn } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
- import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
4
+ import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  var IDENTITY = ["-c", "user.name=ALP", "-c", "user.email=alp@localhost", "-c", "commit.gpgsign=false"];
@@ -103,13 +103,29 @@ async function createWorktree(workdir, root, id, from) {
103
103
  const relative = path.relative(checkout, await realpath(workdir));
104
104
  return { checkout, path: target, workdir: path.join(target, relative), branch, base, ...fingerprint ? { fingerprint } : {} };
105
105
  }
106
+ async function validWorktree(directory) {
107
+ const top = await git(directory, ["rev-parse", "--show-toplevel"]).catch(() => void 0);
108
+ if (top?.code !== 0) return false;
109
+ const [a, b] = await Promise.all([realpath(top.stdout.trim()).catch(() => ""), realpath(directory).catch(() => directory)]);
110
+ return a === b && (await git(directory, ["status", "--porcelain"])).code === 0;
111
+ }
106
112
  async function reattachWorktree(worktree) {
113
+ const exists = !!await stat(worktree.path).catch(() => void 0);
114
+ if (exists && await validWorktree(worktree.path)) {
115
+ const gitdir = await git(worktree.path, ["rev-parse", "--absolute-git-dir"]);
116
+ if (gitdir.code === 0) await rm(path.join(gitdir.stdout.trim(), "index.lock"), { force: true });
117
+ return worktree;
118
+ }
107
119
  if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
108
- if (await stat(worktree.path).catch(() => void 0)) return worktree;
120
+ let preserved;
121
+ if (exists) {
122
+ preserved = `${worktree.path}.preserved-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
123
+ await rename(worktree.path, preserved);
124
+ }
109
125
  await mkdir(path.dirname(worktree.path), { recursive: true, mode: 448 });
110
126
  await git(worktree.checkout, ["worktree", "prune"]);
111
127
  await checked(worktree.checkout, ["worktree", "add", "--quiet", worktree.path, worktree.branch]);
112
- return worktree;
128
+ return preserved ? { ...worktree, preserved } : worktree;
113
129
  }
114
130
  async function checkoutFingerprint(checkout) {
115
131
  const head = await git(checkout, ["rev-parse", "--verify", "HEAD"]);
@@ -181,17 +197,19 @@ async function reclaimWorktrees(root) {
181
197
  for (const name of entries) {
182
198
  const target = path.join(root, name);
183
199
  if (!(await stat(target).catch(() => void 0))?.isDirectory()) continue;
184
- const common = await git(target, ["rev-parse", "--path-format=absolute", "--git-common-dir"]).catch(() => void 0);
185
- if (common?.code !== 0) {
186
- await rm(target, { recursive: true, force: true });
187
- continue;
188
- }
200
+ if (!await validWorktree(target)) continue;
201
+ const common = await git(target, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
202
+ if (common.code !== 0) continue;
189
203
  const checkout = path.dirname(common.stdout.trim());
190
- const branch = (await git(target, ["rev-parse", "--abbrev-ref", "HEAD"])).stdout.trim();
191
- await git(target, ["add", "-A"]);
204
+ const ref = await git(target, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
205
+ const branch = ref.stdout.trim();
206
+ if (ref.code !== 0 || branch !== `alp/${name}`) continue;
207
+ if ((await git(target, ["add", "-A"])).code !== 0) continue;
192
208
  if ((await git(target, ["diff", "--cached", "--quiet"])).code === 1) {
193
- await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"]);
209
+ if ((await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"])).code !== 0) continue;
194
210
  }
211
+ const status = await git(target, ["status", "--porcelain", "--ignored=no"]);
212
+ if (status.code !== 0 || status.stdout.trim()) continue;
195
213
  await removeWorktree({ checkout, path: target, workdir: target, branch, base: "" });
196
214
  kept.push(branch);
197
215
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-runtime",
3
- "version": "0.0.1-beta.4",
3
+ "version": "0.0.1-beta.5",
4
4
  "type": "module",
5
5
  "description": "ALP runtime module",
6
6
  "files": [
@@ -230,8 +230,8 @@
230
230
  "node": ">=22.12"
231
231
  },
232
232
  "dependencies": {
233
- "@anhlp/alp-core": "0.0.1-beta.4",
234
- "@anhlp/alp-protocol": "0.0.1-beta.4",
233
+ "@anhlp/alp-core": "0.0.1-beta.5",
234
+ "@anhlp/alp-protocol": "0.0.1-beta.5",
235
235
  "@anthropic-ai/claude-agent-sdk": "^0.3.292",
236
236
  "@modelcontextprotocol/sdk": "^1.32.1",
237
237
  "@agentclientprotocol/sdk": "1.7.0",
@@ -8,6 +8,7 @@ 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';
12
13
 
13
14
  /**
@@ -40,39 +41,6 @@ type RequestHandler = (method: string, params: any) => Promise<unknown>;
40
41
  export type AcpPermission = { kind: string; title: string; command?: string; paths: string[]; alpTool: boolean };
41
42
 
42
43
  /** 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
44
 
77
45
  const READERS = ['read', 'search', 'think', 'fetch'];
78
46
 
@@ -126,7 +94,8 @@ export function acpWhat(request: AcpPermission) {
126
94
  * user passed in OPENCODE_CONFIG_CONTENT, and ALP answers each by the mode.
127
95
  */
128
96
  export function acpEnv(provider: Pick<AcpProvider, 'command' | 'env'>, base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
129
- const env = { ...base, ...provider.env };
97
+ // Provider env never sheds the agent mark (t-ca1f).
98
+ const env: NodeJS.ProcessEnv = { ...base, ...provider.env, ...(base.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: base.ALP_AGENT_SESSION } : {}) };
130
99
  if (provider.command.split(/[\\/]/).pop()!.replace(/\.exe$/i, '').toLowerCase() !== 'opencode') return env;
131
100
  let config: any = {};
132
101
  try { config = JSON.parse(env.OPENCODE_CONFIG_CONTENT ?? '{}') ?? {}; } catch {}
@@ -188,8 +157,8 @@ export class AcpTransport {
188
157
  async initialize() {
189
158
  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
159
  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'] });
160
+ const launch: { command: string; args: string[]; env?: Record<string, string> } = launchCommand(this.provider.command, this.provider.args, env);
161
+ const child = spawn(launch.command, launch.args, { cwd: this.cwd, env: launch.env ? { ...env, ...launch.env } : env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
193
162
  this.child = child;
194
163
  this.exit = new Promise(resolve => { child.once('close', () => resolve()); child.once('error', () => resolve()); });
195
164
  child.stderr.on('data', () => {});
@@ -431,7 +400,8 @@ export class AcpTransport {
431
400
  }
432
401
  // 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
402
  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] };
403
+ const bridge = bridgeCommand('acp');
404
+ 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
405
  }
436
406
 
437
407
  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.
@@ -29,40 +30,52 @@ type Listener = (method: string, params: any) => void;
29
30
  type RequestHandler = (method: string, params: any) => Promise<unknown>;
30
31
 
31
32
  /** 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
- `;
33
+
34
+ const MODES = ['read-only', 'workspace-write', 'full-access'];
35
+ /**
36
+ * Commands read-only allows. agy matches an allow rule by command prefix and denies
37
+ * redirection, chaining and substitution itself (checked with agy 1.4.10), so each
38
+ * entry must have no flag that writes: git is left out (`git log --output`, and
39
+ * `git status` refreshes the index), as are rg (`--pre`) and find (`-delete`).
40
+ */
41
+ const READ_ONLY_COMMANDS = ['pwd', 'ls', 'cat', 'head', 'tail', 'wc', 'grep'];
42
+ /** agy's file-editing tools, which read-only always denies. */
43
+ const EDIT_TOOLS = new Set(['write_file', 'write_to_file', 'replace_file_content', 'multi_replace_file_content', 'sed_file', 'notebook_edit']);
44
+ const modeOf = (sandbox: unknown) => sandbox === 'danger-full-access' ? 'full-access' : String(sandbox);
45
+
46
+ /**
47
+ * The agy flags for an ALP mode. Headless agy cannot ask the user, so a tool its
48
+ * permission mode does not allow is denied: both limited modes fail closed.
49
+ * - read-only: agy's default request-review policy; built-in reads and search run,
50
+ * READ_ONLY_COMMANDS run; edits and every other command are denied.
51
+ * - workspace-write: edits accepted and commands run in agy's terminal sandbox,
52
+ * which keeps writes in the workspace; a bypass of the sandbox is denied.
53
+ * - full-access: every tool runs without asking.
54
+ * Both limited modes trust the working directory (otherwise agy denies even its
55
+ * reads and edits there) and allow ALP's own MCP server, which carries alp_*.
56
+ */
57
+ export function antigravityModeArgs(sandbox: unknown, cwd: string): string[] {
58
+ const mode = modeOf(sandbox);
59
+ if (mode === 'full-access') return ['--dangerously-skip-permissions'];
60
+ if (!MODES.includes(mode)) throw new Error(`Antigravity does not support mode '${String(sandbox)}'`);
61
+ let real = cwd;
62
+ try { real = realpathSync(cwd); } catch {}
63
+ const settings = {
64
+ toolPermission: mode === 'workspace-write' ? 'proceed-in-sandbox' : 'request-review',
65
+ enableTerminalSandbox: true,
66
+ trustedWorkspaces: [...new Set([cwd, real])],
67
+ permissions: { allow: ['mcp(alp/*)', ...(mode === 'read-only' ? READ_ONLY_COMMANDS.map(command => `command(${command})`) : [])] },
68
+ };
69
+ return [...(mode === 'workspace-write' ? ['--mode', 'accept-edits'] : []), '--sandbox', '--settings', JSON.stringify(settings)];
70
+ }
71
+
72
+ /** What each mode lets an Antigravity agent do, for its instructions. */
73
+ export function antigravityModeText(sandbox: unknown): string {
74
+ const mode = modeOf(sandbox);
75
+ 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.';
76
+ 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.';
77
+ return 'Antigravity runs with full access: every tool runs without asking.';
78
+ }
66
79
 
67
80
  export function encodePrompt(text: string): string {
68
81
  return `${JSON.stringify({ event: 'user', message: { content: text } })}\n`;
@@ -88,6 +101,7 @@ export class AntigravityTransport {
88
101
  private messageText = new Map<string, string>();
89
102
  private messages = 0;
90
103
  private instructionsSent = false;
104
+ private modeNote?: string;
91
105
  private tools: Array<{ name: string; description: string; inputSchema?: unknown }> = [];
92
106
  private bridge?: { server: net.Server; socket: string; token: string; connections: Set<net.Socket> };
93
107
  private readyPromise?: Promise<void>;
@@ -128,7 +142,7 @@ export class AntigravityTransport {
128
142
  if (this.closed) throw new Error('Runtime is closed');
129
143
 
130
144
  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');
145
+ antigravityModeArgs(params.sandbox, params.cwd || this.cwd);
132
146
  this.config = params;
133
147
  this.tools = params.dynamicTools ?? [];
134
148
 
@@ -166,6 +180,10 @@ export class AntigravityTransport {
166
180
  .map((part: any) => part.text);
167
181
  let promptText = parts.join('\n\n');
168
182
 
183
+ if (this.modeNote) {
184
+ promptText = `${this.modeNote}\n\n${promptText}`;
185
+ this.modeNote = undefined;
186
+ }
169
187
  if (!this.instructionsSent && this.config?.developerInstructions) {
170
188
  promptText = `Instructions from ALP, which runs you. Follow them for this whole session.\n\n${this.config.developerInstructions}\n\n${promptText}`;
171
189
  this.instructionsSent = true;
@@ -189,26 +207,21 @@ export class AntigravityTransport {
189
207
  if (method === 'turn/interrupt') {
190
208
  if (this.child && this.activeTurn) {
191
209
  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); }
210
+ await this.stopProcess();
205
211
  this.endTurn(turnId, 'interrupted');
206
212
  }
207
213
  return {};
208
214
  }
209
215
 
210
216
  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');
217
+ if (method === 'session/configure' && params.sandbox && this.config && modeOf(params.sandbox) !== modeOf(this.config.sandbox)) {
218
+ antigravityModeArgs(params.sandbox, this.config.cwd || this.cwd);
219
+ if (this.activeTurn) throw new Error('Antigravity changes mode between turns only');
220
+ // agy takes its mode at launch: the next turn resumes the conversation in a process with the new one.
221
+ this.config = { ...this.config, sandbox: params.sandbox };
222
+ this.modeNote = `ALP changed your permission mode to ${modeOf(params.sandbox)}. ${antigravityModeText(params.sandbox)}`;
223
+ await this.stopProcess();
224
+ }
212
225
  return {};
213
226
  }
214
227
 
@@ -231,7 +244,7 @@ export class AntigravityTransport {
231
244
  '--add-dir',
232
245
  params.cwd || this.cwd,
233
246
  '--disable-slash-commands',
234
- '--dangerously-skip-permissions',
247
+ ...antigravityModeArgs(params.sandbox, params.cwd || this.cwd),
235
248
  ];
236
249
 
237
250
  if (params.model) {
@@ -246,6 +259,8 @@ export class AntigravityTransport {
246
259
  ...this.env,
247
260
  ...(this.provider?.env ?? {}),
248
261
  ...(params.env ?? {}),
262
+ // Provider or session env never sheds the agent mark (t-ca1f).
263
+ ...(this.env.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: this.env.ALP_AGENT_SESSION } : {}),
249
264
  // Session credentials are inherited by this agy's MCP child only, never persisted.
250
265
  ALP_BRIDGE_SOCKET: this.bridge?.socket ?? '',
251
266
  ALP_BRIDGE_TOKEN: this.bridge?.token ?? '',
@@ -403,6 +418,11 @@ export class AntigravityTransport {
403
418
  },
404
419
  });
405
420
  } else if (step.state === 'DONE' || step.state === 'ERROR') {
421
+ // agy 1.4.10 sometimes marks a write_file it denied DONE, with no error and no file written:
422
+ // read-only denies every edit, so never report one as done.
423
+ if (step.state === 'DONE' && modeOf(this.config?.sandbox) === 'read-only' && (EDIT_TOOLS.has(toolName) || EDIT_TOOLS.has(step.tool_info?.name))) {
424
+ step = { ...step, state: 'ERROR', tool_info: { ...step.tool_info, output: undefined, error: { message: `Antigravity denied ${toolName} in read-only mode` } } };
425
+ }
406
426
  const output = typeof step.tool_info?.output === 'string'
407
427
  ? step.tool_info.output
408
428
  : step.tool_info?.error?.message || '';
@@ -433,6 +453,12 @@ export class AntigravityTransport {
433
453
  const isInterrupted = result.error === 'interrupted';
434
454
  this.endTurn(turnId, isInterrupted ? 'interrupted' : 'failed', result.error);
435
455
  } else {
456
+ // Headless agy cannot ask, so it denies a tool the mode does not allow and ends the turn, often with no answer: say so.
457
+ const denied = Array.isArray(result.denied_actions) ? result.denied_actions.map((action: any) => String(action?.display_name || action?.action || '')).filter(Boolean) : [];
458
+ if (denied.length) {
459
+ const text = `Antigravity denied ${[...new Set(denied)].join(', ')} in ${modeOf(this.config?.sandbox)} mode and ended the turn.`;
460
+ this.emit('item/completed', { threadId: this.conversationId, item: { type: 'agentMessage', id: `agy-denied-${turnId}`, text } });
461
+ }
436
462
  this.endTurn(turnId, 'completed');
437
463
  }
438
464
  }
@@ -509,10 +535,10 @@ export class AntigravityTransport {
509
535
  }
510
536
  config.mcpServers ??= {};
511
537
  const existing = config.mcpServers.alp;
512
- if (existing && !existing.args?.some((arg: unknown) => typeof arg === 'string' && arg.startsWith('// ALP Antigravity bridge v1'))) {
538
+ if (existing && !isBridgeArgs('antigravity', existing.args, existing.command)) {
513
539
  throw new Error('Antigravity already has an MCP server named alp; rename it before using ALP');
514
540
  }
515
- const launcher = { command: process.execPath, args: ['-e', BRIDGE], ...(process.versions.electron ? { env: { ELECTRON_RUN_AS_NODE: '1' } } : {}) };
541
+ const launcher = { ...bridgeCommand('antigravity'), ...(process.versions.electron ? { env: { ELECTRON_RUN_AS_NODE: '1' } } : {}) };
516
542
  if (JSON.stringify(existing) === JSON.stringify(launcher)) return;
517
543
  config.mcpServers.alp = launcher;
518
544
  await writeFile(temporary, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
@@ -612,6 +638,22 @@ export class AntigravityTransport {
612
638
  for (const listener of this.listeners) listener(method, params);
613
639
  }
614
640
 
641
+ /** agy exits on SIGINT. Ignore that expected exit; the next prompt resumes its conversation in a fresh process. */
642
+ private async stopProcess(): Promise<void> {
643
+ const child = this.child;
644
+ if (!child) return;
645
+ this.child = undefined;
646
+ this.lines?.close();
647
+ const kill = (signal: NodeJS.Signals) => {
648
+ if (process.platform !== 'win32' && child.pid) {
649
+ try { process.kill(-child.pid, signal); } catch { child.kill(signal); }
650
+ } else child.kill(signal);
651
+ };
652
+ kill('SIGINT');
653
+ const timer = setTimeout(() => kill('SIGKILL'), 1500);
654
+ try { await this.exit; } finally { clearTimeout(timer); }
655
+ }
656
+
615
657
  private fail(error: Error): void {
616
658
  if (this.closed) return;
617
659
  for (const listener of this.failures) listener(error);
@@ -1,19 +1,38 @@
1
- import { readFile, mkdir, writeFile } from 'node:fs/promises';
1
+ import { readFile, readdir, mkdir, writeFile, open, rm } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { writeAtomic } from '@anhlp/alp-core/atomic';
4
4
 
5
- export type AssignmentResultOwner = { assignmentId: string; checkout: string; worktree?: string };
5
+ /** What a finished writer outside a worktree left in its checkout, kept until its requester handles it (recall entries expire, this does not). */
6
+ export type AssignmentResultEvidence = { agent: string; status: string; finishedAt: string; project: string; requesters: string[]; taskId?: string; brief: string; summary: string };
7
+ export const RESULT_OUTCOMES = ['applied', 'discarded', 'acknowledged'] as const;
8
+ export type AssignmentResultHandling = { outcome: typeof RESULT_OUTCOMES[number]; by: string; at: string; note?: string };
9
+ /** 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. */
10
+ export type AssignmentResultOwner = { assignmentId: string; checkout: string; worktree?: string; result?: AssignmentResultEvidence; handled?: AssignmentResultHandling };
11
+ export type ArchivedAssignmentResult = AssignmentResultOwner & { handled: AssignmentResultHandling; archivedAt: string };
6
12
  type Ledger = { version: 1; workspaces: string[]; results: AssignmentResultOwner[] };
13
+ /** Archived results stay this long after the month they were archived in ends; ledger entries never expire. */
14
+ export const ARCHIVE_KEEP_MS = 365 * 24 * 60 * 60 * 1000;
7
15
  const empty = (): Ledger => ({ version: 1, workspaces: [], results: [] });
8
16
  const absolute = (value: unknown): value is string => typeof value === 'string' && path.isAbsolute(value);
17
+ const text = (value: unknown): value is string => typeof value === 'string';
18
+ const evidence = (value: any) => value === undefined || (!!value && typeof value === 'object' && !Array.isArray(value) &&
19
+ [value.agent, value.status, value.finishedAt, value.project, value.brief, value.summary].every(text) &&
20
+ Array.isArray(value.requesters) && value.requesters.every(text) && (value.taskId === undefined || text(value.taskId)));
21
+ const handling = (value: any) => value === undefined || (!!value && typeof value === 'object' && !Array.isArray(value) &&
22
+ RESULT_OUTCOMES.includes(value.outcome) && text(value.by) && text(value.at) && (value.note === undefined || text(value.note)));
9
23
  const valid = (value: any): value is Ledger => value?.version === 1 && Array.isArray(value.workspaces) && value.workspaces.every(absolute) &&
10
- Array.isArray(value.results) && value.results.every((entry: any) => entry && typeof entry.assignmentId === 'string' && absolute(entry.checkout) && (entry.worktree === undefined || absolute(entry.worktree)));
24
+ Array.isArray(value.results) && value.results.every((entry: any) => entry && typeof entry.assignmentId === 'string' && absolute(entry.checkout) && (entry.worktree === undefined || absolute(entry.worktree)) &&
25
+ evidence(entry.result) && handling(entry.handled));
26
+ const MONTH = /^(\d{4})-(\d{2})\.jsonl$/;
11
27
 
12
28
  /** Permanent ownership, independent of native-thread recall expiry. Missing initialized data is never recreated. */
13
29
  export function createAssignmentResults(file?: string) {
14
30
  let memory = empty();
31
+ let archivedInMemory: ArchivedAssignmentResult[] = [];
15
32
  let queue = Promise.resolve();
16
33
  const marker = file ? `${file}.initialized` : undefined;
34
+ // One JSON line per handled result, in a file per month of archiving.
35
+ const archiveDir = file ? path.join(path.dirname(file), 'assignment-archive') : undefined;
17
36
  async function load(initialize = false): Promise<Ledger> {
18
37
  if (!file) return memory;
19
38
  let value: unknown;
@@ -42,6 +61,41 @@ export function createAssignmentResults(file?: string) {
42
61
  queue = result.then(() => {}, () => {});
43
62
  return result;
44
63
  }
64
+ /** Appends a record and syncs it before its ledger entry may go; a crash in between archives it again, never loses it. */
65
+ async function append(record: ArchivedAssignmentResult) {
66
+ if (!archiveDir) { archivedInMemory.push(record); return; }
67
+ await mkdir(archiveDir, { recursive: true, mode: 0o700 });
68
+ const handle = await open(path.join(archiveDir, `${record.archivedAt.slice(0, 7)}.jsonl`), 'a+', 0o600);
69
+ try {
70
+ const { size } = await handle.stat();
71
+ const last = Buffer.alloc(1);
72
+ // A line cut short by a crash must not swallow the next record.
73
+ const torn = size > 0 && (await handle.read(last, 0, 1, size - 1)).bytesRead === 1 && last[0] !== 0x0a;
74
+ await handle.appendFile(`${torn ? '\n' : ''}${JSON.stringify(record)}\n`);
75
+ await handle.sync();
76
+ } finally { await handle.close(); }
77
+ }
78
+ async function archived(): Promise<ArchivedAssignmentResult[]> {
79
+ if (!archiveDir) return archivedInMemory;
80
+ let names: string[];
81
+ try { names = (await readdir(archiveDir)).filter(name => MONTH.test(name)).sort(); }
82
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
83
+ const records: ArchivedAssignmentResult[] = [];
84
+ for (const name of names) {
85
+ for (const line of (await readFile(path.join(archiveDir, name), 'utf8')).split('\n')) {
86
+ try { const record = JSON.parse(line); if (typeof record?.assignmentId === 'string') records.push(record); } catch {}
87
+ }
88
+ }
89
+ return records;
90
+ }
91
+ /** Deletes the archive months that ended more than ARCHIVE_KEEP_MS ago. */
92
+ async function prune(now: number) {
93
+ if (!archiveDir) { archivedInMemory = archivedInMemory.filter(record => now - Date.parse(record.archivedAt) < ARCHIVE_KEEP_MS); return; }
94
+ for (const name of await readdir(archiveDir).catch(() => [] as string[])) {
95
+ const month = MONTH.exec(name);
96
+ if (month && now - Date.UTC(Number(month[1]), Number(month[2])) > ARCHIVE_KEEP_MS) await rm(path.join(archiveDir, name), { force: true });
97
+ }
98
+ }
45
99
  return {
46
100
  register(directory: string) { return serialize(async () => {
47
101
  const value = await load(true);
@@ -59,6 +113,34 @@ export function createAssignmentResults(file?: string) {
59
113
  value.results = value.results.filter(entry => entry.assignmentId !== assignmentId);
60
114
  await save(value);
61
115
  }); },
116
+ /**
117
+ * Records how a produced result was handled, then archives every handled entry and drops it from the ledger.
118
+ * The mark is saved first: from then on the guard lets the checkout go, while the ledger still holds the evidence.
119
+ */
120
+ resolve(assignmentId: string, handled: AssignmentResultHandling) { return serialize(async () => {
121
+ if (!handling(handled)) throw new Error('Invalid result handling');
122
+ const value = await load();
123
+ const entry = value.results.find(owner => owner.assignmentId === assignmentId);
124
+ if (!entry) throw new Error(`No retained assignment result ${assignmentId}`);
125
+ if (!entry.handled) {
126
+ entry.handled = handled;
127
+ await save(value);
128
+ }
129
+ const now = Date.now();
130
+ const records: ArchivedAssignmentResult[] = [];
131
+ for (const owner of value.results) {
132
+ if (!owner.handled) continue;
133
+ const record = { ...owner, handled: owner.handled, archivedAt: new Date(now).toISOString() };
134
+ await append(record);
135
+ records.push(record);
136
+ }
137
+ value.results = value.results.filter(owner => !owner.handled);
138
+ await save(value);
139
+ await prune(now).catch(() => {});
140
+ return records.find(record => record.assignmentId === assignmentId)!;
141
+ }); },
142
+ /** The newest archived record of an assignment, if its archive month is still kept. */
143
+ archived(assignmentId: string) { return serialize(async () => (await archived()).filter(record => record.assignmentId === assignmentId).at(-1)); },
62
144
  inspect() { return serialize(() => load()); },
63
145
  };
64
146
  }
@@ -143,8 +143,8 @@ export function createBoardDomain({ options, sessions, boards, loadedBoards, roo
143
143
  }
144
144
 
145
145
  async function boardTool(session: Session, args: unknown) {
146
- if (!plainObject(args, ['kinds', 'limit']) || (args.kinds !== undefined && (!Array.isArray(args.kinds) || !args.kinds.every((kind: unknown) => PIN_KINDS.includes(kind as PinKind)))) || (args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 1))) {
147
- return toolResult(false, { error: 'kinds lists claim, decision or finding; limit is a positive integer' });
146
+ if (!plainObject(args, ['kinds', 'limit']) || (args.kinds !== undefined && (!Array.isArray(args.kinds) || args.kinds.length > PIN_KINDS.length || !args.kinds.every((kind: unknown) => PIN_KINDS.includes(kind as PinKind)))) || (args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 1))) {
147
+ return toolResult(false, { error: `kinds lists at most ${PIN_KINDS.length} of claim, decision and finding; limit is a positive integer` });
148
148
  }
149
149
  const kinds: string[] = args.kinds ?? [...PIN_KINDS];
150
150
  const pins = (await boardOf(session.mapping.agent.projectRoot)).filter(pin => live(pin) && kinds.includes(pin.kind));
package/src/board.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { realpathSync } from 'node:fs';
3
+ import type { InputLimits } from './input-limits.js';
3
4
 
4
5
  /**
5
6
  * The project board (plans/reference/ALPD.md §18): one group channel per project that every
@@ -16,6 +17,11 @@ export type { PinKind, Pin } from '@anhlp/alp-protocol/dto';
16
17
 
17
18
  export const PIN_BODY_CHARS = 2000;
18
19
  export const PIN_PATHS = 50;
20
+ /** One claimed path; macOS's PATH_MAX. Each segment of a path is one more realpath call. */
21
+ export const PIN_PATH_CHARS = 1024;
22
+ /** alp_pin's paths and alp_board's kinds, checked before any schema walks them. */
23
+ export const PIN_PATHS_INPUT: InputLimits = { bytes: PIN_PATHS * (3 * PIN_PATH_CHARS + 3), items: PIN_PATHS, depth: 1, string: PIN_PATH_CHARS };
24
+ export const BOARD_KINDS_INPUT: InputLimits = { bytes: 64, items: PIN_KINDS.length, depth: 1, string: 16 };
19
25
  /** Decisions and findings kept per project; live claims are always kept. */
20
26
  export const BOARD_KEEP = 200;
21
27
  const DIGEST_CHARS = 3000;
@@ -38,6 +44,7 @@ export function normalizePaths(paths: unknown, project: string, roots: string[]
38
44
  const normalized: string[] = [];
39
45
  for (const entry of paths) {
40
46
  if (typeof entry !== 'string' || !entry.trim()) return 'paths must be nonempty strings';
47
+ if (entry.length > PIN_PATH_CHARS) return `paths must be at most ${PIN_PATH_CHARS} characters each`;
41
48
  const absolute = canonicalPath(path.resolve(project, entry.trim()));
42
49
  if (!roots.some(root => containsPath(canonicalPath(root), absolute))) return `${entry} is outside the project or declared write root`;
43
50
  const relative = path.relative(canonicalPath(project), absolute).split(path.sep).join('/');
package/src/catalog.ts CHANGED
@@ -25,7 +25,16 @@ const model = (runtime: 'codex' | 'claude' | 'antigravity', id: string, label: s
25
25
  ...(defaultThinkingOptionId ? { defaultThinkingOptionId } : {}),
26
26
  });
27
27
 
28
- export const models = MODELS.map(entry => model(entry.runtime as 'codex' | 'claude' | 'antigravity', entry.id, entry.label, entry.description, options(entry.efforts), entry.effort));
28
+ export type CatalogEntry = { runtime: 'codex' | 'claude' | 'antigravity'; id: string; label: string; description: string; efforts: string[]; effort?: string; source?: 'live' | 'fallback' | 'static' };
29
+ const toModel = (entry: CatalogEntry) => model(entry.runtime, entry.id, entry.label, entry.description, options(entry.efforts), entry.effort);
30
+ /** The rows every consumer reads: core MODELS at start, replaced in place by the live catalog (model-catalog.ts). */
31
+ export const entries: CatalogEntry[] = MODELS.map(entry => ({ ...entry, source: 'static' as const })) as CatalogEntry[];
32
+ export const models = entries.map(toModel);
33
+ /** Replaces the catalog in place so every module holding `models`/`entries` sees the new rows. */
34
+ export function applyCatalog(next: CatalogEntry[]) {
35
+ entries.splice(0, entries.length, ...next);
36
+ models.splice(0, models.length, ...next.map(toModel));
37
+ }
29
38
 
30
39
  export function thinkingOptionsFor(runtime: 'codex' | 'claude' | 'antigravity', nativeModel: string) {
31
40
  return models.find(candidate => candidate.id === `${runtime}:${nativeModel}`)?.thinkingOptions ?? thinkingOptions;