@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,307 @@
1
+ import { isRecord } from "../../utils/is-record.js";
2
+ import { hunkDiff } from "../diffs.js";
3
+ /** Codex tools are already normalized names; kinds are fixed per item type. */
4
+ export const CODEX_TOOL_KINDS = {
5
+ shell: "execute",
6
+ apply_patch: "edit",
7
+ web_search: "fetch",
8
+ mcp: "other",
9
+ image_generation: "other",
10
+ /** The plan Codex proposes in Plan mode, put to the user like Claude's ExitPlanMode. */
11
+ plan: "switch_mode",
12
+ };
13
+ function pickCodexError(err) {
14
+ if (!err)
15
+ return "";
16
+ return typeof err === "string" ? err : (err.message ?? "");
17
+ }
18
+ /** Base64 a block carries (an image's or audio's `data`, an embedded resource's `blob`). */
19
+ function carriesBytes(block) {
20
+ const resource = isRecord(block.resource) ? block.resource : {};
21
+ return typeof block.data === "string" || typeof resource.blob === "string";
22
+ }
23
+ /** A block's MIME type, its own or its embedded resource's. */
24
+ function blockMimeType(block) {
25
+ const resource = isRecord(block.resource) ? block.resource : {};
26
+ const mimeType = block.mimeType ?? resource.mimeType;
27
+ return typeof mimeType === "string" ? mimeType : undefined;
28
+ }
29
+ /**
30
+ * One MCP content block, as the stream shows it: what `output` says of it,
31
+ * and its `content` entry. Text is text and an image an image; another
32
+ * block is the text `output` has for it. No block's bytes are ever text: a
33
+ * placeholder naming its type (and MIME type) stands for them.
34
+ */
35
+ function mcpBlock(block) {
36
+ if (isRecord(block) && block.type === "text" && typeof block.text === "string")
37
+ return { shown: block.text, entry: { type: "text", text: block.text } };
38
+ let shown = JSON.stringify(block);
39
+ if (isRecord(block) && carriesBytes(block)) {
40
+ const mimeType = blockMimeType(block);
41
+ shown = `[${String(block.type ?? "binary")}${mimeType ? ` ${mimeType}` : ""}]`;
42
+ if (block.type === "image" && typeof block.data === "string" && mimeType)
43
+ return { shown, entry: { type: "image", data: block.data, mimeType } };
44
+ }
45
+ return { shown, entry: { type: "text", text: shown } };
46
+ }
47
+ // @ref LLP 0002#tool-output-has-three-audiences — `content` is display-grade, `output` model-facing
48
+ /**
49
+ * An MCP tool's result: its blocks as `output` shows them, joined. A result
50
+ * with an image also has `content`, every block in order, as Claude's tool
51
+ * results do; one without has nothing `output` does not say.
52
+ */
53
+ function mcpResult(result) {
54
+ const blocks = isRecord(result) && "content" in result ? result.content : result;
55
+ if (blocks == null)
56
+ return { output: "" };
57
+ if (typeof blocks === "string")
58
+ return { output: blocks };
59
+ if (!Array.isArray(blocks))
60
+ return { output: JSON.stringify(blocks) };
61
+ const read = blocks.map(mcpBlock);
62
+ const output = read.map(({ shown }) => shown).join("");
63
+ if (!read.some(({ entry }) => entry.type === "image"))
64
+ return { output };
65
+ return { output, content: read.map(({ entry }) => entry) };
66
+ }
67
+ const failed = (item) => item.status === "failed";
68
+ /**
69
+ * Why a declined command or change failed: Codex 0.160 completes it as
70
+ * `declined` when its approval was refused, by the user or for them.
71
+ */
72
+ const CODEX_COMMAND_DECLINED = "Declined: the command was not approved, so it did not run.";
73
+ const CODEX_CHANGE_DECLINED = "Declined: the change was not approved, so no file was changed.";
74
+ /** One file change as text: `update path`, `move from -> to`. */
75
+ function describeChange(change) {
76
+ const kind = typeof change.kind === "string" ? change.kind : change.kind?.type;
77
+ const to = typeof change.kind === "object" ? change.kind?.move_path : undefined;
78
+ return `${kind ?? "change"} ${change.path}${to ? ` -> ${to}` : ""}`;
79
+ }
80
+ /** A shell Codex runs a command in, `-lc` and its one argument, the line. */
81
+ const SHELL_WRAPPER = /^(?:\S*\/)?(?:ba|z)?sh -lc (.+)$/s;
82
+ /** Characters a word may hold unquoted and mean only themselves. */
83
+ const PLAIN = /[A-Za-z0-9_@%+=:,./-]/;
84
+ /**
85
+ * The one shell word `text` is, unquoted as the shell would; undefined when
86
+ * it is several words, unterminated, or would expand (an unquoted special
87
+ * character, a `$` or a backquote inside double quotes).
88
+ */
89
+ function shellWord(text) {
90
+ let word = "";
91
+ let i = 0;
92
+ while (i < text.length) {
93
+ const c = text[i];
94
+ if (c === "'") {
95
+ const end = text.indexOf("'", i + 1);
96
+ if (end < 0)
97
+ return undefined;
98
+ word += text.slice(i + 1, end);
99
+ i = end + 1;
100
+ }
101
+ else if (c === '"') {
102
+ i++;
103
+ for (;;) {
104
+ const d = text[i];
105
+ if (d === undefined || d === "$" || d === "`")
106
+ return undefined;
107
+ if (d === '"')
108
+ break;
109
+ if (d === "\\" && '"\\$`'.includes(text[i + 1] ?? "")) {
110
+ word += text[i + 1];
111
+ i += 2;
112
+ }
113
+ else {
114
+ word += d;
115
+ i++;
116
+ }
117
+ }
118
+ i++;
119
+ }
120
+ else if (PLAIN.test(c)) {
121
+ word += c;
122
+ i++;
123
+ }
124
+ else
125
+ return undefined;
126
+ }
127
+ return word;
128
+ }
129
+ // @ref LLP 0002#a-tool-call-says-what-it-acts-on — the line, apart from the shell Codex adds
130
+ /**
131
+ * The line a Codex command runs: Codex wraps it in a shell
132
+ * (`/bin/zsh -lc '<line>'`, quoted as Codex quotes it), and the line is that
133
+ * shell's one argument, unquoted. Codex's `commandActions` are not it: they
134
+ * keep only the pieces Codex recognizes (`cd sub && cat c.txt` is one read of
135
+ * `cat c.txt`) and normalize their quoting. A command of any other shape is
136
+ * as Codex reports it; one that is not a string, nothing.
137
+ */
138
+ export function codexCommandLine(command) {
139
+ if (typeof command !== "string" || !command)
140
+ return undefined;
141
+ const quoted = SHELL_WRAPPER.exec(command)?.[1];
142
+ return (quoted !== undefined && shellWord(quoted)) || command;
143
+ }
144
+ /** A change's kind (`add`, `delete`, `update`), and where an update moves the file. */
145
+ function changeKind(change) {
146
+ if (typeof change.kind === "string")
147
+ return { kind: change.kind };
148
+ return { kind: change.kind?.type, movedTo: change.kind?.move_path ?? undefined };
149
+ }
150
+ /**
151
+ * An update's unified diff as hunks: each `@@` header's start line in the
152
+ * new file, and the lines under it. A move's diff ends with Codex's own
153
+ * `Moved to:` trailer, which is no line of the file.
154
+ */
155
+ function updateHunks(diff, movedTo) {
156
+ const trailer = movedTo !== undefined ? `\n\nMoved to: ${movedTo}` : undefined;
157
+ const body = trailer && diff.endsWith(trailer) ? diff.slice(0, -trailer.length) : diff;
158
+ const hunks = [];
159
+ for (const line of body.replace(/\n$/, "").split("\n")) {
160
+ if (line.startsWith("@@")) {
161
+ const start = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(line)?.[1];
162
+ hunks.push({ ...(start !== undefined && { line: Number(start) }), lines: [] });
163
+ }
164
+ else
165
+ hunks.at(-1)?.lines.push(line);
166
+ }
167
+ return hunks;
168
+ }
169
+ /**
170
+ * What a file change shows: a `diff` entry per hunk of an update, at the
171
+ * file it leaves (a move's destination); an add's content as `newText`; a
172
+ * delete's as `oldText`, its `newText` empty. Its locations are each hunk's
173
+ * start in the new file, a move's source too, and an add's or a delete's
174
+ * path alone.
175
+ */
176
+ export function codexChangeView(changes) {
177
+ const content = [];
178
+ const locations = [];
179
+ for (const change of changes ?? []) {
180
+ const { kind, movedTo } = changeKind(change);
181
+ const diff = change.diff ?? "";
182
+ if (kind === "add" || kind === "delete") {
183
+ locations.push({ path: change.path });
184
+ if (change.diff !== undefined)
185
+ content.push(kind === "add"
186
+ ? { type: "diff", path: change.path, newText: diff }
187
+ : { type: "diff", path: change.path, oldText: diff, newText: "" });
188
+ continue;
189
+ }
190
+ const path = movedTo ?? change.path;
191
+ if (movedTo)
192
+ locations.push({ path: change.path });
193
+ const hunks = updateHunks(diff, movedTo);
194
+ if (!hunks.length)
195
+ locations.push({ path });
196
+ for (const hunk of hunks) {
197
+ locations.push({ path, ...(hunk.line !== undefined && { line: hunk.line }) });
198
+ const entry = hunkDiff(path, hunk.lines);
199
+ if (entry)
200
+ content.push(entry);
201
+ }
202
+ }
203
+ return { content, locations };
204
+ }
205
+ const CODEX_TOOL_ITEMS = {
206
+ collabAgentToolCall: {
207
+ toolName: (item) => item.tool ?? "collabAgentToolCall",
208
+ input: (item) => ({
209
+ ...(item.prompt != null && { prompt: item.prompt }),
210
+ ...(item.model != null && { model: item.model }),
211
+ receiverThreadIds: item.receiverThreadIds ?? [],
212
+ }),
213
+ meta: (item) => ({
214
+ kind: "task",
215
+ ...(item.tool === "spawnAgent" && {
216
+ subagent: {
217
+ ...(item.model && { model: item.model }),
218
+ ...(item.receiverThreadIds?.[0] && { agentId: item.receiverThreadIds[0] }),
219
+ },
220
+ }),
221
+ }),
222
+ result: (item) => ({
223
+ output: JSON.stringify(item.agentsStates ?? {}),
224
+ isError: failed(item) || item.status === "interrupted",
225
+ }),
226
+ },
227
+ commandExecution: {
228
+ toolName: () => "shell",
229
+ input: (item) => ({ command: item.command ?? "" }),
230
+ meta: (item) => {
231
+ const command = codexCommandLine(item.command);
232
+ return { kind: CODEX_TOOL_KINDS.shell, ...(command && { command }) };
233
+ },
234
+ result: (item) => item.status === "declined"
235
+ ? { output: CODEX_COMMAND_DECLINED, isError: true }
236
+ : {
237
+ output: item.aggregatedOutput ?? "",
238
+ isError: failed(item) || (item.exitCode ?? 0) !== 0,
239
+ ...(typeof item.exitCode === "number" && { metadata: { exitCode: item.exitCode } }),
240
+ },
241
+ },
242
+ fileChange: {
243
+ toolName: () => "apply_patch",
244
+ input: (item) => ({ changes: item.changes ?? [] }),
245
+ meta: (item) => ({
246
+ kind: CODEX_TOOL_KINDS.apply_patch,
247
+ locations: codexChangeView(item.changes).locations,
248
+ }),
249
+ // A failed or declined change shows no diff: `completeToolPart` keeps none.
250
+ result: (item) => item.status === "declined"
251
+ ? { output: CODEX_CHANGE_DECLINED, isError: true }
252
+ : {
253
+ output: (item.changes ?? []).map(describeChange).join("\n"),
254
+ isError: failed(item),
255
+ content: codexChangeView(item.changes).content,
256
+ },
257
+ },
258
+ mcpToolCall: {
259
+ toolName: (item) => `${item.server ?? "mcp"}.${item.tool ?? "tool"}`,
260
+ input: (item) => ({ arguments: item.arguments }),
261
+ meta: (item) => ({
262
+ kind: CODEX_TOOL_KINDS.mcp,
263
+ // Codex names both on the item: never read out of `toolName`.
264
+ ...(item.server !== undefined &&
265
+ item.tool !== undefined && { mcp: { server: item.server, tool: item.tool } }),
266
+ }),
267
+ result: (item) => {
268
+ const err = pickCodexError(item.error);
269
+ if (err)
270
+ return { output: err, isError: true };
271
+ return { ...mcpResult(item.result), isError: failed(item) };
272
+ },
273
+ },
274
+ // @ref LLP 0017#codexs-own-pictures-and-an-mcp-tools-picture — a picture Codex makes itself, without its bytes
275
+ imageGeneration: {
276
+ toolName: () => "image_generation",
277
+ // The prompt Codex wrote, when it gives one, comes with the picture.
278
+ input: (item) => (item.revisedPrompt ? { prompt: item.revisedPrompt } : {}),
279
+ inputAtCompletion: true,
280
+ meta: () => ({ kind: CODEX_TOOL_KINDS.image_generation }),
281
+ // Megabytes of base64 stay out of the stream, the journal and every
282
+ // checkpoint: the picture is the file Codex saved.
283
+ result: (item) => item.failure || failed(item)
284
+ ? {
285
+ output: `Image generation failed${item.failure?.type ? `: ${item.failure.type}` : ""}`,
286
+ isError: true,
287
+ }
288
+ : {
289
+ output: "Generated an image.",
290
+ ...(item.savedPath && { metadata: { savedPath: item.savedPath } }),
291
+ isError: false,
292
+ },
293
+ },
294
+ webSearch: {
295
+ toolName: () => "web_search",
296
+ input: (item) => ({ query: item.query ?? "" }),
297
+ meta: () => ({ kind: CODEX_TOOL_KINDS.web_search }),
298
+ result: (item) => ({ output: item.query ?? "", isError: failed(item) }),
299
+ },
300
+ };
301
+ /**
302
+ * The descriptor of an item type that is a tool. Its own keys only: an item
303
+ * typed `constructor` is no tool, whatever the object's prototype holds.
304
+ */
305
+ export function codexToolDescriptor(itemType) {
306
+ return Object.hasOwn(CODEX_TOOL_ITEMS, itemType) ? CODEX_TOOL_ITEMS[itemType] : undefined;
307
+ }
@@ -0,0 +1,183 @@
1
+ import { statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { onAbort } from "../../utils/deadline.js";
4
+ import { InvalidRequestError } from "../../utils/errors.js";
5
+ import { isRecord } from "../../utils/is-record.js";
6
+ import { loginMethod, terminalMethod, } from "../login.js";
7
+ import { codexHome } from "./homes.js";
8
+ /** The logins Codex's app-server runs itself, each with its `account/login/start` type. */
9
+ const LOGINS = [
10
+ { id: "chatgpt", kind: "browser", label: "ChatGPT", credential: "subscription", type: "chatgpt" },
11
+ {
12
+ id: "chatgpt_device_code",
13
+ kind: "device_code",
14
+ label: "ChatGPT, with a device code",
15
+ credential: "subscription",
16
+ type: "chatgptDeviceCode",
17
+ },
18
+ {
19
+ id: "api_key",
20
+ kind: "api_key",
21
+ label: "OpenAI API key",
22
+ credential: "api_key",
23
+ type: "apiKey",
24
+ },
25
+ ];
26
+ /** A login as Codex's app-server says it (`account/read`). */
27
+ export function codexLoginStatus(read) {
28
+ const account = read.account;
29
+ if (!account) {
30
+ // A model provider that needs no OpenAI login runs without one.
31
+ return { state: read.requiresOpenaiAuth === false ? "signed_in" : "signed_out" };
32
+ }
33
+ switch (account.type) {
34
+ case "chatgpt":
35
+ return {
36
+ state: "signed_in",
37
+ credential: "subscription",
38
+ source: "login",
39
+ provider: "openai",
40
+ ...(account.email && { email: account.email }),
41
+ ...(account.planType && account.planType !== "unknown" && { plan: account.planType }),
42
+ };
43
+ case "apiKey":
44
+ return {
45
+ state: "signed_in",
46
+ credential: "api_key",
47
+ source: "login",
48
+ provider: "openai",
49
+ };
50
+ case "amazonBedrock":
51
+ return { state: "signed_in", credential: "cloud", provider: "bedrock" };
52
+ default:
53
+ return { state: "signed_in" };
54
+ }
55
+ }
56
+ /** The variable that picks Codex's login store, its home. */
57
+ const STORE_VARIABLE = "CODEX_HOME";
58
+ /** The login store a turn or a login with this `env` uses: its `CODEX_HOME`, empty when unset. */
59
+ export function codexLoginStore(env) {
60
+ return env?.[STORE_VARIABLE] ?? "";
61
+ }
62
+ // @ref LLP 0011#a-login-change-starts-the-next-turn-on-a-new-cli — the engine reads no login: it sees the file change
63
+ /**
64
+ * What the login file of the store a turn with this `env` runs on looks
65
+ * like (`<CODEX_HOME>/auth.json`, the turn's, else the process's, else
66
+ * `~/.codex`'s; Codex's default `file` store): its device, inode, size and
67
+ * modified and changed times at full precision, or `absent`. Codex writes
68
+ * the file in place on any login change, a token renewal and a rewrite of
69
+ * the same key, and removes it at a sign-out, so a running app-server, which
70
+ * keeps the login it started with, is stale once this differs. A link is
71
+ * followed to its target (a product may link the person's own `auth.json`
72
+ * into a session's home). The file is never opened.
73
+ */
74
+ export function codexLoginMark(env) {
75
+ try {
76
+ const file = statSync(join(codexHome(env), "auth.json"), {
77
+ bigint: true,
78
+ throwIfNoEntry: false,
79
+ });
80
+ if (!file)
81
+ return "absent";
82
+ return `${file.dev}:${file.ino}:${file.size}:${file.mtimeNs}:${file.ctimeNs}`;
83
+ }
84
+ catch (error) {
85
+ // A folder it may not enter, or under Bun a file on the way (ENOTDIR;
86
+ // Node's stat reads that as absent).
87
+ return `unreadable:${error.code ?? "unknown"}`;
88
+ }
89
+ }
90
+ /** Codex's login, through its app-server: `account/read`, `account/login/start`, `account/logout`. */
91
+ export class CodexCliLogin {
92
+ options;
93
+ constructor(options) {
94
+ this.options = options;
95
+ }
96
+ store(env) {
97
+ return codexLoginStore(env);
98
+ }
99
+ /** Initialize a new app-server, run `use` on it, and end it. */
100
+ async with(options, use) {
101
+ const client = await this.options.connect(options.env);
102
+ const offAbort = onAbort(options.signal, () => client.close());
103
+ try {
104
+ options.signal?.throwIfAborted();
105
+ await client.initialize();
106
+ return await use(client);
107
+ }
108
+ finally {
109
+ offAbort();
110
+ client.close();
111
+ }
112
+ }
113
+ async methods(options) {
114
+ return [
115
+ ...LOGINS.map(({ type: _type, ...method }) => method),
116
+ terminalMethod([await this.options.cliPath(), "login"], { ...process.env, ...options.env }, STORE_VARIABLE),
117
+ ];
118
+ }
119
+ async status(options) {
120
+ const read = await this.with(options, (client) => client.request("account/read", { refreshToken: false }));
121
+ return isRecord(read)
122
+ ? codexLoginStatus(read)
123
+ : { state: "unknown", error: "codex answered no account" };
124
+ }
125
+ async start(id, options) {
126
+ const method = loginMethod(LOGINS, id);
127
+ if (method.kind === "api_key" && !options.apiKey)
128
+ throw new InvalidRequestError([
129
+ { path: "apiKey", message: "an API key login needs the key" },
130
+ ]);
131
+ const client = await this.options.connect(options.env);
132
+ // A start the engine gave up on stops its app-server.
133
+ const offAbort = onAbort(options.signal, () => client.close());
134
+ try {
135
+ await client.initialize();
136
+ // This app-server runs this one login, so its end is this login's;
137
+ // waited for from before the request, which its end may follow at once.
138
+ const ended = new Promise((resolve, reject) => {
139
+ client.onNotification(({ method: name, params }) => {
140
+ if (name !== "account/login/completed" || !isRecord(params))
141
+ return;
142
+ if (params.success === true)
143
+ resolve();
144
+ else
145
+ reject(new Error(String(params.error ?? "Codex did not log in.")));
146
+ });
147
+ client.onClose((error) => reject(error ?? new Error("codex app-server closed before the login ended")));
148
+ });
149
+ ended.catch(() => { });
150
+ const started = await client.request("account/login/start", method.kind === "api_key"
151
+ ? { type: method.type, apiKey: options.apiKey }
152
+ : { type: method.type });
153
+ const answer = isRecord(started) ? started : {};
154
+ // A key is stored by the time its login answers.
155
+ if (method.kind === "api_key") {
156
+ client.close();
157
+ return { done: Promise.resolve(), cancel: () => { } };
158
+ }
159
+ const url = answer.authUrl ?? answer.verificationUrl;
160
+ if (typeof url !== "string")
161
+ throw new Error("Codex answered no sign-in address.");
162
+ const done = ended.finally(() => client.close());
163
+ // A caller that only cancels has nothing to hear.
164
+ done.catch(() => { });
165
+ return {
166
+ url,
167
+ ...(typeof answer.userCode === "string" && { userCode: answer.userCode }),
168
+ done,
169
+ cancel: () => client.close(),
170
+ };
171
+ }
172
+ catch (error) {
173
+ client.close();
174
+ throw error;
175
+ }
176
+ finally {
177
+ offAbort();
178
+ }
179
+ }
180
+ async logout(options) {
181
+ await this.with(options, (client) => client.request("account/logout", undefined));
182
+ }
183
+ }