@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
@@ -0,0 +1,245 @@
1
+ import { NO_ANSWERS, inputReply, inputRequest, questionRequest, unanswered, } from "../elicitation.js";
2
+ import { PLAN_OPTIONS, PLAN_TITLE, approvedPlanMode } from "../plan.js";
3
+ import { fromSdkPermissionMode, toSdkPermissionMode } from "./options.js";
4
+ import { claudeMcpTool, claudeToolMeta } from "./tools.js";
5
+ /** What Claude is told when it asks while no turn runs. */
6
+ const NO_TURN = "No turn is running, so nobody can answer this.";
7
+ /** The SDK's warning, at `query()`, that its spawn options shadow `canUseTool`. */
8
+ const CALLBACK_SHADOWED = "CLAUDE_SDK_CAN_USE_TOOL_SHADOWED";
9
+ /**
10
+ * Start a session's query. Under `bypassPermissions` the SDK warns that
11
+ * `canUseTool` is never asked, but Claude still asks it about what needs a
12
+ * person (AskUserQuestion, ExitPlanMode), which is what the callback is for:
13
+ * that warning is left off the host's stderr, where it would print a stack at
14
+ * every spawn. Any other warning, and this one in any other mode, passes.
15
+ */
16
+ export function startQuery(permissionMode, start) {
17
+ if (permissionMode !== "bypassPermissions")
18
+ return start();
19
+ const emit = process.emitWarning;
20
+ process.emitWarning = ((warning, ...rest) => {
21
+ if (rest[0]?.code === CALLBACK_SHADOWED)
22
+ return;
23
+ emit.call(process, warning, ...rest);
24
+ });
25
+ try {
26
+ return start();
27
+ }
28
+ finally {
29
+ process.emitWarning = emit;
30
+ }
31
+ }
32
+ /**
33
+ * The SDK approval callback, fixed at spawn: it asks the turn running when it
34
+ * is called, which Claude does for a call its mode and rules do not approve
35
+ * by themselves (under `bypass_permissions`, only questions and plans). The
36
+ * host `toolPolicy` sees each such call first (full native PermissionResult
37
+ * power), questions and plans included; a call it leaves
38
+ * (`undefined`) goes to the turn: a question to its elicitation, a plan or a
39
+ * tool's approval to its interactive broker. The SDK passes a REAL
40
+ * `toolUseID` (>=0.2.138), so brokered requests correlate to their tool parts
41
+ * exactly.
42
+ */
43
+ export function createCanUseTool(deps) {
44
+ return async (toolName, input, options) => {
45
+ const { signal, toolUseID, agentID, suggestions, blockedPath, decisionReason } = options;
46
+ // The policy gets the `mcp` the request will carry; the rest of the
47
+ // request's metadata is read after the policy, which may change `input`.
48
+ const mcp = claudeMcpTool(toolName, deps.mcpServers?.());
49
+ // The host's policy sees every call first, questions and plans too: a
50
+ // host answers a plan through its own channel (AGNT does). A policy
51
+ // that wants the user to answer them returns undefined.
52
+ const verdict = await deps.policy?.(toolName, input, {
53
+ sessionId: deps.sessionId,
54
+ toolUseId: toolUseID,
55
+ agentId: agentID,
56
+ signal,
57
+ suggestions,
58
+ blockedPath,
59
+ decisionReason,
60
+ ...(mcp && { mcp }),
61
+ });
62
+ if (verdict)
63
+ return verdict;
64
+ const turn = deps.turn();
65
+ // Between turns Claude runs only a query it began itself, which no turn
66
+ // on the stream shows: nobody can be asked, so Claude stops.
67
+ if (!turn)
68
+ return { behavior: "deny", message: NO_TURN, interrupt: true };
69
+ // @ref LLP 0001#d12--what-the-agent-asks-the-user-is-first-class-protocol-opted-into-per-turn — a question is not an approval
70
+ if (toolName === "AskUserQuestion") {
71
+ return answerQuestions(input, toolUseID, turn.elicitation, signal);
72
+ }
73
+ /**
74
+ * Put the call to the turn's user. Undefined: the turn has no broker (one
75
+ * driven outside the runtime), so Claude's mode alone decides and the call runs.
76
+ */
77
+ const ask = async (title, opts) => {
78
+ if (!turn.permissions)
79
+ return undefined;
80
+ // @ref LLP 0002#a-tool-call-says-what-it-acts-on — why Claude asks is `reason`, in the CLI's words
81
+ const toolCall = {
82
+ toolCallId: toolUseID,
83
+ toolName,
84
+ ...(title && { title }),
85
+ ...(decisionReason && { reason: decisionReason }),
86
+ rawInput: input,
87
+ ...claudeToolMeta(toolName, input, deps.mcpServers?.()),
88
+ };
89
+ const decision = await turn.permissions(toolCall, { signal, ...opts });
90
+ // A request Claude withdrew itself (a hook decided first) is not a cancel.
91
+ if (decision.decision === "cancel" && !signal.aborted)
92
+ turn.cancelByRequest();
93
+ return decision;
94
+ };
95
+ if (toolName === "ExitPlanMode") {
96
+ return planVerdict(await ask(PLAN_TITLE, { options: PLAN_OPTIONS }), input);
97
+ }
98
+ // @ref LLP 0001#d4--permission-requests-are-first-class-protocol — "always" is Claude's own rule
99
+ // "Always" is the rule Claude suggests (`Bash(npm test *)`, accept-edits
100
+ // mode, a directory), which Claude keeps for this session, never in the
101
+ // user's settings files. Claude says when no rule would be as narrow as
102
+ // the call (`suppressAlwaysAllowRule`), and a call the user's own ask rule
103
+ // forced is a person's to answer each time: neither offers "always", nor
104
+ // does a call Claude suggests nothing for.
105
+ const { suppressAlwaysAllowRule, matchedAskRule } = options;
106
+ const scoped = suggestions?.length && !suppressAlwaysAllowRule && matchedAskRule === undefined
107
+ ? suggestions
108
+ : undefined;
109
+ const decision = await ask(undefined, {
110
+ always: scoped ? { rule: describeRules(scoped) } : null,
111
+ });
112
+ return toolVerdict(decision, input, scoped);
113
+ };
114
+ }
115
+ /** Claude's answer to a tool call, from the user's decision. */
116
+ function toolVerdict(decision, input, scoped) {
117
+ if (!decision)
118
+ return { behavior: "allow", updatedInput: input };
119
+ if (decision.decision === "allow") {
120
+ // What was approved is what runs: an edited input from the broker
121
+ // replaces the original (silent divergence between the approved and
122
+ // executed input is the worst failure mode in an approval path).
123
+ return {
124
+ behavior: "allow",
125
+ updatedInput: decision.updatedInput ?? input,
126
+ ...(decision.optionId === "allow_always" &&
127
+ scoped && {
128
+ updatedPermissions: scoped.map((s) => ({ ...s, destination: "session" })),
129
+ }),
130
+ };
131
+ }
132
+ return {
133
+ behavior: "deny",
134
+ message: decision.decision === "deny" && decision.message
135
+ ? `${REJECTED} To tell you how to proceed, the user said:\n${decision.message}`
136
+ : (decision.decision === "deny" && decision.reason) || "Denied by user",
137
+ interrupt: decision.decision === "cancel",
138
+ };
139
+ }
140
+ /** What Claude's suggested permission updates cover, as a person reads it. */
141
+ function describeRules(updates) {
142
+ return updates
143
+ .map((u) => {
144
+ switch (u.type) {
145
+ case "addRules":
146
+ case "replaceRules":
147
+ return u.rules
148
+ .map((r) => (r.ruleContent ? `${r.toolName}(${r.ruleContent})` : r.toolName))
149
+ .join(", ");
150
+ case "setMode":
151
+ return u.mode === "acceptEdits"
152
+ ? "edits: accept_edits mode, where file edits and file commands in your folders run without asking"
153
+ : `${fromSdkPermissionMode(u.mode) ?? u.mode} mode`;
154
+ case "addDirectories":
155
+ return `access to ${u.directories.join(", ")}`;
156
+ default:
157
+ return u.type;
158
+ }
159
+ })
160
+ .join("; ");
161
+ }
162
+ /** Claude Code's own words for a tool call the user rejected. */
163
+ const REJECTED = "The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file).";
164
+ /**
165
+ * Claude's ExitPlanMode: its plan, put to the user. Approving picks the mode
166
+ * Claude implements in, in the same turn; keeping planning tells Claude what
167
+ * the user said, in Claude Code's own words.
168
+ */
169
+ function planVerdict(decision, input) {
170
+ if (!decision)
171
+ return { behavior: "allow", updatedInput: input };
172
+ if (decision.decision === "allow") {
173
+ const mode = toSdkPermissionMode(approvedPlanMode(decision.optionId)) ?? "default";
174
+ return {
175
+ behavior: "allow",
176
+ updatedInput: decision.updatedInput ?? input,
177
+ updatedPermissions: [{ type: "setMode", mode, destination: "session" }],
178
+ };
179
+ }
180
+ if (decision.decision === "cancel") {
181
+ return { behavior: "deny", message: "Denied by user", interrupt: true };
182
+ }
183
+ return {
184
+ behavior: "deny",
185
+ message: decision.message
186
+ ? `The user doesn't want to proceed with this plan yet. To tell you how to proceed, the user said:\n${decision.message}`
187
+ : "The user doesn't want to proceed with this plan. STOP what you are doing and wait for the user to tell you how to proceed.",
188
+ };
189
+ }
190
+ /**
191
+ * Claude's AskUserQuestion, asked through the turn's elicitation broker. The
192
+ * answers go back as the tool's `answers` input, keyed by question text, which
193
+ * is how the tool reads them; without a broker Claude is told to carry on.
194
+ */
195
+ async function answerQuestions(input, toolUseID, handler, signal) {
196
+ const asked = (input.questions ?? []).filter((q) => typeof q.question === "string");
197
+ if (!handler || asked.length === 0)
198
+ return { behavior: "deny", message: NO_ANSWERS };
199
+ const questions = asked.map((q, i) => ({
200
+ id: `q${i + 1}`,
201
+ question: q.question,
202
+ ...(typeof q.header === "string" && { header: q.header }),
203
+ ...(q.options?.length && {
204
+ options: q.options.map((o) => ({
205
+ label: String(o.label ?? ""),
206
+ ...(typeof o.description === "string" && { description: o.description }),
207
+ })),
208
+ }),
209
+ ...(q.multiSelect === true && { multiSelect: true }),
210
+ // Claude's tool always takes an answer in the user's own words.
211
+ allowOther: true,
212
+ }));
213
+ const outcome = await handler(questionRequest(questions, toolUseID), { signal });
214
+ if (outcome.action !== "accept") {
215
+ return { behavior: "deny", message: unanswered(outcome.action), interrupt: signal.aborted };
216
+ }
217
+ // A question the user skipped stays unanswered: an empty string would read
218
+ // as an answer.
219
+ const content = outcome.content ?? {};
220
+ const answers = Object.fromEntries(questions.flatMap((q) => {
221
+ const value = content[q.id];
222
+ const answer = Array.isArray(value) ? value.join(", ") : value == null ? "" : String(value);
223
+ return answer ? [[q.question, answer]] : [];
224
+ }));
225
+ return { behavior: "allow", updatedInput: { ...input, answers } };
226
+ }
227
+ /**
228
+ * MCP elicitation from Claude's servers (a form, or a URL to visit), asked
229
+ * through the turn's elicitation broker; declined when its client cannot
230
+ * answer.
231
+ */
232
+ export function createOnElicitation(turn) {
233
+ return async (request, { signal }) => {
234
+ const current = turn();
235
+ // Between turns nobody can be asked. The request is dismissed (`cancel`),
236
+ // as a turn's end resolves a request it left open (LLP 0001, D12), not
237
+ // declined: nobody refused it, and the server may ask again in a turn.
238
+ if (!current)
239
+ return { action: "cancel" };
240
+ if (!current.elicitation)
241
+ return { action: "decline" };
242
+ const asked = inputRequest({ ...request, mode: request.mode ?? "form" });
243
+ return inputReply(await current.elicitation(asked, { signal }));
244
+ };
245
+ }
@@ -0,0 +1,319 @@
1
+ import { emitDiagnostic } from "../../diagnostics.js";
2
+ import { sharedNativeProcesses } from "../../processes/native-processes.js";
3
+ import { onAbort, untilAborted } from "../../utils/deadline.js";
4
+ import { SessionResumeError } from "../../utils/errors.js";
5
+ import { UnsupportedAttachmentError, attachedText, isTextMedia } from "../attachments.js";
6
+ import { SessionAgent } from "../session-agent.js";
7
+ import { ClaudeCredentials, ON_PLACEHOLDER } from "./credentials.js";
8
+ import { ClaudeCliLogin } from "./login.js";
9
+ import { claudeModelDescriptors, fitClaudeThinking, readClaudeModels } from "./models.js";
10
+ import { claudeSessionConfig } from "./options.js";
11
+ import { claudeSessionPool, } from "./session.js";
12
+ /**
13
+ * How long after a cancel a turn Claude has not ended has its process ended,
14
+ * unless `cancelGraceMs` says otherwise (LLP 0001, D9).
15
+ */
16
+ const CANCEL_GRACE_MS = 10_000;
17
+ const CAPABILITIES = {
18
+ multiTurn: true,
19
+ sessionResume: true,
20
+ modelSwitch: "in_session",
21
+ thinkingLevels: true,
22
+ images: true,
23
+ // What `toClaudeContent` sends: PDFs as base64 documents, text as text ones.
24
+ files: ["text", "pdf"],
25
+ mcpServers: true,
26
+ permissionRequests: true,
27
+ // A denial tells Claude what the user said (`approvals.ts`).
28
+ rejectionMessages: true,
29
+ turnScopedSubagents: true,
30
+ steering: true,
31
+ // Every turn setting reaches the SDK (`buildClaudeOptions`).
32
+ ignoredSettings: [],
33
+ };
34
+ /**
35
+ * Our normalized input as Claude message content. The API takes images as data
36
+ * or web URLs and documents as PDF data, plain text or a URL; any other
37
+ * attachment fails the turn instead of reaching Claude unreadable.
38
+ */
39
+ export function toClaudeContent(input) {
40
+ if (typeof input === "string")
41
+ return input;
42
+ const blocks = input.map((part) => {
43
+ if (part.type === "text")
44
+ return { type: "text", text: part.text };
45
+ // `file` inputs (PDFs, text) are document blocks, not images.
46
+ const type = part.type === "file" ? "document" : "image";
47
+ if (part.url !== undefined) {
48
+ if (!/^https?:\/\//i.test(part.url)) {
49
+ throw new UnsupportedAttachmentError(`Claude takes attachments as data or http(s) URLs, not ${part.url}`);
50
+ }
51
+ return { type, source: { type: "url", url: part.url } };
52
+ }
53
+ const data = part.data ?? "";
54
+ if (part.type === "image") {
55
+ return { type, source: { type: "base64", media_type: part.mimeType, data } };
56
+ }
57
+ const title = part.filename ? { title: part.filename } : {};
58
+ if (part.mimeType === "application/pdf") {
59
+ return { type, source: { type: "base64", media_type: part.mimeType, data }, ...title };
60
+ }
61
+ if (isTextMedia(part.mimeType)) {
62
+ const text = attachedText(data);
63
+ return { type, source: { type: "text", media_type: "text/plain", data: text }, ...title };
64
+ }
65
+ throw new UnsupportedAttachmentError(`Claude cannot take ${part.mimeType} file attachments; send text, a PDF or an image`);
66
+ });
67
+ // Kept cast: the SDK's block sources require literal media_type unions
68
+ // ("image/jpeg" | ... and "application/pdf") while our PartInput carries an
69
+ // open string mimeType, so these blocks cannot satisfy the union as typed.
70
+ return blocks;
71
+ }
72
+ /**
73
+ * The SDK shape of a hard resume failure: the turn dies with
74
+ * `error_during_execution` and a null stop reason before any output. (An
75
+ * interrupt produces the same result message — callers must also check that no
76
+ * interrupt was requested.)
77
+ */
78
+ export function claudeResumeFailed(event) {
79
+ return (event.type === "result" &&
80
+ event.subtype === "error_during_execution" &&
81
+ event.stop_reason === null);
82
+ }
83
+ /**
84
+ * Claude Code harness. Reuses a warm `query()` per logical session for fast
85
+ * in-session multi-turn and model hot-swap; falls back to SDK `resume` when a
86
+ * session must be reconstructed (e.g. after idle eviction or across processes).
87
+ */
88
+ export class ClaudeCodeAgent extends SessionAgent {
89
+ agentOptions;
90
+ harness = "claude-code";
91
+ capabilities = CAPABILITIES;
92
+ /** Its CLIs start here: the runtime's, or this OS process's own when it was made without one. */
93
+ processes;
94
+ login;
95
+ pool;
96
+ credentials;
97
+ cancelGraceMs;
98
+ constructor(agentOptions = {}) {
99
+ super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
100
+ this.agentOptions = agentOptions;
101
+ this.cancelGraceMs = agentOptions.cancelGraceMs ?? CANCEL_GRACE_MS;
102
+ this.processes = agentOptions.processes ?? sharedNativeProcesses();
103
+ this.pool = claudeSessionPool({ ...agentOptions, processes: this.processes });
104
+ this.login = new ClaudeCliLogin({
105
+ resolveCliPath: agentOptions.resolveCliPath,
106
+ processes: this.processes,
107
+ inheritConfig: agentOptions.inheritConfig,
108
+ });
109
+ if (agentOptions.credentials)
110
+ this.credentials = new ClaudeCredentials(agentOptions.credentials);
111
+ }
112
+ /** Options on a credential the product holds, when it holds one. */
113
+ withDelivery(options, delivery) {
114
+ return delivery
115
+ ? { ...options, apiKey: delivery.apiKey, env: { ...options.env, ...delivery.env } }
116
+ : options;
117
+ }
118
+ loginChanged(store) {
119
+ this.pool.loginChanged(store);
120
+ }
121
+ async *executeTurn(input, options, controller) {
122
+ let held;
123
+ // The turn a cancel may interrupt, once it is sent.
124
+ let interruptible;
125
+ let unconfirmedSession;
126
+ let removeInterrupt;
127
+ // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — a start under way ends at the abort, at once
128
+ // Until the turn has its process, the abort is the whole stop.
129
+ this.cancelWith(options, async () => held ? this.interrupt(held, interruptible, options.sessionId) : true);
130
+ try {
131
+ controller.signal.throwIfAborted();
132
+ // @ref LLP 0010#a-turn-waits-for-its-cli-until-it-is-cancelled — the install is the server's
133
+ const { resolveCliPath } = this.agentOptions;
134
+ const cliPath = resolveCliPath && (await untilAborted(resolveCliPath(), controller.signal));
135
+ const content = toClaudeContent(input);
136
+ controller.signal.throwIfAborted();
137
+ const thinking = fitClaudeThinking(options.thinkingLevel, options.modelThinking);
138
+ const turnOptions = this.withDelivery(options, await this.credentials?.forTurn(options.sessionId, options.turnId, controller.signal));
139
+ controller.signal.throwIfAborted();
140
+ const wanted = {
141
+ sessionId: options.sessionId,
142
+ config: claudeSessionConfig({ ...turnOptions, thinkingLevel: thinking.send }, cliPath, this.agentOptions.inheritConfig),
143
+ };
144
+ const session = await this.pool.acquire(options.sessionId, wanted, controller.signal);
145
+ held = session;
146
+ const spawned = wanted.spawned === true;
147
+ if (thinking.applied && !session.operatorThinking)
148
+ options.onExecution?.({ thinkingLevel: thinking.applied });
149
+ const notApplied = [];
150
+ // A model known to have no effort levels is sent no level (`fitClaudeThinking`).
151
+ if (options.thinkingLevel !== undefined && thinking.send === undefined)
152
+ notApplied.push("thinkingLevel");
153
+ // A message to resume at goes only with a resume (`buildClaudeOptions`).
154
+ if (options.resumeSessionAt && !options.resumeSessionId)
155
+ notApplied.push("resumeSessionAt");
156
+ if (notApplied.length)
157
+ options.onExecution?.({ notApplied });
158
+ const attemptedResume = spawned && Boolean(options.resumeSessionId);
159
+ if (spawned)
160
+ unconfirmedSession = session;
161
+ // A cancel during connection repair must never submit the prompt.
162
+ controller.signal.throwIfAborted();
163
+ // The turn goes on without a server it does not require, and says so.
164
+ await session.mcp.unavailable.announce(options.onWarning);
165
+ // A cancel while it said so must never submit the prompt either.
166
+ controller.signal.throwIfAborted();
167
+ let reported = false;
168
+ const report = (id) => {
169
+ if (reported)
170
+ return;
171
+ options.onNativeSession?.(id, { resumed: Boolean(options.resumeSessionId) });
172
+ reported = true;
173
+ unconfirmedSession = undefined;
174
+ };
175
+ // A resume is only confirmed once the backend produces output.
176
+ if (!attemptedResume && session.currentSessionId)
177
+ report(session.currentSessionId);
178
+ const turn = session.sendMessage(content, {
179
+ turnId: options.turnId,
180
+ permissions: options.onPermissionRequest,
181
+ elicitation: options.onElicitationRequest,
182
+ });
183
+ interruptible = turn;
184
+ try {
185
+ await this.openSteering(options, (request) => session.steer(toClaudeContent(request.input), request.steerId)
186
+ ? "steered"
187
+ : "no_active_turn");
188
+ removeInterrupt = onAbort(controller.signal, () => {
189
+ void session.interruptTurn();
190
+ void session.endUnstopped(turn, this.cancelGraceMs);
191
+ });
192
+ const mcpServers = session.mcp.names;
193
+ if (mcpServers.length)
194
+ yield { type: "agentServer/mcpServers", names: mcpServers };
195
+ let sawOutput = false;
196
+ for await (const event of turn.events) {
197
+ if (event.type === "assistant" || event.type === "stream_event")
198
+ sawOutput = true;
199
+ if (attemptedResume &&
200
+ !sawOutput &&
201
+ !controller.signal.aborted &&
202
+ claudeResumeFailed(event)) {
203
+ const reason = event.errors?.join("; ") || "Claude failed before loading the conversation";
204
+ throw new SessionResumeError(session.currentConfig.resumeSessionId, reason, {
205
+ cause: new Error(reason),
206
+ });
207
+ }
208
+ const nativeId = "session_id" in event ? event.session_id : undefined;
209
+ const succeeded = event.type === "result" && event.subtype === "success";
210
+ if (nativeId && (!attemptedResume || sawOutput || succeeded))
211
+ report(nativeId);
212
+ yield event;
213
+ }
214
+ if (attemptedResume && unconfirmedSession && !controller.signal.aborted) {
215
+ throw new SessionResumeError(session.currentConfig.resumeSessionId, "Claude ended before confirming the conversation was loaded");
216
+ }
217
+ // Ground truth for the adapter: an interrupted turn and a turn that
218
+ // failed during execution (e.g. a bad resume id) end with the SAME
219
+ // result shape (error_during_execution, null stop_reason). Only the
220
+ // agent knows whether an interrupt was actually requested.
221
+ if (controller.signal.aborted || turn.cancelled)
222
+ yield { type: "agentServer/turnInterrupted" };
223
+ }
224
+ finally {
225
+ // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — through the native turn's end
226
+ // The reservation ends when this generator does: a turn the runtime
227
+ // stopped reading (a transformer or a sink that failed) is stopped
228
+ // first, so the next turn never meets it running and a cancel still
229
+ // reaches it meanwhile.
230
+ await session.stopTurn(turn);
231
+ }
232
+ }
233
+ catch (error) {
234
+ if (!controller.signal.aborted)
235
+ throw error;
236
+ yield { type: "agentServer/turnInterrupted" };
237
+ }
238
+ finally {
239
+ removeInterrupt?.();
240
+ // The product's credential is held while a turn runs, and no longer.
241
+ this.credentials?.endTurn(options.sessionId);
242
+ // A cancelled/failed preparation must not leave an unconfirmed query
243
+ // looking like a healthy warm conversation on the next attempt.
244
+ await unconfirmedSession?.terminate();
245
+ // A warm one waits for the next turn, at most the idle time.
246
+ if (held)
247
+ this.pool.leave(options.sessionId, held);
248
+ }
249
+ }
250
+ checkSteerInput(input) {
251
+ toClaudeContent(input);
252
+ }
253
+ /** The models this login offers in `options.cwd`, from the Claude Code CLI. */
254
+ async listModels(listing) {
255
+ const cliPath = await this.agentOptions.resolveCliPath?.();
256
+ // On a product's credentials the CLI holds the placeholder, which alone decides its list.
257
+ const options = this.withDelivery(listing, this.credentials && ON_PLACEHOLDER);
258
+ options.signal?.throwIfAborted();
259
+ const models = await readClaudeModels({
260
+ cwd: options.cwd,
261
+ env: options.env,
262
+ apiKey: options.apiKey,
263
+ cliPath,
264
+ inheritConfig: this.agentOptions.inheritConfig,
265
+ }, this.processes, options.signal);
266
+ return claudeModelDescriptors(models);
267
+ }
268
+ /**
269
+ * Hot-swap the live session's wire MCP servers without a restart (context
270
+ * intact). A session still starting takes it once ready, after the servers
271
+ * its turn attaches. Returns undefined when the session isn't live. In-process servers
272
+ * are preserved across swaps. The next turn's own `mcpServers` swap back
273
+ * when they still name the old set: keep them in step.
274
+ */
275
+ async setMcpServers(sessionId, servers) {
276
+ return this.pool.client(sessionId)?.setMcpServers(servers);
277
+ }
278
+ /** Resume saved history in a fresh subprocess on the next turn after host suspension. */
279
+ invalidateMcpConnections() {
280
+ this.pool.invalidate();
281
+ }
282
+ /**
283
+ * Interrupt the turn's process for a cancel, which has already aborted the
284
+ * turn: the controller ends the engine's execute loop, so this turn
285
+ * classifies as cancelled even when the generator drains to a natural end
286
+ * before the SDK interrupt lands (the abort-order race that could surface
287
+ * a clean user cancel as `error`/`end_turn`). The SDK interrupt's
288
+ * round-trip confirms the cancel, and so does the turn's end, whoever ended
289
+ * it: Claude, or the grace that ended its process (`endUnstopped`). An
290
+ * interrupt that fails while the turn runs is unconfirmed at once.
291
+ */
292
+ async interrupt(session, turn, sessionId) {
293
+ // @ref LLP 0016.000#the-cancel-answer — a turn that ended is confirmed stopped, however it ended
294
+ const interrupting = session.interruptTurn();
295
+ const interrupted = turn
296
+ ? await Promise.race([interrupting, turn.ended.then(() => true)])
297
+ : await interrupting;
298
+ if (!interrupted) {
299
+ emitDiagnostic(this.agentOptions.onDiagnostic, {
300
+ type: "interruptTimeout",
301
+ sessionId,
302
+ message: "cancel dispatched but the SDK interrupt was not acknowledged in time",
303
+ });
304
+ }
305
+ return interrupted;
306
+ }
307
+ async release(sessionId) {
308
+ await super.release(sessionId);
309
+ await this.pool.release(sessionId);
310
+ this.credentials?.release(sessionId);
311
+ }
312
+ async terminateAll() {
313
+ // Before the turns are aborted: a start under way ends for shutdown, not as a cancel.
314
+ const closed = this.pool.closeAll();
315
+ await super.terminateAll();
316
+ await closed;
317
+ await this.credentials?.close();
318
+ }
319
+ }