@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,240 @@
1
+ import { configFingerprint, directoriesFingerprint } from "../config-fingerprint.js";
2
+ import { claudeSpawner } from "./spawn.js";
3
+ /**
4
+ * A turn's session config. Picked field by field: the long-lived session must
5
+ * not keep a turn's abort signal or callbacks.
6
+ */
7
+ export function claudeSessionConfig(options, cliPath, inheritConfig) {
8
+ const { cwd, additionalDirectories, model, thinkingLevel, permissionMode, maxTurns } = options;
9
+ const { subagentMode, systemPromptAppend, resumeSessionId, resumeSessionAt } = options;
10
+ const { mcpServers, env, apiKey, disableTools } = options;
11
+ return {
12
+ cwd,
13
+ additionalDirectories,
14
+ model,
15
+ thinkingLevel,
16
+ permissionMode,
17
+ maxTurns,
18
+ subagentMode,
19
+ systemPromptAppend,
20
+ resumeSessionId,
21
+ resumeSessionAt,
22
+ mcpServers,
23
+ env,
24
+ apiKey,
25
+ disableTools: disableTools === true,
26
+ cliPath,
27
+ inheritConfig,
28
+ };
29
+ }
30
+ /** How many model turns a query may take unless the turn says otherwise. */
31
+ const DEFAULT_MAX_TURNS = 100;
32
+ /** The settings sources each level loads; built-in plugins and skills load whatever they say. */
33
+ const SETTING_SOURCES = {
34
+ all: ["user", "project", "local"],
35
+ project: ["project"],
36
+ none: [],
37
+ };
38
+ /** What a process loads by itself: the operator's level, and nothing for a turn without tools. */
39
+ function inherited(config) {
40
+ return config.disableTools ? "none" : (config.inheritConfig ?? "all");
41
+ }
42
+ /**
43
+ * Everything a Claude process is started with that it cannot change while it
44
+ * runs. A turn whose key differs from its session's needs a new process, which
45
+ * resumes the conversation. The model, the permission mode and the MCP servers
46
+ * switch on the live process instead, and a different resume target is the
47
+ * pool's own rule. Unset and empty name the same thing, as do directories in
48
+ * any order; credentials are hashed, never kept in the key.
49
+ */
50
+ export function claudeSpawnKey(config) {
51
+ return configFingerprint({
52
+ cwd: config.cwd,
53
+ cliPath: config.cliPath ?? "",
54
+ // Other mode changes switch the live session (`setPermissionMode`);
55
+ // bypass needs its dangerous flag at spawn.
56
+ bypass: config.permissionMode === "bypass_permissions",
57
+ // thinking/effort are fixed at spawn in the modern SDK vocabulary (the
58
+ // old setMaxThinkingTokens hot-swap is deprecated and effort-blind).
59
+ thinkingLevel: config.thinkingLevel ?? "",
60
+ systemPromptAppend: config.systemPromptAppend ?? "",
61
+ // The SDK applies a rewind only at spawn, so any change restarts, a set
62
+ // point clearing too: one extra (context-preserving) respawn after a
63
+ // revert keeps the gate correct even if the stored config lags a turn.
64
+ resumeSessionAt: config.resumeSessionAt ?? "",
65
+ directories: directoriesFingerprint(config.additionalDirectories),
66
+ apiKey: config.apiKey ?? "",
67
+ maxTurns: config.maxTurns ?? DEFAULT_MAX_TURNS,
68
+ disableTools: config.disableTools === true,
69
+ inheritConfig: inherited(config),
70
+ subagentMode: config.subagentMode,
71
+ // No environment and an empty one differ, as they do for the
72
+ // conversation's boundary (`SessionAgent`).
73
+ env: config.env,
74
+ });
75
+ }
76
+ /**
77
+ * Map our permission posture onto the Claude SDK's. `bypassPermissions`
78
+ * auto-approves every tool and is dangerous outside a sandbox, so it must be
79
+ * requested explicitly — an unset/unknown mode falls back to the safe `default`.
80
+ */
81
+ export function toSdkPermissionMode(mode) {
82
+ switch (mode) {
83
+ case "bypass_permissions":
84
+ return "bypassPermissions";
85
+ case "plan":
86
+ return "plan";
87
+ case "accept_edits":
88
+ return "acceptEdits";
89
+ case "dont_ask":
90
+ // Native SDK mode: never prompt, deny unapproved. Unlike
91
+ // bypassPermissions it needs no dangerous flag (and the CLI keeps
92
+ // extended thinking enabled, which bypass turns off).
93
+ return "dontAsk";
94
+ default:
95
+ return "default";
96
+ }
97
+ }
98
+ /** The engine's name for a mode the CLI reports itself in; undefined for one it has none for. */
99
+ export function fromSdkPermissionMode(mode) {
100
+ switch (mode) {
101
+ case "bypassPermissions":
102
+ return "bypass_permissions";
103
+ case "plan":
104
+ return "plan";
105
+ case "acceptEdits":
106
+ return "accept_edits";
107
+ case "dontAsk":
108
+ return "dont_ask";
109
+ case "default":
110
+ return "default";
111
+ default:
112
+ return undefined;
113
+ }
114
+ }
115
+ /**
116
+ * Build the env handed to the Claude subprocess. The SDK REPLACES the child env
117
+ * entirely when `env` is set, so we must spread `process.env` to preserve PATH/
118
+ * HOME (and thus keychain/subscription auth). We only inject ANTHROPIC_API_KEY
119
+ * when an explicit key is supplied — otherwise the CLI's own auth is used.
120
+ *
121
+ * A subscription login also brings that account's claude.ai connectors (Drive,
122
+ * Gmail, …) into every session; at `all` they stay off unless the operator's
123
+ * or the turn's env turns them on. Below `all` they stay off, and so does the
124
+ * auto-memory Claude keeps per repository, whatever either env says: both are
125
+ * the host user's, which no settings source decides (`settingSources: []`
126
+ * still loads the memory).
127
+ *
128
+ * Background tasks and scheduled prompts stay off the same way: Claude answers
129
+ * one that finishes after its turn with a query of its own, which no turn on
130
+ * the stream shows. The CLI's updater stays off whatever either env says: the
131
+ * build that runs is the one the provisioner chose.
132
+ */
133
+ function buildEnv(config, level) {
134
+ return {
135
+ ENABLE_CLAUDEAI_MCP_SERVERS: "false",
136
+ // @ref LLP 0001#d14--nothing-the-agent-does-is-off-the-stream — off until the stream can show it
137
+ CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1",
138
+ CLAUDE_CODE_DISABLE_CRON: "1",
139
+ ...process.env,
140
+ ...(config.apiKey ? { ANTHROPIC_API_KEY: config.apiKey } : {}),
141
+ ...config.env,
142
+ // The engine runs the build it pinned: the CLI must not replace itself.
143
+ DISABLE_AUTOUPDATER: "1",
144
+ ...(config.subagentMode === "turn" && { CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1" }),
145
+ // @ref LLP 0001#d17--a-turn-inherits-what-the-operator-chooses-all-the-projects-or-none — after the spread
146
+ ...(level !== "all" && {
147
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1",
148
+ ENABLE_CLAUDEAI_MCP_SERVERS: "false",
149
+ }),
150
+ };
151
+ }
152
+ /** The environment Claude Code runs a turn with this `env` in, which decides whose login it runs on. */
153
+ export function claudeEnv(config) {
154
+ return buildEnv(config, inherited(config));
155
+ }
156
+ /**
157
+ * The SDK options a Claude process starts with. Its MCP servers are only the
158
+ * host's in-process ones: the session attaches the turn's own after spawn
159
+ * (`ClaudeMcpConnections`), since CLI startup entries can survive the first
160
+ * dynamic removal and reconnect-by-name can reuse their original credentials.
161
+ */
162
+ export function buildClaudeOptions(config, sdkMcpServers, overrides, spawn) {
163
+ const mode = toSdkPermissionMode(config.permissionMode);
164
+ const level = inherited(config);
165
+ const options = {
166
+ cwd: config.cwd,
167
+ maxTurns: config.maxTurns ?? DEFAULT_MAX_TURNS,
168
+ permissionMode: mode,
169
+ // Streaming input mode + partial messages give us token-level deltas.
170
+ includePartialMessages: true,
171
+ systemPrompt: config.systemPromptAppend
172
+ ? { type: "preset", preset: "claude_code", append: config.systemPromptAppend }
173
+ : { type: "preset", preset: "claude_code" },
174
+ // Explicit at every level: the SDK's default for unset must not decide it.
175
+ settingSources: [...SETTING_SOURCES[level]],
176
+ env: buildEnv(config, level),
177
+ };
178
+ if (config.cliPath)
179
+ options.pathToClaudeCodeExecutable = config.cliPath;
180
+ if (config.model)
181
+ options.model = config.model;
182
+ if (config.additionalDirectories?.length)
183
+ options.additionalDirectories = config.additionalDirectories;
184
+ if (mode === "bypassPermissions")
185
+ options.allowDangerouslySkipPermissions = true;
186
+ if (config.thinkingLevel !== undefined) {
187
+ // Modern SDK vocabulary (maxThinkingTokens is deprecated): adaptive
188
+ // thinking with an effort level; `off` disables extended thinking.
189
+ if (config.thinkingLevel === "off") {
190
+ options.thinking = { type: "disabled" };
191
+ }
192
+ else {
193
+ options.thinking = { type: "adaptive" };
194
+ // Claude's ceiling is `max`.
195
+ options.effort = config.thinkingLevel === "ultra" ? "max" : config.thinkingLevel;
196
+ }
197
+ }
198
+ if (config.resumeSessionId) {
199
+ options.resume = config.resumeSessionId;
200
+ // SDK contract: resumeSessionAt is only meaningful WITH resume — never
201
+ // pass it alone (the CLI would get a bare --resume-session-at).
202
+ if (config.resumeSessionAt)
203
+ options.resumeSessionAt = config.resumeSessionAt;
204
+ }
205
+ // Only the servers the host and the turn name: no plugin's, connector's
206
+ // or settings file's. The turn's still attach (`setMcpServers`).
207
+ if (level === "none")
208
+ options.strictMcpConfig = true;
209
+ // Text-only: no built-in tools and no MCP servers, the host's included; it
210
+ // runs at `none`, so nothing ambient brings tools back.
211
+ if (config.disableTools)
212
+ options.tools = [];
213
+ else
214
+ options.mcpServers = { ...sdkMcpServers };
215
+ // Operator overrides land last; the engine wires hooks/canUseTool after
216
+ // this function returns, so those can never be clobbered (and the
217
+ // ClaudeSdkOptionOverrides type excludes them anyway).
218
+ if (overrides)
219
+ Object.assign(options, overrides);
220
+ if (config.subagentMode === "turn")
221
+ options.forwardSubagentText = true;
222
+ // Engine wiring over the operator's: their spawner still runs, as theirs.
223
+ if (spawn)
224
+ options.spawnClaudeCodeProcess = claudeSpawner(spawn, overrides?.spawnClaudeCodeProcess, overrides?.stderr);
225
+ // Fable-class models withhold thinking plaintext by default: blocks stream
226
+ // structure + token estimates only, so every reasoning part arrives with
227
+ // empty text. The hidden `--thinking-display summarized` flag opts into
228
+ // summary text. Applied after operator
229
+ // overrides so an unrelated operator extraArgs can't drop it, while an
230
+ // explicit operator `thinking-display` key still wins.
231
+ if (config.thinkingLevel !== "off") {
232
+ options.extraArgs = { "thinking-display": "summarized", ...options.extraArgs };
233
+ }
234
+ // @ref LLP 0002#steering — Claude replays each steer where it reads it
235
+ // Replay echoes every uuid-stamped user message back at the step Claude
236
+ // reads it, which is where a steer's user message belongs. Engine wiring:
237
+ // applied last, so no operator `extraArgs` can drop it.
238
+ options.extraArgs = { ...options.extraArgs, "replay-user-messages": null };
239
+ return options;
240
+ }
@@ -0,0 +1,204 @@
1
+ import { classifyError } from "../../../protocol/index.js";
2
+ /** Map Anthropic stop reasons / result subtypes onto the normalized enum. */
3
+ function mapClaudeStopReason(stopReason, subtype) {
4
+ if (subtype === "error_max_turns")
5
+ return "max_turn_requests";
6
+ switch (stopReason) {
7
+ case "end_turn":
8
+ case "stop_sequence":
9
+ case "tool_use":
10
+ case "pause_turn":
11
+ return "end_turn";
12
+ case "max_tokens":
13
+ return "max_tokens";
14
+ case "refusal":
15
+ return "refusal";
16
+ default:
17
+ return undefined;
18
+ }
19
+ }
20
+ /**
21
+ * Claude's typed API failure codes, and HTTP statuses, as engine error
22
+ * categories. A code or status this build does not know returns `undefined`,
23
+ * so the message decides rather than a guess. `status === null` is a request
24
+ * that got no HTTP response at all.
25
+ */
26
+ export function claudeErrorCategory(code, status) {
27
+ switch (code) {
28
+ case "authentication_failed":
29
+ case "oauth_org_not_allowed":
30
+ case "account_on_hold":
31
+ case "verification_required":
32
+ case "cloud_credential_error":
33
+ return "auth";
34
+ case "billing_error":
35
+ return "usage_limit";
36
+ case "rate_limit":
37
+ return "rate_limit";
38
+ case "overloaded":
39
+ return "overloaded";
40
+ case "invalid_request":
41
+ case "model_not_found":
42
+ return "invalid_request";
43
+ case "server_error":
44
+ return "internal";
45
+ }
46
+ if (status === 429)
47
+ return "rate_limit";
48
+ if (status === 529 || status === 503)
49
+ return "overloaded";
50
+ if (status === 401 || status === 403)
51
+ return "auth";
52
+ if (status === null)
53
+ return "network";
54
+ return undefined;
55
+ }
56
+ /** A window used up, and no extra usage (overage) answering in its place. */
57
+ export function planUsedUp(info) {
58
+ return (info.status === "rejected" &&
59
+ info.isUsingOverage !== true &&
60
+ info.overageStatus !== "allowed" &&
61
+ info.overageStatus !== "allowed_warning");
62
+ }
63
+ /** A `rate_limit_event`: one window of the claude.ai plan (`resetsAt` is in seconds). */
64
+ function claudeLimits(info) {
65
+ if (!info)
66
+ return [];
67
+ // The status is the reported window's own: another window may still be limited.
68
+ const status = info.status === "rejected" ? "limited" : info.status === "allowed_warning" ? "warning" : "ok";
69
+ return [
70
+ {
71
+ kind: "limits",
72
+ windows: [
73
+ {
74
+ id: info.rateLimitType ?? "plan",
75
+ status,
76
+ ...(info.utilization !== undefined && { usedPercent: info.utilization * 100 }),
77
+ ...(info.resetsAt !== undefined && { resetsAt: info.resetsAt * 1000 }),
78
+ },
79
+ ],
80
+ },
81
+ ];
82
+ }
83
+ /**
84
+ * How a Claude turn ended, from its results: its stop reason, its failure and
85
+ * that failure's category, and whether an interrupt stopped it. A turn runs
86
+ * one more query for each steer it got too late; the last query decides.
87
+ */
88
+ export class ClaudeTurnOutcome {
89
+ stopReason;
90
+ finishReason;
91
+ error;
92
+ /** The typed code of the last failed API request the turn reported. */
93
+ errorCode;
94
+ /** The HTTP status of the API failure its result reported (`api_error_status`). */
95
+ errorStatus;
96
+ /** Plan windows Claude reports used up, with no extra usage serving requests. */
97
+ usedUpWindows = new Set();
98
+ interrupted = false;
99
+ execFailure = false;
100
+ succeeded = false;
101
+ /** The last result left steers for Claude's next query, still this turn. */
102
+ steersPending = false;
103
+ /** One plan window's report: another window may still be used up. */
104
+ limits(info) {
105
+ const id = info?.rateLimitType ?? "plan";
106
+ if (info && planUsedUp(info))
107
+ this.usedUpWindows.add(id);
108
+ else
109
+ this.usedUpWindows.delete(id);
110
+ return claudeLimits(info);
111
+ }
112
+ /** The turn's own request failed: a top-level assistant message says so with a typed code. */
113
+ requestFailed(code) {
114
+ this.errorCode = code;
115
+ }
116
+ /** The streaming model message said why it stopped (`message_delta`). */
117
+ messageStopped(reason) {
118
+ this.finishReason = reason;
119
+ }
120
+ /** The turn was asked to stop (`agentServer/turnInterrupted`, after its result). */
121
+ interrupt() {
122
+ this.interrupted = true;
123
+ }
124
+ /** A query's result; `steersPending`: Claude runs one more query, still this turn. */
125
+ settle(result, steersPending) {
126
+ // With steers pending, Claude's next query is still this turn: only the
127
+ // turn's last result says how it ended, so an earlier query's failure
128
+ // gives way to the next one's outcome.
129
+ if (this.steersPending) {
130
+ this.error = undefined;
131
+ this.errorCode = undefined;
132
+ this.errorStatus = undefined;
133
+ this.execFailure = false;
134
+ }
135
+ this.steersPending = steersPending;
136
+ this.succeeded = result.subtype === "success" && !result.is_error && !steersPending;
137
+ this.finishReason = result.stop_reason ?? result.subtype ?? this.finishReason;
138
+ this.stopReason = mapClaudeStopReason(result.stop_reason, result.subtype);
139
+ if (result.subtype && result.subtype !== "success") {
140
+ if (result.subtype === "error_during_execution" && result.stop_reason === null) {
141
+ // Ambiguous shape: an interrupt AND an execution failure (e.g. a bad
142
+ // resume id) both surface this way. The agent's `turnInterrupted`
143
+ // marker (which arrives after this message) disambiguates in finish(),
144
+ // as it does for an interrupt that aborted a tool (stop reason "tool_use").
145
+ this.execFailure = true;
146
+ }
147
+ else if (result.subtype === "error_max_turns") {
148
+ // Hitting the turn budget is a stop condition, not a failure.
149
+ }
150
+ else {
151
+ this.error = `Claude turn ended: ${result.subtype}`;
152
+ }
153
+ }
154
+ else if (result.is_error) {
155
+ // A failed API call (a rejected key, an exhausted quota, an overloaded
156
+ // provider) ends the turn as a "success" whose text is the error. The
157
+ // text names the failure, so the runtime classifies it (401 -> auth).
158
+ this.error = result.result || "Claude turn ended with an API error";
159
+ if (typeof result.api_error_status === "number")
160
+ this.errorStatus = result.api_error_status;
161
+ }
162
+ }
163
+ /** How the turn ended. */
164
+ finish() {
165
+ // An interrupted turn that did not succeed was cancelled. Claude ends it with
166
+ // error_during_execution and the stop reason of the step it aborted (null
167
+ // while streaming, "tool_use" while a tool runs), or with no result when
168
+ // the process was stopped first. Without an interrupt, error_during_execution
169
+ // is a real failure (a silent "cancelled" here is how a bad resume id used
170
+ // to vanish without a trace).
171
+ const cancelled = this.interrupted && !this.succeeded;
172
+ const error = cancelled
173
+ ? undefined
174
+ : (this.error ??
175
+ (this.execFailure
176
+ ? "Claude turn failed during execution (error_during_execution — e.g. an invalid resumeSessionId fails this way)"
177
+ : undefined));
178
+ const errorCategory = error ? this.errorCategory() : undefined;
179
+ return {
180
+ stopReason: this.stopReason,
181
+ finishReason: this.finishReason,
182
+ error,
183
+ ...(errorCategory && { errorCategory }),
184
+ cancelled,
185
+ };
186
+ }
187
+ /** The turn's failure category: Claude's typed code, made finer where it is coarse. */
188
+ errorCategory() {
189
+ const typed = this.errorCode ? claudeErrorCategory(this.errorCode) : undefined;
190
+ // Claude's code for a 429 is `rate_limit` when the plan itself is used up
191
+ // too; the turn's limit report says so, and a used-up plan waits for its
192
+ // reset rather than a backoff.
193
+ if (typed === "rate_limit" && this.usedUpWindows.size > 0)
194
+ return "usage_limit";
195
+ // `invalid_request` is any 400, a prompt too long for the model among them.
196
+ if (typed === "invalid_request" && this.error && classifyError(this.error) === "context_limit")
197
+ return "context_limit";
198
+ // `server_error` is any 5xx, an overloaded API (529, 503) among them;
199
+ // the result's status says which.
200
+ if (typed === "internal" && this.errorStatus !== undefined)
201
+ return claudeErrorCategory(undefined, this.errorStatus) ?? typed;
202
+ return typed;
203
+ }
204
+ }
@@ -0,0 +1,58 @@
1
+ import { isRecord } from "../../utils/is-record.js";
2
+ import { hunkDiff } from "../diffs.js";
3
+ /** How the CLI begins a failed `Bash` result: its only report of a code. */
4
+ const EXIT_CODE = /^Exit code (\d+)(?:\n|$)/;
5
+ /** An `Edit`'s or an updating `Write`'s `structuredPatch`, and each hunk's start in the new file. */
6
+ function patchView(path, patch) {
7
+ const content = [];
8
+ const locations = [];
9
+ for (const hunk of patch) {
10
+ if (!isRecord(hunk) || !Array.isArray(hunk.lines))
11
+ continue;
12
+ const entry = hunkDiff(path, hunk.lines.filter((line) => typeof line === "string"));
13
+ if (!entry)
14
+ continue;
15
+ content.push(entry);
16
+ locations.push({
17
+ path,
18
+ ...(typeof hunk.newStart === "number" && { line: hunk.newStart }),
19
+ });
20
+ }
21
+ return content.length ? { content, locations } : {};
22
+ }
23
+ // @ref LLP 0002#tool-output-has-three-audiences — the CLI's structured result, not its text, makes the diff
24
+ /**
25
+ * What a Claude tool's result shows, read from the CLI's structured result
26
+ * (`tool_use_result` on its `user` message) and, for a failed command, its
27
+ * text. A failure shows no diff. A command that succeeded carries no exit
28
+ * code: the CLI reports none, and counts some non-zero exits as success
29
+ * (`grep` finding nothing).
30
+ */
31
+ export function claudeResultView(toolName, structured, output, isError) {
32
+ if (isError) {
33
+ const code = toolName === "Bash" ? EXIT_CODE.exec(output)?.[1] : undefined;
34
+ return code !== undefined ? { metadata: { exitCode: Number(code) } } : {};
35
+ }
36
+ if (!isRecord(structured))
37
+ return {};
38
+ if (toolName === "Edit" || toolName === "Write") {
39
+ const path = structured.filePath;
40
+ if (typeof path !== "string")
41
+ return {};
42
+ if (structured.type === "create" && typeof structured.content === "string")
43
+ return {
44
+ content: [{ type: "diff", path, newText: structured.content }],
45
+ locations: [{ path }],
46
+ };
47
+ return Array.isArray(structured.structuredPatch)
48
+ ? patchView(path, structured.structuredPatch)
49
+ : {};
50
+ }
51
+ if (toolName === "NotebookEdit") {
52
+ const { notebook_path: path, old_source: oldText, new_source: newText } = structured;
53
+ if (typeof path !== "string" || typeof oldText !== "string" || typeof newText !== "string")
54
+ return {};
55
+ return { content: [{ type: "diff", path, oldText, newText }] };
56
+ }
57
+ return {};
58
+ }
@@ -0,0 +1,59 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { emitDiagnostic } from "../../diagnostics.js";
4
+ /** The pairs already said in this OS process: each is said once. */
5
+ const said = new Set();
6
+ /** A CLI build's platform package: `@anthropic-ai/claude-agent-sdk-<platform>`, the SDK's own numbering. */
7
+ const PLATFORM_PACKAGE = /^@anthropic-ai\/claude-agent-sdk-[a-z0-9-]+$/;
8
+ /**
9
+ * The release of the CLI build at `cliPath`: the version of the platform
10
+ * package it came in, whose manifest sits beside it (the provisioner's cache,
11
+ * a staged bundle, the package beside an installed SDK). Nothing for a CLI
12
+ * from anywhere else, which names no SDK release.
13
+ */
14
+ function cliBuildVersion(cliPath) {
15
+ try {
16
+ const manifest = JSON.parse(readFileSync(join(dirname(cliPath), "package.json"), "utf8"));
17
+ return typeof manifest.name === "string" &&
18
+ PLATFORM_PACKAGE.test(manifest.name) &&
19
+ typeof manifest.version === "string"
20
+ ? manifest.version
21
+ : undefined;
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ /**
28
+ * Say, once per OS process for each pair, that the Claude SDK that loaded and
29
+ * the CLI build it drives are different releases: a package manager let
30
+ * another SDK in (bun says nothing of an exact peer), or the CLI came from a
31
+ * pin the SDK did not follow. Call it right after `query()`: the SDK names
32
+ * itself there, in `process.env.CLAUDE_AGENT_SDK_VERSION`, from a literal in
33
+ * its own code, so a bundle names it too and no file is read for it. A
34
+ * warning, through `onDiagnostic` and the log; it never fails a turn, and an
35
+ * SDK or a CLI that cannot be named is not compared.
36
+ */
37
+ export function notePairedReleases(cliPath, onDiagnostic, sessionId) {
38
+ try {
39
+ const sdkVersion = process.env.CLAUDE_AGENT_SDK_VERSION;
40
+ const cliVersion = cliPath ? cliBuildVersion(cliPath) : undefined;
41
+ if (!sdkVersion || !cliVersion || sdkVersion === cliVersion)
42
+ return;
43
+ const pair = `${sdkVersion}\0${cliPath}\0${cliVersion}`;
44
+ if (said.has(pair))
45
+ return;
46
+ said.add(pair);
47
+ const message = `Claude SDK ${sdkVersion} drives the CLI build ${cliVersion} (${cliPath}): they are different releases, so the SDK may ask what this CLI does not know. Run the CLI build of the SDK's release (provision.pins.claude) or the SDK of the CLI's.`;
48
+ console.error(`[agent-server] ${message}`);
49
+ emitDiagnostic(onDiagnostic, {
50
+ type: "claudeSdkMismatch",
51
+ sessionId,
52
+ message,
53
+ detail: { sdkVersion, cliVersion, cliPath },
54
+ });
55
+ }
56
+ catch {
57
+ // A warning: nothing here may fail the turn.
58
+ }
59
+ }