@zvada/agent-server 0.3.23 → 0.3.25

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 (280) hide show
  1. package/CHANGELOG.md +64 -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 +745 -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 +331 -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 +92 -0
  91. package/dist/core/processes/lifeline.js +218 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +164 -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 +29 -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 +437 -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 +339 -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 +142 -0
  141. package/dist/protocol/errors.js +190 -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 +292 -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/client/client.d.ts +6 -1
  207. package/dist/types/client/client.d.ts.map +1 -1
  208. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  210. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/options.d.ts +28 -11
  212. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  213. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  214. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  216. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  218. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  219. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  220. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  221. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  222. package/dist/types/core/agents/process-pool.d.ts +8 -0
  223. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  224. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  225. package/dist/types/core/agents/scripted/steps.d.ts +1 -1
  226. package/dist/types/core/presets.d.ts +2 -2
  227. package/dist/types/core/presets.d.ts.map +1 -1
  228. package/dist/types/core/processes/identity.d.ts.map +1 -1
  229. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  230. package/dist/types/core/processes/process-table.d.ts.map +1 -1
  231. package/dist/types/core/provision/extract.d.ts.map +1 -1
  232. package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
  233. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  234. package/dist/types/core/runtime/turn.d.ts +12 -7
  235. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  236. package/dist/types/protocol/clis.d.ts +3 -3
  237. package/dist/types/protocol/conversation.d.ts +6 -6
  238. package/dist/types/protocol/credentials.d.ts +13 -1
  239. package/dist/types/protocol/credentials.d.ts.map +1 -1
  240. package/dist/types/protocol/errors.d.ts +6 -4
  241. package/dist/types/protocol/errors.d.ts.map +1 -1
  242. package/dist/types/protocol/lifecycle.d.ts +4 -4
  243. package/dist/types/protocol/wire-api.d.ts +12 -12
  244. package/dist/types/protocol/wire.d.ts +8 -8
  245. package/dist/types/server/bin.d.ts +3 -0
  246. package/dist/types/server/bin.d.ts.map +1 -0
  247. package/dist/types/server/routes.d.ts.map +1 -1
  248. package/dist/types/server/transports.d.ts +2 -1
  249. package/dist/types/server/transports.d.ts.map +1 -1
  250. package/dist/types/sync/node-sqlite.d.ts +4 -1
  251. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  252. package/docs/consuming.md +56 -7
  253. package/docs/deploy.md +35 -0
  254. package/docs/harnesses.md +30 -5
  255. package/package.json +43 -18
  256. package/src/client/client.ts +114 -44
  257. package/src/core/agents/claude-code/approvals.ts +5 -1
  258. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  259. package/src/core/agents/claude-code/options.ts +28 -11
  260. package/src/core/agents/claude-code/session.ts +13 -0
  261. package/src/core/agents/codex-app-server/homes.ts +11 -2
  262. package/src/core/agents/codex-app-server/login.ts +30 -0
  263. package/src/core/agents/codex-app-server/requests.ts +7 -6
  264. package/src/core/agents/codex-app-server/session.ts +11 -2
  265. package/src/core/agents/process-pool.ts +30 -4
  266. package/src/core/agents/scripted/scripted-agent.ts +2 -1
  267. package/src/core/agents/scripted/steps.ts +1 -1
  268. package/src/core/presets.ts +3 -2
  269. package/src/core/processes/identity.ts +1 -0
  270. package/src/core/processes/lifeline.ts +10 -1
  271. package/src/core/processes/process-table.ts +1 -0
  272. package/src/core/provision/extract.ts +1 -0
  273. package/src/core/runtime/agent-runtime.ts +6 -3
  274. package/src/core/runtime/turn.ts +21 -9
  275. package/src/protocol/credentials.ts +19 -5
  276. package/src/protocol/errors.ts +12 -3
  277. package/src/server/bin.ts +25 -10
  278. package/src/server/routes.ts +3 -2
  279. package/src/server/transports.ts +6 -1
  280. package/src/sync/node-sqlite.ts +19 -3
@@ -145,7 +145,8 @@ async function answerConsent(session: CodexSession, params: Record<string, unkno
145
145
  */
146
146
  function mcpConsentToolCall(params: Record<string, unknown>, items: TurnItems): PermissionToolCall {
147
147
  const meta = isRecord(params._meta) ? params._meta : {};
148
- const server = typeof params.serverName === "string" ? params.serverName : "mcp";
148
+ const serverName = typeof params.serverName === "string" ? params.serverName : undefined;
149
+ const server = serverName ?? "mcp";
149
150
  const message = typeof params.message === "string" ? params.message : undefined;
150
151
  const named = message?.match(/tool "([^"]+)"/)?.[1];
151
152
  const call = items.consentedCall(
@@ -154,17 +155,17 @@ function mcpConsentToolCall(params: Record<string, unknown>, items: TurnItems):
154
155
  named,
155
156
  JSON.stringify(meta.tool_params ?? {}),
156
157
  );
158
+ const tool = call?.tool ?? named;
157
159
  // The arguments are the tool's input, as a Claude MCP approval's are: a
158
160
  // client previews them there.
159
161
  const input = meta.tool_params ?? call?.arguments ?? {};
160
162
  return {
161
163
  toolCallId: call?.id ?? generateUUIDv7(),
162
- toolName: `${server}.${call?.tool ?? named ?? "tool"}`,
164
+ toolName: `${server}.${tool ?? "tool"}`,
163
165
  kind: CODEX_TOOL_KINDS.mcp,
164
- // Both as Codex names them: the consent's server, and the tool of the
165
- // call it was linked to. Its message's words are no name.
166
- ...(typeof params.serverName === "string" &&
167
- call?.tool !== undefined && { mcp: { server: params.serverName, tool: call.tool } }),
166
+ // As Codex names them: the consent's server, and its linked call's tool or
167
+ // else the one its message names (the same either way); neither, no `mcp`.
168
+ ...(serverName !== undefined && tool !== undefined && { mcp: { server: serverName, tool } }),
168
169
  ...(message && { title: message }),
169
170
  rawInput: isRecord(input) ? input : { arguments: input },
170
171
  };
@@ -5,7 +5,7 @@ import { ProcessPool } from "../process-pool.ts";
5
5
  import type { CodexConnection } from "./client.ts";
6
6
  import { type CodexAuth, authFingerprint, logIn } from "./credentials.ts";
7
7
  import { CodexHomes, holdHome, homeIdentity } from "./homes.ts";
8
- import { codexLoginStore } from "./login.ts";
8
+ import { codexLoginMark, codexLoginStore } from "./login.ts";
9
9
  import { CodexMcpState, type CodexTurnMcp, codexTurnMcp, threadServersFingerprint } from "./mcp.ts";
10
10
  import type { CodexModelThinking } from "./models.ts";
11
11
  import {
@@ -125,6 +125,12 @@ export class CodexSessions {
125
125
  {
126
126
  // An app-server reads its login from its home at its start.
127
127
  store: ({ options }) => codexLoginStore(options.env),
128
+ // A process on its store's own login keeps the one it read at its
129
+ // start, and no word of a change outside the engine reaches it: its
130
+ // store's file changing replaces it. One the engine hands a login to
131
+ // (a credential, the user's own login, the turn's key) does not run
132
+ // on the file, and is logged in again at each turn.
133
+ loginMark: ({ options, scope }) => (scope.auth ? undefined : codexLoginMark(options.env)),
128
134
  resumeOf: ({ options }) => options.resumeSessionId,
129
135
  conversationsOf: (session) => [session.threadId],
130
136
  fits: (session, { options, scope }) =>
@@ -156,7 +162,10 @@ export class CodexSessions {
156
162
  * new one, on the same thread. Codex caches an authenticated model WebSocket across turns, so
157
163
  * login alone cannot switch its identity: an account or key change
158
164
  * restarts the process and resumes the thread. Same-account token renewal
159
- * keeps it warm. So does an unchanged `mcp_servers` table, the servers
165
+ * of a login the engine hands it keeps it warm. One on its store's own
166
+ * login is replaced once the store's `auth.json` changed, whatever the
167
+ * change: the engine reads no login to tell a renewal from another
168
+ * account. An unchanged `mcp_servers` table keeps it warm, the servers
160
169
  * the thread carries. A thread's config is fixed once it is open, so
161
170
  * another table resumes the thread in a new process, which checks them
162
171
  * against Codex's configuration again before the thread opens: the user
@@ -69,6 +69,14 @@ export interface ProcessHarness<P extends PooledProcess, T> {
69
69
  * `env` value, say). Absent: one store, which every login change names.
70
70
  */
71
71
  store?(turn: T): string;
72
+ /**
73
+ * A mark of the store's login as it looks now (never the login), for a
74
+ * process that keeps the login it started with. Taken as a start begins and
75
+ * compared when a turn takes a process that fits it: a difference is
76
+ * `loginChanged`. Undefined: nothing to follow this turn. Absent: only a
77
+ * login change the engine is told of replaces a process (LLP 0016.000).
78
+ */
79
+ loginMark?(turn: T): string | undefined;
72
80
  /** The conversation the turn resumes, when it names one. */
73
81
  resumeOf(turn: T): string | undefined;
74
82
  /** The conversations a warm process is on: a turn that resumes another needs another process. */
@@ -122,10 +130,14 @@ interface Held<P> {
122
130
  idleTimer?: ReturnType<typeof setTimeout>;
123
131
  }
124
132
 
125
- /** What a process was started under: its store's login generation and the host resumes so far. */
133
+ /**
134
+ * What a process was started under: its store's login generation, its
135
+ * login's mark when the harness follows one, and the host resumes so far.
136
+ */
126
137
  interface Started {
127
138
  store: string;
128
139
  generation: number;
140
+ loginMark?: string;
129
141
  resumes: number;
130
142
  }
131
143
 
@@ -221,6 +233,13 @@ export class ProcessPool<P extends PooledProcess, T> {
221
233
  if (resume !== undefined && !harness.conversationsOf(process).includes(resume))
222
234
  return "otherConversation";
223
235
  if (!harness.fits(process, turn)) return "doesNotFit";
236
+ // @ref LLP 0011#a-login-change-starts-the-next-turn-on-a-new-cli — a login changed outside the engine, by its mark
237
+ // After `fits`: only a process that would take the turn is compared,
238
+ // and the mark it started under is of the store the turn runs on.
239
+ if (started?.loginMark !== undefined) {
240
+ const now = harness.loginMark?.(turn);
241
+ if (now !== undefined && now !== started.loginMark) return "loginChanged";
242
+ }
224
243
  if (harness.applyLiveChange && !(await harness.applyLiveChange(process, turn, signal)))
225
244
  return "cannotChange";
226
245
  return undefined;
@@ -328,10 +347,17 @@ export class ProcessPool<P extends PooledProcess, T> {
328
347
  replacing: P | undefined,
329
348
  ): Promise<P> {
330
349
  if (this.closed) throw new Error("the process pool is closed");
331
- // Taken as the start begins: a login change or a host resume while the
332
- // process initializes replaces it at its next turn.
350
+ // Taken as the start begins, before the process reads its login: a login
351
+ // change or a host resume while it initializes replaces it at its next
352
+ // turn.
333
353
  const store = this.harness.store?.(turn) ?? "";
334
- const started: Started = { store, generation: this.generation(store), resumes: this.resumes };
354
+ const loginMark = this.harness.loginMark?.(turn);
355
+ const started: Started = {
356
+ store,
357
+ generation: this.generation(store),
358
+ ...(loginMark !== undefined && { loginMark }),
359
+ resumes: this.resumes,
360
+ };
335
361
  const owned: P["client"][] = [];
336
362
  try {
337
363
  const process = await this.harness.spawn(
@@ -249,7 +249,8 @@ export class ScriptedAgent extends SessionAgent {
249
249
  turn: { input: AgentInput; options: AgentExecuteOptions; signal: AbortSignal; calls: number },
250
250
  ): AsyncGenerator<ScriptedEvent, Played> {
251
251
  const { options, signal } = turn;
252
- if (signal.aborted) throw stopped();
252
+ // A hang takes its `stopTakes` whenever the cancel came: a product's test cancels without a sleep.
253
+ if (signal.aborted && !("hang" in step)) throw stopped();
253
254
  if ("say" in step) yield { type: "text", text: step.say };
254
255
  else if ("stream" in step) {
255
256
  for (const [i, word] of words(step.stream).entries()) {
@@ -70,7 +70,7 @@ export const ScriptStepSchema = z.union([
70
70
  z.strictObject({ echo: z.enum(["input", "config"]) }),
71
71
  /** A pause of this many ms. */
72
72
  z.strictObject({ wait: Ms }),
73
- /** Runs until the turn is cancelled, then `stopTakes` ms more before it stops. */
73
+ /** Runs until the turn is cancelled, then `stopTakes` ms more before it stops, also when the cancel came first. */
74
74
  z.strictObject({ hang: z.literal(true), stopTakes: Ms.optional() }),
75
75
  /**
76
76
  * Ends the turn in an error with this message: of `category` when given,
@@ -83,8 +83,8 @@ export interface CreateRegistryOptions {
83
83
  cancelConfirmMs?: number;
84
84
  /**
85
85
  * How long after a cancel the engine ends an agent that has not stopped:
86
- * 2 s on Codex and 10 s on an ACP agent by default. Claude is not ended
87
- * for it (LLP 0016, decision 11).
86
+ * 2 s on Codex, 10 s on Claude and on an ACP agent by default; its turn
87
+ * then ends `cancelled`.
88
88
  */
89
89
  cancelGraceMs?: number;
90
90
  /** Codex embed-tier authentication and process options; CLI resolution stays provisioner-owned. */
@@ -142,6 +142,7 @@ const HARNESSES: Record<
142
142
  credentials: opts.credentials,
143
143
  idleTimeoutMs: opts.idleTimeoutMs,
144
144
  cancelConfirmMs: opts.cancelConfirmMs,
145
+ cancelGraceMs: opts.cancelGraceMs,
145
146
  inheritConfig: opts.inheritConfig,
146
147
  resolveCliPath: cliPath("claude"),
147
148
  processes,
@@ -36,6 +36,7 @@ export function bootId(): string | null {
36
36
  : POSIX
37
37
  ? execFileSync("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], {
38
38
  encoding: "utf8",
39
+ env: process.env,
39
40
  stdio: ["ignore", "pipe", "ignore"],
40
41
  }).trim()
41
42
  : null;
@@ -97,6 +97,7 @@ interface BunRuntime {
97
97
  stdout: "ignore";
98
98
  stderr: "ignore";
99
99
  detached: boolean;
100
+ env: Record<string, string | undefined>;
100
101
  onExit(): void;
101
102
  },
102
103
  ): {
@@ -128,6 +129,10 @@ function startShell(ticks: string, exited: () => void, failed: () => void): Life
128
129
  stdout: "ignore",
129
130
  stderr: "ignore",
130
131
  detached: true,
132
+ // @ref LLP 0007#the-environment-a-process-is-given — this process's environment now
133
+ // Without one, Bun gives the environment it was launched with: a
134
+ // secret the host deleted from `process.env` would live on here.
135
+ env: process.env,
131
136
  onExit: exited,
132
137
  });
133
138
  child.unref();
@@ -142,7 +147,11 @@ function startShell(ticks: string, exited: () => void, failed: () => void): Life
142
147
  };
143
148
  }
144
149
  // Node writes a pipe at once when it can (libuv's `uv_try_write`).
145
- const child = spawn("/bin/sh", args, { detached: true, stdio: ["pipe", "ignore", "ignore"] });
150
+ const child = spawn("/bin/sh", args, {
151
+ detached: true,
152
+ env: process.env,
153
+ stdio: ["pipe", "ignore", "ignore"],
154
+ });
146
155
  child.unref();
147
156
  (child.stdin as { unref?: () => void } | null)?.unref?.();
148
157
  child.stdin?.on("error", () => {});
@@ -57,6 +57,7 @@ function linuxTable(): ProcessRow[] {
57
57
  function psTable(): ProcessRow[] {
58
58
  const out = execFileSync("/bin/ps", ["-axo", "pid=,ppid=,pgid=,stat="], {
59
59
  encoding: "utf8",
60
+ env: process.env,
60
61
  stdio: ["ignore", "pipe", "ignore"],
61
62
  });
62
63
  const rows: ProcessRow[] = [];
@@ -12,6 +12,7 @@ const EXTRACT_TIMEOUT_MS = 5 * 60_000;
12
12
  export async function extractTarGz(tgzPath: string, destDir: string): Promise<void> {
13
13
  await new Promise<void>((resolve, reject) => {
14
14
  const proc = spawn("tar", ["-xzf", tgzPath, "-C", destDir], {
15
+ env: process.env,
15
16
  stdio: ["ignore", "ignore", "pipe"],
16
17
  timeout: EXTRACT_TIMEOUT_MS,
17
18
  });
@@ -350,11 +350,14 @@ export class AgentRuntime {
350
350
  * Cancel the session's in-flight turn. An idle session is a clean no-op ack
351
351
  * (`{confirmed: true, hadTurn: false}`); `confirmed: false` means a turn
352
352
  * existed but the harness did not acknowledge the interrupt — the agent may
353
- * still be running; `turn.ended` remains the source of truth.
353
+ * still be running; `turn.ended` remains the source of truth. A turn
354
+ * admitted but not yet on its harness answers `hadTurn: false` too (the
355
+ * harness had nothing to interrupt), and still ends `cancelled`: the turn
356
+ * keeps the cancel, and its harness begins it stopped.
354
357
  */
355
358
  async cancel(harness: AgentHarness, sessionId: string): Promise<CancelResult> {
356
- // Unblock any harness parked on an approval before (and regardless of)
357
- // the agent-level abort.
359
+ // The turn keeps the cancel (its signal), and any harness parked on an
360
+ // approval is unblocked, before (and regardless of) the agent-level abort.
358
361
  for (const turn of this.turnsOf(sessionId)) void turn.requestCancel();
359
362
  return await this.registry.getAgent(harness).cancel(sessionId);
360
363
  }
@@ -143,8 +143,14 @@ export class Turn {
143
143
  private readonly processor: EventProcessor;
144
144
  /** Its durable sink failed: the turn stops, and every later write fails with it. */
145
145
  private sinkFailure?: EventSinkError;
146
- /** `cancel` or `closeSession` asked it to stop. */
147
- private cancelRequested = false;
146
+ /**
147
+ * Aborted when `cancel` or `closeSession` asks the turn to stop: part of
148
+ * the signal its harness is given, so a cancel that comes before the
149
+ * harness has the turn is not lost.
150
+ */
151
+ private readonly cancelled = new AbortController();
152
+ /** The caller's signal, the runtime's shutdown and the turn's own cancel, together. */
153
+ private readonly signal: AbortSignal;
148
154
  private nativeSessionId?: string;
149
155
  /** When the turn requested a resume: whether the harness honored it. */
150
156
  private resumed?: boolean;
@@ -157,10 +163,11 @@ export class Turn {
157
163
  readonly inputKey: string,
158
164
  private readonly sink: EventSink,
159
165
  /** The caller's signal and the runtime's shutdown, together. */
160
- private readonly signal: AbortSignal,
166
+ signal: AbortSignal,
161
167
  private readonly host: TurnHost,
162
168
  ) {
163
169
  const { sessionId, turnId, config } = request;
170
+ this.signal = AbortSignal.any([signal, this.cancelled.signal]);
164
171
  this.sessionId = sessionId;
165
172
  this.turnId = turnId;
166
173
  this.harness = config.harness;
@@ -180,14 +187,19 @@ export class Turn {
180
187
  this.running = Promise.resolve().then(() => this.execute());
181
188
  }
182
189
 
190
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — a cancel before the harness has the turn
183
191
  /**
184
- * A cancel was asked for: its open requests are answered as cancelled, and
185
- * what the harness throws from now on is it stopping. Resolves once their
186
- * `*.resolved` are written.
192
+ * A cancel was asked for: the turn's signal is aborted, so a harness that
193
+ * has not begun the turn yet begins it stopped; its open requests are
194
+ * answered as cancelled; and what the harness throws from now on is it
195
+ * stopping. Resolves once their `*.resolved` are written.
187
196
  */
188
197
  requestCancel(): Promise<void> {
189
- this.cancelRequested = true;
190
- return this.requests.cancelAll();
198
+ // Taken before the abort, which settles each request bound to the turn's
199
+ // signal and takes it out of the broker: the cancel would not wait for it.
200
+ const answered = this.requests.cancelAll();
201
+ this.cancelled.abort();
202
+ return answered;
191
203
  }
192
204
 
193
205
  private async execute(): Promise<RunSummary> {
@@ -253,7 +265,7 @@ export class Turn {
253
265
  if (this.sinkFailure) throw this.sinkFailure;
254
266
  // A harness asked to stop throws as it stops, whatever its words say;
255
267
  // one that was not is failing.
256
- threw = this.cancelRequested || this.signal.aborted ? "cancelled" : errorInfo(error);
268
+ threw = this.signal.aborted ? "cancelled" : errorInfo(error);
257
269
  if (threw !== "cancelled") {
258
270
  await this.emit({
259
271
  type: "error",
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { AccountInfoSchema } from "./account.ts";
3
- import { AgentHarnessSchema } from "./harness.ts";
3
+ import { type AgentHarness, AgentHarnessSchema } from "./harness.ts";
4
4
 
5
5
  const ApiKeySchema = z.object({
6
6
  type: z.literal("api_key"),
@@ -60,13 +60,27 @@ const RUNS_ON = {
60
60
  "codex-app-server": CodexCredentialSchema,
61
61
  } as const;
62
62
 
63
- /** The credential as the kind `harness` runs on, or why that harness cannot run it. */
63
+ /**
64
+ * The credential as the kind `harness` runs on, or why that harness cannot
65
+ * run it. Any harness may be asked, one only known at run time too: one that
66
+ * runs on no credential a product holds (ACP, scripted) answers why.
67
+ */
64
68
  export function credentialRunsOn<H extends keyof HarnessCredentials>(
65
69
  harness: H,
66
70
  credential: HarnessCredential,
67
- ): { ok: true; credential: HarnessCredentials[H] } | { ok: false; error: string } {
68
- const parsed = RUNS_ON[harness].safeParse(credential);
69
- if (parsed.success) return { ok: true, credential: parsed.data as HarnessCredentials[H] };
71
+ ): { ok: true; credential: HarnessCredentials[H] } | { ok: false; error: string };
72
+ export function credentialRunsOn(
73
+ harness: AgentHarness,
74
+ credential: HarnessCredential,
75
+ ): { ok: true; credential: HarnessCredential } | { ok: false; error: string };
76
+ export function credentialRunsOn(
77
+ harness: AgentHarness,
78
+ credential: HarnessCredential,
79
+ ): { ok: true; credential: HarnessCredential } | { ok: false; error: string } {
80
+ if (!Object.hasOwn(RUNS_ON, harness))
81
+ return { ok: false, error: `${harness} runs on no credential a product holds.` };
82
+ const parsed = RUNS_ON[harness as keyof HarnessCredentials].safeParse(credential);
83
+ if (parsed.success) return { ok: true, credential: parsed.data };
70
84
  const what =
71
85
  credential.type === "api_key" && credential.baseUrl
72
86
  ? "a key for another endpoint"
@@ -9,7 +9,9 @@ import { openVocabulary } from "./vocabulary.ts";
9
9
  * unknown non-`_` values are reserved for this protocol.
10
10
  * `usage_limit` (plan/quota exhausted) and `rate_limit` (429/backoff) are
11
11
  * deliberately distinct — they need different user guidance; collapsing them
12
- * is a display choice, never a wire merge.
12
+ * is a display choice, never a wire merge. So are `resume_failed` (the
13
+ * conversation is gone: offer a fresh start) and `resume_busy` (another
14
+ * process holds it now: try again once that one has let it go).
13
15
  */
14
16
  export const ERROR_CATEGORIES = [
15
17
  "auth",
@@ -22,6 +24,7 @@ export const ERROR_CATEGORIES = [
22
24
  "invalid_request",
23
25
  "process_exit",
24
26
  "resume_failed",
27
+ "resume_busy",
25
28
  "mcp_unavailable",
26
29
  "server_restart",
27
30
  "internal",
@@ -50,6 +53,8 @@ export type ErrorInfo = z.infer<typeof ErrorInfoSchema>;
50
53
  * classifier; lives in /protocol because categories are vocabulary.
51
54
  */
52
55
  const RULES: ReadonlyArray<[ErrorCategory, readonly string[]]> = [
56
+ // Codex 0.160 and newer: another app-server holds the thread warm.
57
+ ["resume_busy", ["already has an active writer"]],
53
58
  ["resume_failed", ["no conversation found with session id", "no rollout found for thread id"]],
54
59
  ["abort", ["aborted", "aborterror", "cancelled", "canceled", "interrupted", "sigint"]],
55
60
  [
@@ -142,13 +147,17 @@ export function classifyError(error: unknown): ErrorCategory {
142
147
  return "internal";
143
148
  }
144
149
 
145
- /** A status code counts on its own, never inside a longer number ("240129 tokens"). */
150
+ /**
151
+ * A status code counts where it stands as a number of its own, never inside
152
+ * a longer number ("240129 tokens") or an identifier's alphanumeric run (a
153
+ * thread id's "-b401-" or "-a429-"): no letter or digit touches it.
154
+ */
146
155
  function mentions(message: string, needle: string): boolean {
147
156
  if (!/\d$/.test(needle)) return message.includes(needle);
148
157
  for (let at = message.indexOf(needle); at >= 0; at = message.indexOf(needle, at + 1)) {
149
158
  const before = message[at - 1] ?? "";
150
159
  const after = message[at + needle.length] ?? "";
151
- if (!/\d/.test(before) && !/\d/.test(after)) return true;
160
+ if (!/[a-z0-9]/.test(before) && !/[a-z0-9]/.test(after)) return true;
152
161
  }
153
162
  return false;
154
163
  }
package/src/server/bin.ts CHANGED
@@ -102,7 +102,7 @@ function usage(exitCode: number): never {
102
102
  " (no key; see feedback --help for categories, evals,",
103
103
  " thread replies and --dry-run)",
104
104
  " --listen [host:]port accept WebSocket clients (an IPv6 host in brackets: [::1]:4747);",
105
- " beyond loopback only with a token",
105
+ " beyond loopback only with a token; under Bun only",
106
106
  " --token-file <path> the token a listener's clients send (Authorization: Bearer);",
107
107
  " or $AGENT_SERVER_TOKEN, never argv (ps shows it to every user)",
108
108
  " --allow-origin <url> a browser origin that may connect to the listener (repeatable;",
@@ -124,7 +124,7 @@ function usage(exitCode: number): never {
124
124
  " --credentials-url <url> ask this product endpoint for each turn's credential",
125
125
  " (LLP 0012); its token in $AGENT_SERVER_CREDENTIALS_TOKEN",
126
126
  " --buffer <n> replay buffer size per session (default 4096; not with --journal)",
127
- " --journal <path> durable session history (wire modes only; Bun SQLite)",
127
+ " --journal <path> durable session history (wire modes only; SQLite: Bun's, or Node's)",
128
128
  " --version, --help (an option's value may also follow `=`: --journal=<path>)",
129
129
  "",
130
130
  "env: AGENT_SERVER_TOKEN (the listener's token, if no --token-file),",
@@ -266,8 +266,9 @@ function parseArgs(argv: string[]): Args {
266
266
  return args;
267
267
  }
268
268
 
269
- /** `host:port`, an IPv6 host in brackets. */
270
- function hostPort({ hostname = "127.0.0.1", port }: { hostname?: string; port: number }): string {
269
+ /** Where `--listen` listens (loopback, port 0, unless it says) as `host:port`, IPv6 in brackets. */
270
+ function hostPort(listen: Args["listen"]): string {
271
+ const { hostname = "127.0.0.1", port = 0 } = listen ?? {};
271
272
  return `${hostname.includes(":") ? `[${hostname}]` : hostname}:${port}`;
272
273
  }
273
274
 
@@ -309,6 +310,10 @@ function listenToken(file: string | undefined): string | undefined {
309
310
  * before a runtime or journal starts, and in the bin's terms.
310
311
  */
311
312
  function listenOptions(args: Args): ListenOptions {
313
+ if (!("Bun" in globalThis))
314
+ fail(
315
+ `--listen ${hostPort(args.listen)} needs Bun (its WebSocket server is Bun.serve): run this bin with bun, or serve over --stdio or --dial here`,
316
+ );
312
317
  const options = {
313
318
  ...args.listen,
314
319
  token: listenToken(args.tokenFile),
@@ -317,7 +322,7 @@ function listenOptions(args: Args): ListenOptions {
317
322
  try {
318
323
  assertListenOptions(options);
319
324
  } catch (error) {
320
- const where = hostPort(args.listen ?? { port: 0 });
325
+ const where = hostPort(args.listen);
321
326
  if ((error as { code?: string }).code === "tokenRequired")
322
327
  fail(
323
328
  `--listen ${where} can be reached from other machines: give it a token (--token-file <path> or $AGENT_SERVER_TOKEN), or listen on 127.0.0.1`,
@@ -327,6 +332,18 @@ function listenOptions(args: Args): ListenOptions {
327
332
  return options;
328
333
  }
329
334
 
335
+ /**
336
+ * The journal on this runtime's SQLite: `bun:sqlite` under Bun, `node:sqlite`
337
+ * under Node (the compiled bin). Each adapter loads only when chosen, since
338
+ * neither runtime has the other's module.
339
+ */
340
+ async function openJournal(path: string) {
341
+ // @ref LLP 0001#d24--bun-runs-the-packages-sources-every-other-runtime-its-compiled-javascript — the bin on either runtime
342
+ return "Bun" in globalThis
343
+ ? new (await import("../sync/sqlite.ts")).SqliteSessionJournal(path)
344
+ : new (await import("../sync/node-sqlite.ts")).NodeSqliteSessionJournal(path);
345
+ }
346
+
330
347
  const args = parseArgs(process.argv.slice(2));
331
348
  if (args.journalPath && (args.mode === "acp" || args.command !== "serve"))
332
349
  fail("--journal is supported only for the stdio/listen/dial wire server");
@@ -459,11 +476,9 @@ if (args.mode === "acp") {
459
476
  } else {
460
477
  if (args.journalPath && args.bufferSize !== undefined)
461
478
  console.error("agent-server: --buffer has no effect with --journal (the journal replays all)");
462
- let journal: import("../sync/sqlite.ts").SqliteSessionJournal | undefined;
479
+ let journal: Awaited<ReturnType<typeof openJournal>> | undefined;
463
480
  try {
464
- journal = args.journalPath
465
- ? new (await import("../sync/sqlite.ts")).SqliteSessionJournal(args.journalPath)
466
- : undefined;
481
+ journal = args.journalPath ? await openJournal(args.journalPath) : undefined;
467
482
  } catch (error) {
468
483
  // Locked by another server, not a database, a newer schema: say which.
469
484
  const why = error instanceof Error ? error.message : String(error);
@@ -494,7 +509,7 @@ if (args.mode === "acp") {
494
509
  } catch (error) {
495
510
  const code = (error as { code?: string }).code;
496
511
  fail(
497
- `cannot listen on ${hostPort(args.listen ?? { port: 0 })}: ${code === "EADDRINUSE" ? "the port is in use" : error instanceof Error ? error.message : error}`,
512
+ `cannot listen on ${hostPort(args.listen)}: ${code === "EADDRINUSE" ? "the port is in use" : error instanceof Error ? error.message : error}`,
498
513
  );
499
514
  }
500
515
  console.error(`agent-server ${VERSION} listening on ${bound.url}`);
@@ -219,8 +219,9 @@ export function executionRoutes(host: RouteHost): Routes<ExecutionMethod> {
219
219
  // running and `turn.ended` stays the source of truth. `hadTurn: false`
220
220
  // while the server tracks an active turn is the pre-first-yield window
221
221
  // (between the turn/start quick-ack and the harness registering its
222
- // abortable turn) — the abort landed on nothing and the turn may run
223
- // to completion, so it must report `unconfirmed`, never a clean cancel.
222
+ // abortable turn): the turn keeps the cancel and its harness begins it
223
+ // stopped, but nothing has confirmed a stop yet, so it reports
224
+ // `unconfirmed`, never a clean cancel, and `turn.ended` says `cancelled`.
224
225
  return {
225
226
  outcome: confirmed && hadTurn ? "cancelled" : "unconfirmed",
226
227
  turnId: active.turnId,
@@ -142,13 +142,18 @@ function carries(authorization: string | null, token: Buffer): boolean {
142
142
  * Accept WebSocket clients (agnt's model: the consumer connects to us). Each
143
143
  * accepted socket becomes an attached transport, which receives the sessions
144
144
  * it subscribes to. It answers native clients, and browsers only from
145
- * `allowedOrigins`; beyond loopback it requires a `token`.
145
+ * `allowedOrigins`; beyond loopback it requires a `token`. Bun only: under
146
+ * any other runtime it throws an error that says what works there.
146
147
  */
147
148
  export function listen(
148
149
  server: AgentServer,
149
150
  opts: ListenOptions = {},
150
151
  ): { url: string; port: number; stop(): void } {
151
152
  assertListenOptions(opts);
153
+ if (!("Bun" in globalThis))
154
+ throw new Error(
155
+ "listen needs Bun (its WebSocket server is Bun.serve): run under Bun, or here serve the wire over stdio (stdioTransport), dial out to the client (dial), or attach each socket of a WebSocket server of your own (channelTransport, server.attach)",
156
+ );
152
157
  const guard = upgradeGuard(opts);
153
158
  const bun = Bun.serve<{ socket?: ReturnType<typeof socketTransport> }>({
154
159
  port: opts.port ?? 0,
@@ -1,14 +1,17 @@
1
- import { DatabaseSync } from "node:sqlite";
1
+ import type { DatabaseSync } from "node:sqlite";
2
2
  import { SqliteJournal } from "./journal-sqlite.ts";
3
3
  import { openJournalFile } from "./sqlite-file.ts";
4
4
 
5
5
  /** Node >=22.16 adapter (node:sqlite). Same schema and guarantees as Bun.
6
- * Transpile the package's TypeScript using the host's normal build pipeline. */
6
+ * `node:sqlite` loads when a journal opens, not when this module does: a
7
+ * bundle holding both adapters (the bin, compiled by Bun into one binary)
8
+ * hoists a static import of it, which Bun, without the module, refuses at
9
+ * start; and Node 22 warns that it is experimental on its first load. */
7
10
  export class NodeSqliteSessionJournal extends SqliteJournal {
8
11
  constructor(path: string) {
9
12
  super(
10
13
  openJournalFile(path, (file) => {
11
- const db = new DatabaseSync(file);
14
+ const db: DatabaseSync = new (nodeSqlite().DatabaseSync)(file);
12
15
  return {
13
16
  exec: (sql) => db.exec(sql),
14
17
  prepare: (sql) => db.prepare(sql),
@@ -18,3 +21,16 @@ export class NodeSqliteSessionJournal extends SqliteJournal {
18
21
  );
19
22
  }
20
23
  }
24
+
25
+ /** `node:sqlite`, loaded now: Bun answers undefined for a module it does not have. */
26
+ function nodeSqlite(): typeof import("node:sqlite") {
27
+ // @ref LLP 0001#d24--bun-runs-the-packages-sources-every-other-runtime-its-compiled-javascript — loaded when a journal opens
28
+ const sqlite = process.getBuiltinModule("node:sqlite") as
29
+ | typeof import("node:sqlite")
30
+ | undefined;
31
+ if (!sqlite)
32
+ throw new Error(
33
+ "this runtime has no node:sqlite: use Node >=22.16, or under Bun the bun:sqlite journal (./sync/sqlite)",
34
+ );
35
+ return sqlite;
36
+ }