@zvada/agent-server 0.3.23 → 0.3.24

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 (246) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +14 -5
  3. package/dist/accounts/chatgpt.js +144 -0
  4. package/dist/accounts/check.js +71 -0
  5. package/dist/accounts/claude.js +80 -0
  6. package/dist/accounts/endpoint.js +104 -0
  7. package/dist/accounts/http.js +58 -0
  8. package/dist/accounts/index.js +9 -0
  9. package/dist/client/client.js +686 -0
  10. package/dist/client/connection.js +338 -0
  11. package/dist/client/history.js +49 -0
  12. package/dist/client/index.js +6 -0
  13. package/dist/client/listeners.js +19 -0
  14. package/dist/client/logins.js +92 -0
  15. package/dist/client/rpc.js +105 -0
  16. package/dist/client/streams.js +432 -0
  17. package/dist/client/transports.js +118 -0
  18. package/dist/client/turns.js +122 -0
  19. package/dist/core/agents/acp/acp-agent.js +425 -0
  20. package/dist/core/agents/acp/adapter.js +231 -0
  21. package/dist/core/agents/acp/client.js +222 -0
  22. package/dist/core/agents/acp/known-agents.js +57 -0
  23. package/dist/core/agents/acp/mappings.js +164 -0
  24. package/dist/core/agents/acp/requests.js +79 -0
  25. package/dist/core/agents/attachments.js +14 -0
  26. package/dist/core/agents/base.js +64 -0
  27. package/dist/core/agents/claude-code/adapter.js +474 -0
  28. package/dist/core/agents/claude-code/approvals.js +245 -0
  29. package/dist/core/agents/claude-code/claude-agent.js +319 -0
  30. package/dist/core/agents/claude-code/credentials.js +142 -0
  31. package/dist/core/agents/claude-code/events.js +11 -0
  32. package/dist/core/agents/claude-code/login.js +217 -0
  33. package/dist/core/agents/claude-code/mcp.js +181 -0
  34. package/dist/core/agents/claude-code/models.js +74 -0
  35. package/dist/core/agents/claude-code/options.js +240 -0
  36. package/dist/core/agents/claude-code/outcome.js +204 -0
  37. package/dist/core/agents/claude-code/results.js +58 -0
  38. package/dist/core/agents/claude-code/sdk-pair.js +59 -0
  39. package/dist/core/agents/claude-code/session.js +593 -0
  40. package/dist/core/agents/claude-code/spawn.js +125 -0
  41. package/dist/core/agents/claude-code/spend.js +118 -0
  42. package/dist/core/agents/claude-code/tools.js +131 -0
  43. package/dist/core/agents/claude-code/turn-usage.js +121 -0
  44. package/dist/core/agents/claude-code/turn.js +199 -0
  45. package/dist/core/agents/codex-app-server/adapter.js +463 -0
  46. package/dist/core/agents/codex-app-server/client.js +338 -0
  47. package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
  48. package/dist/core/agents/codex-app-server/commands.js +184 -0
  49. package/dist/core/agents/codex-app-server/credentials.js +92 -0
  50. package/dist/core/agents/codex-app-server/effort.js +13 -0
  51. package/dist/core/agents/codex-app-server/events.js +18 -0
  52. package/dist/core/agents/codex-app-server/homes.js +118 -0
  53. package/dist/core/agents/codex-app-server/input.js +52 -0
  54. package/dist/core/agents/codex-app-server/items.js +307 -0
  55. package/dist/core/agents/codex-app-server/login.js +183 -0
  56. package/dist/core/agents/codex-app-server/mcp.js +323 -0
  57. package/dist/core/agents/codex-app-server/models.js +160 -0
  58. package/dist/core/agents/codex-app-server/options.js +155 -0
  59. package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
  60. package/dist/core/agents/codex-app-server/protocol.js +38 -0
  61. package/dist/core/agents/codex-app-server/requests.js +250 -0
  62. package/dist/core/agents/codex-app-server/session.js +278 -0
  63. package/dist/core/agents/codex-app-server/subagents.js +260 -0
  64. package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
  65. package/dist/core/agents/codex-app-server/turn-items.js +69 -0
  66. package/dist/core/agents/codex-app-server/turn.js +448 -0
  67. package/dist/core/agents/codex-app-server/user-login.js +78 -0
  68. package/dist/core/agents/config-fingerprint.js +10 -0
  69. package/dist/core/agents/credentials.js +71 -0
  70. package/dist/core/agents/diffs.js +27 -0
  71. package/dist/core/agents/elicitation.js +42 -0
  72. package/dist/core/agents/inherit-config.js +5 -0
  73. package/dist/core/agents/login.js +56 -0
  74. package/dist/core/agents/mcp-config.js +109 -0
  75. package/dist/core/agents/plan.js +6 -0
  76. package/dist/core/agents/process-pool.js +307 -0
  77. package/dist/core/agents/registry.js +49 -0
  78. package/dist/core/agents/scripted/adapter.js +86 -0
  79. package/dist/core/agents/scripted/mcp-call.js +74 -0
  80. package/dist/core/agents/scripted/scripted-agent.js +330 -0
  81. package/dist/core/agents/scripted/scripts.js +154 -0
  82. package/dist/core/agents/scripted/steps.js +87 -0
  83. package/dist/core/agents/session-agent.js +209 -0
  84. package/dist/core/agents/stderr-tail.js +71 -0
  85. package/dist/core/agents/thinking-levels.js +9 -0
  86. package/dist/core/agents/types.js +1 -0
  87. package/dist/core/diagnostics.js +23 -0
  88. package/dist/core/index.js +31 -0
  89. package/dist/core/presets.js +114 -0
  90. package/dist/core/processes/identity.js +91 -0
  91. package/dist/core/processes/lifeline.js +210 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +163 -0
  94. package/dist/core/provision/cache-trust.js +121 -0
  95. package/dist/core/provision/cache-usage.js +61 -0
  96. package/dist/core/provision/checksums.js +22 -0
  97. package/dist/core/provision/extract.js +28 -0
  98. package/dist/core/provision/index.js +4 -0
  99. package/dist/core/provision/install-build.js +99 -0
  100. package/dist/core/provision/npm.js +316 -0
  101. package/dist/core/provision/pins.js +35 -0
  102. package/dist/core/provision/platform.js +65 -0
  103. package/dist/core/provision/provisioner.js +372 -0
  104. package/dist/core/provision/releases.js +68 -0
  105. package/dist/core/provision/tools.js +279 -0
  106. package/dist/core/proxy/anthropic-proxy.js +163 -0
  107. package/dist/core/proxy/api-key-store.js +30 -0
  108. package/dist/core/proxy/index.js +3 -0
  109. package/dist/core/proxy/loopback.js +86 -0
  110. package/dist/core/runtime/agent-runtime.js +434 -0
  111. package/dist/core/runtime/event-processor.js +379 -0
  112. package/dist/core/runtime/event-sink.js +65 -0
  113. package/dist/core/runtime/harness-clis.js +83 -0
  114. package/dist/core/runtime/harness-logins.js +313 -0
  115. package/dist/core/runtime/login-reads.js +71 -0
  116. package/dist/core/runtime/model-lists.js +160 -0
  117. package/dist/core/runtime/permission-policy.js +84 -0
  118. package/dist/core/runtime/request-broker.js +139 -0
  119. package/dist/core/runtime/steering.js +79 -0
  120. package/dist/core/runtime/turn-outcome.js +16 -0
  121. package/dist/core/runtime/turn.js +329 -0
  122. package/dist/core/utils/bounded.js +13 -0
  123. package/dist/core/utils/deadline.js +57 -0
  124. package/dist/core/utils/errors.js +176 -0
  125. package/dist/core/utils/is-record.js +4 -0
  126. package/dist/core/utils/loopback.js +11 -0
  127. package/dist/index.js +4 -0
  128. package/dist/operator/index.js +10 -0
  129. package/dist/operator/mcp.js +139 -0
  130. package/dist/operator/operator.js +499 -0
  131. package/dist/operator/render.js +408 -0
  132. package/dist/operator/view.js +35 -0
  133. package/dist/protocol/account.js +96 -0
  134. package/dist/protocol/async-queue.js +65 -0
  135. package/dist/protocol/auth.js +169 -0
  136. package/dist/protocol/canonical.js +18 -0
  137. package/dist/protocol/clis.js +63 -0
  138. package/dist/protocol/config.js +137 -0
  139. package/dist/protocol/conversation.js +231 -0
  140. package/dist/protocol/credentials.js +141 -0
  141. package/dist/protocol/errors.js +181 -0
  142. package/dist/protocol/execution.js +28 -0
  143. package/dist/protocol/factories.js +231 -0
  144. package/dist/protocol/guards.js +71 -0
  145. package/dist/protocol/harness.js +93 -0
  146. package/dist/protocol/history.js +201 -0
  147. package/dist/protocol/ids.js +37 -0
  148. package/dist/protocol/index.js +36 -0
  149. package/dist/protocol/lifecycle.js +562 -0
  150. package/dist/protocol/meta-keys.js +17 -0
  151. package/dist/protocol/meta.js +13 -0
  152. package/dist/protocol/model-catalog.js +223 -0
  153. package/dist/protocol/models.js +84 -0
  154. package/dist/protocol/part-input.js +94 -0
  155. package/dist/protocol/parts.js +166 -0
  156. package/dist/protocol/plan.js +31 -0
  157. package/dist/protocol/reduce.js +484 -0
  158. package/dist/protocol/selectors.js +136 -0
  159. package/dist/protocol/seq-cursor.js +37 -0
  160. package/dist/protocol/stop-reasons.js +41 -0
  161. package/dist/protocol/thinking.js +31 -0
  162. package/dist/protocol/time.js +21 -0
  163. package/dist/protocol/tokens.js +57 -0
  164. package/dist/protocol/tool-closure.js +70 -0
  165. package/dist/protocol/tool-state.js +153 -0
  166. package/dist/protocol/verify.js +467 -0
  167. package/dist/protocol/vocabulary.js +27 -0
  168. package/dist/protocol/wire-api.js +94 -0
  169. package/dist/protocol/wire.js +669 -0
  170. package/dist/server/acp/binding.js +251 -0
  171. package/dist/server/acp/session-records.js +53 -0
  172. package/dist/server/acp/translate.js +401 -0
  173. package/dist/server/agent-server.js +338 -0
  174. package/dist/server/bin.js +492 -0
  175. package/dist/server/feedback.js +216 -0
  176. package/dist/server/history.js +123 -0
  177. package/dist/server/index.js +8 -0
  178. package/dist/server/install.js +171 -0
  179. package/dist/server/open-parts.js +87 -0
  180. package/dist/server/routes.js +291 -0
  181. package/dist/server/secrets.js +19 -0
  182. package/dist/server/session-gate.js +54 -0
  183. package/dist/server/session-log.js +66 -0
  184. package/dist/server/session-store.js +243 -0
  185. package/dist/server/subscriptions.js +189 -0
  186. package/dist/server/transports.js +214 -0
  187. package/dist/server/wire-error.js +26 -0
  188. package/dist/sync/event-log.js +89 -0
  189. package/dist/sync/fit.js +202 -0
  190. package/dist/sync/history-reader.js +33 -0
  191. package/dist/sync/history-sqlite.js +281 -0
  192. package/dist/sync/history.js +163 -0
  193. package/dist/sync/index.js +5 -0
  194. package/dist/sync/journal-sqlite.js +316 -0
  195. package/dist/sync/journal.js +10 -0
  196. package/dist/sync/live-tails.js +85 -0
  197. package/dist/sync/node-sqlite.js +27 -0
  198. package/dist/sync/projection.js +32 -0
  199. package/dist/sync/recovery.js +117 -0
  200. package/dist/sync/retry.js +45 -0
  201. package/dist/sync/schema.js +73 -0
  202. package/dist/sync/sql.js +94 -0
  203. package/dist/sync/sqlite-file.js +31 -0
  204. package/dist/sync/sqlite.js +18 -0
  205. package/dist/sync/worker.js +212 -0
  206. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  207. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  208. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/options.d.ts +24 -11
  210. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  212. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  213. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  214. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  216. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  218. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  219. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  220. package/dist/types/core/agents/process-pool.d.ts +8 -0
  221. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  222. package/dist/types/core/presets.d.ts +2 -2
  223. package/dist/types/core/presets.d.ts.map +1 -1
  224. package/dist/types/server/bin.d.ts +3 -0
  225. package/dist/types/server/bin.d.ts.map +1 -0
  226. package/dist/types/server/transports.d.ts +2 -1
  227. package/dist/types/server/transports.d.ts.map +1 -1
  228. package/dist/types/sync/node-sqlite.d.ts +4 -1
  229. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  230. package/docs/consuming.md +30 -4
  231. package/docs/deploy.md +28 -0
  232. package/docs/harnesses.md +13 -1
  233. package/package.json +43 -18
  234. package/src/core/agents/claude-code/approvals.ts +5 -1
  235. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  236. package/src/core/agents/claude-code/options.ts +24 -11
  237. package/src/core/agents/claude-code/session.ts +13 -0
  238. package/src/core/agents/codex-app-server/homes.ts +11 -2
  239. package/src/core/agents/codex-app-server/login.ts +30 -0
  240. package/src/core/agents/codex-app-server/requests.ts +7 -6
  241. package/src/core/agents/codex-app-server/session.ts +11 -2
  242. package/src/core/agents/process-pool.ts +30 -4
  243. package/src/core/presets.ts +3 -2
  244. package/src/server/bin.ts +25 -10
  245. package/src/server/transports.ts +6 -1
  246. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,199 @@
1
+ import { AsyncQueue } from "../../../protocol/index.js";
2
+ /**
3
+ * How long a turn waits for Claude to begin the query it runs for steers that
4
+ * came too late for the last one. It begins within a second; past this the
5
+ * steers are dropped and the process replaced, so they cannot run later.
6
+ */
7
+ const STEER_QUERY_TIMEOUT_MS = 60_000;
8
+ /**
9
+ * One turn on a Claude session: the events it yields, the brokers its
10
+ * requests go to, and the messages it still owes an answer for. The session
11
+ * makes one per prompt and ends it with the turn, so none of it can reach the
12
+ * next turn. Its methods say what the session does next.
13
+ */
14
+ export class ClaudeTurn {
15
+ id;
16
+ permissions;
17
+ elicitation;
18
+ /** What the turn yields, until its result or its failure. */
19
+ events = new AsyncQueue();
20
+ /** Settles once the turn is over. */
21
+ ended;
22
+ settleEnded;
23
+ /** The uuid of the turn's prompt. */
24
+ prompt;
25
+ /**
26
+ * Every message this turn sent Claude (its prompt and steers). A result
27
+ * that names none of them answers a query Claude began on its own.
28
+ */
29
+ sent = new Set();
30
+ /**
31
+ * Messages sent that Claude has not taken yet. The prompt waits here while a
32
+ * query Claude began itself runs; a cancel must drop them from its queue.
33
+ */
34
+ queued = new Set();
35
+ /**
36
+ * Steers sent this turn that Claude has not read yet: the uuid each was sent
37
+ * with → its steer id. Claude replays a message at the step it reads it.
38
+ */
39
+ unread = new Map();
40
+ /** The interrupt in flight, shared by everyone stopping the turn (its abort, `cancel`). */
41
+ interrupting;
42
+ stoppedByRequest = false;
43
+ /** Queued messages are being dropped: the turn ends once their fate is known. */
44
+ dropping = false;
45
+ /** The turn's last result arrived while `dropping`. */
46
+ heldResult = false;
47
+ /** Set while Claude is between queries, about to run the unread steers. */
48
+ watchdog;
49
+ constructor(start, prompt) {
50
+ this.id = start.turnId;
51
+ this.permissions = start.permissions;
52
+ this.elicitation = start.elicitation;
53
+ this.prompt = prompt;
54
+ this.sent.add(prompt);
55
+ this.queued.add(prompt);
56
+ this.ended = new Promise((resolve) => {
57
+ this.settleEnded = resolve;
58
+ });
59
+ }
60
+ /** A request of the turn was answered `cancelled`: Claude stops the turn, which ends cancelled. */
61
+ cancelByRequest() {
62
+ this.stoppedByRequest = true;
63
+ }
64
+ /** Whether a cancelled request stopped the turn (Claude interrupts on it). */
65
+ get cancelled() {
66
+ return this.stoppedByRequest;
67
+ }
68
+ /** A steer went to Claude with `uuid`: unread and queued until Claude says otherwise. */
69
+ sendSteer(uuid, steerId) {
70
+ this.sent.add(uuid);
71
+ this.queued.add(uuid);
72
+ this.unread.set(uuid, steerId);
73
+ }
74
+ /** Mark steers read, in order, at this point of the turn's events. */
75
+ read(uuids) {
76
+ for (const uuid of uuids) {
77
+ this.queued.delete(uuid);
78
+ const steerId = this.unread.get(uuid);
79
+ if (steerId === undefined)
80
+ continue;
81
+ this.unread.delete(uuid);
82
+ // Claude began the query that reads it.
83
+ this.stopWaiting();
84
+ this.events.push({ type: "agentServer/steerRead", steerId });
85
+ }
86
+ }
87
+ /**
88
+ * Claude took a message of this turn (its `command_lifecycle` "started"): it
89
+ * is no longer queued, and the query for the steers has begun.
90
+ */
91
+ took(uuid) {
92
+ if (!this.sent.has(uuid))
93
+ return;
94
+ this.queued.delete(uuid);
95
+ this.stopWaiting();
96
+ }
97
+ /**
98
+ * Whether a result answers this turn. Claude names the messages a query
99
+ * consumed (`user_message_uuids`); a result that names none and no origin
100
+ * either (an older CLI, a failure) is taken at its word.
101
+ */
102
+ answeredBy(result) {
103
+ const named = result.user_message_uuids?.length
104
+ ? result.user_message_uuids
105
+ : result.user_message_uuid
106
+ ? [result.user_message_uuid]
107
+ : [];
108
+ if (named.length)
109
+ return named.some((uuid) => this.sent.has(uuid));
110
+ // A query Claude began itself names where it came from (a finished
111
+ // background task: `origin.kind` "task-notification"); ours carry none.
112
+ return result.origin === undefined;
113
+ }
114
+ /**
115
+ * The result that answers this turn came: its events say what the query
116
+ * spent, then the result. "end": the turn is over. "await-steers": Claude
117
+ * has steers it has not read and runs them as its next query, still this
118
+ * turn. "hold": queued messages are being dropped, and the turn ends once
119
+ * their fate is known (`dropped`).
120
+ */
121
+ settle(result, spent) {
122
+ const steersPending = this.unread.size > 0;
123
+ this.events.push({ type: "agentServer/querySettled", ...spent, steersPending });
124
+ this.events.push(result);
125
+ if (this.dropping) {
126
+ this.heldResult = true;
127
+ return "hold";
128
+ }
129
+ return steersPending ? "await-steers" : "end";
130
+ }
131
+ /** Wait for the query Claude runs for the unread steers; give up if it never begins. */
132
+ awaitSteerQuery(onTimeout) {
133
+ this.stopWaiting();
134
+ this.watchdog = setTimeout(() => {
135
+ this.watchdog = undefined;
136
+ onTimeout();
137
+ }, STEER_QUERY_TIMEOUT_MS);
138
+ this.watchdog.unref?.();
139
+ }
140
+ /**
141
+ * Whether stopping the turn must drop messages from Claude's queue: a plain
142
+ * interrupt keeps them, so unread steers would run as Claude's next query,
143
+ * after the turn, and a prompt still waiting behind a query Claude began
144
+ * itself would run as if never cancelled. Only a process past its first
145
+ * query (`queryBegun`) can be running one of its own: before that, the CLI's
146
+ * own first-command latch aborts the prompt, as a plain interrupt asks.
147
+ */
148
+ mustDropQueued(queryBegun) {
149
+ return this.unread.size > 0 || (this.queued.size > 0 && queryBegun);
150
+ }
151
+ /** Claude was asked to drop the turn's queued messages: until `dropped`, a result is held. */
152
+ dropQueued() {
153
+ this.dropping = true;
154
+ }
155
+ /**
156
+ * The queue cancel's receipt came (undefined: none came, or not in time).
157
+ * What Claude dropped leaves the turn; until now a steer Claude read was
158
+ * still shown where it read it. "replace": something sent may still run, so
159
+ * the process must go and the next turn resumes without it. "end":
160
+ * everything sent is read or dropped and no query of the turn runs any more,
161
+ * since its last result is in, Claude was between queries, or its prompt
162
+ * never ran. "continue": a query of the turn still runs, and its result ends
163
+ * the turn.
164
+ */
165
+ dropped(receipt) {
166
+ this.dropping = false;
167
+ for (const uuid of receipt?.cancelled ?? []) {
168
+ this.unread.delete(uuid);
169
+ this.queued.delete(uuid);
170
+ }
171
+ if (!receipt || this.unread.size > 0 || this.queued.size > 0)
172
+ return "replace";
173
+ const promptDropped = receipt.cancelled?.includes(this.prompt) === true;
174
+ return this.heldResult || this.watchdog !== undefined || promptDropped ? "end" : "continue";
175
+ }
176
+ /** Run `interrupt` once for everyone stopping the turn, until it settles. */
177
+ interruptOnce(interrupt) {
178
+ this.interrupting ??= interrupt().finally(() => {
179
+ this.interrupting = undefined;
180
+ });
181
+ return this.interrupting;
182
+ }
183
+ /** The turn is over: its events end, and nothing it waited for matters. */
184
+ end() {
185
+ this.stopWaiting();
186
+ this.events.end();
187
+ this.settleEnded();
188
+ }
189
+ fail(error) {
190
+ this.stopWaiting();
191
+ this.events.fail(error);
192
+ this.settleEnded();
193
+ }
194
+ stopWaiting() {
195
+ if (this.watchdog)
196
+ clearTimeout(this.watchdog);
197
+ this.watchdog = undefined;
198
+ }
199
+ }
@@ -0,0 +1,463 @@
1
+ import { DEFAULT_TOKEN_USAGE, TOOL_OUTCOME_UNKNOWN, classifyError, completeToolPart, createReasoningPart, createTextPart, createToolPart, generateUUIDv7, setToolMeta, } from "../../../protocol/index.js";
2
+ import { isRecord } from "../../utils/is-record.js";
3
+ import { CODEX_PLAN_DECIDED, isSyntheticEvent, } from "./events.js";
4
+ import { CODEX_TOOL_KINDS, codexToolDescriptor } from "./items.js";
5
+ import { codexItem, codexTurn } from "./protocol.js";
6
+ /** The numbers among a usage breakdown's fields. */
7
+ function counts(value) {
8
+ if (!isRecord(value))
9
+ return undefined;
10
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "number"));
11
+ }
12
+ /** Field-by-field `a - b` of two Codex usage breakdowns, never below zero. */
13
+ function subtractUsage(a, b) {
14
+ return Object.fromEntries(Object.entries(a).map(([key, value]) => [key, Math.max(value - (b[key] ?? 0), 0)]));
15
+ }
16
+ /** An error's text and typed code, as Codex nests them (`TurnError`). */
17
+ function codexError(value) {
18
+ if (!isRecord(value))
19
+ return undefined;
20
+ return {
21
+ ...(typeof value.message === "string" && { message: value.message }),
22
+ codexErrorInfo: value.codexErrorInfo,
23
+ };
24
+ }
25
+ /**
26
+ * Which attempt a Codex retry is, of how many. Codex 0.160 sends the count
27
+ * only in its text ("Reconnecting... 2/5"), with no field for it and no
28
+ * wait: a text of any other shape, or a count past its total, gives none.
29
+ */
30
+ // @ref LLP 0002#plan-usage-and-retries — a field the harness did not say is left out
31
+ function codexRetryCount(message) {
32
+ const match = /^Reconnecting\.\.\. (\d{1,3})\/(\d{1,3})$/.exec(message);
33
+ if (!match)
34
+ return {};
35
+ const attempt = Number(match[1]);
36
+ const maxAttempts = Number(match[2]);
37
+ if (attempt < 1 || attempt > maxAttempts)
38
+ return {};
39
+ return { attempt, maxAttempts };
40
+ }
41
+ /**
42
+ * Parses `codex app-server` v2 notifications into AdapterEvents. This harness
43
+ * streams token-level deltas (item/agentMessage/delta, item/reasoning/*Delta),
44
+ * so no diffing is needed. Items carry camelCase fields. Tool-like items
45
+ * (commandExecution/fileChange/mcpToolCall/webSearch/imageGeneration) become
46
+ * tool parts that complete on item/completed.
47
+ */
48
+ export class CodexAppServerTransformer {
49
+ ctx;
50
+ /** The text and reasoning parts, by item id. */
51
+ texts = new Map();
52
+ /** The tool parts (commands, changes, MCP calls, searches, plans), by item id. */
53
+ tools = new Map();
54
+ /** The sub-agents' activities, by item id. */
55
+ activities = new Map();
56
+ usage = { ...DEFAULT_TOKEN_USAGE };
57
+ /** The thread's totals when this turn began: Codex's `total` counts the whole thread. */
58
+ baseline;
59
+ /** Codex's turns in this one: a plan's, then the one implementing it. */
60
+ turnIds = new Set();
61
+ reportedModels = new Set();
62
+ stopReason;
63
+ /** From the failure's typed `codexErrorInfo`, when it had one. */
64
+ errorCategory;
65
+ finishReason;
66
+ error;
67
+ /** Codex stopped the turn (`interrupted`), as after an approval answered cancel. */
68
+ interrupted = false;
69
+ constructor(ctx) {
70
+ this.ctx = { sessionId: ctx.sessionId, messageId: "" };
71
+ }
72
+ process(raw) {
73
+ // What the Codex agent yields.
74
+ const event = raw;
75
+ return isSyntheticEvent(event) ? this.synthetic(event) : this.notification(event);
76
+ }
77
+ finish() {
78
+ return {
79
+ usage: this.usage,
80
+ ...(this.reportedModels.size && { reportedModels: [...this.reportedModels] }),
81
+ stopReason: this.stopReason,
82
+ finishReason: this.finishReason,
83
+ error: this.error,
84
+ ...(this.error && this.errorCategory && { errorCategory: this.errorCategory }),
85
+ ...(this.interrupted && { cancelled: true }),
86
+ };
87
+ }
88
+ synthetic(event) {
89
+ return event.method === CODEX_PLAN_DECIDED
90
+ ? this.planDecided(event.params)
91
+ : this.stopUnconfirmed(event.params);
92
+ }
93
+ notification(n) {
94
+ const { params } = n;
95
+ switch (n.method) {
96
+ case "model/rerouted":
97
+ if (typeof params.toModel !== "string" || !params.toModel)
98
+ return [];
99
+ this.reportedModels.add(params.toModel);
100
+ // What follows is the rerouted model's.
101
+ return [{ kind: "model", model: params.toModel }];
102
+ case "item/started": {
103
+ const item = codexItem(n);
104
+ return item ? this.openItem(item) : [];
105
+ }
106
+ case "item/completed": {
107
+ const item = codexItem(n);
108
+ return item ? this.completeItem(item) : [];
109
+ }
110
+ case "item/agentMessage/delta":
111
+ return this.textDelta(params.itemId, params.delta, "text");
112
+ case "item/reasoning/textDelta":
113
+ case "item/reasoning/summaryTextDelta":
114
+ return this.textDelta(params.itemId, params.delta, "reasoning");
115
+ case "turn/started": {
116
+ const id = codexTurn(n)?.id;
117
+ if (id)
118
+ this.turnIds.add(id);
119
+ return [];
120
+ }
121
+ case "thread/tokenUsage/updated": {
122
+ const usage = isRecord(params.tokenUsage) ? params.tokenUsage : undefined;
123
+ const total = counts(usage?.total);
124
+ if (!total)
125
+ return [];
126
+ // A resumed thread first restates the previous turn's totals, before
127
+ // `turn/started` names this turn: count only this turn's updates.
128
+ if (params.turnId && !this.turnIds.has(params.turnId))
129
+ return [];
130
+ // This turn used what the thread's totals grew by. Its first update's
131
+ // `last` is the turn's first request, so the totals before it are the
132
+ // turn's starting point.
133
+ const last = counts(usage?.last);
134
+ this.baseline ??= last ? subtractUsage(total, last) : {};
135
+ this.captureUsage(subtractUsage(total, this.baseline));
136
+ // The context in use is the latest request's.
137
+ const latest = last ?? total;
138
+ const used = latest.totalTokens ?? (latest.inputTokens ?? 0) + (latest.outputTokens ?? 0);
139
+ const size = usage?.modelContextWindow;
140
+ return [{ kind: "usage", used, ...(typeof size === "number" && { size }) }];
141
+ }
142
+ case "account/rateLimits/updated":
143
+ return codexLimits(params.rateLimits);
144
+ case "turn/completed": {
145
+ // A failed turn's `error` that Codex will not retry comes before this,
146
+ // some time before on 0.160, and the agent holds the turn open until
147
+ // this comes: what that error said stays the turn's.
148
+ const turn = codexTurn(n);
149
+ if (!this.error && turn?.error) {
150
+ this.error = turn.error.message ?? "codex turn error";
151
+ this.errorCategory = codexErrorCategory(turn.error.codexErrorInfo);
152
+ }
153
+ else if (!this.error && turn?.status === "failed") {
154
+ this.error = "Codex ended the turn as failed without saying why";
155
+ }
156
+ // @ref LLP 0001#d4--permission-requests-are-first-class-protocol — a cancelled answer stops the turn
157
+ // Codex stops a turn whose approval was answered cancel: it ended
158
+ // cancelled, as a Claude turn does, not as finished.
159
+ this.interrupted = !this.error && turn?.status === "interrupted";
160
+ this.finishReason = this.error ? "error" : this.interrupted ? "interrupted" : "completed";
161
+ if (!this.error)
162
+ this.stopReason = "end_turn";
163
+ return [];
164
+ }
165
+ case "error": {
166
+ // v2 errors carry a nested TurnError and may be transient. A retrying
167
+ // one tells the user why the turn is waiting; one Codex will not
168
+ // retry says why its turn failed, and its turn/completed follows.
169
+ const error = codexError(params.error);
170
+ const message = error?.message ??
171
+ (typeof params.message === "string" ? params.message : "codex app-server error");
172
+ const category = codexErrorCategory(error?.codexErrorInfo);
173
+ if (params.willRetry) {
174
+ return [
175
+ {
176
+ kind: "retry",
177
+ category: category ?? classifyError(message),
178
+ message,
179
+ ...codexRetryCount(message),
180
+ },
181
+ ];
182
+ }
183
+ this.error = message;
184
+ this.errorCategory = category;
185
+ this.finishReason = "error";
186
+ return [];
187
+ }
188
+ default:
189
+ return [];
190
+ }
191
+ }
192
+ openItem(item) {
193
+ switch (item.type) {
194
+ case "subAgentActivity":
195
+ return this.activity(item);
196
+ case "userMessage":
197
+ // @ref LLP 0002#steering — Codex starts a steer's message where it reads it
198
+ // A message Codex was steered with carries the steer's id; the turn's
199
+ // own message has none (the runtime ignores ids it did not accept).
200
+ return item.clientId ? [{ kind: "steer-inserted", steerId: item.clientId }] : [];
201
+ case "agentMessage": {
202
+ const part = createTextPart(this.ctx, item.text ?? "", true);
203
+ this.texts.set(item.id, part);
204
+ return [{ kind: "part-open", part }];
205
+ }
206
+ case "plan":
207
+ return [{ kind: "part-open", part: this.plan(item) }];
208
+ case "reasoning": {
209
+ const part = createReasoningPart(this.ctx, item.text ?? "", true);
210
+ this.texts.set(item.id, part);
211
+ return [{ kind: "part-open", part }];
212
+ }
213
+ default: {
214
+ // commandExecution / fileChange / mcpToolCall / webSearch /
215
+ // imageGeneration share one descriptor vocabulary; userMessage and
216
+ // unknown item types produce no assistant output.
217
+ const d = codexToolDescriptor(item.type);
218
+ return d ? [{ kind: "part-open", part: this.openTool(item, d) }] : [];
219
+ }
220
+ }
221
+ }
222
+ completeItem(item) {
223
+ switch (item.type) {
224
+ case "subAgentActivity":
225
+ return this.activity(item);
226
+ case "plan": {
227
+ // The plan waits on the user: the agent's decision completes it.
228
+ const known = this.tools.has(item.id);
229
+ return [{ kind: known ? "part-update" : "part-open", part: this.plan(item) }];
230
+ }
231
+ case "contextCompaction":
232
+ // Codex compacted the thread's context to keep going: a turn never asks
233
+ // it to (`thread/compact/start` is a turn of its own), so it was automatic.
234
+ // It reports no token counts.
235
+ return [{ kind: "compacted", trigger: "auto" }];
236
+ case "agentMessage":
237
+ case "reasoning": {
238
+ const existing = this.texts.get(item.id);
239
+ const part = existing ??
240
+ (item.type === "agentMessage"
241
+ ? createTextPart(this.ctx, item.text ?? "", true)
242
+ : createReasoningPart(this.ctx, item.text ?? "", true));
243
+ // Reasoning items complete with text:"" while their thought content
244
+ // streamed via item/reasoning/summaryTextDelta — an empty completed
245
+ // text must not clobber the accumulated delta text (consumers persist
246
+ // the terminal snapshot).
247
+ if (item.text)
248
+ part.text = item.text;
249
+ part.state = "done";
250
+ if (!existing)
251
+ this.texts.set(item.id, part);
252
+ return [{ kind: "part-update", part }];
253
+ }
254
+ default: {
255
+ const d = codexToolDescriptor(item.type);
256
+ if (!d)
257
+ return [];
258
+ const tool = this.tools.get(item.id) ?? this.openTool(item, d);
259
+ if (d.inputAtCompletion && tool.state.status === "in_progress")
260
+ tool.state = { ...tool.state, input: d.input(item) };
261
+ setToolMeta(tool, d.meta(item));
262
+ completeToolPart(tool, d.result(item));
263
+ return [{ kind: "part-update", part: tool }];
264
+ }
265
+ }
266
+ }
267
+ /** Codex's proposed plan, as the switch_mode tool part its approval points at. */
268
+ plan(item) {
269
+ const input = { plan: item.text ?? "" };
270
+ const existing = this.tools.get(item.id);
271
+ if (existing?.state.status === "in_progress") {
272
+ existing.state = { ...existing.state, input };
273
+ return existing;
274
+ }
275
+ const part = createToolPart(this.ctx, item.id, "plan", input, { kind: CODEX_TOOL_KINDS.plan });
276
+ this.tools.set(item.id, part);
277
+ return part;
278
+ }
279
+ planDecided(decided) {
280
+ // The turn ends cancelled; its closure cancels the plan's part.
281
+ if (decided.decision === "cancelled") {
282
+ this.interrupted = true;
283
+ this.finishReason = "interrupted";
284
+ return [];
285
+ }
286
+ const tool = this.tools.get(decided.itemId);
287
+ if (tool?.state.status !== "in_progress")
288
+ return [];
289
+ if (decided.decision === "kept_planning") {
290
+ completeToolPart(tool, {
291
+ output: decided.message
292
+ ? `The user wants to keep planning, and said:\n${decided.message}`
293
+ : "The user wants to keep planning.",
294
+ isError: true,
295
+ });
296
+ return [{ kind: "part-update", part: tool }];
297
+ }
298
+ completeToolPart(tool, {
299
+ output: decided.decision === "approved" ? "The user approved the plan." : "",
300
+ });
301
+ return [
302
+ { kind: "part-update", part: tool },
303
+ ...(decided.permissionMode
304
+ ? [{ kind: "mode", permissionMode: decided.permissionMode }]
305
+ : []),
306
+ ];
307
+ }
308
+ // @ref LLP 0002#tools-a-turn-leaves-open — a command a cancel could not stop is not cancelled
309
+ /**
310
+ * A command the cancel could not confirm stopped may still be running: it
311
+ * fails with its outcome unknown instead of closing as cancelled, closed by
312
+ * the engine as the reducer closes a tool its turn left running.
313
+ */
314
+ stopUnconfirmed({ itemIds }) {
315
+ return itemIds.flatMap((itemId) => {
316
+ const tool = this.tools.get(itemId);
317
+ const open = tool?.state;
318
+ if (!tool || (open?.status !== "pending" && open?.status !== "in_progress"))
319
+ return [];
320
+ const now = Date.now();
321
+ tool.state = {
322
+ status: "failed",
323
+ input: open.status === "in_progress" ? open.input : {},
324
+ error: TOOL_OUTCOME_UNKNOWN,
325
+ closure: "outcome_unknown",
326
+ time: { start: open.status === "in_progress" ? open.time.start : now, end: now },
327
+ };
328
+ return [{ kind: "part-update", part: tool }];
329
+ });
330
+ }
331
+ activity(item) {
332
+ if (!item.agentThreadId ||
333
+ !item.kind ||
334
+ !["started", "interacted", "interrupted", "completed"].includes(item.kind))
335
+ return [];
336
+ const existing = this.activities.get(item.id);
337
+ const part = {
338
+ ...this.ctx,
339
+ id: existing?.id ?? generateUUIDv7(),
340
+ type: "subagent",
341
+ nativeActivityId: item.id,
342
+ nativeThreadId: item.agentThreadId,
343
+ ...(item.agentPath && { path: item.agentPath }),
344
+ activity: item.kind,
345
+ };
346
+ this.activities.set(item.id, part);
347
+ return [{ kind: existing ? "part-update" : "part-open", part }];
348
+ }
349
+ textDelta(itemId, delta, kind) {
350
+ if (typeof itemId !== "string" || typeof delta !== "string" || !itemId || !delta)
351
+ return [];
352
+ const events = [];
353
+ let part = this.texts.get(itemId);
354
+ if (!part) {
355
+ part =
356
+ kind === "text"
357
+ ? createTextPart(this.ctx, "", true)
358
+ : createReasoningPart(this.ctx, "", true);
359
+ this.texts.set(itemId, part);
360
+ // The processor snapshots at emit time, after the append below. Open
361
+ // with a copy so this delta arrives once.
362
+ events.push({ kind: "part-open", part: structuredClone(part) });
363
+ }
364
+ part.text += delta;
365
+ events.push(kind === "text"
366
+ ? { kind: "text-delta", partId: part.id, text: delta }
367
+ : { kind: "reasoning-delta", partId: part.id, text: delta });
368
+ return events;
369
+ }
370
+ openTool(item, d) {
371
+ const part = createToolPart(this.ctx, item.id, d.toolName(item), d.input(item), d.meta(item));
372
+ this.tools.set(item.id, part);
373
+ return part;
374
+ }
375
+ captureUsage(total) {
376
+ this.usage = {
377
+ input: Math.max((total.inputTokens ?? 0) -
378
+ (total.cachedInputTokens ?? 0) -
379
+ (total.cacheWriteInputTokens ?? 0), 0),
380
+ output: total.outputTokens ?? 0,
381
+ reasoning: total.reasoningOutputTokens ?? 0,
382
+ cache: { read: total.cachedInputTokens ?? 0, write: total.cacheWriteInputTokens ?? 0 },
383
+ };
384
+ }
385
+ }
386
+ export function createCodexAppServerTransformer(ctx) {
387
+ return new CodexAppServerTransformer(ctx);
388
+ }
389
+ /** Codex's usage windows, named by length the way Claude names its own. */
390
+ function windowId(slot, minutes, limitId) {
391
+ const name = minutes === 300 ? "five_hour" : minutes === 10_080 ? "seven_day" : slot;
392
+ return typeof limitId === "string" && limitId && limitId !== "codex"
393
+ ? `${limitId}:${name}`
394
+ : name;
395
+ }
396
+ /** `account/rateLimits/updated` as the account's plan usage. */
397
+ function codexLimits(limits) {
398
+ if (!isRecord(limits))
399
+ return [];
400
+ const windows = ["primary", "secondary"].flatMap((slot) => {
401
+ const window = limits[slot];
402
+ if (!isRecord(window))
403
+ return [];
404
+ const { usedPercent, windowDurationMins, resetsAt } = window;
405
+ return [
406
+ {
407
+ id: windowId(slot, windowDurationMins, limits.limitId),
408
+ ...(typeof usedPercent === "number" && { usedPercent }),
409
+ // Unix seconds, like Claude's.
410
+ ...(typeof resetsAt === "number" && {
411
+ resetsAt: resetsAt < 1e12 ? resetsAt * 1000 : resetsAt,
412
+ }),
413
+ ...(typeof windowDurationMins === "number" && { windowMinutes: windowDurationMins }),
414
+ },
415
+ ];
416
+ });
417
+ return [
418
+ {
419
+ kind: "limits",
420
+ // A null reached-type does not clear a limit Codex reported before.
421
+ ...(limits.rateLimitReachedType ? { status: "limited" } : {}),
422
+ windows,
423
+ ...(typeof limits.planType === "string" && limits.planType && { planType: limits.planType }),
424
+ },
425
+ ];
426
+ }
427
+ /** Codex's typed failure (`codexErrorInfo`) as an engine error category. */
428
+ export function codexErrorCategory(info) {
429
+ const code = typeof info === "string" ? info : isRecord(info) ? Object.keys(info)[0] : undefined;
430
+ const detail = isRecord(info) ? Object.values(info)[0] : undefined;
431
+ const status = isRecord(detail) ? detail.httpStatusCode : undefined;
432
+ switch (code) {
433
+ case "usageLimitExceeded":
434
+ case "sessionBudgetExceeded":
435
+ return "usage_limit";
436
+ case "rateLimitExceeded":
437
+ return "rate_limit";
438
+ case "serverOverloaded":
439
+ return "overloaded";
440
+ case "contextWindowExceeded":
441
+ return "context_limit";
442
+ case "unauthorized":
443
+ return "auth";
444
+ case "badRequest":
445
+ return "invalid_request";
446
+ case "internalServerError":
447
+ return "internal";
448
+ case "httpConnectionFailed":
449
+ case "responseStreamConnectionFailed":
450
+ case "responseStreamDisconnected":
451
+ case "responseTooManyFailedAttempts":
452
+ if (status === 429)
453
+ return "rate_limit";
454
+ if (status === 529 || status === 503)
455
+ return "overloaded";
456
+ // A key the API refused: Codex reports it as a failed connection.
457
+ if (status === 401)
458
+ return "auth";
459
+ return "network";
460
+ default:
461
+ return undefined;
462
+ }
463
+ }