@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,448 @@
1
+ import { AsyncQueue } from "../../../protocol/index.js";
2
+ import { onAbort, withTimeout } from "../../utils/deadline.js";
3
+ import { CodexRpcError } from "./client.js";
4
+ import { CODEX_STOP_UNCONFIRMED } from "./events.js";
5
+ import { toUserInput } from "./input.js";
6
+ import { askPlan } from "./plan-approval.js";
7
+ import { codexItem, codexTurn, failing, retrying } from "./protocol.js";
8
+ /** One of Codex's turns, `turn/start` to its end, within an engine turn. */
9
+ export class NativeTurn {
10
+ /** Codex's id for it, once `turn/started` names it. */
11
+ id;
12
+ /** Its notifications, for the stream. */
13
+ queue = new AsyncQueue();
14
+ /** How it ended; absent while it runs. */
15
+ outcome;
16
+ /** The plan it proposed, when it planned. */
17
+ plan;
18
+ /** The error Codex would not retry, held for the stream until Codex's turn ends. */
19
+ failure;
20
+ /** Its events took their last: at its end, or once a managed turn's cleanup is done. */
21
+ finished = false;
22
+ settle;
23
+ /** Settles once it ended, or once Codex's process did. */
24
+ over = new Promise((done) => {
25
+ this.settle = done;
26
+ });
27
+ /** Codex ended it with `n`. */
28
+ end(n) {
29
+ const status = codexTurn(n)?.status;
30
+ this.outcome =
31
+ n.method === "error"
32
+ ? "error"
33
+ : status === "interrupted" || status === "failed"
34
+ ? status
35
+ : "completed";
36
+ this.settle();
37
+ }
38
+ /** Codex's process went away under it. */
39
+ lost() {
40
+ this.settle();
41
+ }
42
+ /** Its events end, or fail with `error`. */
43
+ finish(error) {
44
+ this.finished = true;
45
+ if (error === undefined)
46
+ this.queue.end();
47
+ else
48
+ this.queue.fail(error);
49
+ }
50
+ }
51
+ /**
52
+ * Stop a turn by Codex's `turn/interrupt`, then stop the commands it started.
53
+ * When Codex does not answer within `graceMs`, or the turn never began, its
54
+ * events fail and its process ends.
55
+ */
56
+ export class InterruptStop {
57
+ session;
58
+ commands;
59
+ signal;
60
+ graceMs;
61
+ continues = true;
62
+ forceTimer;
63
+ constructor(session, commands, signal, graceMs) {
64
+ this.session = session;
65
+ this.commands = commands;
66
+ this.signal = signal;
67
+ this.graceMs = graceMs;
68
+ }
69
+ nativeEnded(native, n) {
70
+ if (this.signal.aborted) {
71
+ native.finish(new Error("turn aborted"));
72
+ return;
73
+ }
74
+ native.queue.push(n);
75
+ native.finish();
76
+ // @ref LLP 0002#tools-a-turn-leaves-open — a cancelled tool did not go on running
77
+ // Codex stopped its turn itself (an approval answered cancel, by a client
78
+ // or by `requestTimeoutMs`): the turn ends cancelled, so what it started
79
+ // is stopped, as after the engine's own cancel.
80
+ if (native.outcome === "interrupted")
81
+ this.commands.interrupted();
82
+ // Codex failed its turn and never said it ended: the session's next
83
+ // turn/start would steer it and take its turn/completed, so its process
84
+ // is done with.
85
+ if (native.outcome === "error")
86
+ this.session.client.close();
87
+ }
88
+ cancel(native) {
89
+ // Codex's turn ended before the cancel (the user deciding on a plan, or
90
+ // its end still on its way to the stream): what it left running was left
91
+ // on purpose, as after any turn's end. Nothing is stopped.
92
+ if (native?.outcome)
93
+ return Promise.resolve(true);
94
+ this.commands.interrupted();
95
+ // No turn was started: ending its process stops all there is.
96
+ if (!native) {
97
+ this.force(undefined);
98
+ return Promise.resolve(true);
99
+ }
100
+ // Started, and not yet named: Codex may be running it.
101
+ if (!native.id) {
102
+ this.force(native);
103
+ return Promise.resolve(false);
104
+ }
105
+ this.forceTimer = setTimeout(() => this.force(native), this.graceMs);
106
+ this.forceTimer.unref?.();
107
+ return this.session.client
108
+ .request("turn/interrupt", { threadId: this.session.threadId, turnId: native.id }, this.graceMs)
109
+ .then(async () => {
110
+ // Nothing started, nothing to stop. (A command Codex starts before
111
+ // its turn ends is stopped when the turn ends.)
112
+ if (!this.commands.running)
113
+ return true;
114
+ // It ends its turn but keeps the command it was running alive as a
115
+ // background terminal, until that is stopped.
116
+ await withTimeout(native.over, this.graceMs);
117
+ return (await this.commands.stop()).length === 0;
118
+ }, () => {
119
+ this.force(native);
120
+ return false;
121
+ });
122
+ }
123
+ outcomeUnknown() {
124
+ return this.commands.outcomeUnknown();
125
+ }
126
+ async dispose() {
127
+ clearTimeout(this.forceTimer);
128
+ }
129
+ /** Give up on Codex's turn: its events fail, and its process ends. */
130
+ force(native) {
131
+ if (native?.finished)
132
+ return;
133
+ native?.finish(new Error("turn aborted"));
134
+ this.session.client.close();
135
+ }
136
+ }
137
+ /**
138
+ * Whether Codex refused a `turn/steer` because its turn takes no input: it
139
+ * ended, another started, or it is a review or compaction turn
140
+ * (`activeTurnNotSteerable`). Seen from 0.160: "no active turn to steer", and
141
+ * "expected active turn id `…` but found `…`".
142
+ */
143
+ export function codexSteerRefused(error) {
144
+ if (!(error instanceof CodexRpcError))
145
+ return false;
146
+ return (/no active turn|expected active turn id/i.test(error.message) ||
147
+ JSON.stringify(error.data ?? null).includes("activeTurnNotSteerable"));
148
+ }
149
+ /**
150
+ * Steer Codex's running turn. Codex reads it after the step it is on and
151
+ * starts a user message for it carrying the steer id (`clientId`).
152
+ */
153
+ async function steerTurn(client, threadId, expectedTurnId, request) {
154
+ try {
155
+ await client.request("turn/steer", {
156
+ threadId,
157
+ expectedTurnId,
158
+ clientUserMessageId: request.steerId,
159
+ input: toUserInput(request.input),
160
+ });
161
+ return "steered";
162
+ }
163
+ catch (error) {
164
+ if (client.closed || codexSteerRefused(error))
165
+ return "no_active_turn";
166
+ // Codex answered with an error: it took nothing.
167
+ if (error instanceof CodexRpcError)
168
+ throw error;
169
+ // No answer (a timeout): Codex may have taken it. The stream shows it
170
+ // where Codex reads it, or the turn's end lists it undelivered.
171
+ return "steered";
172
+ }
173
+ }
174
+ /**
175
+ * One engine turn on a Codex session: Codex's turns within it (a plan's, then
176
+ * the one carrying out the answer), the listener that feeds them, the watchdog
177
+ * on a retrying Codex and the cancel's acknowledgement. Made once the session
178
+ * is ready and disposed with the turn, so none of it can leak into the next.
179
+ */
180
+ export class CodexTurn {
181
+ session;
182
+ scope;
183
+ options;
184
+ commands;
185
+ stop;
186
+ steering;
187
+ timing;
188
+ /**
189
+ * Codex's turn running now, or the last one. The first is made with the
190
+ * listener, which feeds it from then on: what Codex says before the turn
191
+ * starts is the turn's.
192
+ */
193
+ native = new NativeTurn();
194
+ /** Codex's turns in this one: a plan's, then the one carrying out its answer. */
195
+ turnIds = new Set();
196
+ /**
197
+ * The one deadline the turn waits on: while Codex retries, how long it may
198
+ * go silent (`watchStall`); once its turn is failing, how long its
199
+ * turn/completed may take (`failed`). A cancel and the turn's end clear it.
200
+ */
201
+ stallTimer;
202
+ acknowledged;
203
+ unsubscribe;
204
+ accepted = false;
205
+ constructor(session, scope, options, commands, stop, steering, timing) {
206
+ this.session = session;
207
+ this.scope = scope;
208
+ this.options = options;
209
+ this.commands = commands;
210
+ this.stop = stop;
211
+ this.steering = steering;
212
+ this.timing = timing;
213
+ const { client } = session;
214
+ this.unsubscribe = [
215
+ client.onNotification((n) => this.observe(n)),
216
+ // If the subprocess dies mid-turn, fail the turn instead of hanging.
217
+ client.onClose((error) => {
218
+ const native = this.native;
219
+ native.lost();
220
+ if (native.outcome)
221
+ return;
222
+ native.finish(this.signal.aborted
223
+ ? new Error("turn aborted")
224
+ : (error ?? new Error("codex app-server exited mid-turn")));
225
+ }),
226
+ onAbort(this.signal, () => void this.cancel()),
227
+ ];
228
+ }
229
+ get signal() {
230
+ return this.scope.signal;
231
+ }
232
+ /** Stop Codex's turn for the cancel, once: whether it stopped. */
233
+ cancel() {
234
+ this.clearStall();
235
+ this.acknowledged ??= this.stop.cancel(this.native);
236
+ return this.acknowledged;
237
+ }
238
+ /**
239
+ * Codex took a turn of this one (it accepted `turn/start`): from then on
240
+ * it writes the thread, which before had nothing to resume.
241
+ */
242
+ get taken() {
243
+ return this.accepted;
244
+ }
245
+ /** Whether the turn puts Codex's plan to the user: a plan turn with someone to ask. */
246
+ get asksAboutPlans() {
247
+ return this.stop.continues && this.scope.mode === "plan" && !!this.scope.onPermissionRequest;
248
+ }
249
+ /** Run the turn: Codex's first turn, then each one an answer to its plan runs. */
250
+ async *run(input) {
251
+ const { thread } = this.session;
252
+ const previous = thread.settings;
253
+ const first = await thread.forTurn(this.options, this.session, this.scope.mode);
254
+ if (first.applied)
255
+ this.options.onExecution?.(first.applied);
256
+ const params = { threadId: this.session.threadId, input, ...first.params };
257
+ let native = this.start(this.native, params, first.next);
258
+ yield* this.events(native);
259
+ // A turn that failed may have failed on the model or effort it switched
260
+ // to, which Codex keeps on the thread: put the thread back on its own.
261
+ // (Only the first of Codex's turns sends them.)
262
+ if (this.stop.continues &&
263
+ !this.signal.aborted &&
264
+ (native.outcome === "failed" || native.outcome === "error"))
265
+ await thread.restore(this.session, previous, params);
266
+ let next = yield* askPlan(this, native);
267
+ while (next) {
268
+ native = this.start(new NativeTurn(), next.params, next.settings, next.sandbox);
269
+ yield* this.events(native);
270
+ next = yield* askPlan(this, native);
271
+ }
272
+ if (native.outcome === "interrupted")
273
+ yield* this.endCancelled();
274
+ }
275
+ /**
276
+ * The turn ends cancelled: what finished after Codex's turn ended says so,
277
+ * and a command whose stop was not confirmed, or that the turn left
278
+ * running, is not cancelled: its outcome is unknown.
279
+ */
280
+ async *endCancelled() {
281
+ yield* this.commands.drainLate();
282
+ const itemIds = await this.stop.outcomeUnknown();
283
+ if (itemIds.length)
284
+ yield { method: CODEX_STOP_UNCONFIRMED, params: { itemIds } };
285
+ }
286
+ dispose() {
287
+ this.clearStall();
288
+ for (const off of this.unsubscribe)
289
+ off();
290
+ }
291
+ /** One of Codex's turns, to the stream. */
292
+ async *events(native) {
293
+ for await (const event of native.queue) {
294
+ this.commands.shown(event);
295
+ yield event;
296
+ }
297
+ }
298
+ /**
299
+ * Start Codex's next turn in this one. What it changes on the thread is
300
+ * committed now, and put back when Codex refuses it: a refused turn/start
301
+ * changes nothing on the thread.
302
+ */
303
+ start(native, params, settings, sandbox = this.session.sandbox) {
304
+ const { session } = this;
305
+ if (this.signal.aborted)
306
+ throw new Error("turn aborted");
307
+ if (session.startedBeforeResume()) {
308
+ session.client.close();
309
+ throw new Error("Codex process was invalidated before turn admission");
310
+ }
311
+ const previous = { settings: session.thread.settings, sandbox: session.sandbox };
312
+ this.native = native;
313
+ session.thread.settings = settings;
314
+ session.sandbox = sandbox;
315
+ const environments = session.environments && { environments: session.environments };
316
+ session.client.request("turn/start", { ...params, ...environments }).then(() => {
317
+ this.accepted = true;
318
+ }, (error) => {
319
+ // Codex refused it: the thread is as it was.
320
+ const refused = error instanceof CodexRpcError;
321
+ if (refused) {
322
+ session.thread.settings = previous.settings;
323
+ session.sandbox = previous.sandbox;
324
+ }
325
+ // A cancelled turn ends by its cancel. Any other ends with this error,
326
+ // before the close below could end it as "exited mid-turn".
327
+ if (!this.signal.aborted) {
328
+ native.queue.push({ method: "error", params: { message: String(error) } });
329
+ native.finish();
330
+ }
331
+ // Anything but a refusal (no answer in time) leaves the thread's
332
+ // settings unknown, so this process is done with.
333
+ if (!refused)
334
+ session.client.close();
335
+ });
336
+ return native;
337
+ }
338
+ observe(n) {
339
+ this.scope.items.observe(n);
340
+ this.scope.subagents?.observe(n);
341
+ if (n.params.threadId && n.params.threadId !== this.session.threadId)
342
+ return;
343
+ // An item of an earlier turn is not this one's: a command the earlier
344
+ // turn's cancel killed completes late, as `failed`.
345
+ if (n.method.startsWith("item/") &&
346
+ typeof n.params.turnId === "string" &&
347
+ !this.turnIds.has(n.params.turnId))
348
+ return;
349
+ const native = this.native;
350
+ switch (n.method) {
351
+ case "turn/started": {
352
+ const id = codexTurn(n)?.id;
353
+ if (id)
354
+ this.began(native, id);
355
+ break;
356
+ }
357
+ case "item/started":
358
+ this.commands.started(codexItem(n));
359
+ break;
360
+ case "item/completed": {
361
+ const item = codexItem(n);
362
+ if (item?.type === "plan")
363
+ native.plan = { itemId: item.id, text: item.text ?? "" };
364
+ // Codex's turn ended (its plan's question open): its events take no
365
+ // more, and a completion of one of its commands waits for the
366
+ // stream, shown even when a cancel comes with it.
367
+ if (this.commands.completed(item) && native.finished) {
368
+ this.commands.holdLate(n);
369
+ return;
370
+ }
371
+ break;
372
+ }
373
+ }
374
+ if (n.method === "turn/completed") {
375
+ this.ended(native, n);
376
+ return;
377
+ }
378
+ if (native.finished)
379
+ return;
380
+ if (failing(n)) {
381
+ this.failed(native, n);
382
+ return;
383
+ }
384
+ native.queue.push(n);
385
+ this.watchStall(n);
386
+ }
387
+ began(native, id) {
388
+ native.id = id;
389
+ this.turnIds.add(id);
390
+ const { client, threadId } = this.session;
391
+ // @ref LLP 0001#d13--input-while-a-turn-runs-steers-it — Codex takes steers once its turn exists
392
+ this.steering.open((request) => steerTurn(client, threadId, id, request));
393
+ }
394
+ /**
395
+ * Codex's turn failed. It ends at its own turn/completed, which Codex sends
396
+ * after: ended here, Codex's turn would still be running, and the session's
397
+ * next turn/start would steer it and end on its turn/completed. Without one
398
+ * within `confirmMs`, it ends with the error, and its process with it. The
399
+ * wait runs from the first failure: a later one changes nothing, or a run
400
+ * of them would keep the turn open. After a cancel, its interrupt's grace
401
+ * governs.
402
+ */
403
+ // @ref LLP 0013#f11-a-failed-codex-turn-ended-the-next-one — no native turn outlives its engine turn
404
+ failed(native, n) {
405
+ if (native.failure)
406
+ return;
407
+ native.failure = n;
408
+ if (this.signal.aborted)
409
+ return;
410
+ this.clearStall();
411
+ this.stallTimer = setTimeout(() => this.ended(native, n), this.timing.confirmMs);
412
+ this.stallTimer.unref?.();
413
+ }
414
+ ended(native, n) {
415
+ // The stream hears why Codex's turn failed, then that it ended.
416
+ if (native.failure && native.failure !== n)
417
+ native.queue.push(native.failure);
418
+ native.end(n);
419
+ this.clearStall();
420
+ // A plan turn's end may only pause this one: steers wait for the turn
421
+ // that carries out the user's answer.
422
+ if (n.method === "turn/completed" && this.asksAboutPlans)
423
+ this.steering.hold();
424
+ this.stop.nativeEnded(native, n);
425
+ }
426
+ /**
427
+ * A retryable error promises more notifications. If none arrive, the
428
+ * subprocess is wedged-but-alive and the turn would hang forever: bound it.
429
+ * A failing turn's deadline is not this one's to move: what Codex sends
430
+ * after its error leaves it as it is.
431
+ */
432
+ watchStall(n) {
433
+ if (this.native.failure)
434
+ return;
435
+ this.clearStall();
436
+ if (this.signal.aborted || !retrying(n))
437
+ return;
438
+ this.stallTimer = setTimeout(() => {
439
+ this.native.finish(new Error("codex app-server went silent after a retryable error"));
440
+ this.session.client.close();
441
+ }, this.timing.retryStallMs);
442
+ this.stallTimer.unref?.();
443
+ }
444
+ clearStall() {
445
+ clearTimeout(this.stallTimer);
446
+ this.stallTimer = undefined;
447
+ }
448
+ }
@@ -0,0 +1,78 @@
1
+ import { claimsOf } from "../../../protocol/index.js";
2
+ import { onAbort } from "../../utils/deadline.js";
3
+ import { AgentServerError } from "../../utils/errors.js";
4
+ import { isRecord } from "../../utils/is-record.js";
5
+ /**
6
+ * One read of the user's own login: a new app-server on the engine's own
7
+ * Codex home (`connect` gives it the engine's environment, never a session's
8
+ * `CODEX_HOME`), asked once and ended at once. Nothing is kept between reads.
9
+ */
10
+ export function userLoginReader(connect) {
11
+ return async (refreshToken, signal) => {
12
+ signal?.throwIfAborted();
13
+ const client = await connect();
14
+ const offAbort = onAbort(signal, () => client.close());
15
+ try {
16
+ signal?.throwIfAborted();
17
+ await client.initialize();
18
+ const answer = await client.request("getAuthStatus", { includeToken: true, refreshToken });
19
+ return isRecord(answer) ? answer : {};
20
+ }
21
+ finally {
22
+ offAbort();
23
+ client.close();
24
+ }
25
+ };
26
+ }
27
+ /** The user has no login Codex can hand to a session's process: they sign in, and the turn is sent again. */
28
+ const notSignedIn = (why) => new AgentServerError(`${why} Sign in to Codex on this computer (\`codex login\`, or auth/login with no env) and try again.`, "credentialsReconnect", "auth");
29
+ /** ChatGPT tokens of an access token: its account and plan, from its own claims. */
30
+ function chatGptTokens(accessToken) {
31
+ const auth = claimsOf(accessToken)["https://api.openai.com/auth"];
32
+ const identity = isRecord(auth) ? auth : {};
33
+ const accountId = identity.chatgpt_account_id;
34
+ if (typeof accountId !== "string" || !accountId)
35
+ throw notSignedIn("Codex's ChatGPT login names no account.");
36
+ const plan = identity.chatgpt_plan_type;
37
+ return {
38
+ accessToken,
39
+ chatgptAccountId: accountId,
40
+ ...(typeof plan === "string" && plan && { chatgptPlanType: plan }),
41
+ };
42
+ }
43
+ const chatGptToken = (status) => status.authMethod === "chatgpt" && typeof status.authToken === "string" && status.authToken
44
+ ? status.authToken
45
+ : undefined;
46
+ // @ref LLP 0017#the-persons-own-login-in-a-home-of-the-sessions-own — read from Codex, held in memory
47
+ /**
48
+ * The user's own Codex login as a session's process logs in with it: a
49
+ * ChatGPT login as its tokens, held in that process's memory, or an API key.
50
+ * When Codex refuses the token it holds, a fresher one: the login read again,
51
+ * and when that is still the refused token, renewed by Codex in the user's
52
+ * own home under its own lock. No login, or one that cannot be handed over,
53
+ * fails the turn before any process of the session starts.
54
+ */
55
+ export async function userAuth(read, signal) {
56
+ const status = await read(false, signal);
57
+ if (status.authMethod === "apikey" && typeof status.authToken === "string" && status.authToken)
58
+ return { type: "apiKey", apiKey: status.authToken };
59
+ const token = chatGptToken(status);
60
+ if (!token) {
61
+ throw notSignedIn(status.authMethod
62
+ ? `Codex's own login (${status.authMethod}) cannot run a session in a home of its own.`
63
+ : "Codex is not signed in.");
64
+ }
65
+ let current = chatGptTokens(token);
66
+ return {
67
+ type: "chatgptAuthTokens",
68
+ tokens: current,
69
+ refresh: async () => {
70
+ const again = chatGptToken(await read(false));
71
+ const fresher = again && again !== current.accessToken ? again : chatGptToken(await read(true));
72
+ if (!fresher)
73
+ throw notSignedIn("Codex's ChatGPT login ended.");
74
+ current = chatGptTokens(fresher);
75
+ return current;
76
+ },
77
+ };
78
+ }
@@ -0,0 +1,10 @@
1
+ import { createHash } from "node:crypto";
2
+ import { canonicalJson } from "../../protocol/index.js";
3
+ /** Stable, non-reversible identity for config that may contain credentials. */
4
+ export function configFingerprint(value) {
5
+ return createHash("sha256").update(canonicalJson(value)).digest("hex");
6
+ }
7
+ /** A session's extra directories: order and duplicates don't change what it may touch. */
8
+ export function directoriesFingerprint(directories) {
9
+ return configFingerprint([...new Set(directories ?? [])].sort());
10
+ }
@@ -0,0 +1,71 @@
1
+ import { CredentialAnswerSchema, credentialRunsOn, } from "../../protocol/index.js";
2
+ import { untilAborted } from "../utils/deadline.js";
3
+ import { AgentServerError } from "../utils/errors.js";
4
+ import { isLoopbackHost } from "../utils/loopback.js";
5
+ /**
6
+ * The product's credential for a harness, as the kind it runs on: one it
7
+ * cannot run fails the turn here, before anything starts. A turn cancelled
8
+ * meanwhile stops waiting at once, whether or not the source heeds `signal`,
9
+ * and an answer that comes after is dropped.
10
+ */
11
+ export async function credentialFor(source, request, signal) {
12
+ const credential = await untilAborted(source(request, signal), signal);
13
+ if (!credential)
14
+ return undefined;
15
+ const runs = credentialRunsOn(request.harness, credential);
16
+ if (runs.ok)
17
+ return runs.credential;
18
+ throw new AgentServerError(runs.error, "credentialsUnavailable", "internal");
19
+ }
20
+ /** How long a credential endpoint has to answer: inside Codex's 10 s for a token refresh. */
21
+ const ENDPOINT_TIMEOUT_MS = 8_000;
22
+ /** Credentials travel encrypted, unless they never leave this machine. */
23
+ function checkEndpoint(url) {
24
+ const parsed = URL.canParse(url) ? new URL(url) : undefined;
25
+ if (parsed?.protocol === "https:")
26
+ return;
27
+ if (parsed?.protocol === "http:" && isLoopbackHost(parsed.hostname))
28
+ return;
29
+ throw new Error("a credential endpoint must be https (or http on this machine)");
30
+ }
31
+ /** What an endpoint's refusal said, as the engine tells it: its words only where they are the person's. */
32
+ async function refusal(response) {
33
+ const body = await response.json().catch(() => undefined);
34
+ const answer = typeof body === "object" && body !== null ? body : {};
35
+ // The product's own words (an `AccountError`): the person signs in again, or it says why not.
36
+ if (response.status === 409 && typeof answer.error === "string") {
37
+ const words = answer.error.slice(0, 200);
38
+ return answer.reconnect === true
39
+ ? new AgentServerError(words, "credentialsReconnect", "auth")
40
+ : new AgentServerError(words, "credentialsUnavailable", "internal");
41
+ }
42
+ return new AgentServerError(response.status === 401 || response.status === 403
43
+ ? "the credential endpoint refused this engine's token"
44
+ : `the credential endpoint answered ${response.status}`, "credentialsUnavailable", "internal");
45
+ }
46
+ /**
47
+ * A product's credential endpoint (`createCredentialHandler` in
48
+ * `@zvada/agent-server/accounts`): the engine asks it before each turn, with a
49
+ * refused token's hash, never the token. `token` authenticates this engine to
50
+ * it. The URL is https, or http on loopback.
51
+ */
52
+ export function credentialsFromUrl(options) {
53
+ checkEndpoint(options.url);
54
+ const doFetch = options.fetch ?? globalThis.fetch;
55
+ return async (request, signal) => {
56
+ const timeout = AbortSignal.timeout(ENDPOINT_TIMEOUT_MS);
57
+ const response = await doFetch(options.url, {
58
+ method: "POST",
59
+ headers: {
60
+ "content-type": "application/json",
61
+ ...(options.token && { authorization: `Bearer ${options.token}` }),
62
+ },
63
+ body: JSON.stringify(request),
64
+ redirect: "manual",
65
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
66
+ });
67
+ if (!response.ok)
68
+ throw await refusal(response);
69
+ return CredentialAnswerSchema.parse(await response.json()).credential ?? undefined;
70
+ };
71
+ }
@@ -0,0 +1,27 @@
1
+ // @ref LLP 0002#tool-output-has-three-audiences — a diff entry per hunk, as `claude-agent-acp` builds them
2
+ /**
3
+ * One hunk of a unified diff as a `diff` entry: `oldText` is its context and
4
+ * removed lines, `newText` its context and added lines, each joined by a
5
+ * newline. A `` marker is no line of either file,
6
+ * so it is dropped. Undefined for a hunk with no lines.
7
+ */
8
+ export function hunkDiff(path, lines) {
9
+ const oldLines = [];
10
+ const newLines = [];
11
+ for (const line of lines) {
12
+ if (line.startsWith("\\"))
13
+ continue;
14
+ const text = line.slice(1);
15
+ if (line.startsWith("-"))
16
+ oldLines.push(text);
17
+ else if (line.startsWith("+"))
18
+ newLines.push(text);
19
+ else {
20
+ oldLines.push(text);
21
+ newLines.push(text);
22
+ }
23
+ }
24
+ if (!oldLines.length && !newLines.length)
25
+ return undefined;
26
+ return { type: "diff", path, oldText: oldLines.join("\n"), newText: newLines.join("\n") };
27
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Told to the agent when the turn's client answers no questions
3
+ * (`config.elicitation` off), so it carries on instead of waiting.
4
+ */
5
+ export const NO_ANSWERS = "The user cannot answer questions in this session. Continue with your best judgment and state the assumptions you make.";
6
+ /** The agent's own questions (Claude's AskUserQuestion, Codex's request_user_input), as the broker asks them. */
7
+ export function questionRequest(questions, toolCallId) {
8
+ return {
9
+ mode: "question",
10
+ message: questions.length === 1 ? questions[0].question : `${questions.length} questions`,
11
+ ...(toolCallId && { toolCallId }),
12
+ questions,
13
+ };
14
+ }
15
+ /** What the agent is told when the user leaves its question unanswered. */
16
+ export function unanswered(action) {
17
+ return action === "decline"
18
+ ? "The user declined to answer."
19
+ : "The user dismissed the question without answering.";
20
+ }
21
+ /** An MCP server's request for input, as the broker asks it: what it leaves empty is left out. */
22
+ export function inputRequest(request) {
23
+ return {
24
+ mode: request.mode,
25
+ message: request.message,
26
+ ...(request.serverName && { serverName: request.serverName }),
27
+ ...(request.toolCallId && { toolCallId: request.toolCallId }),
28
+ ...(request.requestedSchema && { requestedSchema: request.requestedSchema }),
29
+ ...(request.url && { url: request.url }),
30
+ ...(request.elicitationId && { elicitationId: request.elicitationId }),
31
+ };
32
+ }
33
+ /** The broker's outcome, as the MCP server that asked takes it. */
34
+ export function inputReply(outcome) {
35
+ if (outcome.action !== "accept")
36
+ return { action: outcome.action };
37
+ return {
38
+ action: "accept",
39
+ // The user answered the server's own schema, whose values MCP types.
40
+ ...(outcome.content && { content: outcome.content }),
41
+ };
42
+ }
@@ -0,0 +1,5 @@
1
+ /** Every level, for a command line to check a value against. */
2
+ export const INHERIT_CONFIGS = ["all", "project", "none"];
3
+ export function isInheritConfig(value) {
4
+ return INHERIT_CONFIGS.includes(value);
5
+ }