@anhlp/alp-runtime 0.0.0-stage → 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 (127) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +6 -2
  4. package/dist/acp-transport.d.ts +130 -0
  5. package/dist/acp-transport.js +482 -0
  6. package/dist/antigravity-transport.d.ts +107 -0
  7. package/dist/antigravity-transport.js +665 -0
  8. package/dist/assignment-results.d.ts +55 -0
  9. package/dist/assignment-results.js +181 -0
  10. package/dist/attachments.d.ts +84 -0
  11. package/dist/attachments.js +213 -0
  12. package/dist/board-domain.d.ts +56 -0
  13. package/dist/board-domain.js +157 -0
  14. package/dist/board.d.ts +27 -0
  15. package/dist/board.js +76 -0
  16. package/dist/catalog.d.ts +44 -0
  17. package/dist/catalog.js +47 -0
  18. package/dist/claude-transport.d.ts +251 -0
  19. package/dist/claude-transport.js +931 -0
  20. package/dist/compact.d.ts +29 -0
  21. package/dist/compact.js +49 -0
  22. package/dist/configure.d.ts +44 -0
  23. package/dist/configure.js +64 -0
  24. package/dist/contracts.d.ts +378 -0
  25. package/dist/contracts.js +16 -0
  26. package/dist/conversation.d.ts +45 -0
  27. package/dist/conversation.js +62 -0
  28. package/dist/events.d.ts +1 -0
  29. package/dist/events.js +0 -0
  30. package/dist/github.d.ts +10 -0
  31. package/dist/github.js +39 -0
  32. package/dist/handoff.d.ts +36 -0
  33. package/dist/handoff.js +73 -0
  34. package/dist/index.d.ts +39 -0
  35. package/dist/index.js +122 -0
  36. package/dist/input-limits.d.ts +25 -0
  37. package/dist/input-limits.js +48 -0
  38. package/dist/language.d.ts +51 -0
  39. package/dist/language.js +94 -0
  40. package/dist/live.d.ts +48 -0
  41. package/dist/live.js +50 -0
  42. package/dist/mailbox.d.ts +26 -0
  43. package/dist/mailbox.js +38 -0
  44. package/dist/mcp-tools.d.ts +123 -0
  45. package/dist/mcp-tools.js +97 -0
  46. package/dist/model-catalog.d.ts +162 -0
  47. package/dist/model-catalog.js +338 -0
  48. package/dist/model-probes.d.ts +7 -0
  49. package/dist/model-probes.js +69 -0
  50. package/dist/permission-path.d.ts +2 -0
  51. package/dist/permission-path.js +44 -0
  52. package/dist/process-info.d.ts +14 -0
  53. package/dist/process-info.js +32 -0
  54. package/dist/providers.d.ts +28 -0
  55. package/dist/providers.js +73 -0
  56. package/dist/recall.d.ts +42 -0
  57. package/dist/recall.js +61 -0
  58. package/dist/resolve.d.ts +123 -0
  59. package/dist/resolve.js +242 -0
  60. package/dist/runtime-context.d.ts +43 -0
  61. package/dist/runtime-context.js +61 -0
  62. package/dist/runtime.d.ts +13 -0
  63. package/dist/runtime.js +4818 -0
  64. package/dist/session-config.d.ts +2345 -0
  65. package/dist/session-config.js +209 -0
  66. package/dist/session-state.d.ts +190 -0
  67. package/dist/session-state.js +0 -0
  68. package/dist/skill-resources.d.ts +30 -0
  69. package/dist/skill-resources.js +55 -0
  70. package/dist/tool-detail.d.ts +81 -0
  71. package/dist/tool-detail.js +332 -0
  72. package/dist/tool-results.d.ts +12 -0
  73. package/dist/tool-results.js +25 -0
  74. package/dist/tools.d.ts +827 -0
  75. package/dist/tools.js +463 -0
  76. package/dist/transport.d.ts +47 -0
  77. package/dist/transport.js +171 -0
  78. package/dist/usage.d.ts +25 -0
  79. package/dist/usage.js +60 -0
  80. package/dist/workspace.d.ts +127 -0
  81. package/dist/workspace.js +340 -0
  82. package/dist/worktree-domain.d.ts +89 -0
  83. package/dist/worktree-domain.js +199 -0
  84. package/dist/write-error.d.ts +2 -0
  85. package/dist/write-error.js +10 -0
  86. package/package.json +262 -4
  87. package/src/acp-transport.ts +481 -0
  88. package/src/antigravity-transport.ts +740 -0
  89. package/src/assignment-results.ts +154 -0
  90. package/src/attachments.ts +254 -0
  91. package/src/board-domain.ts +185 -0
  92. package/src/board.ts +87 -0
  93. package/src/catalog.ts +43 -0
  94. package/src/claude-transport.ts +1097 -0
  95. package/src/compact.ts +62 -0
  96. package/src/configure.ts +93 -0
  97. package/src/contracts.ts +363 -0
  98. package/src/conversation.ts +81 -0
  99. package/src/events.ts +1 -0
  100. package/src/github.ts +37 -0
  101. package/src/handoff.ts +86 -0
  102. package/src/index.ts +41 -0
  103. package/src/input-limits.ts +65 -0
  104. package/src/language.ts +130 -0
  105. package/src/live.ts +90 -0
  106. package/src/mailbox.ts +49 -0
  107. package/src/mcp-tools.ts +106 -0
  108. package/src/model-catalog.ts +316 -0
  109. package/src/model-probes.ts +58 -0
  110. package/src/permission-path.ts +37 -0
  111. package/src/process-info.ts +40 -0
  112. package/src/providers.ts +87 -0
  113. package/src/recall.ts +86 -0
  114. package/src/resolve.ts +238 -0
  115. package/src/runtime-context.ts +49 -0
  116. package/src/runtime.ts +5608 -0
  117. package/src/session-config.ts +312 -0
  118. package/src/session-state.ts +180 -0
  119. package/src/skill-resources.ts +73 -0
  120. package/src/tool-detail.ts +397 -0
  121. package/src/tool-results.ts +26 -0
  122. package/src/tools.ts +466 -0
  123. package/src/transport.ts +118 -0
  124. package/src/usage.ts +79 -0
  125. package/src/workspace.ts +424 -0
  126. package/src/worktree-domain.ts +220 -0
  127. package/src/write-error.ts +4 -0
@@ -0,0 +1,482 @@
1
+ // packages/runtime/src/acp-transport.ts
2
+ import { writablePath } from "./permission-path.js";
3
+ import { spawn, execFile } from "node:child_process";
4
+ import { randomBytes, randomUUID } from "node:crypto";
5
+ import { rmSync } from "node:fs";
6
+ import net from "node:net";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { createInterface } from "node:readline";
10
+ import { commandDecision, unwrapShell } from "@anhlp/alp-core/permissions";
11
+ import { launchCommand } from "@anhlp/alp-core/providers";
12
+ import { bridgeCommand } from "@anhlp/alp-core/bridges";
13
+ import { acpText, acpToolDetail } from "./tool-detail.js";
14
+ import { feedAcpSession } from "./model-catalog.js";
15
+ var READERS = ["read", "search", "think", "fetch"];
16
+ function acpPermission(toolCall, tools) {
17
+ const raw = toolCall?.rawInput;
18
+ const kind = typeof toolCall?.kind === "string" ? toolCall.kind : "other";
19
+ const title = typeof toolCall?.title === "string" ? toolCall.title : "";
20
+ const command = kind === "execute" ? typeof raw?.command === "string" ? raw.command : Array.isArray(raw?.command) ? raw.command.join(" ") : title || void 0 : void 0;
21
+ const paths = (Array.isArray(toolCall?.locations) ? toolCall.locations : []).map((location) => location?.path).filter((value) => typeof value === "string");
22
+ const named = `${title} ${typeof toolCall?.name === "string" ? toolCall.name : ""}`;
23
+ const alpTool = !["execute", "edit", "delete", "move"].includes(kind) && tools.some((tool) => new RegExp(`\\b${tool}\\b`).test(named));
24
+ return { kind, title, ...command ? { command } : {}, paths, alpTool };
25
+ }
26
+ function acpDecision(request, mode, profile, workdir) {
27
+ if (request.alpTool) return "allow";
28
+ const rule = request.command !== void 0 && profile ? commandDecision(profile, request.command) : void 0;
29
+ if (rule === "deny") return "deny";
30
+ if (rule === "allow") return "allow";
31
+ if (rule === "ask") return "rule";
32
+ if (mode === "full-access" || READERS.includes(request.kind)) return "allow";
33
+ if (mode === "workspace-write") {
34
+ if (["edit", "delete", "move"].includes(request.kind) && !request.paths.length) return "mode";
35
+ const outside = request.paths.some((file) => !writablePath(file, workdir));
36
+ if (!outside) return "allow";
37
+ }
38
+ return "mode";
39
+ }
40
+ function acpWhat(request) {
41
+ if (request.command !== void 0) return `run \`${unwrapShell(request.command).slice(0, 400)}\``;
42
+ return `${request.kind === "other" ? "use" : request.kind} ${request.title ? `\`${request.title.slice(0, 300)}\`` : "a tool"}${request.paths.length ? ` (${request.paths.slice(0, 5).join(", ")})` : ""}`;
43
+ }
44
+ function acpEnv(provider, base) {
45
+ const env = { ...base, ...provider.env, ...base.ALP_AGENT_SESSION ? { ALP_AGENT_SESSION: base.ALP_AGENT_SESSION } : {} };
46
+ if (provider.command.split(/[\\/]/).pop().replace(/\.exe$/i, "").toLowerCase() !== "opencode") return env;
47
+ let config = {};
48
+ try {
49
+ config = JSON.parse(env.OPENCODE_CONFIG_CONTENT ?? "{}") ?? {};
50
+ } catch {
51
+ }
52
+ if (typeof config !== "object" || Array.isArray(config)) config = {};
53
+ const permission = typeof config.permission === "object" && config.permission && !Array.isArray(config.permission) ? config.permission : {};
54
+ return { ...env, OPENCODE_CONFIG_CONTENT: JSON.stringify({ ...config, permission: { ...permission, edit: "ask", bash: "ask", webfetch: "ask" } }) };
55
+ }
56
+ function acpServers(servers, http) {
57
+ return Object.entries(servers).map(([name, server]) => {
58
+ if (server.url) {
59
+ if (!http) throw new Error(`MCP server '${name}' is HTTP, which this ACP agent does not take; use a stdio server`);
60
+ return { type: "http", name, url: server.url, headers: Object.entries(server.http_headers ?? {}).map(([key, value]) => ({ name: key, value: String(value) })) };
61
+ }
62
+ return { name, command: server.command, args: server.args ?? [], env: Object.entries(server.env ?? {}).map(([key, value]) => ({ name: key, value: String(value) })) };
63
+ });
64
+ }
65
+ function acpContent(part) {
66
+ if (typeof part?.text === "string") return { type: "text", text: part.text };
67
+ const image = part?.type === "image" && typeof part.url === "string" ? /^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(part.url) : null;
68
+ return image ? { type: "image", mimeType: image[1], data: image[2] } : null;
69
+ }
70
+ var AcpTransport = class {
71
+ constructor(provider, cwd, env) {
72
+ this.provider = provider;
73
+ this.cwd = cwd;
74
+ this.env = env;
75
+ }
76
+ child;
77
+ exit = Promise.resolve();
78
+ sequence = 0;
79
+ pending = /* @__PURE__ */ new Map();
80
+ listeners = /* @__PURE__ */ new Set();
81
+ failures = /* @__PURE__ */ new Set();
82
+ requestHandler;
83
+ closed = false;
84
+ capabilities = {};
85
+ /** ACP agents say in initialize whether a prompt may hold images (promptCapabilities.image). */
86
+ takesImages() {
87
+ return this.capabilities?.promptCapabilities?.image === true;
88
+ }
89
+ sessionId = "";
90
+ config;
91
+ /** Instructions go with the first prompt of a new session; a loaded one has them already. */
92
+ instructionsSent = false;
93
+ loading = false;
94
+ activeTurn;
95
+ /** The running prompt; a cancelled one still answers before the next starts. */
96
+ prompting;
97
+ /** Text of the running turn's current message; a tool call starts the next one. */
98
+ message;
99
+ messages = 0;
100
+ toolCalls = /* @__PURE__ */ new Map();
101
+ /** Permission questions of the running turn, answered cancelled when it is cancelled. */
102
+ questions = /* @__PURE__ */ new Set();
103
+ bridge;
104
+ tools = [];
105
+ async initialize() {
106
+ if (/\.(cmd|bat|ps1)$/i.test(this.provider.command)) throw new Error(`${this.provider.label}: the command must be a native executable, not a shell launcher`);
107
+ const env = acpEnv(this.provider, this.env);
108
+ const launch = launchCommand(this.provider.command, this.provider.args, env);
109
+ const child = spawn(launch.command, launch.args, { cwd: this.cwd, env: launch.env ? { ...env, ...launch.env } : env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
110
+ this.child = child;
111
+ this.exit = new Promise((resolve) => {
112
+ child.once("close", () => resolve());
113
+ child.once("error", () => resolve());
114
+ });
115
+ child.stderr.on("data", () => {
116
+ });
117
+ child.stdin.on("error", (error) => this.fail(error));
118
+ child.on("error", (error) => this.fail(new Error(`${this.provider.label} did not start: ${error.message}`)));
119
+ child.on("close", (code) => {
120
+ if (!this.closed) this.fail(new Error(`${this.provider.label} exited (${code})`));
121
+ });
122
+ createInterface({ input: child.stdout }).on("line", (line) => this.receive(line));
123
+ const result = await this.call("initialize", {
124
+ protocolVersion: 1,
125
+ // The agent reads, writes and runs commands with its own tools; ALP answers its permission requests.
126
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
127
+ clientInfo: { name: "alp", title: "ALP", version: "0.0.0" }
128
+ }, 3e4);
129
+ if (result?.protocolVersion !== 1) throw new Error(`${this.provider.label} speaks ACP version ${result?.protocolVersion}; ALP speaks version 1`);
130
+ this.capabilities = result.agentCapabilities ?? {};
131
+ }
132
+ onNotification(listener) {
133
+ this.listeners.add(listener);
134
+ return () => this.listeners.delete(listener);
135
+ }
136
+ onFailure(listener) {
137
+ this.failures.add(listener);
138
+ return () => this.failures.delete(listener);
139
+ }
140
+ onRequest(handler) {
141
+ this.requestHandler = handler;
142
+ }
143
+ async request(method, params) {
144
+ if (this.closed) throw new Error("Runtime is closed");
145
+ if (method === "thread/start" || method === "thread/resume") {
146
+ this.config = params;
147
+ this.tools = params.dynamicTools ?? [];
148
+ const mcpServers = [...acpServers(params.mcpServers ?? {}, Boolean(this.capabilities.mcpCapabilities?.http)), ...this.tools.length ? [await this.openBridge()] : []];
149
+ if (method === "thread/resume") {
150
+ if (!this.capabilities.loadSession) throw new Error(`${this.provider.label} cannot resume a session: it does not support session/load`);
151
+ this.loading = true;
152
+ try {
153
+ await this.call("session/load", { sessionId: params.threadId, cwd: params.cwd, mcpServers }, 12e4);
154
+ } finally {
155
+ this.loading = false;
156
+ }
157
+ this.sessionId = params.threadId;
158
+ this.instructionsSent = true;
159
+ } else {
160
+ const result = await this.call("session/new", { cwd: params.cwd, mcpServers }, 12e4);
161
+ this.sessionId = result.sessionId;
162
+ feedAcpSession(this.provider.id, result);
163
+ await this.chooseModel(result.models, result.configOptions);
164
+ }
165
+ return { thread: { id: this.sessionId, turns: [] }, cwd: params.cwd, model: params.model, reasoningEffort: params.thinking };
166
+ }
167
+ if (method === "turn/start") {
168
+ if (!this.sessionId) throw new Error(`${this.provider.label} session is not open`);
169
+ if (this.prompting) await Promise.race([this.prompting, new Promise((resolve) => setTimeout(resolve, 1e4).unref())]);
170
+ if (this.closed) throw new Error("Runtime is closed");
171
+ const turnId = randomUUID();
172
+ this.activeTurn = turnId;
173
+ this.message = void 0;
174
+ const prompt = (params.input ?? []).map(acpContent).filter(Boolean);
175
+ if (prompt.some((part) => part.type === "image") && !this.takesImages()) throw new Error(`${this.provider.label} takes no images`);
176
+ if (!this.instructionsSent && this.config?.developerInstructions) {
177
+ prompt.unshift({ type: "text", text: `Instructions from ALP, which runs you. Follow them for this whole session.
178
+
179
+ ${this.config.developerInstructions}` });
180
+ this.instructionsSent = true;
181
+ }
182
+ this.prompting = this.call("session/prompt", { sessionId: this.sessionId, prompt }).then(
183
+ (result) => {
184
+ this.turnUsage(turnId, result?.usage);
185
+ this.endTurn(turnId, result?.stopReason);
186
+ },
187
+ (error) => this.endTurn(turnId, "error", error instanceof Error ? error.message : String(error))
188
+ ).finally(() => {
189
+ if (this.activeTurn === void 0 || this.activeTurn === turnId) this.prompting = void 0;
190
+ });
191
+ return { turn: { id: turnId } };
192
+ }
193
+ if (method === "turn/steer") throw new Error(`${this.provider.label} takes no messages during a turn; ALP delivers them when it ends`);
194
+ if (method === "turn/interrupt") {
195
+ if (this.sessionId) this.write({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: this.sessionId } });
196
+ for (const answer of this.questions) answer({ outcome: { outcome: "cancelled" } });
197
+ this.questions.clear();
198
+ return {};
199
+ }
200
+ if (method === "session/configure") return {};
201
+ if (method === "thread/delete") return {};
202
+ throw new Error(`${this.provider.label} does not support '${method}'`);
203
+ }
204
+ /** Picks the session's model when ALP was given one and the agent offers a choice. */
205
+ async chooseModel(models, configOptions) {
206
+ const wanted = this.config?.model?.includes("/") ? this.config.model.slice(this.config.model.indexOf("/") + 1) : void 0;
207
+ if (!wanted) return;
208
+ const config = configOptions?.find((option) => option.category === "model" && option.type === "select");
209
+ if (config) {
210
+ if (config.currentValue === wanted) return;
211
+ const options = (config.options ?? []).flatMap((option) => option.options ?? [option]);
212
+ if (!options.some((option) => option.value === wanted)) throw new Error(`${this.provider.label} has no model '${wanted}'`);
213
+ await this.call("session/set_config_option", { sessionId: this.sessionId, configId: config.id, value: wanted }, 3e4);
214
+ return;
215
+ }
216
+ if (models?.currentModelId === wanted) return;
217
+ if (!Array.isArray(models?.availableModels)) throw new Error(`${this.provider.label} does not let ALP choose its model; use acp:${this.provider.id} alone`);
218
+ if (!models.availableModels.some((model) => model?.modelId === wanted)) throw new Error(`${this.provider.label} has no model '${wanted}'`);
219
+ await this.call("session/set_model", { sessionId: this.sessionId, modelId: wanted }, 3e4);
220
+ }
221
+ /** The tokens of the turn the prompt response says (ACP's unstable usage), before its end. */
222
+ turnUsage(turnId, usage) {
223
+ if (this.closed || this.activeTurn !== turnId || !usage || typeof usage !== "object") return;
224
+ const last = { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, cachedInputTokens: usage.cachedReadTokens };
225
+ this.emit("thread/tokenUsage/updated", { threadId: this.sessionId, turnId, tokenUsage: { last } });
226
+ }
227
+ endTurn(turnId, stopReason, error) {
228
+ if (this.closed || this.activeTurn !== turnId) return;
229
+ this.closeMessage();
230
+ this.activeTurn = void 0;
231
+ this.toolCalls.clear();
232
+ const status = stopReason === "end_turn" ? "completed" : stopReason === "cancelled" ? "interrupted" : "failed";
233
+ this.emit("turn/completed", {
234
+ threadId: this.sessionId,
235
+ turn: { id: turnId, status, ...status === "failed" ? { error: { message: error ?? `${this.provider.label} stopped: ${stopReason}` } } : {} }
236
+ });
237
+ }
238
+ closeMessage() {
239
+ if (this.message?.text) this.emit("item/completed", { threadId: this.sessionId, item: { type: "agentMessage", id: this.message.id, text: this.message.text } });
240
+ this.message = void 0;
241
+ }
242
+ update(update) {
243
+ if (this.loading || !this.activeTurn || !update) return;
244
+ const kind = update.sessionUpdate;
245
+ if (kind === "agent_message_chunk") {
246
+ const text = update.content?.type === "text" && typeof update.content.text === "string" ? update.content.text : "";
247
+ if (!text) return;
248
+ this.message ??= { id: `acp-${this.activeTurn}-${++this.messages}`, text: "" };
249
+ this.message.text += text;
250
+ this.emit("item/agentMessage/delta", { threadId: this.sessionId, itemId: this.message.id, delta: text });
251
+ return;
252
+ }
253
+ if (kind === "tool_call" || kind === "tool_call_update") {
254
+ const id = String(update.toolCallId ?? "");
255
+ if (!id) return;
256
+ let call = this.toolCalls.get(id);
257
+ const first = !call;
258
+ if (call?.done) return;
259
+ if (!call) {
260
+ const request = acpPermission(update, this.tools.map((tool) => tool.name));
261
+ call = { command: request.command ?? `${request.kind}: ${request.title}`, alp: request.alpTool, state: {} };
262
+ this.toolCalls.set(id, call);
263
+ this.closeMessage();
264
+ }
265
+ for (const field of ["kind", "title", "rawInput", "rawOutput", "locations", "content"]) if (update[field] !== void 0 && update[field] !== null) call.state[field] = update[field];
266
+ if (call.alp) return;
267
+ const detail = acpToolDetail(call.state);
268
+ const typed = detail ? { tool: call.state.title || call.state.kind || "tool", detail } : {};
269
+ const done = update.status === "completed" || update.status === "failed";
270
+ if (first) this.emit("item/started", { threadId: this.sessionId, item: { type: "commandExecution", id, command: call.command, cwd: this.cwd, status: "inProgress", aggregatedOutput: "", ...typed } });
271
+ else if (!done && detail) this.emit("item/updated", { threadId: this.sessionId, item: { type: "commandExecution", id, command: call.command, cwd: this.cwd, status: "inProgress", aggregatedOutput: "", ...typed } });
272
+ if (done) {
273
+ call.state = {};
274
+ call.done = true;
275
+ const output = (Array.isArray(update.content) ? update.content : []).map((part) => part?.type === "content" && part.content?.type === "text" ? part.content.text : part?.type === "diff" ? `diff ${part.path}` : "").filter(Boolean).join("\n");
276
+ const error = update.status === "failed" && detail ? { error: acpText(update.content) ?? (typeof update.rawOutput === "string" ? update.rawOutput : void 0) } : {};
277
+ this.emit("item/completed", { threadId: this.sessionId, item: { type: "commandExecution", id, command: call.command, cwd: this.cwd, status: update.status, exitCode: update.status === "failed" ? 1 : 0, aggregatedOutput: output, ...typed, ...error } });
278
+ }
279
+ return;
280
+ }
281
+ if (kind === "usage_update" && typeof update.used === "number") {
282
+ const last = { totalTokens: update.used };
283
+ const cost = update.cost?.currency === "USD" && typeof update.cost.amount === "number" ? { totalCostUsd: update.cost.amount } : {};
284
+ this.emit("thread/tokenUsage/updated", { threadId: this.sessionId, turnId: this.activeTurn, tokenUsage: { last, total: last, ...typeof update.size === "number" ? { modelContextWindow: update.size } : {}, ...cost } });
285
+ }
286
+ }
287
+ /** The agent asks before using a tool; ALP's runtime decides, and the answer picks one of the agent's options. */
288
+ async permission(params) {
289
+ const options = Array.isArray(params?.options) ? params.options : [];
290
+ const pick = (...kinds) => kinds.map((kind) => options.find((option2) => option2?.kind === kind)).find(Boolean);
291
+ if (!this.activeTurn || !this.requestHandler) return { outcome: { outcome: "cancelled" } };
292
+ const request = acpPermission(params?.toolCall, this.tools.map((tool) => tool.name));
293
+ const question = new Promise((resolve) => this.questions.add(resolve));
294
+ const answer = await Promise.race([this.requestHandler("item/acp/permission", request), question]);
295
+ if (answer?.outcome) return answer;
296
+ const option = answer?.allow ? pick("allow_once", "allow_always") : pick("reject_once", "reject_always");
297
+ return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
298
+ }
299
+ receive(line) {
300
+ if (line.length > 16 * 1024 * 1024) {
301
+ this.fail(new Error(`${this.provider.label} sent a frame over the size limit`));
302
+ return;
303
+ }
304
+ let message;
305
+ try {
306
+ message = JSON.parse(line);
307
+ } catch {
308
+ return;
309
+ }
310
+ if (message.method && message.id !== void 0) {
311
+ const answer = message.method === "session/request_permission" ? this.permission(message.params) : Promise.reject(Object.assign(new Error(`ALP does not offer '${message.method}'`), { code: -32601 }));
312
+ answer.then(
313
+ (result) => {
314
+ if (!this.closed) this.write({ jsonrpc: "2.0", id: message.id, result });
315
+ },
316
+ (error) => {
317
+ if (!this.closed) this.write({ jsonrpc: "2.0", id: message.id, error: { code: error?.code ?? -32603, message: error instanceof Error ? error.message : String(error) } });
318
+ }
319
+ );
320
+ } else if (message.id !== void 0) {
321
+ const waiter = this.pending.get(message.id);
322
+ if (!waiter) return;
323
+ this.pending.delete(message.id);
324
+ clearTimeout(waiter.timer);
325
+ if (message.error) {
326
+ const auth = message.error.code === -32e3 || /auth/i.test(String(message.error.message ?? ""));
327
+ waiter.reject(new Error(auth ? `${this.provider.label} needs you to sign in first: run it once in a terminal and log in (${message.error.message ?? "authentication required"})` : `${this.provider.label}: ${message.error.message ?? "request failed"}`));
328
+ } else waiter.resolve(message.result);
329
+ } else if (message.method === "session/update" && message.params?.sessionId === this.sessionId) {
330
+ this.update(message.params.update);
331
+ }
332
+ }
333
+ call(method, params, timeout) {
334
+ if (this.closed) return Promise.reject(new Error("Runtime is closed"));
335
+ const id = ++this.sequence;
336
+ return new Promise((resolve, reject) => {
337
+ const timer = timeout ? setTimeout(() => {
338
+ this.pending.delete(id);
339
+ reject(new Error(`${this.provider.label} did not answer ${method} within ${timeout / 1e3} s`));
340
+ }, timeout) : void 0;
341
+ this.pending.set(id, { resolve, reject, timer });
342
+ try {
343
+ this.write({ jsonrpc: "2.0", id, method, params });
344
+ } catch (error) {
345
+ clearTimeout(timer);
346
+ this.pending.delete(id);
347
+ reject(error);
348
+ }
349
+ });
350
+ }
351
+ write(value) {
352
+ if (this.closed || !this.child) throw new Error("Runtime is closed");
353
+ this.child.stdin.write(`${JSON.stringify(value)}
354
+ `);
355
+ }
356
+ /** Starts the socket ALP's MCP bridge connects to, and returns the server entry for the agent. */
357
+ async openBridge() {
358
+ if (!this.bridge) {
359
+ const token = randomBytes(16).toString("hex");
360
+ const name = `alp-acp-${randomBytes(6).toString("hex")}`;
361
+ const socket = process.platform === "win32" ? `\\\\.\\pipe\\${name}` : path.join(os.tmpdir(), `${name}.sock`);
362
+ const connections = /* @__PURE__ */ new Set();
363
+ const server = net.createServer((connection) => {
364
+ connections.add(connection);
365
+ connection.once("close", () => connections.delete(connection));
366
+ this.serveBridge(connection, token);
367
+ });
368
+ await new Promise((resolve, reject) => {
369
+ server.once("error", reject);
370
+ server.listen(socket, () => resolve());
371
+ });
372
+ this.bridge = { server, socket, token, connections };
373
+ }
374
+ const electron = process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [];
375
+ const bridge = bridgeCommand("acp");
376
+ return { name: "alp", command: bridge.command, args: bridge.args, env: [{ name: "ALP_BRIDGE_SOCKET", value: this.bridge.socket }, { name: "ALP_BRIDGE_TOKEN", value: this.bridge.token }, ...electron] };
377
+ }
378
+ serveBridge(connection, token) {
379
+ let trusted = false;
380
+ connection.setEncoding("utf8");
381
+ connection.on("error", () => {
382
+ });
383
+ const reply = (value) => {
384
+ if (!connection.destroyed) connection.write(`${JSON.stringify(value)}
385
+ `);
386
+ };
387
+ createInterface({ input: connection }).on("line", async (line) => {
388
+ let message;
389
+ try {
390
+ message = JSON.parse(line);
391
+ } catch {
392
+ connection.destroy();
393
+ return;
394
+ }
395
+ if (!trusted) {
396
+ if (message.token !== token) {
397
+ connection.destroy();
398
+ return;
399
+ }
400
+ trusted = true;
401
+ return;
402
+ }
403
+ if (message.op === "list") {
404
+ reply({ id: message.id, tools: this.tools.map((tool) => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema ?? { type: "object" } })) });
405
+ return;
406
+ }
407
+ if (message.op === "call") reply({ id: message.id, result: await this.toolCall(String(message.name), message.arguments ?? {}) });
408
+ });
409
+ }
410
+ async toolCall(tool, args) {
411
+ if (!this.requestHandler || !this.activeTurn || !this.tools.some((candidate) => candidate.name === tool)) {
412
+ return { content: [{ type: "text", text: this.activeTurn ? `Unknown ALP tool '${tool}'` : "ALP tools are unavailable between turns" }], isError: true };
413
+ }
414
+ const callId = `acp-tool-${randomUUID()}`;
415
+ const item = { type: "dynamicToolCall", id: callId, callId, tool, arguments: args };
416
+ this.closeMessage();
417
+ this.emit("item/started", { threadId: this.sessionId, item: { ...item, status: "inProgress" } });
418
+ const result = await this.requestHandler("item/tool/call", { threadId: this.sessionId, turnId: this.activeTurn, callId, namespace: null, tool, arguments: args }).catch((error) => ({ success: false, contentItems: [{ type: "inputText", text: error instanceof Error ? error.message : String(error) }] }));
419
+ const ok = result?.success !== false;
420
+ this.emit("item/completed", { threadId: this.sessionId, item: { ...item, status: ok ? "completed" : "failed", success: ok, contentItems: result?.contentItems ?? [] } });
421
+ return { content: (result?.contentItems ?? []).map((part) => ({ type: "text", text: part.text ?? JSON.stringify(part) })), isError: !ok };
422
+ }
423
+ emit(method, params) {
424
+ for (const listener of this.listeners) listener(method, params);
425
+ }
426
+ fail(error) {
427
+ if (this.closed) return;
428
+ for (const waiter of this.pending.values()) {
429
+ clearTimeout(waiter.timer);
430
+ waiter.reject(error);
431
+ }
432
+ this.pending.clear();
433
+ for (const listener of this.failures) listener(error);
434
+ void this.close();
435
+ }
436
+ async close() {
437
+ if (this.closed) return this.exit;
438
+ this.closed = true;
439
+ for (const waiter of this.pending.values()) {
440
+ clearTimeout(waiter.timer);
441
+ waiter.reject(new Error("Runtime closed"));
442
+ }
443
+ this.pending.clear();
444
+ this.listeners.clear();
445
+ this.failures.clear();
446
+ for (const answer of this.questions) answer({ outcome: { outcome: "cancelled" } });
447
+ this.questions.clear();
448
+ if (this.bridge) {
449
+ this.bridge.server.close();
450
+ for (const connection of this.bridge.connections) connection.destroy();
451
+ if (process.platform !== "win32") try {
452
+ rmSync(this.bridge.socket, { force: true });
453
+ } catch {
454
+ }
455
+ }
456
+ const child = this.child;
457
+ if (!child) return;
458
+ child.stdin.end();
459
+ const timer = setTimeout(() => {
460
+ if (process.platform === "win32" && child.pid) execFile("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true }, () => {
461
+ });
462
+ else child.kill("SIGKILL");
463
+ }, 1500);
464
+ let deadline;
465
+ try {
466
+ await Promise.race([this.exit, new Promise((resolve) => {
467
+ deadline = setTimeout(resolve, 4e3);
468
+ })]);
469
+ } finally {
470
+ clearTimeout(timer);
471
+ clearTimeout(deadline);
472
+ }
473
+ }
474
+ };
475
+ export {
476
+ AcpTransport,
477
+ acpContent,
478
+ acpDecision,
479
+ acpEnv,
480
+ acpPermission,
481
+ acpWhat
482
+ };
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Antigravity provider definition for ALP.
3
+ */
4
+ export type AntigravityProvider = {
5
+ id: string;
6
+ label: string;
7
+ command: string;
8
+ args?: string[];
9
+ env?: Record<string, string>;
10
+ models?: Array<{
11
+ id: string;
12
+ label?: string;
13
+ description?: string;
14
+ }>;
15
+ additionalModels?: Array<{
16
+ id: string;
17
+ label?: string;
18
+ description?: string;
19
+ }>;
20
+ enabled?: boolean;
21
+ };
22
+ type Listener = (method: string, params: any) => void;
23
+ type RequestHandler = (method: string, params: any) => Promise<unknown>;
24
+ /**
25
+ * Whether read-only allows a terminal command line, by ALP's own reading of the allowlist:
26
+ * one allowed command with no shell syntax. Unknown input is refused.
27
+ */
28
+ export declare function antigravityReadOnlyCommandAllowed(commandLine: unknown): boolean;
29
+ /**
30
+ * The agy flags for an ALP mode. Headless agy cannot ask the user, so a tool its
31
+ * permission mode does not allow is denied: both limited modes fail closed.
32
+ * - read-only: agy's default request-review policy; built-in reads and search run,
33
+ * READ_ONLY_COMMANDS run; edits and every other command are denied.
34
+ * - workspace-write: edits accepted and commands run in agy's terminal sandbox,
35
+ * which keeps writes in the workspace; a bypass of the sandbox is denied.
36
+ * - full-access: every tool runs without asking.
37
+ * Both limited modes trust the working directory (otherwise agy denies even its
38
+ * reads and edits there) and allow ALP's own MCP server, which carries alp_*.
39
+ */
40
+ export declare function antigravityModeArgs(sandbox: unknown, cwd: string): string[];
41
+ /** Efforts `agy --effort` takes (agy --help: low|medium|high|xhigh|max); others leave agy's default. */
42
+ export declare const AGY_EFFORTS: string[];
43
+ export declare function antigravityEffortArgs(thinking: unknown): string[];
44
+ /** What each mode lets an Antigravity agent do, for its instructions. */
45
+ export declare function antigravityModeText(sandbox: unknown): string;
46
+ export declare function encodePrompt(text: string): string;
47
+ /**
48
+ * AntigravityTransport runs the Antigravity CLI (agy) over its stream-json protocol.
49
+ * Emits line-delimited JSON events and parses stdout line by line.
50
+ */
51
+ export declare class AntigravityTransport {
52
+ private readonly command;
53
+ private readonly cwd;
54
+ private readonly env;
55
+ private readonly provider?;
56
+ /** Antigravity's prompt is one line of text: no images. */
57
+ takesImages(): boolean;
58
+ private child?;
59
+ private lines?;
60
+ private exit;
61
+ private listeners;
62
+ private failures;
63
+ private requestHandler?;
64
+ private closed;
65
+ private conversationId;
66
+ private config;
67
+ private activeTurn?;
68
+ private messageText;
69
+ private messages;
70
+ private instructionsSent;
71
+ private modeNote?;
72
+ private tools;
73
+ private bridge?;
74
+ private readyPromise?;
75
+ private resolveReady?;
76
+ private rejectReady?;
77
+ private external?;
78
+ private externalStarting?;
79
+ private readonly startupAbort;
80
+ constructor(command?: string, cwd?: string, env?: NodeJS.ProcessEnv, provider?: AntigravityProvider | undefined);
81
+ initialize(): Promise<void>;
82
+ onNotification(listener: Listener): () => void;
83
+ onFailure(listener: (error: Error) => void): () => void;
84
+ onRequest(handler: RequestHandler): void;
85
+ request(method: string, params: any): Promise<any>;
86
+ private startProcess;
87
+ private receiveLine;
88
+ private handleStepUpdate;
89
+ /** Whether read-only refuses this tool step: an edit, or a terminal command outside the allowlist. */
90
+ private readOnlyRefuses;
91
+ private handleResult;
92
+ private endTurn;
93
+ private openBridge;
94
+ /** One stable launcher; each child inherits its own socket/token from agy.
95
+ * No session endpoint or credential is written to the global configuration.
96
+ * Leave the launcher installed: removing it would break concurrent sessions.
97
+ */
98
+ private registerMcpServer;
99
+ private serveBridge;
100
+ private toolCall;
101
+ private emit;
102
+ /** agy exits on SIGINT. Ignore that expected exit; the next prompt resumes its conversation in a fresh process. */
103
+ private stopProcess;
104
+ private fail;
105
+ close(): Promise<void>;
106
+ }
107
+ export {};