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

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 +71 -10
  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 +32 -3
  18. package/dist/index.d.ts +10 -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 +665 -47
  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 +31 -5
  42. package/dist/workspace.js +92 -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 +79 -10
  51. package/src/compact.ts +62 -0
  52. package/src/configure.ts +3 -3
  53. package/src/contracts.ts +28 -2
  54. package/src/index.ts +10 -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 +718 -48
  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 +124 -18
@@ -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
  /**
@@ -77,11 +81,33 @@ export declare function mergeWorktree(worktree: Worktree, change: WorktreeChange
77
81
  export declare function removeWorktree(worktree: Worktree, { deleteBranch }?: {
78
82
  deleteBranch?: boolean | undefined;
79
83
  }): Promise<void>;
84
+ /**
85
+ * Why reclaimWorktrees left a directory in place: `invalid`, not the top level of a working git
86
+ * worktree; `not-linked`, a repository of its own rather than a worktree of one; `other-branch`,
87
+ * another branch or a detached HEAD, which does not hold this work; `commit-failed`, its work could
88
+ * not be committed (`detail` says why); `uncommitted`, something was still not committed after
89
+ * that; `ignored-files`, its work is committed but it holds ignored files that exist nowhere else.
90
+ */
91
+ export type LeftWorktree = {
92
+ name: string;
93
+ path: string;
94
+ reason: 'invalid' | 'not-linked' | 'other-branch' | 'commit-failed' | 'uncommitted' | 'ignored-files';
95
+ branch?: string;
96
+ detail?: string;
97
+ files?: string[];
98
+ };
80
99
  /**
81
100
  * After a crash: commits work left in worktrees under `root` to their branches and
82
- * removes the directories. Returns the branches that were kept.
101
+ * removes the directories. Returns the branches that were kept, and the directories left in
102
+ * place with the reason. A directory is removed only once everything in it is committed to
103
+ * its own `alp/<name>` branch and it holds no ignored file to keep (`.env*`); any other one
104
+ * stays, so recovery reuses or preserves it and nothing uncommitted is lost. Stale locks a
105
+ * killed git command left in such a worktree are removed first (clearStaleLocks).
83
106
  */
84
- export declare function reclaimWorktrees(root: string): Promise<string[]>;
107
+ export declare function reclaimWorktrees(root: string): Promise<{
108
+ kept: string[];
109
+ left: LeftWorktree[];
110
+ }>;
85
111
  /**
86
112
  * A disposable copy of a checkout for an assignment that may build and test but
87
113
  * must not touch the requester's tree (ALPD §26): a detached worktree at the
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 dirs = await gitDirs(worktree.path);
116
+ if (dirs) await clearStaleLocks(dirs, worktree.branch);
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"]);
@@ -175,27 +191,92 @@ async function removeWorktree(worktree, { deleteBranch = false } = {}) {
175
191
  await git(worktree.checkout, ["worktree", "prune"]);
176
192
  if (deleteBranch) await git(worktree.checkout, ["branch", "-D", worktree.branch]);
177
193
  }
194
+ async function gitDirs(target) {
195
+ const result = await git(target, ["rev-parse", "--path-format=absolute", "--absolute-git-dir", "--git-common-dir"]);
196
+ if (result.code !== 0) return void 0;
197
+ const [own, common] = result.stdout.trim().split("\n").map((line) => path.resolve(line.trim()));
198
+ return own && common ? { own, common } : void 0;
199
+ }
200
+ var SHARED_LOCK_STALE_MS = 1e4;
201
+ async function clearStaleLocks(dirs, branch) {
202
+ if (dirs.own === dirs.common) return;
203
+ const own = (await readdir(dirs.own).catch(() => [])).filter((name) => name.endsWith(".lock"));
204
+ const refs = (await readdir(path.join(dirs.own, "refs"), { recursive: true }).catch(() => [])).filter((name) => name.endsWith(".lock")).map((name) => path.join("refs", name));
205
+ for (const name of [...own, ...refs]) await unlink(path.join(dirs.own, name)).catch(() => {
206
+ });
207
+ const shared = `${path.join(dirs.common, "refs", "heads", ...branch.split("/"))}.lock`;
208
+ const info = await lstat(shared).catch(() => void 0);
209
+ if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink(shared).catch(() => {
210
+ });
211
+ }
212
+ var KEEP_IGNORED = /^\.env/;
213
+ async function ignoredToKeep(target) {
214
+ const result = await git(target, ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"]);
215
+ if (result.code !== 0) return void 0;
216
+ return result.stdout.split("\0").filter(Boolean).map((entry) => entry.replace(/\/$/, "")).filter((entry) => KEEP_IGNORED.test(path.posix.basename(entry))).sort();
217
+ }
218
+ var firstLine = (result) => (result.stderr || result.stdout).trim().split("\n")[0] ?? "";
178
219
  async function reclaimWorktrees(root) {
179
220
  const kept = [];
221
+ const left = [];
180
222
  const entries = await readdir(root).catch(() => []);
181
223
  for (const name of entries) {
182
224
  const target = path.join(root, name);
225
+ const leave = (reason, extra = {}) => {
226
+ left.push({ name, path: target, reason, ...extra });
227
+ };
183
228
  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 });
229
+ if (!await validWorktree(target)) {
230
+ leave("invalid");
231
+ continue;
232
+ }
233
+ const dirs = await gitDirs(target);
234
+ if (!dirs) {
235
+ leave("invalid");
236
+ continue;
237
+ }
238
+ if (dirs.own === dirs.common) {
239
+ leave("not-linked");
240
+ continue;
241
+ }
242
+ const checkout = path.dirname(dirs.common);
243
+ const ref = await git(target, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
244
+ const branch = ref.stdout.trim();
245
+ if (ref.code !== 0 || branch !== `alp/${name}`) {
246
+ leave("other-branch", ref.code === 0 && branch ? { branch } : {});
247
+ continue;
248
+ }
249
+ await clearStaleLocks(dirs, branch);
250
+ const added = await git(target, ["add", "-A"]);
251
+ if (added.code !== 0) {
252
+ leave("commit-failed", { branch, detail: firstLine(added) });
187
253
  continue;
188
254
  }
189
- 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"]);
192
255
  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"]);
256
+ const committed = await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"]);
257
+ if (committed.code !== 0) {
258
+ leave("commit-failed", { branch, detail: firstLine(committed) });
259
+ continue;
260
+ }
261
+ }
262
+ const status = await git(target, ["status", "--porcelain", "--ignored=no"]);
263
+ if (status.code !== 0 || status.stdout.trim()) {
264
+ leave("uncommitted", { branch });
265
+ continue;
266
+ }
267
+ const ignored = await ignoredToKeep(target);
268
+ if (!ignored) {
269
+ leave("ignored-files", { branch, detail: "git could not list its ignored files" });
270
+ continue;
271
+ }
272
+ if (ignored.length) {
273
+ leave("ignored-files", { branch, files: ignored });
274
+ continue;
194
275
  }
195
276
  await removeWorktree({ checkout, path: target, workdir: target, branch, base: "" });
196
277
  kept.push(branch);
197
278
  }
198
- return kept;
279
+ return { kept, left };
199
280
  }
200
281
  async function createCopy(workdir, root, id) {
201
282
  const checkout = await checkoutOf(workdir);
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.6",
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.6",
234
+ "@anhlp/alp-protocol": "0.0.1-beta.6",
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);