@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,6 @@
1
- import { AsyncQueue, generateUUIDv7 } from "../../../protocol/index.js";
1
+ import { AsyncQueue, classifyError, generateUUIDv7 } from "../../../protocol/index.js";
2
2
  import { onAbort, untilAborted, withTimeout } from "../../utils/deadline.js";
3
- import { SessionResumeError } from "../../utils/errors.js";
3
+ import { AgentExitedError, SessionResumeError } from "../../utils/errors.js";
4
4
  import { CANCEL_CONFIRM_MS } from "../base.js";
5
5
  import { IDLE_TIMEOUT_MS, ProcessPool, } from "../process-pool.js";
6
6
  import { createCanUseTool, createOnElicitation, startQuery } from "./approvals.js";
@@ -10,9 +10,10 @@ import { ClaudeMcpConnections } from "./mcp.js";
10
10
  import { buildClaudeOptions, claudeSpawnKey, fromSdkPermissionMode, toSdkPermissionMode, } from "./options.js";
11
11
  import { planUsedUp } from "./outcome.js";
12
12
  import { notePairedReleases } from "./sdk-pair.js";
13
- import { withStderr } from "./spawn.js";
14
13
  import { ClaudeSpend } from "./spend.js";
15
14
  import { ClaudeTurn } from "./turn.js";
15
+ /** How long a cancelled turn has to end before its process is replaced (LLP 0001, D9). */
16
+ const CANCEL_GRACE_MS = 10_000;
16
17
  /** Claude repeats a message it was sent, where it reads it (`--replay-user-messages`). */
17
18
  function isReplay(event) {
18
19
  return event.type === "user" && "isReplay" in event && event.isReplay === true;
@@ -72,6 +73,8 @@ export class ClaudeSession {
72
73
  planWindows = new Map();
73
74
  /** The `claude` process the engine started for it; none under an operator's spawner. */
74
75
  native;
76
+ /** The CLI was still running when the session asked it to stop. */
77
+ stoppedCli = false;
75
78
  /** Its end, once it began: settles when its process is stopped. */
76
79
  ending;
77
80
  closeHandlers = new Set();
@@ -271,7 +274,7 @@ export class ClaudeSession {
271
274
  }
272
275
  this.state = "busy";
273
276
  const prompt = this.userMessage(content);
274
- const turn = new ClaudeTurn(start, prompt.uuid);
277
+ const turn = new ClaudeTurn(start, prompt.uuid, () => void this.cancelTurn(turn));
275
278
  this.turn = turn;
276
279
  for (const report of this.rejectedWindowReports())
277
280
  turn.events.push(report);
@@ -286,7 +289,7 @@ export class ClaudeSession {
286
289
  * False when no turn takes input.
287
290
  */
288
291
  steer(content, steerId) {
289
- if (this.state !== "busy" || !this.turn)
292
+ if (this.state !== "busy" || !this.turn || this.turn.cancelled)
290
293
  return false;
291
294
  const message = this.userMessage(content);
292
295
  this.turn.sendSteer(message.uuid, steerId);
@@ -353,13 +356,15 @@ export class ClaudeSession {
353
356
  }
354
357
  // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — cancelGraceMs: an agent that has not stopped is ended
355
358
  /**
356
- * End the process of a cancelled `turn` that has not ended within
357
- * `graceMs`: Claude did not stop it (a frozen or hung CLI), and nothing
358
- * else would. The turn's events end, so it ends cancelled, and the pool
359
- * hears `replaced` (`onSessionEnd`); the next turn resumes on a new
360
- * process. A turn that ended, and any turn after it, is left alone.
359
+ * Interrupt this turn. If Claude still hasn't stopped it at `cancelGraceMs`,
360
+ * end the process. The turn's events end and the next turn resumes on a
361
+ * new process. A request answered after its turn ended stops nothing.
361
362
  */
362
- async endUnstopped(turn, graceMs) {
363
+ async cancelTurn(turn) {
364
+ if (this.turn !== turn)
365
+ return;
366
+ void this.interruptTurn();
367
+ const graceMs = this.settings.cancelGraceMs ?? CANCEL_GRACE_MS;
363
368
  if ((await withTimeout(turn.ended, graceMs)) === undefined && this.turn === turn)
364
369
  await this.terminate("replaced");
365
370
  }
@@ -436,6 +441,8 @@ export class ClaudeSession {
436
441
  this.promptQueue.end();
437
442
  this.turn?.end();
438
443
  this.turn = null;
444
+ const child = this.native?.child;
445
+ this.stoppedCli = child?.exitCode === null && child.signalCode === null;
439
446
  try {
440
447
  // The SDK documents close() as the forceful subprocess/MCP cleanup path.
441
448
  query?.close();
@@ -459,25 +466,49 @@ export class ClaudeSession {
459
466
  async consumeEvents() {
460
467
  if (!this.query)
461
468
  return;
469
+ let initializing = true;
470
+ // The SDK already sent initialize. Its receipt is independent of the first turn event.
471
+ void this.query.initializationResult?.().then(() => {
472
+ initializing = false;
473
+ }, () => { });
462
474
  try {
463
475
  for await (const event of this.query) {
464
476
  this.cliStarted = true;
465
477
  this.observe(event);
466
478
  this.route(event);
479
+ if (this.startupError)
480
+ return;
467
481
  }
482
+ // @ref LLP 0016.000#when-a-process-exits-before-answering — only the session knows who ended this query
483
+ if (!this.closed && (this.turn || !this.cliStarted || this.state === "starting"))
484
+ throw new AgentExitedError("Claude ended the turn without a result");
468
485
  }
469
486
  catch (thrown) {
470
- // The SDK words an exit from its own spawner with the CLI's stderr; ours keeps that tail.
471
- const err = withStderr(thrown, this.native?.stderrTail ?? "");
472
- if (this.turn)
473
- this.turn.fail(err);
474
- else
475
- this.startupError = err;
487
+ const pending = initializing ? ["initialize"] : this.turn ? ["the turn"] : [];
488
+ await this.failStream(thrown, pending);
476
489
  }
477
490
  finally {
478
491
  await this.terminate();
479
492
  }
480
493
  }
494
+ async failStream(cause, pending) {
495
+ const native = this.native;
496
+ const exit = await native?.exitAfterDisconnect();
497
+ if (this.stoppedCli || this.turn?.cancelled)
498
+ return;
499
+ let error = cause;
500
+ if (native && exit && (exit.code !== null || exit.signal !== null)) {
501
+ const resume = this.config.resumeSessionId;
502
+ error =
503
+ resume && !this.queryBegun && classifyError(native.stderrTail) === "resume_failed"
504
+ ? new SessionResumeError(resume, native.stderrTail.trim())
505
+ : native.exitError("Claude Code", exit, pending);
506
+ }
507
+ if (this.turn)
508
+ this.turn.fail(error);
509
+ else
510
+ this.startupError = error;
511
+ }
481
512
  /** What an event says of the session: its native id, its mode, plan windows, spend, steers read. */
482
513
  observe(event) {
483
514
  if (event.type === "system" && event.subtype === "init") {
@@ -550,11 +581,12 @@ export class ClaudeSession {
550
581
  settleUnshown(result) {
551
582
  if (result.subtype !== "success" && result.origin === undefined) {
552
583
  const reason = result.errors.join("; ") || "Claude failed during startup";
553
- throw this.config.resumeSessionId
584
+ this.startupError = this.config.resumeSessionId
554
585
  ? new SessionResumeError(this.config.resumeSessionId, reason, {
555
586
  cause: new Error(reason),
556
587
  })
557
588
  : new Error(reason);
589
+ return;
558
590
  }
559
591
  this.spend.charge(result);
560
592
  if (this.state === "idle")
@@ -1,8 +1,5 @@
1
1
  import { EventEmitter } from "node:events";
2
2
  import { StringDecoder } from "node:string_decoder";
3
- import { redactSecrets } from "../stderr-tail.js";
4
- /** The longest stderr tail an SDK exit error carries. */
5
- const SDK_TAIL_MAX = 2048;
6
3
  /**
7
4
  * The CLI as the SDK sees it: the child's pipes, and its `exit` once stderr
8
5
  * has closed too (at most 200 ms after it), as the SDK's own spawner delivers
@@ -100,26 +97,3 @@ export function claudeSpawner(spawn, operator, stderr) {
100
97
  return new SpawnedClaude(native, stdin, stdout);
101
98
  };
102
99
  }
103
- /** The SDK's bare exit error: what its own spawner would have followed with `. stderr: <tail>`. */
104
- const BARE_EXIT = /^Claude Code process (?:exited with code \S+|terminated by signal \S+)$/;
105
- /**
106
- * Put the CLI's own words back into the SDK's exit error, as the SDK's own
107
- * spawner words it ("Claude Code process exited with code 1. stderr: …"):
108
- * the last 2 KB, trimmed, with its secrets redacted (the SDK redacts its own;
109
- * this marks each `[REDACTED]`). The SDK builds that tail only from its own
110
- * spawner. Its message alone changes, so the error keeps its class and fields.
111
- */
112
- export function withStderr(error, tail) {
113
- if (!(error instanceof Error) || !BARE_EXIT.test(error.message))
114
- return error;
115
- let kept = tail.length > SDK_TAIL_MAX ? tail.slice(-SDK_TAIL_MAX) : tail;
116
- // A cut that splits a surrogate pair drops its half, as the SDK's does.
117
- const first = kept.charCodeAt(0);
118
- if (first >= 0xdc00 && first <= 0xdfff)
119
- kept = kept.slice(1);
120
- // As the SDK redacts its own tail, before it quotes it.
121
- kept = redactSecrets(kept).trim();
122
- if (kept)
123
- error.message = `${error.message}. stderr: ${kept}`;
124
- return error;
125
- }
@@ -12,6 +12,7 @@ const STEER_QUERY_TIMEOUT_MS = 60_000;
12
12
  * next turn. Its methods say what the session does next.
13
13
  */
14
14
  export class ClaudeTurn {
15
+ dropUnread;
15
16
  id;
16
17
  signal;
17
18
  permissions;
@@ -47,7 +48,8 @@ export class ClaudeTurn {
47
48
  heldResult = false;
48
49
  /** Set while Claude is between queries, about to run the unread steers. */
49
50
  watchdog;
50
- constructor(start, prompt) {
51
+ constructor(start, prompt, dropUnread) {
52
+ this.dropUnread = dropUnread;
51
53
  this.id = start.turnId;
52
54
  this.signal = start.signal;
53
55
  this.permissions = start.permissions;
@@ -59,9 +61,11 @@ export class ClaudeTurn {
59
61
  this.settleEnded = resolve;
60
62
  });
61
63
  }
62
- /** A request of the turn was answered `cancelled`: Claude stops the turn, which ends cancelled. */
64
+ /** Drop unread steers before the SDK's denial lets Claude start their query. */
63
65
  cancelByRequest() {
64
66
  this.stoppedByRequest = true;
67
+ if (this.unread.size)
68
+ this.dropUnread();
65
69
  }
66
70
  /** Whether a cancelled request stopped the turn (Claude interrupts on it). */
67
71
  get cancelled() {
@@ -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
+ }