@zvada/agent-server 0.3.27 → 0.3.28

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