@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,338 @@
1
+ import { StringDecoder } from "node:string_decoder";
2
+ import { AgentExitedError } from "../../utils/errors.js";
3
+ /** What the pinned native server logs of a cleanup that failed; it still exits 0. */
4
+ const SHUTDOWN_FAILED = /failed to submit Shutdown|timed out waiting for .*shut down|shutdown timed out/;
5
+ /** The stderr the shutdown sniff keeps between chunks: a line split across two is still read. */
6
+ const SNIFF_MAX = 4096;
7
+ /** How long Codex's own shutdown (EOF) has before its process is stopped. */
8
+ const SHUTDOWN_TIMEOUT_MS = 2_000;
9
+ /**
10
+ * How the harness introduces itself to Codex. It has no version of its own to
11
+ * give: core cannot read the package's manifest (only the server's bin does),
12
+ * and `0.0.0` says so, where a made-up version would not.
13
+ */
14
+ const CLIENT_INFO = { name: "agent-server", title: null, version: "0.0.0" };
15
+ /**
16
+ * Every page of a list Codex answers in pages (`data` and `nextCursor`), in
17
+ * order. A page without `data`, a cursor Codex gave before or more than
18
+ * `maxPages` pages means Codex cannot say what the list holds: an error.
19
+ */
20
+ export async function* pages(connection, method, params, { timeoutMs, maxPages = Number.POSITIVE_INFINITY } = {}) {
21
+ const cursors = new Set();
22
+ let cursor;
23
+ for (let read = 1;; read++) {
24
+ const page = (await connection.request(method, { ...params, ...(cursor && { cursor }) }, timeoutMs));
25
+ if (!Array.isArray(page?.data))
26
+ throw new Error(`Codex answered ${method} without a list`);
27
+ yield page.data;
28
+ cursor = typeof page.nextCursor === "string" && page.nextCursor ? page.nextCursor : undefined;
29
+ if (!cursor)
30
+ return;
31
+ if (cursors.has(cursor) || read >= maxPages)
32
+ throw new Error(`Codex's ${method} did not end`);
33
+ cursors.add(cursor);
34
+ }
35
+ }
36
+ /** The JSON-RPC error Codex answered a request with. */
37
+ export class CodexRpcError extends Error {
38
+ code;
39
+ data;
40
+ constructor(message, code, data) {
41
+ super(message);
42
+ this.code = code;
43
+ this.data = data;
44
+ this.name = "CodexRpcError";
45
+ }
46
+ }
47
+ /**
48
+ * Newline-delimited (JSONL) JSON-RPC client over a `codex app-server` subprocess.
49
+ * Requests get monotonic ids resolved against a pending map; notifications fan
50
+ * out to handlers. Inbound server→client requests (approvals) go to the
51
+ * registered request handler; without one they are declined (-32601).
52
+ */
53
+ export class CodexAppServerClient {
54
+ opts;
55
+ native;
56
+ shutdown;
57
+ nextId = 1;
58
+ buffer = "";
59
+ decoder = new StringDecoder("utf8");
60
+ pending = new Map();
61
+ handlers = new Set();
62
+ closeHandlers = new Set();
63
+ requestHandler;
64
+ exited = false;
65
+ lastExit;
66
+ nativeShutdownFailed = false;
67
+ /** The app-server's exit, or the end of a stop that could not end it. */
68
+ leaving;
69
+ constructor(opts) {
70
+ this.opts = opts;
71
+ }
72
+ onNotification(handler) {
73
+ this.handlers.add(handler);
74
+ return () => this.handlers.delete(handler);
75
+ }
76
+ setRequestHandler(handler) {
77
+ this.requestHandler = handler;
78
+ }
79
+ onClose(handler) {
80
+ this.closeHandlers.add(handler);
81
+ return () => this.closeHandlers.delete(handler);
82
+ }
83
+ get closed() {
84
+ return this.exited;
85
+ }
86
+ get exitError() {
87
+ return this.lastExit;
88
+ }
89
+ async initialize() {
90
+ this.start();
91
+ await this.request("initialize", {
92
+ clientInfo: CLIENT_INFO,
93
+ capabilities: this.opts.experimentalApi ? { experimentalApi: true } : null,
94
+ }, this.opts.startupTimeoutMs ?? 15_000);
95
+ }
96
+ request(method, params, timeoutMs) {
97
+ if (!this.native || this.exited)
98
+ return Promise.reject(this.lastExit ?? new Error("codex app-server not running"));
99
+ const id = this.nextId++;
100
+ return new Promise((resolve, reject) => {
101
+ const deadline = timeoutMs ?? this.opts.requestTimeoutMs ?? 30_000;
102
+ const timer = setTimeout(() => {
103
+ this.pending.delete(id);
104
+ reject(new Error(`codex app-server '${method}' timed out after ${deadline}ms`));
105
+ }, deadline);
106
+ this.pending.set(id, { method, resolve, reject, timer });
107
+ try {
108
+ this.write({ id, method, params });
109
+ }
110
+ catch (error) {
111
+ clearTimeout(timer);
112
+ this.pending.delete(id);
113
+ reject(error);
114
+ }
115
+ });
116
+ }
117
+ close() {
118
+ if (this.shutdown)
119
+ return;
120
+ const native = this.native;
121
+ const wasOpen = !this.exited;
122
+ this.native = undefined;
123
+ this.exited = true;
124
+ // Forced process exit cannot attest that native child commands stopped.
125
+ this.shutdown = Promise.resolve(!native);
126
+ this.rejectPending((method) => new Error(`codex app-server closed before '${method}'`));
127
+ // SIGTERM stops its command at once (0.07 s, measured); the walk and the
128
+ // SIGKILL after the grace cover an app-server that cannot act on it.
129
+ if (native)
130
+ this.leaving = Promise.race([native.exited, native.stop()]);
131
+ if (wasOpen)
132
+ this.notifyClosed();
133
+ }
134
+ gone() {
135
+ return Promise.resolve(this.leaving).then(() => { }, () => { });
136
+ }
137
+ /** EOF invokes native thread/tool cleanup. Killing the server alone proves nothing about workers. */
138
+ closeAndWait(timeoutMs = SHUTDOWN_TIMEOUT_MS) {
139
+ if (this.shutdown)
140
+ return this.shutdown;
141
+ const native = this.native;
142
+ if (!native)
143
+ return Promise.resolve(true);
144
+ const { child } = native;
145
+ if (this.exited || child.exitCode !== null || child.signalCode !== null) {
146
+ this.shutdown = Promise.resolve(false);
147
+ return this.shutdown;
148
+ }
149
+ this.exited = true;
150
+ // Gone when it exited, or when the stop a slow shutdown falls back to is
151
+ // done: that can outlast the answer this returns.
152
+ let stopped = () => { };
153
+ this.leaving = Promise.race([
154
+ native.exited,
155
+ new Promise((resolve) => {
156
+ stopped = resolve;
157
+ }),
158
+ ]);
159
+ this.shutdown = new Promise((resolve) => {
160
+ let forced = false;
161
+ const finish = (confirmed) => {
162
+ clearTimeout(killTimer);
163
+ clearTimeout(deadline);
164
+ if (this.native === native)
165
+ this.native = undefined;
166
+ resolve(confirmed);
167
+ };
168
+ void native.exited.then(({ code, signal }) => finish(!forced && !this.nativeShutdownFailed && code === 0 && signal === null));
169
+ // @ref LLP 0007#what-each-harness-does — a SIGKILLed app-server leaves its commands running
170
+ const killTimer = setTimeout(() => {
171
+ forced = true;
172
+ void native.stop().then(stopped, stopped);
173
+ }, timeoutMs);
174
+ const deadline = setTimeout(() => finish(false), timeoutMs * 2);
175
+ // In stdio mode SIGTERM bypasses Codex's async shutdown. EOF drains
176
+ // connection tasks and awaits shutdown_threads before a clean exit.
177
+ child.stdin?.end();
178
+ });
179
+ this.rejectPending((method) => new Error(`codex app-server closed before '${method}'`));
180
+ this.notifyClosed();
181
+ return this.shutdown;
182
+ }
183
+ /** Every request still waiting for its answer fails, with the error `why` gives it. */
184
+ rejectPending(why) {
185
+ for (const [id, p] of this.pending) {
186
+ if (p.timer)
187
+ clearTimeout(p.timer);
188
+ p.reject(why(p.method));
189
+ this.pending.delete(id);
190
+ }
191
+ }
192
+ notifyClosed(error) {
193
+ for (const handler of this.closeHandlers)
194
+ handler(error);
195
+ this.closeHandlers.clear();
196
+ }
197
+ start() {
198
+ if (this.native && !this.exited)
199
+ return;
200
+ this.exited = false;
201
+ this.lastExit = undefined;
202
+ this.shutdown = undefined;
203
+ this.nativeShutdownFailed = false;
204
+ const native = this.opts.processes.spawn({
205
+ command: this.opts.codexPath ?? "codex",
206
+ args: [
207
+ "app-server",
208
+ ...(this.opts.ephemeralCredentials ? ["-c", 'cli_auth_credentials_store="ephemeral"'] : []),
209
+ ...(this.opts.pluginsOff ? ["-c", "features.plugins=false"] : []),
210
+ ],
211
+ cwd: this.opts.cwd,
212
+ env: this.opts.env ?? process.env,
213
+ harness: "codex-app-server",
214
+ ...(this.opts.sessionId !== undefined && { sessionId: this.opts.sessionId }),
215
+ });
216
+ this.native = native;
217
+ this.leaving = native.exited;
218
+ const proc = native.child;
219
+ proc.stdout?.on("data", (chunk) => this.onStdout(chunk));
220
+ // A broken pipe usually means the process died: its exit, which says
221
+ // how and carries its stderr, is the error to keep when it follows.
222
+ const onPipeError = (err) => setTimeout(() => {
223
+ if (this.native === native)
224
+ this.onExit(err);
225
+ }, 1_000).unref?.();
226
+ proc.stdin?.on("error", onPipeError);
227
+ proc.stdout?.on("error", onPipeError);
228
+ // The pinned native server logs its cleanup failures but still exits 0.
229
+ let recent = "";
230
+ proc.stderr?.on("data", (chunk) => {
231
+ recent += String(chunk);
232
+ if (SHUTDOWN_FAILED.test(recent))
233
+ this.nativeShutdownFailed = true;
234
+ recent = recent.slice(-SNIFF_MAX);
235
+ });
236
+ proc.on("error", (err) => this.onExit(err));
237
+ // Its exit once stdout and stderr closed: a response it wrote just before
238
+ // is read first, and stderr's last flush, usually the line that says WHY
239
+ // (a missing or expired login prints there and exits 1), is in the tail.
240
+ void native.exited.then(({ code, signal }) => {
241
+ const tail = native.stderrTail.trim().replace(/\s+/g, " ");
242
+ // The process exiting is the failure (`process_exit`), whatever its stderr says.
243
+ this.onExit(new AgentExitedError(`codex app-server exited (code=${code} signal=${signal})${tail ? `: ${tail}` : ""}`));
244
+ });
245
+ }
246
+ onStdout(chunk) {
247
+ this.buffer += this.decoder.write(chunk);
248
+ let nl = this.buffer.indexOf("\n");
249
+ while (nl !== -1) {
250
+ const line = this.buffer.slice(0, nl).trim();
251
+ this.buffer = this.buffer.slice(nl + 1);
252
+ if (line) {
253
+ try {
254
+ this.handleMessage(JSON.parse(line));
255
+ }
256
+ catch {
257
+ // ignore non-JSON lines
258
+ }
259
+ }
260
+ nl = this.buffer.indexOf("\n");
261
+ }
262
+ }
263
+ handleMessage(msg) {
264
+ if (!msg || typeof msg !== "object")
265
+ return;
266
+ const m = msg;
267
+ if (typeof m.id === "number" && m.method === undefined) {
268
+ const pending = this.pending.get(m.id);
269
+ if (!pending)
270
+ return;
271
+ this.pending.delete(m.id);
272
+ if (pending.timer)
273
+ clearTimeout(pending.timer);
274
+ if (m.error) {
275
+ pending.reject(new CodexRpcError(m.error.message ?? `error from '${pending.method}'`, m.error.code, m.error.data));
276
+ }
277
+ else
278
+ pending.resolve(m.result);
279
+ return;
280
+ }
281
+ if (typeof m.method === "string") {
282
+ if (typeof m.id === "number") {
283
+ // Server→client request (approvals). Route to the handler; decline
284
+ // when none is installed (approvalPolicy "never" turns).
285
+ const handler = this.requestHandler;
286
+ const id = m.id;
287
+ if (!handler) {
288
+ this.write({ id, error: { code: -32601, message: `unsupported: ${m.method}` } });
289
+ return;
290
+ }
291
+ void handler(m.method, (m.params ?? {}))
292
+ .then((result) => this.write({ id, result }))
293
+ .catch((err) => this.write({ id, error: { code: -32603, message: String(err) } }));
294
+ return;
295
+ }
296
+ const notification = {
297
+ method: m.method,
298
+ params: (m.params ?? {}),
299
+ };
300
+ for (const handler of this.handlers)
301
+ handler(notification);
302
+ }
303
+ }
304
+ onExit(error) {
305
+ if (this.exited)
306
+ return;
307
+ this.exited = true;
308
+ this.lastExit = error;
309
+ // A broken pipe closes it while the app-server may still run (wedged,
310
+ // its stdin gone). It is stopped, so the process that takes its thread
311
+ // waits the stop's grace at most, not for an exit that never comes.
312
+ const native = this.native;
313
+ if (native)
314
+ this.leaving = Promise.race([native.exited, native.stop()]);
315
+ this.rejectPending(() => error);
316
+ this.notifyClosed(error);
317
+ }
318
+ write(payload) {
319
+ this.native?.child.stdin?.write(`${JSON.stringify(payload, wellFormed)}\n`);
320
+ }
321
+ }
322
+ // @ref LLP 0013#f12-a-lone-surrogate-hung-codex — a line Codex cannot read is never answered
323
+ /**
324
+ * A `JSON.stringify` replacer that makes every string and every key
325
+ * well-formed (a lone UTF-16 surrogate becomes U+FFFD). JSON.stringify
326
+ * writes a lone surrogate as its `\ud83d` escape, which Codex 0.160 cannot
327
+ * parse ("unexpected end of hex escape"): it drops the line and never answers.
328
+ * A key is an MCP server's name, say.
329
+ */
330
+ function wellFormed(_key, value) {
331
+ if (typeof value === "string")
332
+ return value.toWellFormed();
333
+ if (typeof value !== "object" || value === null || Array.isArray(value))
334
+ return value;
335
+ if (Object.keys(value).every((key) => key.isWellFormed()))
336
+ return value;
337
+ return Object.fromEntries(Object.entries(value).map(([key, v]) => [key.toWellFormed(), v]));
338
+ }
@@ -0,0 +1,294 @@
1
+ import { sharedNativeProcesses } from "../../processes/native-processes.js";
2
+ import { onAbort, untilAborted } from "../../utils/deadline.js";
3
+ import { configFingerprint } from "../config-fingerprint.js";
4
+ import { IDLE_TIMEOUT_MS } from "../process-pool.js";
5
+ import { SessionAgent } from "../session-agent.js";
6
+ import { CodexAppServerClient, } from "./client.js";
7
+ import { TurnCommands } from "./commands.js";
8
+ import { authFor, logIn } from "./credentials.js";
9
+ import { toUserInput } from "./input.js";
10
+ import { CodexCliLogin } from "./login.js";
11
+ import { codexModelDescriptors, listCodexModels, readCodexListing } from "./models.js";
12
+ import { CODEX_TOOLS_REQUIRED, clientOptionsFor } from "./options.js";
13
+ import { CodexSessions } from "./session.js";
14
+ import { CodexTurnSubagents, ManagedStop } from "./subagents.js";
15
+ import { TurnItems } from "./turn-items.js";
16
+ import { CodexTurn, InterruptStop } from "./turn.js";
17
+ import { userAuth, userLoginReader } from "./user-login.js";
18
+ const CAPABILITIES = {
19
+ multiTurn: true,
20
+ sessionResume: true,
21
+ // Model/effort are overridable per turn/start, so no restart is needed.
22
+ modelSwitch: "in_session",
23
+ thinkingLevels: true,
24
+ images: true,
25
+ // Codex has no input for file content: text is inlined (`input.ts`).
26
+ files: ["text"],
27
+ mcpServers: true,
28
+ permissionRequests: true,
29
+ // Its approval's answer is a bare verdict.
30
+ rejectionMessages: false,
31
+ turnScopedSubagents: true,
32
+ steering: true,
33
+ ignoredSettings: [
34
+ // Nothing in this harness sends a turn limit to the app-server.
35
+ "maxTurns",
36
+ // thread/resume continues a thread at its end; nothing here names a message in it.
37
+ "resumeSessionAt",
38
+ ],
39
+ };
40
+ /** How long a retryable error may go unanswered before the turn is failed. */
41
+ const RETRY_STALL_TIMEOUT_MS = 120_000;
42
+ /** How long a cancelled turn has to stop before Codex's process is ended, unless `cancelGraceMs` says otherwise. */
43
+ const CANCEL_GRACE_MS = 2_000;
44
+ /**
45
+ * Codex harness backed by a long-lived `codex app-server` subprocess speaking
46
+ * JSON-RPC. Unlike the SDK harness this streams token-level deltas. A client +
47
+ * thread is created per logical session and reused for multi-turn; model/effort
48
+ * are passed per `turn/start`. Resume uses `thread/resume` with the native id.
49
+ */
50
+ export class CodexAppServerAgent extends SessionAgent {
51
+ agentOptions;
52
+ harness = "codex-app-server";
53
+ capabilities = CAPABILITIES;
54
+ /** Its CLIs start here: the runtime's, or this OS process's own when it was made without one. */
55
+ processes;
56
+ timing;
57
+ sessions;
58
+ login = new CodexCliLogin({
59
+ connect: (env) => this.connect({ cwd: process.cwd(), ...(env && { env }) }, { experimentalApi: false }),
60
+ cliPath: async () => (await this.cliPath()) ?? "codex",
61
+ });
62
+ /**
63
+ * The user's own login (`userLogin`), read from an app-server with the
64
+ * engine's own environment: never a session's `CODEX_HOME`.
65
+ */
66
+ readUserLogin = userLoginReader(() => this.connect({ cwd: process.cwd() }, { experimentalApi: false }));
67
+ constructor(agentOptions = {}) {
68
+ super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
69
+ this.agentOptions = agentOptions;
70
+ this.processes = agentOptions.processes ?? sharedNativeProcesses();
71
+ this.timing = {
72
+ confirmMs: this.cancelConfirmMs,
73
+ graceMs: agentOptions.cancelGraceMs ?? CANCEL_GRACE_MS,
74
+ retryStallMs: agentOptions.retryStallTimeoutMs ?? RETRY_STALL_TIMEOUT_MS,
75
+ };
76
+ this.sessions = new CodexSessions(
77
+ // Plan mode is a collaboration mode, which Codex 0.160 takes only from a
78
+ // client that opted into its experimental API (as host-managed ChatGPT
79
+ // auth and turn-scoped subagents need anyway); a session can enter plan
80
+ // mode on any later turn.
81
+ (options, auth, signal) => this.connect(options, {
82
+ auth,
83
+ experimentalApi: true,
84
+ signal,
85
+ sessionId: options.sessionId,
86
+ }), agentOptions.idleTimeoutMs ?? IDLE_TIMEOUT_MS, {
87
+ inheritConfig: agentOptions.inheritConfig,
88
+ builtInTools: agentOptions.builtInTools,
89
+ });
90
+ }
91
+ /** On a product's credentials, each session may list as a different account. */
92
+ get modelsPerSession() {
93
+ return Boolean(this.agentOptions.credentials);
94
+ }
95
+ async *executeTurn(input, options, controller) {
96
+ const { signal } = controller;
97
+ const scope = {
98
+ onPermissionRequest: options.onPermissionRequest,
99
+ onElicitationRequest: options.onElicitationRequest,
100
+ signal,
101
+ items: new TurnItems(),
102
+ mode: options.permissionMode ?? "default",
103
+ };
104
+ let session;
105
+ let stop;
106
+ let turn;
107
+ // @ref LLP 0001#d21--a-codex-turn-that-names-no-home-carries-its-mcp-servers-in-its-thread — a thread is the session's once Codex takes a turn on it
108
+ // The thread the turn asked for is the session's already. One this turn
109
+ // started is not yet: Codex writes a thread at its first turn, so until
110
+ // then nothing of it can be resumed, and a turn that fails before
111
+ // leaves the session without a conversation, not with one no later
112
+ // process could resume.
113
+ let named = false;
114
+ const nameStarted = () => {
115
+ if (named || !session || !turn?.taken)
116
+ return;
117
+ named = true;
118
+ options.onNativeSession?.(session.threadId, { resumed: false });
119
+ };
120
+ try {
121
+ signal.throwIfAborted();
122
+ // @ref LLP 0001#d5--messages-map-to-model-messages-no-silent-surface — no silent surface
123
+ // A turn Codex cannot run as asked fails before any process starts:
124
+ // its tools are not to be turned off, and an attachment it cannot take
125
+ // would go unread.
126
+ if (options.disableTools)
127
+ throw new Error(CODEX_TOOLS_REQUIRED);
128
+ const userInput = toUserInput(input);
129
+ const predecessor = this.sessions.stopUnsettled(options.sessionId);
130
+ if (predecessor && !(await predecessor))
131
+ throw new Error("Previous Codex execution has not stopped");
132
+ const mcp = this.sessions.mcpFor(options);
133
+ scope.auth = await authFor({
134
+ credentials: this.agentOptions.credentials,
135
+ sessionId: options.sessionId,
136
+ turnId: options.turnId,
137
+ apiKey: options.apiKey,
138
+ userLogin: this.userLoginFor(options.env),
139
+ signal,
140
+ });
141
+ signal.throwIfAborted();
142
+ session = await this.sessions.acquire(options, scope, mcp);
143
+ named = session.threadId === options.resumeSessionId;
144
+ if (named)
145
+ options.onNativeSession?.(session.threadId, { resumed: true });
146
+ const commands = new TurnCommands(session.client, session.threadId, this.timing.graceMs);
147
+ const turnStop = this.stopFor(session, scope, commands, options.sessionId);
148
+ stop = turnStop;
149
+ // Codex's turn, once there is one; before, its process, or a managed
150
+ // turn's cleanup.
151
+ this.cancelWith(options, () => turn?.cancel() ?? turnStop.cancel());
152
+ signal.throwIfAborted();
153
+ const offPreparing = onAbort(signal, () => void turnStop.cancel());
154
+ try {
155
+ await session.mcp.prepare(session.threadId, mcp, options.onWarning);
156
+ signal.throwIfAborted();
157
+ }
158
+ finally {
159
+ offPreparing();
160
+ }
161
+ const steering = {
162
+ open: (deliver) => void this.openSteering(options, deliver),
163
+ hold: () => this.holdSteering(options),
164
+ };
165
+ turn = new CodexTurn(session, scope, options, commands, turnStop, steering, this.timing);
166
+ for await (const event of turn.run(userInput)) {
167
+ nameStarted();
168
+ yield event;
169
+ }
170
+ }
171
+ catch (error) {
172
+ // A turn Codex took is on the thread, whatever came of it. A session
173
+ // released meanwhile refuses the name; the turn ends as it was ending.
174
+ try {
175
+ nameStarted();
176
+ }
177
+ catch { }
178
+ if (!signal.aborted)
179
+ throw error;
180
+ if (turn)
181
+ yield* turn.endCancelled();
182
+ throw new Error("turn aborted");
183
+ }
184
+ finally {
185
+ await stop?.dispose();
186
+ turn?.dispose();
187
+ if (session)
188
+ this.sessions.leave(options.sessionId, session, scope);
189
+ }
190
+ }
191
+ /**
192
+ * The user's own login, for a turn (or a model list) whose `env` names a
193
+ * home, when the operator set `userLogin`: read again for each, so a login
194
+ * the user changed is the next turn's. None otherwise: a turn that names
195
+ * no home runs on its home's own login.
196
+ */
197
+ userLoginFor(env) {
198
+ if (!this.agentOptions.userLogin || !env?.CODEX_HOME)
199
+ return undefined;
200
+ return (signal) => userAuth(this.readUserLogin, signal);
201
+ }
202
+ /** How the turn stops: by Codex's interrupt, or, managed, with its native cleanup. */
203
+ stopFor(session, scope, commands, sessionId) {
204
+ const { client, threadId } = session;
205
+ const { graceMs } = this.timing;
206
+ if (session.subagentMode !== "turn")
207
+ return new InterruptStop(session, commands, scope.signal, graceMs);
208
+ scope.subagents = new CodexTurnSubagents(client, threadId);
209
+ return new ManagedStop(scope.subagents, client, threadId, commands, scope.signal, graceMs, () => this.sessions.quarantine(sessionId, client));
210
+ }
211
+ checkSteerInput(input) {
212
+ toUserInput(input);
213
+ }
214
+ /**
215
+ * The models Codex offers this login. Reuses the session's process when
216
+ * `sessionId` has one started with the same `env` (its `CODEX_HOME` decides
217
+ * the login and config); otherwise starts `codex app-server` just to ask,
218
+ * with the account the product's `credentials` hold for that session.
219
+ */
220
+ async listModels(options) {
221
+ const live = options.sessionId ? this.sessions.get(options.sessionId) : undefined;
222
+ if (live && !live.client.closed && live.envFingerprint === configFingerprint(options.env)) {
223
+ const listing = await readCodexListing(live.client, options.cwd);
224
+ return codexModelDescriptors(listing.models, this.harness, listing.configuredModel);
225
+ }
226
+ // The account a turn with these options would log in as.
227
+ const auth = await authFor({
228
+ credentials: this.agentOptions.credentials,
229
+ sessionId: options.sessionId,
230
+ apiKey: options.apiKey,
231
+ userLogin: this.userLoginFor(options.env),
232
+ ...(options.signal && { signal: options.signal }),
233
+ });
234
+ options.signal?.throwIfAborted();
235
+ const client = await this.connect(options, {
236
+ auth,
237
+ experimentalApi: auth?.type === "chatgptAuthTokens",
238
+ });
239
+ const listing = await listCodexModels(client, options.cwd, {
240
+ signal: options.signal,
241
+ ...(auth && { login: (connection) => logIn(connection, auth) }),
242
+ });
243
+ return codexModelDescriptors(listing.models, this.harness, listing.configuredModel);
244
+ }
245
+ /** With no turn running, a managed session's process not yet confirmed stopped. */
246
+ stopWithoutTurn(sessionId) {
247
+ return this.sessions.stopUnsettled(sessionId);
248
+ }
249
+ /** Unchanged MCP config reloads retain dead remote connections after VM resume. */
250
+ invalidateMcpConnections() {
251
+ this.sessions.invalidate();
252
+ }
253
+ loginChanged(store) {
254
+ this.sessions.loginChanged(store);
255
+ }
256
+ async release(sessionId) {
257
+ // A host may release this harness before switching providers. Do not let
258
+ // that path discard ownership while managed child cleanup is unconfirmed.
259
+ if (this.sessions.managed(sessionId) && !(await this.cancel(sessionId)).confirmed)
260
+ throw new Error("Codex native cleanup was not confirmed; cannot release the session");
261
+ await super.release(sessionId);
262
+ // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — released once its process has exited, as a Claude session is
263
+ await this.sessions.release(sessionId);
264
+ }
265
+ async terminateAll() {
266
+ await super.terminateAll();
267
+ await this.sessions.terminateAll();
268
+ }
269
+ /**
270
+ * The CLI to run: the provisioner's, else `$CODEX_CLI_PATH`; PATH's `codex`
271
+ * when neither. A turn waits for it until the turn is cancelled.
272
+ */
273
+ async cliPath(signal) {
274
+ // @ref LLP 0010#a-turn-waits-for-its-cli-until-it-is-cancelled — the install is the server's
275
+ const { resolveCliPath } = this.agentOptions;
276
+ const resolved = resolveCliPath && (await untilAborted(resolveCliPath(), signal));
277
+ return resolved ?? process.env.CODEX_CLI_PATH;
278
+ }
279
+ /**
280
+ * A connection to a new `codex app-server` for a folder, its `env` and a
281
+ * login; recorded for `sessionId`, which a model listing has none of.
282
+ */
283
+ async connect(options, spawn) {
284
+ const { auth, experimentalApi, signal, sessionId } = spawn;
285
+ const codexPath = (await this.cliPath(signal)) ?? "codex";
286
+ signal?.throwIfAborted();
287
+ const clientOptions = {
288
+ ...clientOptionsFor(codexPath, options, auth, experimentalApi, this.agentOptions.inheritConfig),
289
+ processes: this.processes,
290
+ ...(sessionId !== undefined && { sessionId }),
291
+ };
292
+ return (this.agentOptions.createClient?.(clientOptions) ?? new CodexAppServerClient(clientOptions));
293
+ }
294
+ }