@zvada/agent-server 0.3.27 → 0.3.30

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 (190) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +6 -4
  3. package/dist/core/agents/acp/account.js +111 -0
  4. package/dist/core/agents/acp/acp-agent.js +249 -158
  5. package/dist/core/agents/acp/adapter.js +103 -34
  6. package/dist/core/agents/acp/client.js +169 -42
  7. package/dist/core/agents/acp/known-agents.js +12 -5
  8. package/dist/core/agents/acp/mappings.js +84 -20
  9. package/dist/core/agents/acp/models.js +59 -0
  10. package/dist/core/agents/acp/profile.js +36 -0
  11. package/dist/core/agents/acp/prompts.js +248 -0
  12. package/dist/core/agents/acp/requests.js +4 -4
  13. package/dist/core/agents/claude-code/claude-agent.js +2 -12
  14. package/dist/core/agents/claude-code/login.js +4 -1
  15. package/dist/core/agents/claude-code/session.js +50 -18
  16. package/dist/core/agents/claude-code/spawn.js +0 -26
  17. package/dist/core/agents/claude-code/turn.js +6 -2
  18. package/dist/core/agents/codex-app-server/client.js +12 -13
  19. package/dist/core/agents/codex-app-server/login.js +4 -1
  20. package/dist/core/agents/gemini/failures.js +133 -0
  21. package/dist/core/agents/gemini/login.js +173 -0
  22. package/dist/core/agents/gemini/profile.js +138 -0
  23. package/dist/core/agents/gemini/tools.js +91 -0
  24. package/dist/core/agents/login.js +8 -6
  25. package/dist/core/agents/stderr-tail.js +5 -2
  26. package/dist/core/presets.js +13 -0
  27. package/dist/core/processes/native-processes.js +23 -1
  28. package/dist/core/provision/install-build.js +70 -26
  29. package/dist/core/provision/pins.js +5 -0
  30. package/dist/core/provision/provisioner.js +39 -16
  31. package/dist/core/provision/releases.js +39 -1
  32. package/dist/core/provision/tools.js +87 -28
  33. package/dist/operator/errors.js +2 -2
  34. package/dist/operator/operator.js +201 -90
  35. package/dist/operator/render.js +34 -28
  36. package/dist/operator/session-tools.js +2 -1
  37. package/dist/protocol/account.js +5 -1
  38. package/dist/protocol/auth.js +5 -1
  39. package/dist/protocol/config.js +4 -2
  40. package/dist/protocol/credentials.js +9 -1
  41. package/dist/protocol/harness.js +9 -1
  42. package/dist/protocol/part-input.js +2 -6
  43. package/dist/protocol/text-parts.js +10 -0
  44. package/dist/server/bin.js +22 -7
  45. package/dist/server/install.js +6 -4
  46. package/dist/types/core/agents/acp/account.d.ts +55 -0
  47. package/dist/types/core/agents/acp/account.d.ts.map +1 -0
  48. package/dist/types/core/agents/acp/acp-agent.d.ts +65 -36
  49. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  50. package/dist/types/core/agents/acp/adapter.d.ts +28 -3
  51. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  52. package/dist/types/core/agents/acp/client.d.ts +66 -4
  53. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  54. package/dist/types/core/agents/acp/known-agents.d.ts +4 -2
  55. package/dist/types/core/agents/acp/known-agents.d.ts.map +1 -1
  56. package/dist/types/core/agents/acp/mappings.d.ts +53 -7
  57. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  58. package/dist/types/core/agents/acp/models.d.ts +22 -0
  59. package/dist/types/core/agents/acp/models.d.ts.map +1 -0
  60. package/dist/types/core/agents/acp/profile.d.ts +97 -0
  61. package/dist/types/core/agents/acp/profile.d.ts.map +1 -0
  62. package/dist/types/core/agents/acp/prompts.d.ts +108 -0
  63. package/dist/types/core/agents/acp/prompts.d.ts.map +1 -0
  64. package/dist/types/core/agents/acp/requests.d.ts +7 -1
  65. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  66. package/dist/types/core/agents/claude-code/claude-agent.d.ts +1 -2
  67. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  68. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  69. package/dist/types/core/agents/claude-code/options.d.ts +1 -1
  70. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  71. package/dist/types/core/agents/claude-code/session.d.ts +7 -6
  72. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  73. package/dist/types/core/agents/claude-code/spawn.d.ts +0 -8
  74. package/dist/types/core/agents/claude-code/spawn.d.ts.map +1 -1
  75. package/dist/types/core/agents/claude-code/turn.d.ts +3 -2
  76. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -1
  77. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  78. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  79. package/dist/types/core/agents/gemini/failures.d.ts +25 -0
  80. package/dist/types/core/agents/gemini/failures.d.ts.map +1 -0
  81. package/dist/types/core/agents/gemini/login.d.ts +28 -0
  82. package/dist/types/core/agents/gemini/login.d.ts.map +1 -0
  83. package/dist/types/core/agents/gemini/profile.d.ts +30 -0
  84. package/dist/types/core/agents/gemini/profile.d.ts.map +1 -0
  85. package/dist/types/core/agents/gemini/tools.d.ts +18 -0
  86. package/dist/types/core/agents/gemini/tools.d.ts.map +1 -0
  87. package/dist/types/core/agents/login.d.ts +15 -5
  88. package/dist/types/core/agents/login.d.ts.map +1 -1
  89. package/dist/types/core/agents/stderr-tail.d.ts +1 -1
  90. package/dist/types/core/agents/stderr-tail.d.ts.map +1 -1
  91. package/dist/types/core/presets.d.ts +2 -2
  92. package/dist/types/core/presets.d.ts.map +1 -1
  93. package/dist/types/core/processes/native-processes.d.ts +6 -0
  94. package/dist/types/core/processes/native-processes.d.ts.map +1 -1
  95. package/dist/types/core/provision/checksums.d.ts +7 -1
  96. package/dist/types/core/provision/checksums.d.ts.map +1 -1
  97. package/dist/types/core/provision/install-build.d.ts +32 -6
  98. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  99. package/dist/types/core/provision/pins.d.ts +4 -0
  100. package/dist/types/core/provision/pins.d.ts.map +1 -1
  101. package/dist/types/core/provision/provisioner.d.ts +18 -7
  102. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  103. package/dist/types/core/provision/releases.d.ts +2 -1
  104. package/dist/types/core/provision/releases.d.ts.map +1 -1
  105. package/dist/types/core/provision/tools.d.ts +36 -7
  106. package/dist/types/core/provision/tools.d.ts.map +1 -1
  107. package/dist/types/operator/errors.d.ts +5 -1
  108. package/dist/types/operator/errors.d.ts.map +1 -1
  109. package/dist/types/operator/operator.d.ts.map +1 -1
  110. package/dist/types/operator/render.d.ts +11 -6
  111. package/dist/types/operator/render.d.ts.map +1 -1
  112. package/dist/types/operator/session-tools.d.ts.map +1 -1
  113. package/dist/types/operator/types.d.ts +5 -4
  114. package/dist/types/operator/types.d.ts.map +1 -1
  115. package/dist/types/protocol/account.d.ts +4 -2
  116. package/dist/types/protocol/account.d.ts.map +1 -1
  117. package/dist/types/protocol/auth.d.ts +10 -7
  118. package/dist/types/protocol/auth.d.ts.map +1 -1
  119. package/dist/types/protocol/clis.d.ts +4 -3
  120. package/dist/types/protocol/clis.d.ts.map +1 -1
  121. package/dist/types/protocol/config.d.ts +6 -2
  122. package/dist/types/protocol/config.d.ts.map +1 -1
  123. package/dist/types/protocol/conversation.d.ts +3 -3
  124. package/dist/types/protocol/credentials.d.ts +8 -0
  125. package/dist/types/protocol/credentials.d.ts.map +1 -1
  126. package/dist/types/protocol/execution.d.ts +1 -1
  127. package/dist/types/protocol/harness.d.ts +5 -2
  128. package/dist/types/protocol/harness.d.ts.map +1 -1
  129. package/dist/types/protocol/lifecycle.d.ts +8 -8
  130. package/dist/types/protocol/models.d.ts +3 -0
  131. package/dist/types/protocol/models.d.ts.map +1 -1
  132. package/dist/types/protocol/part-input.d.ts.map +1 -1
  133. package/dist/types/protocol/text-parts.d.ts +10 -0
  134. package/dist/types/protocol/text-parts.d.ts.map +1 -0
  135. package/dist/types/protocol/wire-api.d.ts +39 -29
  136. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  137. package/dist/types/protocol/wire.d.ts +13 -10
  138. package/dist/types/protocol/wire.d.ts.map +1 -1
  139. package/dist/types/server/install.d.ts +2 -1
  140. package/dist/types/server/install.d.ts.map +1 -1
  141. package/docs/consuming.md +8 -1
  142. package/docs/deploy.md +17 -8
  143. package/docs/harnesses.md +173 -44
  144. package/package.json +1 -1
  145. package/src/core/agents/acp/account.ts +158 -0
  146. package/src/core/agents/acp/acp-agent.ts +290 -178
  147. package/src/core/agents/acp/adapter.ts +126 -35
  148. package/src/core/agents/acp/client.ts +196 -49
  149. package/src/core/agents/acp/known-agents.ts +14 -5
  150. package/src/core/agents/acp/mappings.ts +112 -21
  151. package/src/core/agents/acp/models.ts +72 -0
  152. package/src/core/agents/acp/profile.ts +133 -0
  153. package/src/core/agents/acp/prompts.ts +287 -0
  154. package/src/core/agents/acp/requests.ts +16 -9
  155. package/src/core/agents/claude-code/claude-agent.ts +2 -13
  156. package/src/core/agents/claude-code/login.ts +4 -1
  157. package/src/core/agents/claude-code/options.ts +1 -1
  158. package/src/core/agents/claude-code/session.ts +50 -16
  159. package/src/core/agents/claude-code/spawn.ts +0 -26
  160. package/src/core/agents/claude-code/turn.ts +7 -2
  161. package/src/core/agents/codex-app-server/client.ts +11 -18
  162. package/src/core/agents/codex-app-server/login.ts +4 -5
  163. package/src/core/agents/gemini/failures.ts +148 -0
  164. package/src/core/agents/gemini/login.ts +188 -0
  165. package/src/core/agents/gemini/profile.ts +163 -0
  166. package/src/core/agents/gemini/tools.ts +99 -0
  167. package/src/core/agents/login.ts +14 -8
  168. package/src/core/agents/stderr-tail.ts +5 -2
  169. package/src/core/presets.ts +15 -2
  170. package/src/core/processes/native-processes.ts +32 -1
  171. package/src/core/provision/checksums.ts +12 -2
  172. package/src/core/provision/install-build.ts +122 -55
  173. package/src/core/provision/pins.ts +5 -0
  174. package/src/core/provision/provisioner.ts +62 -27
  175. package/src/core/provision/releases.ts +47 -1
  176. package/src/core/provision/tools.ts +124 -31
  177. package/src/operator/errors.ts +5 -2
  178. package/src/operator/operator.ts +208 -91
  179. package/src/operator/render.ts +61 -33
  180. package/src/operator/session-tools.ts +2 -1
  181. package/src/operator/types.ts +5 -4
  182. package/src/protocol/account.ts +5 -2
  183. package/src/protocol/auth.ts +5 -1
  184. package/src/protocol/config.ts +4 -2
  185. package/src/protocol/credentials.ts +11 -2
  186. package/src/protocol/harness.ts +9 -1
  187. package/src/protocol/part-input.ts +2 -5
  188. package/src/protocol/text-parts.ts +10 -0
  189. package/src/server/bin.ts +20 -6
  190. package/src/server/install.ts +6 -3
@@ -1,6 +1,5 @@
1
1
  import { StringDecoder } from "node:string_decoder";
2
2
  import type { NativeProcess, NativeProcesses } from "../../processes/native-processes.ts";
3
- import { AgentExitedError } from "../../utils/errors.ts";
4
3
  import type { CodexNotification } from "./protocol.ts";
5
4
 
6
5
  /** What the pinned native server logs of a cleanup that failed; it still exits 0. */
@@ -224,14 +223,16 @@ export class CodexAppServerClient implements CodexConnection {
224
223
  }
225
224
 
226
225
  request(method: string, params: unknown, timeoutMs?: number): Promise<unknown> {
227
- if (!this.native || this.exited)
226
+ const native = this.native;
227
+ if (!native || this.exited)
228
228
  return Promise.reject(this.lastExit ?? new Error("codex app-server not running"));
229
229
  const id = this.nextId++;
230
230
  return new Promise<unknown>((resolve, reject) => {
231
231
  const deadline = timeoutMs ?? this.opts.requestTimeoutMs ?? 30_000;
232
232
  const timer = setTimeout(() => {
233
233
  this.pending.delete(id);
234
- reject(new Error(`codex app-server '${method}' timed out after ${deadline}ms`));
234
+ const stderr = method === "initialize" ? `. ${native.stderrSummary}` : "";
235
+ reject(new Error(`codex app-server '${method}' timed out after ${deadline}ms${stderr}`));
235
236
  }, deadline);
236
237
  this.pending.set(id, { method, resolve, reject, timer });
237
238
  try {
@@ -346,10 +347,9 @@ export class CodexAppServerClient implements CodexConnection {
346
347
  proc.stdout?.on("data", (chunk: Buffer) => this.onStdout(chunk));
347
348
  // A broken pipe usually means the process died: its exit, which says
348
349
  // how and carries its stderr, is the error to keep when it follows.
349
- const onPipeError = (err: Error) =>
350
- setTimeout(() => {
351
- if (this.native === native) this.onExit(err);
352
- }, 1_000).unref?.();
350
+ const onPipeError = async (err: Error) => {
351
+ if (!(await native.exitAfterDisconnect()) && this.native === native) this.onExit(err);
352
+ };
353
353
  proc.stdin?.on("error", onPipeError);
354
354
  proc.stdout?.on("error", onPipeError);
355
355
  // The pinned native server logs its cleanup failures but still exits 0.
@@ -360,17 +360,10 @@ export class CodexAppServerClient implements CodexConnection {
360
360
  recent = recent.slice(-SNIFF_MAX);
361
361
  });
362
362
  proc.on("error", (err) => this.onExit(err));
363
- // Its exit once stdout and stderr closed: a response it wrote just before
364
- // is read first, and stderr's last flush, usually the line that says WHY
365
- // (a missing or expired login prints there and exits 1), is in the tail.
366
- void native.exited.then(({ code, signal }) => {
367
- const tail = native.stderrTail.trim().replace(/\s+/g, " ");
368
- // The process exiting is the failure (`process_exit`), whatever its stderr says.
369
- this.onExit(
370
- new AgentExitedError(
371
- `codex app-server exited (code=${code} signal=${signal})${tail ? `: ${tail}` : ""}`,
372
- ),
373
- );
363
+ void native.exited.then((exit) => {
364
+ if (this.native !== native || this.exited) return;
365
+ const pending = Array.from(this.pending.values(), (request) => request.method);
366
+ this.onExit(native.exitError("codex app-server", exit, pending));
374
367
  });
375
368
  }
376
369
 
@@ -144,11 +144,10 @@ export class CodexCliLogin implements CliLogin {
144
144
  async methods(options: LoginOptions): Promise<AuthMethod[]> {
145
145
  return [
146
146
  ...LOGINS.map(({ type: _type, ...method }) => method),
147
- terminalMethod(
148
- [await this.options.cliPath(), "login"],
149
- { ...process.env, ...options.env },
150
- STORE_VARIABLE,
151
- ),
147
+ terminalMethod([await this.options.cliPath(), "login"], {
148
+ variable: STORE_VARIABLE,
149
+ env: { ...process.env, ...options.env },
150
+ }),
152
151
  ];
153
152
  }
154
153
 
@@ -0,0 +1,148 @@
1
+ import type { SessionUpdate } from "@agentclientprotocol/sdk";
2
+ import { type ErrorCategory, type ErrorInfo, classifyError } from "../../../protocol/index.ts";
3
+ import type { AcpRawEvent } from "../acp/adapter.ts";
4
+ import type { EventTransformer } from "../types.ts";
5
+
6
+ /**
7
+ * What Antigravity says when its model call failed, in place of a JSON-RPC
8
+ * error (measured on 1.5.14, LLP 0020.001, When the model call fails):
9
+ * `⚠ agent executor error: generating and executing: Error <code>, Message:
10
+ * <Google's sentence>, Status: <STATUS>, Details: […]` for an HTTP status,
11
+ * and the same prefix with the transport's own words for a request that got
12
+ * no HTTP response (a TLS failure, in a container with no CA certificates).
13
+ * The prefix is the marker: an executor error worded another way after it
14
+ * still fails the turn, read by the engine's words.
15
+ */
16
+ const EXECUTOR_ERROR = /^\s*⚠ agent executor error: (?:generating and executing: )?(.*?)\s*$/s;
17
+ const HTTP_ERROR = /^Error (\d{3}), Message: (.*?), Status: ([A-Z_]+)(?:, Details: (.*))?$/is;
18
+
19
+ /** The transport's own words for a request that got no HTTP response. */
20
+ const NO_RESPONSE = /^doRequest: error sending request\b/;
21
+
22
+ /**
23
+ * A key Google refuses, whatever the status: a made-up key is a 400
24
+ * `INVALID_ARGUMENT`, a string it takes for an access token a 401. Google
25
+ * names its own reason in `Details` (`reason:API_KEY_INVALID` in agy's dump);
26
+ * where that is missing, its sentence says it.
27
+ */
28
+ const BAD_KEY = { reason: /\breason:API_KEY_INVALID\b/, sentence: /^API key not valid\b/ };
29
+
30
+ /** What it says when the connection to Google closed or broke. */
31
+ const NETWORK_ISSUE =
32
+ /^\s*⚠ (There was a network issue connecting to the server, please try again\.)\s*$/;
33
+
34
+ /**
35
+ * Google's API statuses, as data of that provider. A 429 is `rate_limit`
36
+ * whether it is a per-minute limit or an exhausted quota: Google answers both
37
+ * with the one status and the one sentence, so its words cannot tell them
38
+ * apart. Any other status is read from its words (`classifyError`).
39
+ */
40
+ const GOOGLE_STATUSES: Partial<Record<number, ErrorCategory>> = {
41
+ 400: "invalid_request",
42
+ 401: "auth",
43
+ 403: "auth",
44
+ 404: "invalid_request",
45
+ 429: "rate_limit",
46
+ 503: "overloaded",
47
+ };
48
+
49
+ /**
50
+ * The failure an Antigravity message chunk reports, when the chunk's whole
51
+ * text is one of its wordings: the category from Google's status (its word
52
+ * in any case), `network` for a request that got no HTTP response, and any
53
+ * other executor error by its words (`classifyError`); the message Google's
54
+ * own sentence with its status, never the map dump of `Details`, or the
55
+ * executor's words as they are.
56
+ */
57
+ export function antigravityFailure(text: string): ErrorInfo | undefined {
58
+ const network = NETWORK_ISSUE.exec(text);
59
+ if (network) return { category: "network", message: network[1] ?? text.trim() };
60
+ const rest = EXECUTOR_ERROR.exec(text)?.[1];
61
+ if (rest === undefined) return undefined;
62
+ const http = HTTP_ERROR.exec(rest);
63
+ if (!http)
64
+ return { category: NO_RESPONSE.test(rest) ? "network" : classifyError(rest), message: rest };
65
+ const [, code = "", sentence = "", status = "", details = ""] = http;
66
+ const message = `${sentence} (${code} ${status})`;
67
+ if (BAD_KEY.reason.test(details) || BAD_KEY.sentence.test(sentence))
68
+ return { category: "auth", message };
69
+ return { category: GOOGLE_STATUSES[Number(code)] ?? classifyError(message), message };
70
+ }
71
+
72
+ /**
73
+ * Whether an update is the agent saying or doing something in its turn (a
74
+ * message or thought chunk, a tool call or its update), not a report on the
75
+ * session (usage, mode, commands, options, its title).
76
+ */
77
+ function isContent(update: SessionUpdate): boolean {
78
+ switch (update.sessionUpdate) {
79
+ case "agent_message_chunk":
80
+ case "agent_thought_chunk":
81
+ case "tool_call":
82
+ case "tool_call_update":
83
+ return true;
84
+ default:
85
+ return false;
86
+ }
87
+ }
88
+
89
+ // @ref LLP 0020#12-a-failed-model-call-fails-the-turn — the agent's last message chunk is its report of a failure
90
+ /**
91
+ * The gemini adapter's reading of a failed model call, in front of the ACP
92
+ * adapter: Antigravity never fails a prompt for it, but sends one message
93
+ * chunk saying so (`antigravityFailure`) and answers `end_turn`. Such a chunk
94
+ * is held; any later content of the turn (`isContent`) lets it go as the
95
+ * text it is, in its place, while updates that are not content do not. A
96
+ * steer read waits behind it: after the chunk once it goes, or before the
97
+ * turn's end (the agent took the steer). At the prompt's answer a chunk still
98
+ * held fails the turn instead, with its category and message and the
99
+ * answer's usage; a cancelled prompt stays cancelled, its words shown.
100
+ */
101
+ export function antigravityFailures(
102
+ acp: EventTransformer<AcpRawEvent>,
103
+ ): EventTransformer<AcpRawEvent> {
104
+ let held: { event: AcpRawEvent; failure: ErrorInfo; reads: AcpRawEvent[] } | undefined;
105
+ const release = () => {
106
+ const events = held ? [held.event, ...held.reads] : [];
107
+ held = undefined;
108
+ return events.flatMap((one) => acp.process(one));
109
+ };
110
+ return {
111
+ process(event) {
112
+ if (event.method === "session/update") {
113
+ const { update } = event.params;
114
+ const text =
115
+ update.sessionUpdate === "agent_message_chunk" && update.content.type === "text"
116
+ ? update.content.text
117
+ : "";
118
+ const failure = text ? antigravityFailure(text) : undefined;
119
+ if (failure) {
120
+ const before = release();
121
+ held = { event, failure, reads: [] };
122
+ return before;
123
+ }
124
+ return isContent(update) ? [...release(), ...acp.process(event)] : acp.process(event);
125
+ }
126
+ if (
127
+ event.method === "session/prompt_result" &&
128
+ held &&
129
+ event.params.stopReason !== "cancelled"
130
+ ) {
131
+ const { failure, reads } = held;
132
+ held = undefined;
133
+ return [
134
+ ...reads.flatMap((read) => acp.process(read)),
135
+ ...acp.process({ method: "error", params: { ...failure, usage: event.params.usage } }),
136
+ ];
137
+ }
138
+ if (event.method === "agentServer/steerRead" && held) {
139
+ held.reads.push(event);
140
+ return [];
141
+ }
142
+ return event.method === "agentServer/mcpServers"
143
+ ? acp.process(event)
144
+ : [...release(), ...acp.process(event)];
145
+ },
146
+ finish: () => acp.finish(),
147
+ };
148
+ }
@@ -0,0 +1,188 @@
1
+ import type { AuthMethod } from "../../../protocol/index.ts";
2
+ import type { NativeProcess } from "../../processes/native-processes.ts";
3
+ import { onAbort } from "../../utils/deadline.ts";
4
+ import { InvalidRequestError } from "../../utils/errors.ts";
5
+ import { isRecord } from "../../utils/is-record.ts";
6
+ import { type AcpAccount, type AcpAccountRead, privateFolder } from "../acp/account.ts";
7
+ import {
8
+ type CliLogin,
9
+ type LoginOptions,
10
+ type LoginStatus,
11
+ type NativeLogin,
12
+ loginMethod,
13
+ terminalMethod,
14
+ } from "../login.ts";
15
+
16
+ /** The login Antigravity runs itself: a Google sign-in whose page shows a code to paste. */
17
+ const LOGINS: readonly AuthMethod[] = [
18
+ { id: "google", kind: "browser", label: "Google account", credential: "subscription" },
19
+ ];
20
+
21
+ /** What the agent answers `session/new` with when no one is signed in. */
22
+ const SIGNED_OUT = -32000;
23
+
24
+ /**
25
+ * Where `agy acp --login` sends the person: Google's sign-in page, whose
26
+ * redirect shows the code. Taken once its line ended: output comes in chunks.
27
+ */
28
+ const SIGN_IN_URL = /(https:\/\/accounts\.google\.com\/\S+)\r?\n/;
29
+
30
+ const REFUSED =
31
+ "Antigravity did not accept this code: sign in again, and paste the code the page shows.";
32
+
33
+ /** The plan a session says the account is on (`_meta.antigravity.tier`), when it says one. */
34
+ function tierOf(read: AcpAccountRead): { id?: string; name?: string } {
35
+ const meta = read.session._meta;
36
+ const antigravity = isRecord(meta) ? meta.antigravity : undefined;
37
+ const tier = isRecord(antigravity) ? antigravity.tier : undefined;
38
+ if (!isRecord(tier)) return {};
39
+ return {
40
+ ...(typeof tier.id === "string" && { id: tier.id }),
41
+ ...(typeof tier.name === "string" && { name: tier.name }),
42
+ };
43
+ }
44
+
45
+ /**
46
+ * A login as a session with no turn says it, and no more: a session that
47
+ * names a plan (`_meta.antigravity.tier`, as a Google sign-in's does) is a
48
+ * subscription from the CLI's login, on that plan; one that names none (a
49
+ * key's) is signed in, and claims no credential, source or plan. A wrong key
50
+ * reads signed in too, since its session opens: its first turn fails, as an
51
+ * authentication error (LLP 0020, decision 9).
52
+ */
53
+ function antigravityLoginStatus(read: AcpAccountRead): LoginStatus {
54
+ const tier = tierOf(read);
55
+ if (!tier.id && !tier.name) return { state: "signed_in" };
56
+ return {
57
+ state: "signed_in",
58
+ credential: "subscription",
59
+ source: "login",
60
+ provider: "google",
61
+ ...(tier.id && { plan: tier.id }),
62
+ ...(tier.name && { label: tier.name }),
63
+ };
64
+ }
65
+
66
+ // @ref LLP 0011#the-engine-reads-and-runs-the-clis-login-and-holds-no-credential — the CLI's own flow, its own store
67
+ /**
68
+ * The Antigravity CLI's login: one per OS user, in the system keyring
69
+ * (`store` absent), whatever folder flags it runs with. Its status is a
70
+ * session the agent opens, or refuses; sign-in is `agy acp --login`; sign-out
71
+ * the agent's ACP `logout`.
72
+ */
73
+ export class AntigravityCliLogin implements CliLogin {
74
+ constructor(private readonly account: AcpAccount) {}
75
+
76
+ /**
77
+ * Its sign-ins, and the command that runs one in a terminal, with the
78
+ * launch's fixed environment: refused, as a turn is, with no agy to run.
79
+ */
80
+ async methods(_options: LoginOptions): Promise<AuthMethod[]> {
81
+ const launch = await this.account.launch();
82
+ const terminal = terminalMethod([launch.command, ...(launch.args ?? []), "--login"]);
83
+ return [...LOGINS, { ...terminal, ...(launch.fixedEnv && { env: launch.fixedEnv }) }];
84
+ }
85
+
86
+ async status(options: LoginOptions): Promise<LoginStatus> {
87
+ try {
88
+ return antigravityLoginStatus(
89
+ await this.account.open(options, async (_client, read) => read),
90
+ );
91
+ } catch (error) {
92
+ if ((error as { code?: unknown }).code === SIGNED_OUT) return { state: "signed_out" };
93
+ return { state: "unknown", error: error instanceof Error ? error.message : String(error) };
94
+ }
95
+ }
96
+
97
+ /**
98
+ * `agy acp --login`: it prints the sign-in address, then reads the code
99
+ * the page shows from stdin, and exits 0 once it stored the login. A desktop
100
+ * agy also opens the browser itself.
101
+ */
102
+ async start(id: string, options: LoginOptions): Promise<NativeLogin> {
103
+ loginMethod(LOGINS, id);
104
+ const launch = await this.account.launch(options.signal);
105
+ // Antigravity takes the folder it starts in as its workspace: one of its own.
106
+ const folder = privateFolder();
107
+ let native: NativeProcess;
108
+ try {
109
+ native = this.account.processes.spawn({
110
+ command: launch.command,
111
+ args: [...(launch.args ?? []), "--login"],
112
+ cwd: folder.path,
113
+ env: { ...process.env, ...launch.env, ...options.env, ...launch.fixedEnv },
114
+ harness: "gemini",
115
+ });
116
+ } catch (error) {
117
+ void folder.removeAfter();
118
+ throw error;
119
+ }
120
+ void folder.removeAfter(native.exited);
121
+ const stop = () => void native.stop();
122
+ let printed = "";
123
+ const codeUrl = new Promise<string>((resolve, reject) => {
124
+ native.child.stdout?.setEncoding("utf8").on("data", (chunk: string) => {
125
+ printed += chunk;
126
+ const url = SIGN_IN_URL.exec(printed)?.[1];
127
+ if (url) resolve(url);
128
+ });
129
+ native.child.once("error", reject);
130
+ void native.exited.then(() =>
131
+ reject(new Error(lastLine(printed) || "agy acp --login answered no sign-in address")),
132
+ );
133
+ });
134
+ // A start the engine gave up on stops its CLI.
135
+ const offAbort = onAbort(options.signal, stop);
136
+ let url: string;
137
+ try {
138
+ url = await codeUrl;
139
+ } catch (error) {
140
+ stop();
141
+ throw error;
142
+ } finally {
143
+ offAbort();
144
+ }
145
+ let codeSent = false;
146
+ const done = native.exited.then(({ code }) => {
147
+ if (code === 0) return;
148
+ const said = lastLine(printed) || native.stderrTail.trim() || `agy exited ${code}`;
149
+ throw codeSent ? new Error(REFUSED, { cause: new Error(said) }) : new Error(said);
150
+ });
151
+ // A caller that only cancels has nothing to hear.
152
+ done.catch(() => {});
153
+ return {
154
+ codeUrl: url,
155
+ done,
156
+ complete: async (pasted) => {
157
+ const code = pasted.trim();
158
+ if (!code) throw new InvalidRequestError([{ path: "code", message: "no code was pasted" }]);
159
+ codeSent = true;
160
+ // One line, then nothing more: the CLI takes it, or ends refusing it.
161
+ native.child.stdin?.end(`${code}\n`);
162
+ await done;
163
+ },
164
+ cancel: stop,
165
+ };
166
+ }
167
+
168
+ /** The method Google documents, ACP `logout`: it removes the OS keyring entry (LLP 0020.002). */
169
+ async logout(options: LoginOptions): Promise<void> {
170
+ await this.account.connect(options, async (client, init) => {
171
+ if (!init.agentCapabilities?.auth?.logout) {
172
+ throw new Error("This Antigravity CLI cannot sign out from here: run agy, then /logout.");
173
+ }
174
+ await client.request("logout", {});
175
+ });
176
+ }
177
+ }
178
+
179
+ /** The last thing a CLI printed: why it ended. */
180
+ function lastLine(text: string): string {
181
+ return (
182
+ text
183
+ .split("\n")
184
+ .map((line) => line.trim())
185
+ .filter(Boolean)
186
+ .at(-1) ?? ""
187
+ );
188
+ }
@@ -0,0 +1,163 @@
1
+ import type { InitializeResponse } from "@agentclientprotocol/sdk";
2
+ import type { AgentCapabilities, RunConfig } from "../../../protocol/index.ts";
3
+ import { CliNotFoundError, CliProvisionError, InvalidRequestError } from "../../utils/errors.ts";
4
+ import { type AcpAgentOptions, ProfiledAcpAgent } from "../acp/acp-agent.ts";
5
+ import { createAcpTransformer } from "../acp/adapter.ts";
6
+ import type { AcpProfile } from "../acp/profile.ts";
7
+ import type { InheritConfig } from "../inherit-config.ts";
8
+ import type { AdapterFactory } from "../types.ts";
9
+ import { antigravityFailures } from "./failures.ts";
10
+ import { AntigravityCliLogin } from "./login.ts";
11
+ import { antigravityToolRules } from "./tools.ts";
12
+
13
+ /** The oldest Antigravity CLI the harness drives: the one its behaviour was measured on. */
14
+ export const ANTIGRAVITY_FLOOR = "1.5.13";
15
+
16
+ const CAPABILITIES: AgentCapabilities = {
17
+ multiTurn: true,
18
+ sessionResume: true,
19
+ // Set on the live session through its `model` option.
20
+ modelSwitch: "in_session",
21
+ // Its `thought_level` option, with each model's own levels.
22
+ thinkingLevels: true,
23
+ images: true,
24
+ // A PDF or another binary file is taken and dropped unread: only text is offered.
25
+ files: ["text"],
26
+ mcpServers: true,
27
+ permissionRequests: true,
28
+ // The answer is an option id.
29
+ rejectionMessages: false,
30
+ // A prompt sent while one runs is input to the running turn (LLP 0016.000).
31
+ steering: true,
32
+ ignoredSettings: [
33
+ // A prompt runs until the agent ends it: ACP v1 has no turn limit.
34
+ "maxTurns",
35
+ // session/resume names a session, not a message in it.
36
+ "resumeSessionAt",
37
+ // It runs on the person's own Antigravity sign-in.
38
+ "apiKey",
39
+ // ACP v1 cannot ask an agent to run without its tools.
40
+ "disableTools",
41
+ ] satisfies Array<keyof RunConfig>,
42
+ };
43
+
44
+ /**
45
+ * A Gemini model, by its id: `gemini-<version>-…`. Antigravity also lists
46
+ * Claude and GPT-OSS models and its `gemini-pro-orchestrator-*` entries,
47
+ * which the harness does not offer.
48
+ */
49
+ export function isGeminiModel(id: string): boolean {
50
+ return /^gemini-\d/.test(id);
51
+ }
52
+
53
+ /** Whether `found` is at least `floor`, by its numeric parts. */
54
+ function atLeast(found: string, floor: string): boolean {
55
+ const parts = (version: string) => version.split(/[.-]/).map((part) => Number.parseInt(part, 10));
56
+ const [have, need] = [parts(found), parts(floor)];
57
+ for (let i = 0; i < need.length; i++) {
58
+ const a = have[i] ?? 0;
59
+ const b = need[i] ?? 0;
60
+ if (Number.isNaN(a)) return false;
61
+ if (a !== b) return a > b;
62
+ }
63
+ return true;
64
+ }
65
+
66
+ // @ref LLP 0020#11-inheritconfig-must-be-all — the folder's configuration always loads; the person's needs a home of its own
67
+ /** Why a turn at each level below `all` cannot run (LLP 0020, decision 11). */
68
+ const CANNOT_INHERIT: Record<Exclude<InheritConfig, "all">, string> = {
69
+ none: "the gemini harness cannot run at inheritConfig `none`: Antigravity always loads the folder's own rules, skills, MCP servers and hooks, and nothing turns that off",
70
+ project:
71
+ "the gemini harness cannot run at inheritConfig `project` yet: keeping the person's own configuration out takes an Antigravity home of the session's own (`--gemini-dir`), which this harness does not take yet",
72
+ };
73
+
74
+ /** Refuse a turn at a level Antigravity cannot keep to. */
75
+ function admit(level: InheritConfig): void {
76
+ if (level === "all") return;
77
+ throw new InvalidRequestError([{ path: "inheritConfig", message: CANNOT_INHERIT[level] }]);
78
+ }
79
+
80
+ /**
81
+ * Refuse an Antigravity CLI older than the floor, or one that does not say
82
+ * its version: a CLI found and unusable, the operator's environment as a bad
83
+ * override is (`CliProvisionError`, `invalid_request`), never an engine fault.
84
+ * The engine's own build is the pin, above the floor, so only the person's
85
+ * own agy (`system` mode) or an overridden one can trip it: `agy update` is
86
+ * theirs to run.
87
+ */
88
+ function accept(init: InitializeResponse): void {
89
+ const version = init.agentInfo?.version;
90
+ if (version && atLeast(version, ANTIGRAVITY_FLOOR)) return;
91
+ throw new CliProvisionError(
92
+ `the gemini harness needs Antigravity CLI ${ANTIGRAVITY_FLOOR} or later, and found ${version ?? "one that does not say its version"}: update it with \`agy update\``,
93
+ { category: "invalid_request" },
94
+ );
95
+ }
96
+
97
+ // @ref LLP 0020#10-the-engine-installs-and-pins-agy — Google's switch, set on every start, keeps the pinned build the one that runs
98
+ /**
99
+ * What every agy the harness starts runs with, over any environment a turn
100
+ * brings (`fixedEnv`; a turn's comes from the wire): no update of itself,
101
+ * which would replace the pinned build in the cache with Google's latest.
102
+ * Google documents the variable, set to `true`, in
103
+ * https://antigravity.google/docs/cli/troubleshooting.
104
+ */
105
+ const NO_SELF_UPDATE = { AGY_CLI_DISABLE_AUTO_UPDATE: "true" };
106
+
107
+ /** What the gemini harness is made with: the operator's, never the wire's. */
108
+ export interface GeminiOptions {
109
+ inheritConfig?: InheritConfig;
110
+ /** Where agy is: the registry's provisioner, as for the other harnesses. */
111
+ resolveCliPath: () => Promise<string | undefined>;
112
+ }
113
+
114
+ /**
115
+ * The `gemini` harness's profile: Google's Antigravity CLI (`agy acp`) on the
116
+ * person's own Antigravity sign-in, offering Gemini models only.
117
+ */
118
+ export function geminiProfile(options: GeminiOptions): AcpProfile {
119
+ return {
120
+ harness: "gemini",
121
+ capabilities: CAPABILITIES,
122
+ launch: () =>
123
+ options.resolveCliPath().then((command) => {
124
+ if (!command) throw new CliNotFoundError("agy", "set $ANTIGRAVITY_CLI_PATH");
125
+ return { command, args: ["acp"], fixedEnv: NO_SELF_UPDATE };
126
+ }),
127
+ admit: () => admit(options.inheritConfig ?? "all"),
128
+ accept,
129
+ // It takes HTTP servers, though its `initialize` says so only for `--process-per-session`.
130
+ httpMcp: true,
131
+ // Map agy's `auto` back to `bypass_permissions` on the stream. The flag lifts its terminal sandbox.
132
+ modeIds: { bypass_permissions: "auto" },
133
+ modeArgs: { bypass_permissions: ["--dangerously-skip-permissions"] },
134
+ // A system prompt given again on resume is added on top: given once, at the start.
135
+ newSession: {
136
+ settings: ["systemPromptAppend"],
137
+ meta: ({ systemPromptAppend }) =>
138
+ systemPromptAppend
139
+ ? { antigravity: { systemPrompt: { append: systemPromptAppend } } }
140
+ : undefined,
141
+ },
142
+ models: { offers: isGeminiModel },
143
+ tools: antigravityToolRules,
144
+ login: (account) => new AntigravityCliLogin(account),
145
+ };
146
+ }
147
+
148
+ // @ref LLP 0016.000#an-acp-agents-profile — one registration builds the agent and its adapter from one profile
149
+ /**
150
+ * The `gemini` harness as the registry registers it: the ACP agent on its
151
+ * profile, and the ACP adapter reading the same profile behind Antigravity's
152
+ * failure reading (`antigravityFailures`).
153
+ */
154
+ export function geminiHarness(
155
+ options: GeminiOptions & Omit<AcpAgentOptions, "resolveLaunch">,
156
+ ): [ProfiledAcpAgent, AdapterFactory] {
157
+ const { inheritConfig, resolveCliPath, ...shared } = options;
158
+ const profile = geminiProfile({ ...(inheritConfig && { inheritConfig }), resolveCliPath });
159
+ return [
160
+ new ProfiledAcpAgent(profile, shared),
161
+ (ctx) => antigravityFailures(createAcpTransformer(ctx, profile)),
162
+ ];
163
+ }
@@ -0,0 +1,99 @@
1
+ import type { McpTool } from "../../../protocol/index.ts";
2
+ import { isRecord } from "../../utils/is-record.ts";
3
+ import type { AcpToolRules } from "../acp/profile.ts";
4
+
5
+ /** How Antigravity names an MCP tool: `mcp_<server>_<tool>`. */
6
+ const MCP_PREFIX = "mcp_";
7
+
8
+ /** A server's name as Antigravity spells it in a tool's: spaces made `_`, hyphens kept. */
9
+ const spelled = (server: string) => server.replace(/ /g, "_");
10
+
11
+ /**
12
+ * The server and tool of an MCP call, against the session's own server
13
+ * names, the longest that fits first: Antigravity's `_` joins both and is
14
+ * in either, so a name it cannot tell apart that way names neither, nor do
15
+ * two servers it spells the same.
16
+ */
17
+ export function antigravityMcpTool(name: string, servers: readonly string[]): McpTool | undefined {
18
+ if (!name.startsWith(MCP_PREFIX)) return undefined;
19
+ const rest = name.slice(MCP_PREFIX.length);
20
+ let known: { server?: string; length: number } | undefined;
21
+ for (const server of servers) {
22
+ const prefix = `${spelled(server)}_`;
23
+ if (!rest.startsWith(prefix) || rest.length <= prefix.length) continue;
24
+ if (!known || prefix.length > known.length) known = { server, length: prefix.length };
25
+ else if (prefix.length === known.length) known = { length: prefix.length };
26
+ }
27
+ return known?.server === undefined
28
+ ? undefined
29
+ : { server: known.server, tool: rest.slice(known.length) };
30
+ }
31
+
32
+ /** What follows Antigravity's own lines about a command (when it ran, its exit code). */
33
+ const COMMAND_OUTPUT = "\nCommand output:\n";
34
+
35
+ /** Antigravity's line for a command that could not start (its folder gone): the reason. */
36
+ const NOT_RUN = /^Command failed to run: .*$/m;
37
+
38
+ /**
39
+ * A finished call's output, where Antigravity's `rawOutput` is
40
+ * `{ output, exit_code? }`: a command's is what the command printed, after
41
+ * Antigravity's lines about it ("No output from the command." is none), with
42
+ * its `exit_code`, which Antigravity sends even when it says the call
43
+ * `completed` with a non-zero one; a denied or failed call's is empty and has
44
+ * none. A command that could not run ("Command failed to run: <reason>",
45
+ * which Antigravity says `completed`, with no exit code) failed, its text
46
+ * that line. Its writes, reads and MCP calls send no text, and none is made up.
47
+ */
48
+ function antigravityOutput(
49
+ name: string,
50
+ rawOutput: unknown,
51
+ ): { text: string; exitCode?: number; failed?: boolean } | undefined {
52
+ if (!isRecord(rawOutput) || typeof rawOutput.output !== "string") return undefined;
53
+ const { output, exit_code: exitCode } = rawOutput;
54
+ const code = typeof exitCode === "number" ? { exitCode } : {};
55
+ if (name !== "run_command") return { text: output, ...code };
56
+ const at = output.indexOf(COMMAND_OUTPUT);
57
+ // Antigravity's own lines only, never what the command printed.
58
+ const notRun = NOT_RUN.exec(at !== -1 ? output.slice(0, at) : output)?.[0];
59
+ if (notRun) return { text: notRun, ...code, failed: true };
60
+ const text =
61
+ at !== -1
62
+ ? output.slice(at + COMMAND_OUTPUT.length)
63
+ : output.includes("\nNo output from the command.")
64
+ ? ""
65
+ : output;
66
+ return { text, ...code };
67
+ }
68
+
69
+ /** Antigravity's one tool for a server from a configuration file, the person's or the project's. */
70
+ const CALL_MCP_TOOL = "call_mcp_tool";
71
+
72
+ /** The server and tool `call_mcp_tool` names in its input (`ServerName`, `ToolName`). */
73
+ function configuredMcpTool(rawInput: unknown): McpTool | undefined {
74
+ if (!isRecord(rawInput)) return undefined;
75
+ const { ServerName: server, ToolName: tool } = rawInput;
76
+ return typeof server === "string" && server && typeof tool === "string" && tool
77
+ ? { server, tool }
78
+ : undefined;
79
+ }
80
+
81
+ // @ref LLP 0002#a-tool-call-says-what-it-acts-on — Antigravity's own names, read once here
82
+ /**
83
+ * What an Antigravity tool call is beyond ACP's kind: `run_command`'s
84
+ * `CommandLine` is its command; an MCP tool is `mcp_<server>_<tool>` for a
85
+ * server the engine passed, and `call_mcp_tool` with `ServerName` and
86
+ * `ToolName` for one from a configuration file. Its other calls say nothing
87
+ * more, and nothing is guessed.
88
+ */
89
+ export const antigravityToolRules: AcpToolRules = {
90
+ describe: (call, servers) => {
91
+ const name = call.name ?? "";
92
+ const mcp =
93
+ name === CALL_MCP_TOOL ? configuredMcpTool(call.rawInput) : antigravityMcpTool(name, servers);
94
+ const line = isRecord(call.rawInput) ? call.rawInput.CommandLine : undefined;
95
+ const command = name === "run_command" && typeof line === "string" && line ? line : undefined;
96
+ return { ...(mcp && { mcp }), ...(command && { command }) };
97
+ },
98
+ output: (call) => antigravityOutput(call.name ?? "", call.rawOutput),
99
+ };