@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvada/agent-server",
3
- "version": "0.3.23",
3
+ "version": "0.3.25",
4
4
  "description": "Harness-agnostic agent execution engine: run Claude Code, Codex (app-server), and any ACP agent behind one interface with a normalized event stream, multi-turn sessions, and resume. Root export is the wire contract; /core, /server, /client are the seats.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,7 +25,16 @@
25
25
  "engines": {
26
26
  "bun": ">=1.2.0"
27
27
  },
28
- "files": ["src", "dist/types", "docs", "AGENTS.md", "README.md", "CHANGELOG.md", "LICENSE"],
28
+ "files": [
29
+ "src",
30
+ "dist/types",
31
+ "dist/**/*.js",
32
+ "docs",
33
+ "AGENTS.md",
34
+ "README.md",
35
+ "CHANGELOG.md",
36
+ "LICENSE"
37
+ ],
29
38
  "publishConfig": {
30
39
  "access": "public"
31
40
  },
@@ -39,83 +48,99 @@
39
48
  ".": {
40
49
  "agent-server-source": "./src/index.ts",
41
50
  "types": "./dist/types/index.d.ts",
42
- "default": "./src/index.ts"
51
+ "bun": "./src/index.ts",
52
+ "default": "./dist/index.js"
43
53
  },
44
54
  "./protocol": {
45
55
  "agent-server-source": "./src/protocol/index.ts",
46
56
  "types": "./dist/types/protocol/index.d.ts",
47
- "default": "./src/protocol/index.ts"
57
+ "bun": "./src/protocol/index.ts",
58
+ "default": "./dist/protocol/index.js"
48
59
  },
49
60
  "./protocol/factories": {
50
61
  "agent-server-source": "./src/protocol/factories.ts",
51
62
  "types": "./dist/types/protocol/factories.d.ts",
52
- "default": "./src/protocol/factories.ts"
63
+ "bun": "./src/protocol/factories.ts",
64
+ "default": "./dist/protocol/factories.js"
53
65
  },
54
66
  "./protocol/guards": {
55
67
  "agent-server-source": "./src/protocol/guards.ts",
56
68
  "types": "./dist/types/protocol/guards.d.ts",
57
- "default": "./src/protocol/guards.ts"
69
+ "bun": "./src/protocol/guards.ts",
70
+ "default": "./dist/protocol/guards.js"
58
71
  },
59
72
  "./protocol/stop-reasons": {
60
73
  "agent-server-source": "./src/protocol/stop-reasons.ts",
61
74
  "types": "./dist/types/protocol/stop-reasons.d.ts",
62
- "default": "./src/protocol/stop-reasons.ts"
75
+ "bun": "./src/protocol/stop-reasons.ts",
76
+ "default": "./dist/protocol/stop-reasons.js"
63
77
  },
64
78
  "./protocol/seq-cursor": {
65
79
  "agent-server-source": "./src/protocol/seq-cursor.ts",
66
80
  "types": "./dist/types/protocol/seq-cursor.d.ts",
67
- "default": "./src/protocol/seq-cursor.ts"
81
+ "bun": "./src/protocol/seq-cursor.ts",
82
+ "default": "./dist/protocol/seq-cursor.js"
68
83
  },
69
84
  "./protocol/selectors": {
70
85
  "agent-server-source": "./src/protocol/selectors.ts",
71
86
  "types": "./dist/types/protocol/selectors.d.ts",
72
- "default": "./src/protocol/selectors.ts"
87
+ "bun": "./src/protocol/selectors.ts",
88
+ "default": "./dist/protocol/selectors.js"
73
89
  },
74
90
  "./core": {
75
91
  "agent-server-source": "./src/core/index.ts",
76
92
  "types": "./dist/types/core/index.d.ts",
77
- "default": "./src/core/index.ts"
93
+ "bun": "./src/core/index.ts",
94
+ "default": "./dist/core/index.js"
78
95
  },
79
96
  "./core/proxy": {
80
97
  "agent-server-source": "./src/core/proxy/index.ts",
81
98
  "types": "./dist/types/core/proxy/index.d.ts",
82
- "default": "./src/core/proxy/index.ts"
99
+ "bun": "./src/core/proxy/index.ts",
100
+ "default": "./dist/core/proxy/index.js"
83
101
  },
84
102
  "./server": {
85
103
  "agent-server-source": "./src/server/index.ts",
86
104
  "types": "./dist/types/server/index.d.ts",
87
- "default": "./src/server/index.ts"
105
+ "bun": "./src/server/index.ts",
106
+ "default": "./dist/server/index.js"
88
107
  },
89
108
  "./client": {
90
109
  "agent-server-source": "./src/client/index.ts",
91
110
  "types": "./dist/types/client/index.d.ts",
92
- "default": "./src/client/index.ts"
111
+ "bun": "./src/client/index.ts",
112
+ "default": "./dist/client/index.js"
93
113
  },
94
114
  "./accounts": {
95
115
  "agent-server-source": "./src/accounts/index.ts",
96
116
  "types": "./dist/types/accounts/index.d.ts",
97
- "default": "./src/accounts/index.ts"
117
+ "bun": "./src/accounts/index.ts",
118
+ "default": "./dist/accounts/index.js"
98
119
  },
99
120
  "./operator": {
100
121
  "agent-server-source": "./src/operator/index.ts",
101
122
  "types": "./dist/types/operator/index.d.ts",
102
- "default": "./src/operator/index.ts"
123
+ "bun": "./src/operator/index.ts",
124
+ "default": "./dist/operator/index.js"
103
125
  },
104
126
  "./package.json": "./package.json",
105
127
  "./sync": {
106
128
  "agent-server-source": "./src/sync/index.ts",
107
129
  "types": "./dist/types/sync/index.d.ts",
108
- "default": "./src/sync/index.ts"
130
+ "bun": "./src/sync/index.ts",
131
+ "default": "./dist/sync/index.js"
109
132
  },
110
133
  "./sync/sqlite": {
111
134
  "agent-server-source": "./src/sync/sqlite.ts",
112
135
  "types": "./dist/types/sync/sqlite.d.ts",
113
- "default": "./src/sync/sqlite.ts"
136
+ "bun": "./src/sync/sqlite.ts",
137
+ "default": "./dist/sync/sqlite.js"
114
138
  },
115
139
  "./sync/node-sqlite": {
116
140
  "agent-server-source": "./src/sync/node-sqlite.ts",
117
141
  "types": "./dist/types/sync/node-sqlite.d.ts",
118
- "default": "./src/sync/node-sqlite.ts"
142
+ "bun": "./src/sync/node-sqlite.ts",
143
+ "default": "./dist/sync/node-sqlite.js"
119
144
  }
120
145
  },
121
146
  "peerDependencies": {
@@ -121,6 +121,51 @@ function stopOn(handle: Handle, signal: AbortSignal | undefined): void {
121
121
  void handle.result.then(off, off);
122
122
  }
123
123
 
124
+ /** A `turn/start` this client has not sent yet: `gone` settles at its first send or its end. */
125
+ interface Start {
126
+ sessionId: string;
127
+ turnId: string;
128
+ gone: Promise<void>;
129
+ }
130
+
131
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — a cancel sent right behind its start reaches the turn
132
+ /**
133
+ * The `turn/start`s this client has not sent yet, each from before its
134
+ * first `await` until its first send or its end. The server takes a
135
+ * connection's requests in order and admits a turn in its start's handler,
136
+ * so a cancel for one of their turns goes out after that first send. Once
137
+ * sent, a start delays no cancel: after a redial a cancel can overtake its
138
+ * re-send, and is answered `no_active_turn`. Before its first send a start
139
+ * waits only on the handshake, a request the client's close fails, so no
140
+ * cancel waits past the close.
141
+ */
142
+ class Starts {
143
+ private readonly unsent = new Set<Start>();
144
+
145
+ /** Record a start; the function returned lets it go (its first send, or its end), and may be called again. */
146
+ begin(sessionId: string, turnId: string): () => void {
147
+ let settle = () => {};
148
+ const gone = new Promise<void>((resolve) => {
149
+ settle = resolve;
150
+ });
151
+ const start: Start = { sessionId, turnId, gone };
152
+ this.unsent.add(start);
153
+ return () => {
154
+ this.unsent.delete(start);
155
+ settle();
156
+ };
157
+ }
158
+
159
+ /** `send`, once no start of `turnId` (without one, of the session) is unsent; in the call when none is. */
160
+ after<T>(sessionId: string, turnId: string | undefined, send: () => Promise<T>): Promise<T> {
161
+ const waiting = [...this.unsent].filter(
162
+ (start) => start.sessionId === sessionId && (turnId === undefined || start.turnId === turnId),
163
+ );
164
+ if (waiting.length === 0) return send();
165
+ return Promise.all(waiting.map((start) => start.gone)).then(send);
166
+ }
167
+ }
168
+
124
169
  /** How often `prepareClis` asks again while an install runs, besides when one ends. */
125
170
  const PREPARE_POLL_MS = 2_000;
126
171
 
@@ -136,6 +181,7 @@ const PREPARE_POLL_MS = 2_000;
136
181
  export class AgentServerClient {
137
182
  private readonly connection: Connection;
138
183
  private readonly turns = new Turns();
184
+ private readonly starts = new Starts();
139
185
  private readonly progress = new Listeners<HarnessCliProgress>();
140
186
  private readonly authUpdates = new Listeners<AuthUpdated>();
141
187
  private readonly streams: Streams;
@@ -270,41 +316,50 @@ export class AgentServerClient {
270
316
  * it), and `onEvent` hears it to its end.
271
317
  */
272
318
  async runTurn(params: TurnStartParams, options: FollowOptions = {}): Promise<TurnHandle> {
273
- await this.initialize();
274
319
  const sessionId = params.sessionId ?? generateUUIDv7();
275
320
  const turnId = params.turnId ?? generateUUIDv7();
276
- if (this.turns.running(sessionId))
277
- throw new Error(`session ${sessionId} already has an active turn`);
278
- const handle = this.turns.open(sessionId, turnId, true);
279
- stopOn(handle, options.signal);
321
+ // Before the first `await`: a cancel sent right behind this call goes out after the start.
322
+ const release = this.starts.begin(sessionId, turnId);
280
323
  try {
281
- const accepted = await this.connection.resend(
282
- WIRE_METHODS.turnStart,
283
- { ...params, sessionId, turnId, subscribe: true },
284
- // A turn that already ended streams nothing: its end is in the ack.
285
- (ack) => {
286
- if (!ack.terminal) this.joinAt(handle, ack.headSeq, { turnId });
287
- },
288
- );
289
- const { terminal } = accepted;
290
- if (terminal && (terminal.sessionId !== sessionId || terminal.turnId !== turnId))
291
- throw new Error("Turn receipt belongs to a different request");
292
- // A retried start of a turn that already ended: its end, without its events
293
- // (`replay` or `history` serve its transcript).
294
- if (terminal) handle.push(terminal);
295
- else
296
- await this.catchUp(
297
- handle,
298
- accepted.deduplicated
299
- ? (accepted.startedSeq ?? accepted.headSeq + 1)
300
- : accepted.headSeq + 1,
301
- accepted.headSeq,
324
+ await this.initialize();
325
+ if (this.turns.running(sessionId))
326
+ throw new Error(`session ${sessionId} already has an active turn`);
327
+ const handle = this.turns.open(sessionId, turnId, true);
328
+ try {
329
+ stopOn(handle, options.signal);
330
+ // `resend` sends (or fails for no connection) before its first `await`, in this call.
331
+ const sending = this.connection.resend(
332
+ WIRE_METHODS.turnStart,
333
+ { ...params, sessionId, turnId, subscribe: true },
334
+ // A turn that already ended streams nothing: its end is in the ack.
335
+ (ack) => {
336
+ if (!ack.terminal) this.joinAt(handle, ack.headSeq, { turnId });
337
+ },
302
338
  );
303
- } catch (error) {
304
- handle.fail(error);
305
- throw error;
339
+ release();
340
+ const accepted = await sending;
341
+ const { terminal } = accepted;
342
+ if (terminal && (terminal.sessionId !== sessionId || terminal.turnId !== turnId))
343
+ throw new Error("Turn receipt belongs to a different request");
344
+ // A retried start of a turn that already ended: its end, without its events
345
+ // (`replay` or `history` serve its transcript).
346
+ if (terminal) handle.push(terminal);
347
+ else
348
+ await this.catchUp(
349
+ handle,
350
+ accepted.deduplicated
351
+ ? (accepted.startedSeq ?? accepted.headSeq + 1)
352
+ : accepted.headSeq + 1,
353
+ accepted.headSeq,
354
+ );
355
+ } catch (error) {
356
+ handle.fail(error);
357
+ throw error;
358
+ }
359
+ return this.handleOf(handle);
360
+ } finally {
361
+ release();
306
362
  }
307
- return this.handleOf(handle);
308
363
  }
309
364
 
310
365
  /**
@@ -313,17 +368,26 @@ export class AgentServerClient {
313
368
  * before.
314
369
  */
315
370
  async startTurn(params: TurnStartParams): Promise<TurnStartResult> {
316
- await this.initialize();
317
371
  const sessionId = params.sessionId ?? generateUUIDv7();
318
372
  const turnId = params.turnId ?? generateUUIDv7();
319
- return this.connection.request(
320
- WIRE_METHODS.turnStart,
321
- { ...params, sessionId, turnId },
322
- (ack) => {
323
- if (params.subscribe !== false && !ack.terminal)
324
- this.streams.joined(sessionId, ack.headSeq, { turnId });
325
- },
326
- );
373
+ // As in `runTurn`: a cancel sent right behind this call goes out after the start.
374
+ const release = this.starts.begin(sessionId, turnId);
375
+ try {
376
+ await this.initialize();
377
+ // `request` sends (or fails for no connection) in this call.
378
+ const answer = this.connection.request(
379
+ WIRE_METHODS.turnStart,
380
+ { ...params, sessionId, turnId },
381
+ (ack) => {
382
+ if (params.subscribe !== false && !ack.terminal)
383
+ this.streams.joined(sessionId, ack.headSeq, { turnId });
384
+ },
385
+ );
386
+ release();
387
+ return await answer;
388
+ } finally {
389
+ release();
390
+ }
327
391
  }
328
392
 
329
393
  /**
@@ -388,13 +452,19 @@ export class AgentServerClient {
388
452
  * finished turn then returns `{outcome: "no_active_turn", activeTurnId}`
389
453
  * instead of killing the turn that replaced it. `{outcome: "unconfirmed"}`
390
454
  * means the harness did not acknowledge the interrupt — the agent may still
391
- * be running; `turn.ended` remains the source of truth.
455
+ * be running; `turn.ended` remains the source of truth. A cancel for a
456
+ * turn this client is starting (`runTurn`, `startTurn`) goes out after
457
+ * that start's first send, so one sent right behind the start reaches the
458
+ * turn. After a reconnect a cancel can reach the server before a re-sent
459
+ * start, and is then answered `no_active_turn`.
392
460
  */
393
461
  cancelTurn(sessionId: string, turnId?: string): Promise<TurnCancelResult> {
394
- return this.connection.request(WIRE_METHODS.turnCancel, {
395
- sessionId,
396
- ...(turnId !== undefined ? { turnId } : {}),
397
- });
462
+ return this.starts.after(sessionId, turnId, () =>
463
+ this.connection.request(WIRE_METHODS.turnCancel, {
464
+ sessionId,
465
+ ...(turnId !== undefined ? { turnId } : {}),
466
+ }),
467
+ );
398
468
  }
399
469
 
400
470
  /** Answer a `permission.requested` event. */
@@ -15,7 +15,7 @@ import {
15
15
  } from "../elicitation.ts";
16
16
  import { PLAN_OPTIONS, PLAN_TITLE, approvedPlanMode } from "../plan.ts";
17
17
  import { type ClaudeToolPolicy, fromSdkPermissionMode, toSdkPermissionMode } from "./options.ts";
18
- import { claudeToolMeta } from "./tools.ts";
18
+ import { claudeMcpTool, claudeToolMeta } from "./tools.ts";
19
19
  import type { ClaudeTurn } from "./turn.ts";
20
20
 
21
21
  /** What a request needs of the turn it is asked in. */
@@ -69,6 +69,9 @@ export function createCanUseTool(deps: {
69
69
  }): CanUseTool {
70
70
  return async (toolName, input, options) => {
71
71
  const { signal, toolUseID, agentID, suggestions, blockedPath, decisionReason } = options;
72
+ // The policy gets the `mcp` the request will carry; the rest of the
73
+ // request's metadata is read after the policy, which may change `input`.
74
+ const mcp = claudeMcpTool(toolName, deps.mcpServers?.());
72
75
  // The host's policy sees every call first, questions and plans too: a
73
76
  // host answers a plan through its own channel (AGNT does). A policy
74
77
  // that wants the user to answer them returns undefined.
@@ -80,6 +83,7 @@ export function createCanUseTool(deps: {
80
83
  suggestions,
81
84
  blockedPath,
82
85
  decisionReason,
86
+ ...(mcp && { mcp }),
83
87
  });
84
88
  if (verdict) return verdict;
85
89
  const turn = deps.turn();
@@ -28,9 +28,16 @@ import {
28
28
  type ClaudeSessionPool,
29
29
  claudeSessionPool,
30
30
  } from "./session.ts";
31
+ import type { ClaudeTurn } from "./turn.ts";
31
32
 
32
33
  type ClaudeContent = SDKUserMessage["message"]["content"];
33
34
 
35
+ /**
36
+ * How long after a cancel a turn Claude has not ended has its process ended,
37
+ * unless `cancelGraceMs` says otherwise (LLP 0001, D9).
38
+ */
39
+ const CANCEL_GRACE_MS = 10_000;
40
+
34
41
  const CAPABILITIES: AgentCapabilities = {
35
42
  multiTurn: true,
36
43
  sessionResume: true,
@@ -117,9 +124,11 @@ export class ClaudeCodeAgent extends SessionAgent {
117
124
  readonly login: ClaudeCliLogin;
118
125
  private readonly pool: ClaudeSessionPool;
119
126
  private readonly credentials?: ClaudeCredentials;
127
+ private readonly cancelGraceMs: number;
120
128
 
121
129
  constructor(private readonly agentOptions: ClaudeCodeAgentOptions = {}) {
122
130
  super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
131
+ this.cancelGraceMs = agentOptions.cancelGraceMs ?? CANCEL_GRACE_MS;
123
132
  this.processes = agentOptions.processes ?? sharedNativeProcesses();
124
133
  this.pool = claudeSessionPool({ ...agentOptions, processes: this.processes });
125
134
  this.login = new ClaudeCliLogin({
@@ -151,11 +160,15 @@ export class ClaudeCodeAgent extends SessionAgent {
151
160
  controller: AbortController,
152
161
  ): AsyncIterableIterator<ClaudeRawEvent> {
153
162
  let held: ClaudeSession | undefined;
163
+ // The turn a cancel may interrupt, once it is sent.
164
+ let interruptible: ClaudeTurn | undefined;
154
165
  let unconfirmedSession: ClaudeSession | undefined;
155
166
  let removeInterrupt: (() => void) | undefined;
156
167
  // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — a start under way ends at the abort, at once
157
168
  // Until the turn has its process, the abort is the whole stop.
158
- this.cancelWith(options, async () => (held ? this.interrupt(held, options.sessionId) : true));
169
+ this.cancelWith(options, async () =>
170
+ held ? this.interrupt(held, interruptible, options.sessionId) : true,
171
+ );
159
172
  try {
160
173
  controller.signal.throwIfAborted();
161
174
  // @ref LLP 0010#a-turn-waits-for-its-cli-until-it-is-cancelled — the install is the server's
@@ -211,13 +224,17 @@ export class ClaudeCodeAgent extends SessionAgent {
211
224
  permissions: options.onPermissionRequest,
212
225
  elicitation: options.onElicitationRequest,
213
226
  });
227
+ interruptible = turn;
214
228
  try {
215
229
  await this.openSteering(options, (request) =>
216
230
  session.steer(toClaudeContent(request.input), request.steerId)
217
231
  ? "steered"
218
232
  : "no_active_turn",
219
233
  );
220
- removeInterrupt = onAbort(controller.signal, () => void session.interruptTurn());
234
+ removeInterrupt = onAbort(controller.signal, () => {
235
+ void session.interruptTurn();
236
+ void session.endUnstopped(turn, this.cancelGraceMs);
237
+ });
221
238
  const mcpServers = session.mcp.names;
222
239
  if (mcpServers.length) yield { type: "agentServer/mcpServers", names: mcpServers };
223
240
  let sawOutput = false;
@@ -324,10 +341,20 @@ export class ClaudeCodeAgent extends SessionAgent {
324
341
  * classifies as cancelled even when the generator drains to a natural end
325
342
  * before the SDK interrupt lands (the abort-order race that could surface
326
343
  * a clean user cancel as `error`/`end_turn`). The SDK interrupt's
327
- * round-trip is what confirms the cancel.
344
+ * round-trip confirms the cancel, and so does the turn's end, whoever ended
345
+ * it: Claude, or the grace that ended its process (`endUnstopped`). An
346
+ * interrupt that fails while the turn runs is unconfirmed at once.
328
347
  */
329
- private async interrupt(session: ClaudeSession, sessionId: string): Promise<boolean> {
330
- const interrupted = await session.interruptTurn();
348
+ private async interrupt(
349
+ session: ClaudeSession,
350
+ turn: ClaudeTurn | undefined,
351
+ sessionId: string,
352
+ ): Promise<boolean> {
353
+ // @ref LLP 0016.000#the-cancel-answer — a turn that ended is confirmed stopped, however it ended
354
+ const interrupting = session.interruptTurn();
355
+ const interrupted = turn
356
+ ? await Promise.race([interrupting, turn.ended.then(() => true)])
357
+ : await interrupting;
331
358
  if (!interrupted) {
332
359
  emitDiagnostic(this.agentOptions.onDiagnostic, {
333
360
  type: "interruptTimeout",
@@ -5,7 +5,7 @@ import type {
5
5
  PermissionUpdate,
6
6
  SettingSource,
7
7
  } from "@anthropic-ai/claude-agent-sdk";
8
- import type { PermissionMode } from "../../../protocol/index.ts";
8
+ import type { McpTool, PermissionMode } from "../../../protocol/index.ts";
9
9
  import type { DiagnosticHandler } from "../../diagnostics.ts";
10
10
  import type { NativeProcesses } from "../../processes/native-processes.ts";
11
11
  import type { AgentExecuteOptions } from "../base.ts";
@@ -72,6 +72,12 @@ export type ClaudeToolPolicy = (
72
72
  blockedPath?: string;
73
73
  /** The SDK's explanation for why this permission request fired, when it gives one. */
74
74
  decisionReason?: string;
75
+ /**
76
+ * An MCP tool's server and tool, as the permission request for this call
77
+ * names them (by the servers the session attached, so a server whose name
78
+ * holds `__` resolves); absent for a tool that is no MCP tool.
79
+ */
80
+ mcp?: McpTool;
75
81
  },
76
82
  ) => PermissionResult | undefined | Promise<PermissionResult | undefined>;
77
83
 
@@ -111,13 +117,19 @@ export interface ClaudeCodeAgentOptions {
111
117
  /** Idle time before an unused session's subprocess is shut down (default 5 minutes). */
112
118
  idleTimeoutMs?: number;
113
119
  /**
114
- * How long a cancel waits for Claude to acknowledge its interrupt before
115
- * it answers `confirmed: false` (`CANCEL_CONFIRM_MS`, 2 s, by default),
116
- * and how long a turn the runtime stopped reading has to end before its
117
- * process is replaced. An interrupt Claude never acknowledges leaves the
118
- * process and the turn running (LLP 0016, decision 11).
120
+ * How long a cancel waits for Claude to acknowledge its interrupt, or for
121
+ * its turn to end, before it answers `confirmed: false`
122
+ * (`CANCEL_CONFIRM_MS`, 2 s, by default), and how long a turn the runtime
123
+ * stopped reading has to end before its process is replaced.
119
124
  */
120
125
  cancelConfirmMs?: number;
126
+ /**
127
+ * How long after a cancel a turn Claude has not ended has its process
128
+ * ended (10 s by default); the turn then ends `cancelled`, `onSessionEnd`
129
+ * says `replaced`, and the session's next turn resumes the conversation
130
+ * on a new process (LLP 0001, D9).
131
+ */
132
+ cancelGraceMs?: number;
121
133
  /**
122
134
  * In-process MCP servers to attach to every session (the SDK's
123
135
  * `createSdkMcpServer` output). Called once per session spawn. Operator
@@ -135,11 +147,16 @@ export interface ClaudeCodeAgentOptions {
135
147
  /**
136
148
  * Called exactly once when a live session's subprocess ends, with why:
137
149
  * `idle` (idle-timeout eviction), `replaced` (config change or host resume
138
- * required a new process), `released` (explicit release/close), `shutdown`
139
- * (terminateAll). The seam for host-managed per-session resources — BYOK
140
- * proxy keys, recorders — instead of re-deriving termination from side
141
- * effects. NOTE: `replaced` sessions usually respawn immediately with
142
- * context preserved; drop only resources bound to the dead subprocess.
150
+ * required a new process, or a cancelled turn outlived `cancelGraceMs`),
151
+ * `released` (explicit release/close), `shutdown` (terminateAll). The
152
+ * seam for host-managed per-session resources — BYOK proxy keys,
153
+ * recorders — instead of re-deriving termination from side effects.
154
+ * NOTE: `replaced` sessions usually respawn immediately with context
155
+ * preserved; drop only resources bound to the dead subprocess.
156
+ * A cancel during a start answers at once; this callback for that
157
+ * process (`released`, as for a close) can come after the cancel's
158
+ * answer, and comes before that turn's end: set up the next turn's
159
+ * per-session resources after the turn's end, not the cancel's answer.
143
160
  */
144
161
  onSessionEnd?: (sessionId: string, reason: ClaudeSessionEndReason) => void;
145
162
  /** Operational diagnostics (interrupt timeouts). */
@@ -378,6 +378,19 @@ export class ClaudeSession implements PooledProcess, PooledClient {
378
378
  if (this.turn === turn) await this.terminate("replaced");
379
379
  }
380
380
 
381
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — cancelGraceMs: an agent that has not stopped is ended
382
+ /**
383
+ * End the process of a cancelled `turn` that has not ended within
384
+ * `graceMs`: Claude did not stop it (a frozen or hung CLI), and nothing
385
+ * else would. The turn's events end, so it ends cancelled, and the pool
386
+ * hears `replaced` (`onSessionEnd`); the next turn resumes on a new
387
+ * process. A turn that ended, and any turn after it, is left alone.
388
+ */
389
+ async endUnstopped(turn: ClaudeTurn, graceMs: number): Promise<void> {
390
+ if ((await withTimeout(turn.ended, graceMs)) === undefined && this.turn === turn)
391
+ await this.terminate("replaced");
392
+ }
393
+
381
394
  private async interrupt(turn: ClaudeTurn | undefined, timeoutMs: number): Promise<boolean> {
382
395
  if (this.state === "idle" || this.state === "terminated") return true;
383
396
  if (this.state === "starting" || !this.cliStarted || !this.query) {
@@ -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) {}