@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
@@ -1,10 +1,19 @@
1
1
  import { closeSync, existsSync, openSync, realpathSync, statSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { isAbsolute, resolve } from "node:path";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
4
  import { InvalidRequestError } from "../../utils/errors.ts";
5
5
  import type { AgentExecuteOptions } from "../base.ts";
6
6
  import type { InheritConfig } from "../inherit-config.ts";
7
7
 
8
+ /**
9
+ * The Codex home a process with this `env` runs in, absolute: the one the
10
+ * `env` names, else the engine's own (`$CODEX_HOME`, else `~/.codex`), the
11
+ * user's shared home.
12
+ */
13
+ export function codexHome(env?: Record<string, string>): string {
14
+ return resolve(env?.CODEX_HOME || process.env.CODEX_HOME || join(homedir(), ".codex"));
15
+ }
16
+
8
17
  /**
9
18
  * Which logical session owns each `CODEX_HOME` its turns name. A turn that
10
19
  * names one claims it for its session, which keeps it until it is released,
@@ -36,7 +45,7 @@ export class CodexHomes {
36
45
  );
37
46
  }
38
47
  if (!isAbsolute(home)) throw refused("must be an absolute path");
39
- const shared = resolve(process.env.CODEX_HOME ?? `${homedir()}/.codex`);
48
+ const shared = codexHome();
40
49
  // A home a turn names is written to. At `all` a turn runs in the user's
41
50
  // by naming none.
42
51
  const isShared = () =>
@@ -1,3 +1,5 @@
1
+ import { statSync } from "node:fs";
2
+ import { join } from "node:path";
1
3
  import type { AuthMethod } from "../../../protocol/index.ts";
2
4
  import { onAbort } from "../../utils/deadline.ts";
3
5
  import { InvalidRequestError } from "../../utils/errors.ts";
@@ -11,6 +13,7 @@ import {
11
13
  terminalMethod,
12
14
  } from "../login.ts";
13
15
  import type { CodexConnection } from "./client.ts";
16
+ import { codexHome } from "./homes.ts";
14
17
 
15
18
  /** The logins Codex's app-server runs itself, each with its `account/login/start` type. */
16
19
  const LOGINS: readonly (AuthMethod & { type: string })[] = [
@@ -86,6 +89,33 @@ export function codexLoginStore(env: Record<string, string> | undefined): string
86
89
  return env?.[STORE_VARIABLE] ?? "";
87
90
  }
88
91
 
92
+ // @ref LLP 0011#a-login-change-starts-the-next-turn-on-a-new-cli — the engine reads no login: it sees the file change
93
+ /**
94
+ * What the login file of the store a turn with this `env` runs on looks
95
+ * like (`<CODEX_HOME>/auth.json`, the turn's, else the process's, else
96
+ * `~/.codex`'s; Codex's default `file` store): its device, inode, size and
97
+ * modified and changed times at full precision, or `absent`. Codex writes
98
+ * the file in place on any login change, a token renewal and a rewrite of
99
+ * the same key, and removes it at a sign-out, so a running app-server, which
100
+ * keeps the login it started with, is stale once this differs. A link is
101
+ * followed to its target (a product may link the person's own `auth.json`
102
+ * into a session's home). The file is never opened.
103
+ */
104
+ export function codexLoginMark(env: Record<string, string> | undefined): string {
105
+ try {
106
+ const file = statSync(join(codexHome(env), "auth.json"), {
107
+ bigint: true,
108
+ throwIfNoEntry: false,
109
+ });
110
+ if (!file) return "absent";
111
+ return `${file.dev}:${file.ino}:${file.size}:${file.mtimeNs}:${file.ctimeNs}`;
112
+ } catch (error) {
113
+ // A folder it may not enter, or under Bun a file on the way (ENOTDIR;
114
+ // Node's stat reads that as absent).
115
+ return `unreadable:${(error as NodeJS.ErrnoException).code ?? "unknown"}`;
116
+ }
117
+ }
118
+
89
119
  /** Codex's login, through its app-server: `account/read`, `account/login/start`, `account/logout`. */
90
120
  export class CodexCliLogin implements CliLogin {
91
121
  constructor(private readonly options: CodexCliLoginOptions) {}
@@ -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(
@@ -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,
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}`);
@@ -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
+ }