@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.28

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 (364) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +716 -2
  5. package/dist/ablation.d.ts +2 -0
  6. package/dist/ablation.js +3 -0
  7. package/dist/ablation.js.map +1 -0
  8. package/dist/completion/check.d.ts +64 -0
  9. package/dist/completion/check.js +152 -0
  10. package/dist/completion/check.js.map +1 -0
  11. package/dist/completion/checks.d.ts +45 -0
  12. package/dist/completion/checks.js +173 -0
  13. package/dist/completion/checks.js.map +1 -0
  14. package/dist/completion/flags.d.ts +25 -0
  15. package/dist/completion/flags.js +87 -0
  16. package/dist/completion/flags.js.map +1 -0
  17. package/dist/completion/index.d.ts +8 -0
  18. package/dist/completion/index.js +9 -0
  19. package/dist/completion/index.js.map +1 -0
  20. package/dist/completion/snapshot.d.ts +33 -0
  21. package/dist/completion/snapshot.js +83 -0
  22. package/dist/completion/snapshot.js.map +1 -0
  23. package/dist/context/cap.d.ts +32 -0
  24. package/dist/context/cap.js +50 -0
  25. package/dist/context/cap.js.map +1 -0
  26. package/dist/context/estimate.d.ts +18 -0
  27. package/dist/context/estimate.js +20 -0
  28. package/dist/context/estimate.js.map +1 -0
  29. package/dist/context/file-spill.d.ts +5 -0
  30. package/dist/context/file-spill.js +25 -0
  31. package/dist/context/file-spill.js.map +1 -0
  32. package/dist/context/index.d.ts +10 -0
  33. package/dist/context/index.js +10 -0
  34. package/dist/context/index.js.map +1 -0
  35. package/dist/context/mask.d.ts +27 -0
  36. package/dist/context/mask.js +71 -0
  37. package/dist/context/mask.js.map +1 -0
  38. package/dist/context/mid-turn.d.ts +40 -0
  39. package/dist/context/mid-turn.js +82 -0
  40. package/dist/context/mid-turn.js.map +1 -0
  41. package/dist/context/policy.d.ts +9 -0
  42. package/dist/context/policy.js +140 -0
  43. package/dist/context/policy.js.map +1 -0
  44. package/dist/context/spill-ledger.d.ts +25 -0
  45. package/dist/context/spill-ledger.js +54 -0
  46. package/dist/context/spill-ledger.js.map +1 -0
  47. package/dist/context/spill.d.ts +6 -0
  48. package/dist/context/spill.js +14 -0
  49. package/dist/context/spill.js.map +1 -0
  50. package/dist/context/summarize.d.ts +53 -0
  51. package/dist/context/summarize.js +204 -0
  52. package/dist/context/summarize.js.map +1 -0
  53. package/dist/context/summary-template.d.ts +29 -0
  54. package/dist/context/summary-template.js +69 -0
  55. package/dist/context/summary-template.js.map +1 -0
  56. package/dist/context/types.d.ts +150 -0
  57. package/dist/context/types.js +2 -0
  58. package/dist/context/types.js.map +1 -0
  59. package/dist/context/write-cap.d.ts +19 -0
  60. package/dist/context/write-cap.js +41 -0
  61. package/dist/context/write-cap.js.map +1 -0
  62. package/dist/create-harness.d.ts +7 -0
  63. package/dist/create-harness.js +21 -0
  64. package/dist/create-harness.js.map +1 -0
  65. package/dist/credentials/addresses.d.ts +14 -0
  66. package/dist/credentials/addresses.js +144 -0
  67. package/dist/credentials/addresses.js.map +1 -0
  68. package/dist/credentials/allowlist.d.ts +34 -0
  69. package/dist/credentials/allowlist.js +77 -0
  70. package/dist/credentials/allowlist.js.map +1 -0
  71. package/dist/credentials/egress-proxy.d.ts +70 -0
  72. package/dist/credentials/egress-proxy.js +482 -0
  73. package/dist/credentials/egress-proxy.js.map +1 -0
  74. package/dist/credentials/index.d.ts +9 -0
  75. package/dist/credentials/index.js +10 -0
  76. package/dist/credentials/index.js.map +1 -0
  77. package/dist/credentials/scrub.d.ts +16 -0
  78. package/dist/credentials/scrub.js +93 -0
  79. package/dist/credentials/scrub.js.map +1 -0
  80. package/dist/errors.d.ts +56 -0
  81. package/dist/errors.js +63 -0
  82. package/dist/errors.js.map +1 -0
  83. package/dist/extensions/compose.d.ts +27 -0
  84. package/dist/extensions/compose.js +83 -0
  85. package/dist/extensions/compose.js.map +1 -0
  86. package/dist/extensions/context-files-node.d.ts +28 -0
  87. package/dist/extensions/context-files-node.js +74 -0
  88. package/dist/extensions/context-files-node.js.map +1 -0
  89. package/dist/extensions/context-files.d.ts +68 -0
  90. package/dist/extensions/context-files.js +214 -0
  91. package/dist/extensions/context-files.js.map +1 -0
  92. package/dist/extensions/digest.d.ts +6 -0
  93. package/dist/extensions/digest.js +68 -0
  94. package/dist/extensions/digest.js.map +1 -0
  95. package/dist/extensions/index.d.ts +10 -0
  96. package/dist/extensions/index.js +10 -0
  97. package/dist/extensions/index.js.map +1 -0
  98. package/dist/extensions/load.d.ts +42 -0
  99. package/dist/extensions/load.js +211 -0
  100. package/dist/extensions/load.js.map +1 -0
  101. package/dist/extensions/lock.d.ts +8 -0
  102. package/dist/extensions/lock.js +95 -0
  103. package/dist/extensions/lock.js.map +1 -0
  104. package/dist/extensions/node.d.ts +10 -0
  105. package/dist/extensions/node.js +11 -0
  106. package/dist/extensions/node.js.map +1 -0
  107. package/dist/extensions/project-dirs.d.ts +24 -0
  108. package/dist/extensions/project-dirs.js +97 -0
  109. package/dist/extensions/project-dirs.js.map +1 -0
  110. package/dist/extensions/skills-node.d.ts +34 -0
  111. package/dist/extensions/skills-node.js +123 -0
  112. package/dist/extensions/skills-node.js.map +1 -0
  113. package/dist/extensions/skills.d.ts +51 -0
  114. package/dist/extensions/skills.js +175 -0
  115. package/dist/extensions/skills.js.map +1 -0
  116. package/dist/extensions/trust-file.d.ts +3 -0
  117. package/dist/extensions/trust-file.js +62 -0
  118. package/dist/extensions/trust-file.js.map +1 -0
  119. package/dist/extensions/trust-store-node.d.ts +10 -0
  120. package/dist/extensions/trust-store-node.js +33 -0
  121. package/dist/extensions/trust-store-node.js.map +1 -0
  122. package/dist/extensions/types.d.ts +42 -0
  123. package/dist/extensions/types.js +2 -0
  124. package/dist/extensions/types.js.map +1 -0
  125. package/dist/harness.d.ts +156 -0
  126. package/dist/harness.js +2 -0
  127. package/dist/harness.js.map +1 -0
  128. package/dist/index.d.ts +4 -0
  129. package/dist/index.js +5 -0
  130. package/dist/index.js.map +1 -0
  131. package/dist/mcp/connection.d.ts +22 -0
  132. package/dist/mcp/connection.js +267 -0
  133. package/dist/mcp/connection.js.map +1 -0
  134. package/dist/mcp/content.d.ts +27 -0
  135. package/dist/mcp/content.js +177 -0
  136. package/dist/mcp/content.js.map +1 -0
  137. package/dist/mcp/errors.d.ts +19 -0
  138. package/dist/mcp/errors.js +21 -0
  139. package/dist/mcp/errors.js.map +1 -0
  140. package/dist/mcp/index.d.ts +10 -0
  141. package/dist/mcp/index.js +10 -0
  142. package/dist/mcp/index.js.map +1 -0
  143. package/dist/mcp/manager.d.ts +7 -0
  144. package/dist/mcp/manager.js +173 -0
  145. package/dist/mcp/manager.js.map +1 -0
  146. package/dist/mcp/record.d.ts +7 -0
  147. package/dist/mcp/record.js +20 -0
  148. package/dist/mcp/record.js.map +1 -0
  149. package/dist/mcp/stdio.d.ts +39 -0
  150. package/dist/mcp/stdio.js +382 -0
  151. package/dist/mcp/stdio.js.map +1 -0
  152. package/dist/mcp/types.d.ts +172 -0
  153. package/dist/mcp/types.js +2 -0
  154. package/dist/mcp/types.js.map +1 -0
  155. package/dist/memory/index.d.ts +2 -0
  156. package/dist/memory/index.js +3 -0
  157. package/dist/memory/index.js.map +1 -0
  158. package/dist/permissions/default-rules.d.ts +7 -0
  159. package/dist/permissions/default-rules.js +42 -0
  160. package/dist/permissions/default-rules.js.map +1 -0
  161. package/dist/permissions/errors.d.ts +11 -0
  162. package/dist/permissions/errors.js +14 -0
  163. package/dist/permissions/errors.js.map +1 -0
  164. package/dist/permissions/index.d.ts +9 -0
  165. package/dist/permissions/index.js +9 -0
  166. package/dist/permissions/index.js.map +1 -0
  167. package/dist/permissions/match.d.ts +33 -0
  168. package/dist/permissions/match.js +287 -0
  169. package/dist/permissions/match.js.map +1 -0
  170. package/dist/permissions/pipeline.d.ts +9 -0
  171. package/dist/permissions/pipeline.js +235 -0
  172. package/dist/permissions/pipeline.js.map +1 -0
  173. package/dist/permissions/rules.d.ts +22 -0
  174. package/dist/permissions/rules.js +74 -0
  175. package/dist/permissions/rules.js.map +1 -0
  176. package/dist/permissions/shadow.d.ts +5 -0
  177. package/dist/permissions/shadow.js +22 -0
  178. package/dist/permissions/shadow.js.map +1 -0
  179. package/dist/permissions/types.d.ts +104 -0
  180. package/dist/permissions/types.js +2 -0
  181. package/dist/permissions/types.js.map +1 -0
  182. package/dist/sandbox/base.d.ts +35 -0
  183. package/dist/sandbox/base.js +60 -0
  184. package/dist/sandbox/base.js.map +1 -0
  185. package/dist/sandbox/docker/index.d.ts +35 -0
  186. package/dist/sandbox/docker/index.js +448 -0
  187. package/dist/sandbox/docker/index.js.map +1 -0
  188. package/dist/sandbox/errors.d.ts +16 -0
  189. package/dist/sandbox/errors.js +22 -0
  190. package/dist/sandbox/errors.js.map +1 -0
  191. package/dist/sandbox/host-files.d.ts +63 -0
  192. package/dist/sandbox/host-files.js +248 -0
  193. package/dist/sandbox/host-files.js.map +1 -0
  194. package/dist/sandbox/index.d.ts +8 -0
  195. package/dist/sandbox/index.js +8 -0
  196. package/dist/sandbox/index.js.map +1 -0
  197. package/dist/sandbox/none.d.ts +17 -0
  198. package/dist/sandbox/none.js +108 -0
  199. package/dist/sandbox/none.js.map +1 -0
  200. package/dist/sandbox/process.d.ts +61 -0
  201. package/dist/sandbox/process.js +253 -0
  202. package/dist/sandbox/process.js.map +1 -0
  203. package/dist/sandbox/spawn-env.d.ts +20 -0
  204. package/dist/sandbox/spawn-env.js +128 -0
  205. package/dist/sandbox/spawn-env.js.map +1 -0
  206. package/dist/sandbox/srt/index.d.ts +35 -0
  207. package/dist/sandbox/srt/index.js +264 -0
  208. package/dist/sandbox/srt/index.js.map +1 -0
  209. package/dist/sandbox/srt/settings.d.ts +48 -0
  210. package/dist/sandbox/srt/settings.js +31 -0
  211. package/dist/sandbox/srt/settings.js.map +1 -0
  212. package/dist/sandbox/types.d.ts +88 -0
  213. package/dist/sandbox/types.js +6 -0
  214. package/dist/sandbox/types.js.map +1 -0
  215. package/dist/server/answers.d.ts +16 -0
  216. package/dist/server/answers.js +43 -0
  217. package/dist/server/answers.js.map +1 -0
  218. package/dist/server/connection.d.ts +99 -0
  219. package/dist/server/connection.js +309 -0
  220. package/dist/server/connection.js.map +1 -0
  221. package/dist/server/dispatcher.d.ts +86 -0
  222. package/dist/server/dispatcher.js +800 -0
  223. package/dist/server/dispatcher.js.map +1 -0
  224. package/dist/server/index.d.ts +13 -0
  225. package/dist/server/index.js +12 -0
  226. package/dist/server/index.js.map +1 -0
  227. package/dist/server/local-transport.d.ts +44 -0
  228. package/dist/server/local-transport.js +103 -0
  229. package/dist/server/local-transport.js.map +1 -0
  230. package/dist/server/outbox.d.ts +31 -0
  231. package/dist/server/outbox.js +130 -0
  232. package/dist/server/outbox.js.map +1 -0
  233. package/dist/server/params.d.ts +25 -0
  234. package/dist/server/params.js +112 -0
  235. package/dist/server/params.js.map +1 -0
  236. package/dist/server/protocol.schema.json +2448 -0
  237. package/dist/server/rpc-session.d.ts +43 -0
  238. package/dist/server/rpc-session.js +167 -0
  239. package/dist/server/rpc-session.js.map +1 -0
  240. package/dist/server/stdio-streams.d.ts +67 -0
  241. package/dist/server/stdio-streams.js +218 -0
  242. package/dist/server/stdio-streams.js.map +1 -0
  243. package/dist/server/stdio.d.ts +59 -0
  244. package/dist/server/stdio.js +189 -0
  245. package/dist/server/stdio.js.map +1 -0
  246. package/dist/server/websocket.d.ts +106 -0
  247. package/dist/server/websocket.js +327 -0
  248. package/dist/server/websocket.js.map +1 -0
  249. package/dist/session/approvals.d.ts +81 -0
  250. package/dist/session/approvals.js +217 -0
  251. package/dist/session/approvals.js.map +1 -0
  252. package/dist/session/code-call-log.d.ts +42 -0
  253. package/dist/session/code-call-log.js +63 -0
  254. package/dist/session/code-call-log.js.map +1 -0
  255. package/dist/session/code-call-result.d.ts +19 -0
  256. package/dist/session/code-call-result.js +95 -0
  257. package/dist/session/code-call-result.js.map +1 -0
  258. package/dist/session/code-call.d.ts +49 -0
  259. package/dist/session/code-call.js +345 -0
  260. package/dist/session/code-call.js.map +1 -0
  261. package/dist/session/effect-scope.d.ts +11 -0
  262. package/dist/session/effect-scope.js +10 -0
  263. package/dist/session/effect-scope.js.map +1 -0
  264. package/dist/session/errors.d.ts +19 -0
  265. package/dist/session/errors.js +27 -0
  266. package/dist/session/errors.js.map +1 -0
  267. package/dist/session/file-index.d.ts +8 -0
  268. package/dist/session/file-index.js +70 -0
  269. package/dist/session/file-index.js.map +1 -0
  270. package/dist/session/file-key-store.d.ts +16 -0
  271. package/dist/session/file-key-store.js +169 -0
  272. package/dist/session/file-key-store.js.map +1 -0
  273. package/dist/session/file-lock.d.ts +52 -0
  274. package/dist/session/file-lock.js +324 -0
  275. package/dist/session/file-lock.js.map +1 -0
  276. package/dist/session/index.d.ts +22 -0
  277. package/dist/session/index.js +20 -0
  278. package/dist/session/index.js.map +1 -0
  279. package/dist/session/jsonl-store.d.ts +37 -0
  280. package/dist/session/jsonl-store.js +386 -0
  281. package/dist/session/jsonl-store.js.map +1 -0
  282. package/dist/session/jsonl.d.ts +9 -0
  283. package/dist/session/jsonl.js +10 -0
  284. package/dist/session/jsonl.js.map +1 -0
  285. package/dist/session/lock.d.ts +19 -0
  286. package/dist/session/lock.js +2 -0
  287. package/dist/session/lock.js.map +1 -0
  288. package/dist/session/memory-store.d.ts +12 -0
  289. package/dist/session/memory-store.js +60 -0
  290. package/dist/session/memory-store.js.map +1 -0
  291. package/dist/session/migrate.d.ts +41 -0
  292. package/dist/session/migrate.js +86 -0
  293. package/dist/session/migrate.js.map +1 -0
  294. package/dist/session/pointer.d.ts +15 -0
  295. package/dist/session/pointer.js +22 -0
  296. package/dist/session/pointer.js.map +1 -0
  297. package/dist/session/rebuild.d.ts +53 -0
  298. package/dist/session/rebuild.js +230 -0
  299. package/dist/session/rebuild.js.map +1 -0
  300. package/dist/session/resume.d.ts +26 -0
  301. package/dist/session/resume.js +128 -0
  302. package/dist/session/resume.js.map +1 -0
  303. package/dist/session/retention.d.ts +97 -0
  304. package/dist/session/retention.js +702 -0
  305. package/dist/session/retention.js.map +1 -0
  306. package/dist/session/runner.d.ts +156 -0
  307. package/dist/session/runner.js +656 -0
  308. package/dist/session/runner.js.map +1 -0
  309. package/dist/session/scheduler.d.ts +47 -0
  310. package/dist/session/scheduler.js +85 -0
  311. package/dist/session/scheduler.js.map +1 -0
  312. package/dist/session/secret-key-store.d.ts +47 -0
  313. package/dist/session/secret-key-store.js +79 -0
  314. package/dist/session/secret-key-store.js.map +1 -0
  315. package/dist/session/session.d.ts +106 -0
  316. package/dist/session/session.js +353 -0
  317. package/dist/session/session.js.map +1 -0
  318. package/dist/session/sticky.d.ts +48 -0
  319. package/dist/session/sticky.js +232 -0
  320. package/dist/session/sticky.js.map +1 -0
  321. package/dist/session/store.d.ts +108 -0
  322. package/dist/session/store.js +163 -0
  323. package/dist/session/store.js.map +1 -0
  324. package/dist/telemetry/index.d.ts +2 -0
  325. package/dist/telemetry/index.js +3 -0
  326. package/dist/telemetry/index.js.map +1 -0
  327. package/dist/testing/fake-sandbox.d.ts +34 -0
  328. package/dist/testing/fake-sandbox.js +221 -0
  329. package/dist/testing/fake-sandbox.js.map +1 -0
  330. package/dist/testing/index.d.ts +10 -0
  331. package/dist/testing/index.js +11 -0
  332. package/dist/testing/index.js.map +1 -0
  333. package/dist/testing/key-store-conformance.d.ts +22 -0
  334. package/dist/testing/key-store-conformance.js +97 -0
  335. package/dist/testing/key-store-conformance.js.map +1 -0
  336. package/dist/testing/run-cases.d.ts +21 -0
  337. package/dist/testing/run-cases.js +20 -0
  338. package/dist/testing/run-cases.js.map +1 -0
  339. package/dist/testing/sandbox-conformance.d.ts +64 -0
  340. package/dist/testing/sandbox-conformance.js +361 -0
  341. package/dist/testing/sandbox-conformance.js.map +1 -0
  342. package/dist/testing/scheduler-conformance.d.ts +32 -0
  343. package/dist/testing/scheduler-conformance.js +72 -0
  344. package/dist/testing/scheduler-conformance.js.map +1 -0
  345. package/dist/testing/store-conformance.d.ts +21 -0
  346. package/dist/testing/store-conformance.js +320 -0
  347. package/dist/testing/store-conformance.js.map +1 -0
  348. package/dist/tools/errors.d.ts +13 -0
  349. package/dist/tools/errors.js +17 -0
  350. package/dist/tools/errors.js.map +1 -0
  351. package/dist/tools/index.d.ts +8 -0
  352. package/dist/tools/index.js +8 -0
  353. package/dist/tools/index.js.map +1 -0
  354. package/dist/tools/registry.d.ts +3 -0
  355. package/dist/tools/registry.js +234 -0
  356. package/dist/tools/registry.js.map +1 -0
  357. package/dist/tools/tool-search.d.ts +30 -0
  358. package/dist/tools/tool-search.js +118 -0
  359. package/dist/tools/tool-search.js.map +1 -0
  360. package/dist/tools/types.d.ts +106 -0
  361. package/dist/tools/types.js +2 -0
  362. package/dist/tools/types.js.map +1 -0
  363. package/llms.txt +435 -0
  364. package/package.json +118 -3
@@ -0,0 +1,800 @@
1
+ /**
2
+ * The dispatcher: the one place every interface talks to. It takes the protocol's commands, runs turns through
3
+ * `runTurn()`, and sends the replies, the events and one `turn/settled` per turn back through each connection. The
4
+ * dispatcher holds no session state of its own beyond which turn runs where and which questions it has asked: the log
5
+ * is the state, so a client that joins late reads the log and a restart loses nothing. A turn holds the session's
6
+ * writer lock only while it runs, so another process that wants the session gets `locked` from its own `turn/start`.
7
+ *
8
+ * A call that needs a person ends its turn `awaiting_approval`. Once its `approval_requested` entry is durable, every
9
+ * connection that watches the session is asked with `approval/request` or `clarification/request`. The first answer
10
+ * wins: the others are withdrawn with `$/cancelRequest`, and the answer goes through `Approvals.resolve()`, which runs
11
+ * as a turn of its own once the session is free. A client that reconnects finds the request in `initialize` and is
12
+ * asked again when it opens the session.
13
+ */
14
+ import { ErrorCodes, } from "@buildanagent/protocol";
15
+ import { CAPABILITIES, SDK_VERSION, } from "@buildanagent/sdk";
16
+ import { HarnessError, isHarnessError } from "../errors.js";
17
+ import { createApprovals } from "../session/approvals.js";
18
+ import { codeCallRequestIds } from "../session/code-call-log.js";
19
+ import { pendingApprovals } from "../session/rebuild.js";
20
+ import { runTurn } from "../session/runner.js";
21
+ import { listSessions, openSession } from "../session/session.js";
22
+ import { resolutionOf, toolError, toolResultOf } from "./answers.js";
23
+ import { Failure, ServerConnection } from "./connection.js";
24
+ import { paramsProblem } from "./params.js";
25
+ /** The methods a client must opt into, by listing each in the `capabilities` of its `initialize`. */
26
+ export const EXPERIMENTAL_METHODS = ["session/checkout", "session/fork"];
27
+ const PAGE_SIZE = 50;
28
+ const DEFAULT_QUEUE_SIZE = 128;
29
+ const failure = (code, message) => new Failure(code, message);
30
+ const newOpened = (cwd) => ({ cwd, answers: new Map(), generation: 0, reasks: new Map() });
31
+ /** How many times `#armFor` reads the log before it gives up on a read that answers keep making stale. */
32
+ const ARM_READS = 3;
33
+ /**
34
+ * The `error.kind` of a resume's `turn/settled` when its answers were never written, because the lock could not be
35
+ * taken or the resume was stopped first. The requests still wait in the log.
36
+ */
37
+ const NOT_APPLIED = "answer_not_applied";
38
+ /** How many times one request is asked again after resumes that could not apply its answer. */
39
+ const MAX_REASKS = 3;
40
+ /** What `turn/settled` says about a resume that wrote none of its answers. */
41
+ function notApplied(stopReason, why) {
42
+ return {
43
+ stopReason,
44
+ steps: 0,
45
+ costUsd: null,
46
+ error: { kind: NOT_APPLIED, message: `${why}, so no answer was applied and each request still waits` },
47
+ };
48
+ }
49
+ const completionOf = (completion) => completion === undefined ? {} : { completion };
50
+ /** What `turn/settled` says about a finished turn, or about a turn that failed before it could finish. */
51
+ function summaryOf(result, error) {
52
+ if (result === undefined) {
53
+ return {
54
+ stopReason: "error",
55
+ steps: 0,
56
+ costUsd: null,
57
+ error: { kind: "harness", message: error instanceof Error ? error.message : String(error) },
58
+ };
59
+ }
60
+ const failed = "error" in result ? result.error : undefined;
61
+ return {
62
+ stopReason: result.stopReason,
63
+ steps: result.steps,
64
+ costUsd: result.cost.total,
65
+ ...(failed === undefined ? {} : { error: { kind: failed.kind, message: failed.message } }),
66
+ };
67
+ }
68
+ /** The summary of a resume. Only a turn's requests reach a resume, so a code call's result, which settles no turn, is an error. */
69
+ function resumedSummary(result) {
70
+ return "status" in result
71
+ ? summaryOf(undefined, new Error("an answer resolved a code call, which settles no turn"))
72
+ : summaryOf(result);
73
+ }
74
+ /**
75
+ * A store that tells `onAppend` about each batch it stores, with the file it went to, so the dispatcher can announce
76
+ * entries as they land. Delivery never fails a write that has landed.
77
+ */
78
+ function watched(store, onAppend) {
79
+ return {
80
+ async append(key, entries, options) {
81
+ const stored = await store.append(key, entries, options);
82
+ onAppend(key, stored);
83
+ return stored;
84
+ },
85
+ load: (key, options) => store.load(key, options),
86
+ list: (userId) => store.list(userId),
87
+ delete: (key) => store.delete(key),
88
+ ...(store.loadRaw === undefined
89
+ ? {}
90
+ : { loadRaw: (key) => store.loadRaw(key) }),
91
+ };
92
+ }
93
+ const replayEvent = (session, entry) => ({
94
+ jsonrpc: "2.0",
95
+ method: "event",
96
+ params: { session, seq: entry.seq, event: { type: "entry_appended", entry } },
97
+ });
98
+ async function collect(entries) {
99
+ const out = [];
100
+ for await (const entry of entries)
101
+ out.push(entry);
102
+ return out;
103
+ }
104
+ function checkQueueSize(size) {
105
+ if (size === undefined)
106
+ return DEFAULT_QUEUE_SIZE;
107
+ if (!Number.isInteger(size) || size < 1) {
108
+ throw new HarnessError("invalid_dispatcher_options", `queueSize must be a whole number of at least 1, got ${size}`);
109
+ }
110
+ return size;
111
+ }
112
+ class HarnessDispatcher {
113
+ #options;
114
+ #closed = false;
115
+ #connections = new Set();
116
+ #opened = new Map();
117
+ #lastSeq = new Map();
118
+ #newId;
119
+ #queueSize;
120
+ #approvals;
121
+ #requests = 0;
122
+ constructor(options) {
123
+ this.#options = options;
124
+ this.#newId = options.newId ?? (() => globalThis.crypto.randomUUID());
125
+ this.#queueSize = checkQueueSize(options.queueSize);
126
+ this.#approvals = options.approvals ?? createApprovals(options.harness);
127
+ }
128
+ /**
129
+ * The store a turn on `session` writes through. Each batch written to the session's current file is announced under
130
+ * the session's own id; a batch that goes to another file, such as a child's, belongs to that file's session.
131
+ */
132
+ #storeFor(session, handle) {
133
+ return watched(this.#options.store, (key, entries) => {
134
+ const current = handle();
135
+ if (current === undefined || key.sessionId === current.file())
136
+ this.#appended(session, entries);
137
+ });
138
+ }
139
+ connect(send, options = {}) {
140
+ if (this.#closed)
141
+ throw new Error("the dispatcher is closed");
142
+ const connection = new ServerConnection(this, send, this.#queueSize, options.onClose);
143
+ this.#connections.add(connection);
144
+ return connection;
145
+ }
146
+ async close() {
147
+ this.#closed = true;
148
+ const running = [...this.#opened.values()].flatMap((opened) => opened.running === undefined ? [] : [opened.running]);
149
+ for (const turn of running)
150
+ turn.controller.abort("the dispatcher closed");
151
+ await Promise.all(running.map((turn) => turn.done));
152
+ this.#connections.clear();
153
+ }
154
+ detach(connection) {
155
+ this.#connections.delete(connection);
156
+ }
157
+ key(session) {
158
+ return { userId: this.#options.userId, sessionId: session };
159
+ }
160
+ #watchers(session) {
161
+ return [...this.#connections].filter((connection) => connection.watching(session));
162
+ }
163
+ /** Sends to every connection that has opened the session. `seq` is the log's sequence number at that moment. */
164
+ emit(session, event, seq) {
165
+ const at = seq ?? this.#lastSeq.get(session) ?? -1;
166
+ const message = { jsonrpc: "2.0", method: "event", params: { session, seq: at, event } };
167
+ for (const connection of this.#connections)
168
+ connection.event(message);
169
+ }
170
+ #appended(session, entries) {
171
+ for (const entry of entries) {
172
+ this.#lastSeq.set(session, entry.seq);
173
+ this.emit(session, { type: "entry_appended", entry }, entry.seq);
174
+ // The entry is durable now, so a client that hears of the request can always find it in the log.
175
+ if (entry.type === "approval_requested") {
176
+ for (const connection of this.#watchers(session))
177
+ this.#ask(connection, session, entry.request);
178
+ }
179
+ }
180
+ }
181
+ settled(session, turn, result) {
182
+ for (const connection of this.#connections) {
183
+ connection.settled({ jsonrpc: "2.0", method: "turn/settled", params: { session, turn, result } });
184
+ }
185
+ }
186
+ async dispatch(connection, sent) {
187
+ // JSON-RPC lets a command leave out its params, so the handlers below, which read them as the protocol types them,
188
+ // get an empty object instead.
189
+ const command = (sent.params === undefined ? { ...sent, params: {} } : sent);
190
+ // An experimental method answers NotOptedIn before its params are read, as it would for any params.
191
+ const experimental = EXPERIMENTAL_METHODS;
192
+ if (experimental.includes(command.method) && !connection.optedIn(command.method)) {
193
+ throw failure(ErrorCodes.NotOptedIn, `${command.method} is experimental: list it in the capabilities of initialize`);
194
+ }
195
+ // Every handler below reads its params as the protocol types them, so a command that breaks its schema is refused
196
+ // here, before any of them runs.
197
+ const problem = paramsProblem(command);
198
+ if (problem !== undefined)
199
+ throw failure(ErrorCodes.InvalidParams, problem);
200
+ switch (command.method) {
201
+ case "initialize":
202
+ return { result: await this.#initialize(connection, command.params.capabilities) };
203
+ case "session/create":
204
+ return { result: await this.#create(connection, command.params) };
205
+ case "session/open":
206
+ return this.#open(connection, command.params);
207
+ case "session/list":
208
+ return { result: await this.#list(command.params.cursor) };
209
+ case "turn/start":
210
+ return this.#start(connection, command.id, command.params.session, command.params.input);
211
+ case "turn/steer":
212
+ case "turn/followUp":
213
+ return { result: this.#redirect(connection, command.method, command.params.session, command.params.input) };
214
+ case "turn/interrupt":
215
+ return { result: this.#interrupt(connection, command.params.session, command.params.reason) };
216
+ case "approval/list":
217
+ return { result: await this.#approvalList(connection, command.params.session) };
218
+ case "session/checkout":
219
+ case "session/fork":
220
+ return { result: await this.#branch(connection, command) };
221
+ default:
222
+ throw failure(ErrorCodes.MethodNotFound, `unknown method ${String(command.method)}`);
223
+ }
224
+ }
225
+ async #initialize(connection, requested) {
226
+ connection.optIn(requested);
227
+ const pending = [];
228
+ for await (const summary of listSessions(this.#options.store, this.#options.userId)) {
229
+ // One unreadable session must not stop every client from connecting.
230
+ try {
231
+ const session = await openSession({
232
+ store: this.#options.store,
233
+ index: this.#options.index,
234
+ key: this.key(summary.sessionId),
235
+ });
236
+ for (const entry of pendingApprovals(await session.path()))
237
+ pending.push({ session: summary.sessionId, request: entry.request });
238
+ }
239
+ catch {
240
+ // skipped
241
+ }
242
+ }
243
+ return {
244
+ serverInfo: {
245
+ name: this.#options.serverName ?? "buildanagent-harness",
246
+ version: this.#options.harness.harnessVersion,
247
+ sdkVersion: SDK_VERSION,
248
+ specVersion: "v1",
249
+ },
250
+ capabilities: [...CAPABILITIES, ...(this.#options.capabilities ?? [])],
251
+ experimental: [...EXPERIMENTAL_METHODS],
252
+ pending,
253
+ };
254
+ }
255
+ async #exists(session) {
256
+ for await (const _ of this.#options.store.load(this.key(session), { fromSeq: 0 }))
257
+ return true;
258
+ return false;
259
+ }
260
+ async #create(connection, params) {
261
+ const id = params.session ?? this.#newId();
262
+ if (this.#opened.has(id))
263
+ throw failure(ErrorCodes.InvalidParams, `session ${id} already exists`);
264
+ // Reserve the id before the first await, so two creates of one id cannot both pass.
265
+ const reserved = newOpened(params.cwd);
266
+ this.#opened.set(id, reserved);
267
+ try {
268
+ if (await this.#exists(id))
269
+ throw failure(ErrorCodes.InvalidParams, `session ${id} already exists`);
270
+ }
271
+ catch (error) {
272
+ if (this.#opened.get(id) === reserved)
273
+ this.#opened.delete(id);
274
+ throw error;
275
+ }
276
+ connection.watch(id);
277
+ return { session: id, head: null };
278
+ }
279
+ /**
280
+ * Opens a session for the connection. Its live events are held from the start, so that none is sent before the
281
+ * response, lost, or sent twice: after the response, the connection gets the replay from `fromSeq`, then what was
282
+ * held, then the live stream, and is asked again about every request that still waits.
283
+ */
284
+ async #open(connection, params) {
285
+ const id = params.session ?? "";
286
+ // The schema check has already refused a fromSeq that is not a whole number of at least 0.
287
+ const { fromSeq } = params;
288
+ if (!connection.hold(id))
289
+ throw failure(ErrorCodes.InvalidParams, `session ${JSON.stringify(id)} is being opened`);
290
+ try {
291
+ return await this.#openHeld(connection, id, params.cwd, fromSeq);
292
+ }
293
+ catch (error) {
294
+ // A failed open leaves the client with no access and nothing of what was held.
295
+ connection.unhold(id);
296
+ throw error;
297
+ }
298
+ }
299
+ async #openHeld(connection, id, cwd, fromSeq) {
300
+ // A session this dispatcher created has no file until its first turn, but a second client may still open it.
301
+ const exists = id !== "" && (await this.#exists(id));
302
+ if (id === "" || !(exists || this.#opened.has(id)))
303
+ throw failure(ErrorCodes.InvalidParams, `no session ${JSON.stringify(id)}`);
304
+ const reader = exists
305
+ ? await openSession({ store: this.#options.store, index: this.#options.index, key: this.key(id) })
306
+ : undefined;
307
+ const replay = fromSeq === undefined ? [] : await this.#replay(reader?.file(), fromSeq);
308
+ if (!this.#opened.has(id))
309
+ this.#opened.set(id, newOpened(cwd));
310
+ const replayedTo = fromSeq === undefined ? -1 : (replay.at(-1)?.seq ?? fromSeq - 1);
311
+ return {
312
+ result: { session: id, head: reader?.head() ?? null },
313
+ after: () => {
314
+ connection.release(id, replay.map((entry) => replayEvent(id, entry)), replayedTo);
315
+ void this.#armFor(connection, id);
316
+ },
317
+ };
318
+ }
319
+ /**
320
+ * The entries of the session's current file from `fromSeq` on, read from the log, which holds every entry: the log is
321
+ * the replay window, so no `fromSeq` is too old. A `fromSeq` past the entry after the last refuses the open.
322
+ */
323
+ async #replay(file, fromSeq) {
324
+ if (file === undefined) {
325
+ if (fromSeq === 0)
326
+ return [];
327
+ throw failure(ErrorCodes.InvalidParams, `fromSeq ${fromSeq} is past the end of the session's log`);
328
+ }
329
+ // One entry before fromSeq is read too, to tell a client that has everything from one whose fromSeq is too far.
330
+ const entries = await collect(this.#options.store.load(this.key(file), { fromSeq: Math.max(0, fromSeq - 1) }));
331
+ if (fromSeq === 0)
332
+ return entries;
333
+ if (entries[0]?.seq !== fromSeq - 1)
334
+ throw failure(ErrorCodes.InvalidParams, `fromSeq ${fromSeq} is past the end of the session's log`);
335
+ return entries.slice(1);
336
+ }
337
+ async #list(cursor) {
338
+ const from = cursor === undefined ? 0 : /^\d+$/.test(cursor) ? Number(cursor) : -1;
339
+ if (from < 0)
340
+ throw failure(ErrorCodes.InvalidParams, "the cursor is not one this server gave");
341
+ const all = [];
342
+ for await (const item of listSessions(this.#options.store, this.#options.userId)) {
343
+ all.push({
344
+ session: item.sessionId,
345
+ startedAt: item.startedAt,
346
+ lastEntryAt: item.lastEntryAt,
347
+ entryCount: item.entryCount,
348
+ });
349
+ }
350
+ const page = all.slice(from, from + PAGE_SIZE);
351
+ return from + PAGE_SIZE < all.length
352
+ ? { sessions: page, nextCursor: String(from + PAGE_SIZE) }
353
+ : { sessions: page };
354
+ }
355
+ /** Marks the session busy with a new turn, before any await, so a second command in the same tick sees it busy. */
356
+ #claim(opened, owner) {
357
+ let finish;
358
+ const done = new Promise((resolve) => {
359
+ finish = resolve;
360
+ });
361
+ const running = {
362
+ turn: this.#newId(),
363
+ run: undefined,
364
+ done,
365
+ finish,
366
+ controller: new AbortController(),
367
+ queued: [],
368
+ owner,
369
+ };
370
+ opened.running = running;
371
+ return running;
372
+ }
373
+ /** Opens the session with its lock, writing through a store that announces what lands in its current file. */
374
+ async #lockedHandle(session) {
375
+ let handle;
376
+ handle = await openSession({
377
+ store: this.#storeFor(session, () => handle),
378
+ index: this.#options.index,
379
+ lock: this.#options.lock,
380
+ key: this.key(session),
381
+ });
382
+ return handle;
383
+ }
384
+ async #start(connection, requestId, session, input) {
385
+ const opened = connection.watching(session) ? this.#opened.get(session) : undefined;
386
+ if (opened === undefined)
387
+ return { result: { accepted: false, reason: "invalid" } };
388
+ if (this.#closed)
389
+ throw failure(ErrorCodes.InternalError, "the dispatcher is closed");
390
+ if (opened.running !== undefined || opened.branching === true) {
391
+ return { result: { accepted: false, reason: "busy" } };
392
+ }
393
+ const running = this.#claim(opened, connection);
394
+ // The client may cancel the turn by the id of its turn/start until the turn settles.
395
+ const cancel = () => running.controller.abort("the client cancelled the turn");
396
+ connection.trackTurn(requestId, cancel);
397
+ const refuse = () => {
398
+ connection.untrackTurn(requestId, cancel);
399
+ opened.running = undefined;
400
+ running.finish();
401
+ // An answer that came while this turn was taking the lock waited for the session; it is free again.
402
+ this.#pump(session);
403
+ };
404
+ let handle;
405
+ try {
406
+ handle = await this.#lockedHandle(session);
407
+ }
408
+ catch (error) {
409
+ refuse();
410
+ if (isHarnessError(error) && error.code === "session_locked")
411
+ return { result: { accepted: false, reason: "locked" } };
412
+ throw error;
413
+ }
414
+ if (this.#closed) {
415
+ // close() returned while this turn was still taking the lock: give it back and refuse.
416
+ await handle.close().catch(() => undefined);
417
+ refuse();
418
+ throw failure(ErrorCodes.InternalError, "the dispatcher is closed");
419
+ }
420
+ // The response goes out first; the run starts after it, so no event can reach a client before its disposition.
421
+ let begin;
422
+ const started = new Promise((resolve) => {
423
+ begin = resolve;
424
+ });
425
+ void this.#run(handle, session, opened, running, input, started).finally(() => connection.untrackTurn(requestId, cancel));
426
+ return { result: { accepted: true, turn: running.turn }, after: begin };
427
+ }
428
+ /** What every turn and every resume passes to the runner besides its own settings. */
429
+ #turnHooks(session, running) {
430
+ const observer = (event) => this.emit(session, event);
431
+ return {
432
+ ...this.#options.turn,
433
+ observers: [observer],
434
+ signal: running.controller.signal,
435
+ clientTool: this.#clientTool(session, running.owner),
436
+ onRun: (run) => {
437
+ running.run = run;
438
+ for (const apply of running.queued.splice(0))
439
+ apply(run);
440
+ },
441
+ };
442
+ }
443
+ async #run(handle, session, opened, running, input, started) {
444
+ await started;
445
+ let summary;
446
+ try {
447
+ await this.#seed(handle, session);
448
+ const result = await runTurn(handle, this.#options.harness, {
449
+ ...this.#turnHooks(session, running),
450
+ ...completionOf(this.#options.completion?.(session)),
451
+ input,
452
+ // The first run has ended and a retry may follow: a steer sent now waits in the queue for the retry's run.
453
+ onOverflowRetry: () => {
454
+ running.run = undefined;
455
+ },
456
+ onContextFill: (fill) => this.emit(session, { type: "context_fill", tokens: fill.tokens, budget: fill.budget }),
457
+ onCompletionCheck: (entry) => this.emit(session, { type: "completion_check", entry }, entry.seq),
458
+ });
459
+ summary = summaryOf(result);
460
+ }
461
+ catch (error) {
462
+ summary = summaryOf(undefined, error);
463
+ }
464
+ finally {
465
+ // A lock that will not release must not leave the session busy or the turn unsettled.
466
+ await handle.close().catch(() => undefined);
467
+ this.#release(opened, running);
468
+ }
469
+ this.settled(session, running.turn, summary);
470
+ running.finish();
471
+ // An answer that came while the turn ran resumes it now.
472
+ this.#pump(session);
473
+ }
474
+ /**
475
+ * Frees the session. A steer or follow-up still queued for a run that never started ends with its turn: its
476
+ * disposition named the turn, `turn/settled` says the turn ended, and the log has no message for it.
477
+ */
478
+ #release(opened, running) {
479
+ running.queued.length = 0;
480
+ running.run = undefined;
481
+ opened.running = undefined;
482
+ }
483
+ /** Seeds the sequence a run's own events carry, so a session an earlier process wrote does not start at -1. */
484
+ async #seed(handle, session) {
485
+ const last = (await handle.path()).at(-1);
486
+ if (last !== undefined)
487
+ this.#lastSeq.set(session, Math.max(last.seq, this.#lastSeq.get(session) ?? -1));
488
+ }
489
+ #redirect(connection, method, session, input) {
490
+ const running = connection.watching(session) ? this.#opened.get(session)?.running : undefined;
491
+ if (running === undefined)
492
+ return { accepted: false, reason: "invalid" };
493
+ const apply = (run) => {
494
+ try {
495
+ const queued = method === "turn/steer" ? run.steer([...input]) : run.followUp([...input]);
496
+ // A message the run ends before applying is rejected as undelivered: the turn's own end says what happened.
497
+ Promise.resolve(queued).catch(() => undefined);
498
+ return true;
499
+ }
500
+ catch {
501
+ return false;
502
+ }
503
+ };
504
+ if (running.run === undefined) {
505
+ running.queued.push((run) => void apply(run));
506
+ return { accepted: true, turn: running.turn };
507
+ }
508
+ return apply(running.run) ? { accepted: true, turn: running.turn } : { accepted: false, reason: "invalid" };
509
+ }
510
+ #interrupt(connection, session, reason) {
511
+ const running = connection.watching(session) ? this.#opened.get(session)?.running : undefined;
512
+ if (running === undefined)
513
+ return { interrupted: false };
514
+ running.controller.abort(reason);
515
+ return { interrupted: true };
516
+ }
517
+ async #approvalList(connection, session) {
518
+ if (!connection.watching(session) || !this.#opened.has(session))
519
+ throw failure(ErrorCodes.InvalidParams, `no session ${JSON.stringify(session)} is open`);
520
+ const reader = await openSession({
521
+ store: this.#options.store,
522
+ index: this.#options.index,
523
+ key: this.key(session),
524
+ });
525
+ // The host's own pending() decides, with a code call's requests taken out: the protocol does not yet carry one, so a
526
+ // client is never shown one.
527
+ const waiting = await this.#approvals.pending(reader);
528
+ const codeRequests = codeCallRequestIds(await reader.path());
529
+ return { pending: waiting.flatMap(({ request }) => (codeRequests.has(request.id) ? [] : [request])) };
530
+ }
531
+ /** A fresh id for a server request, unique within this dispatcher. */
532
+ #requestId() {
533
+ this.#requests += 1;
534
+ return `sr-${this.#requests}`;
535
+ }
536
+ /**
537
+ * Asks one connection about a signed request, unless it already waits on that connection or someone has answered
538
+ * it. Only a connection that watches the session is asked.
539
+ */
540
+ #ask(connection, session, request) {
541
+ const opened = this.#opened.get(session);
542
+ if (!connection.watching(session) || opened === undefined)
543
+ return;
544
+ if (opened.answers.has(request.id) || connection.asking(request.id))
545
+ return;
546
+ const id = this.#requestId();
547
+ connection.ask(request.kind === "clarification"
548
+ ? { jsonrpc: "2.0", id, method: "clarification/request", params: { session, request } }
549
+ : { jsonrpc: "2.0", id, method: "approval/request", params: { session, request } }, {
550
+ session,
551
+ pendingId: request.id,
552
+ answer: (answer) => this.#answer(connection, session, request, answer),
553
+ // A request for a person lives in the log, so a lost connection loses nothing: the next client is asked.
554
+ lost: () => undefined,
555
+ });
556
+ }
557
+ /**
558
+ * Asks one connection about every request of the session that still waits, as the log says now. An answer taken or
559
+ * applied while the log was being read makes that read stale, so the log is read again before anyone is asked.
560
+ */
561
+ async #armFor(connection, session, only) {
562
+ const opened = this.#opened.get(session);
563
+ if (opened === undefined)
564
+ return;
565
+ let waiting = [];
566
+ for (let read = 0; read < ARM_READS; read++) {
567
+ const generation = opened.generation;
568
+ try {
569
+ waiting = await this.#waiting(session);
570
+ }
571
+ catch {
572
+ // A session with no file yet has nothing to ask, and an unreadable one is listed by initialize as it can be.
573
+ return;
574
+ }
575
+ if (opened.generation === generation)
576
+ break;
577
+ // Answers kept changing for every read: ask nothing now, since the next resume asks again.
578
+ if (read === ARM_READS - 1)
579
+ return;
580
+ }
581
+ for (const request of waiting)
582
+ if (only === undefined || only.has(request.id))
583
+ this.#ask(connection, session, request);
584
+ }
585
+ async #waiting(session) {
586
+ const reader = await openSession({
587
+ store: this.#options.store,
588
+ index: this.#options.index,
589
+ key: this.key(session),
590
+ });
591
+ return pendingApprovals(await reader.path()).map((entry) => entry.request);
592
+ }
593
+ /**
594
+ * Takes a client's answer to an approval or a clarification. The first well-formed answer to a signed request wins
595
+ * and the others are withdrawn; a malformed one is asked again on the same connection; an error leaves the request
596
+ * waiting in the log for the next time the session is opened.
597
+ */
598
+ #answer(connection, session, request, answer) {
599
+ if ("error" in answer)
600
+ return;
601
+ const opened = this.#opened.get(session);
602
+ if (opened === undefined || opened.answers.has(request.id))
603
+ return;
604
+ const resolution = resolutionOf(answer.result, request);
605
+ if (resolution === undefined) {
606
+ this.#ask(connection, session, request);
607
+ return;
608
+ }
609
+ opened.answers.set(request.id, { resolution, by: connection, applying: false });
610
+ opened.generation += 1;
611
+ for (const other of this.#connections)
612
+ other.withdrawPending(request.id);
613
+ this.#pump(session);
614
+ }
615
+ /** Starts a resume with the answers that wait, once the session is free. */
616
+ #pump(session) {
617
+ const opened = this.#opened.get(session);
618
+ if (opened === undefined || opened.running !== undefined || opened.branching === true || this.#closed)
619
+ return;
620
+ const answers = [...opened.answers.entries()].filter(([, answer]) => !answer.applying);
621
+ if (answers.length === 0)
622
+ return;
623
+ for (const [, answer] of answers)
624
+ answer.applying = true;
625
+ const running = this.#claim(opened, answers[0]?.[1].by);
626
+ void this.#resume(session, opened, running, answers);
627
+ }
628
+ /**
629
+ * Resumes the session with the answers through `Approvals.resolve()`, as a turn of its own that ends with
630
+ * `turn/settled`. An answer whose request no longer waits, because another process settled it, is dropped, and a
631
+ * resume with no answer left runs nothing and settles nothing.
632
+ */
633
+ async #resume(session, opened, running, answers) {
634
+ let summary;
635
+ let written = false;
636
+ try {
637
+ const handle = await this.#lockedHandle(session);
638
+ try {
639
+ const waiting = new Set(pendingApprovals(await handle.path()).map((entry) => entry.request.id));
640
+ const resolutions = answers.flatMap(([id, answer]) => (waiting.has(id) ? [answer.resolution] : []));
641
+ if (resolutions.length > 0) {
642
+ await this.#seed(handle, session);
643
+ // A close or an interrupt while the lock was being taken leaves the answers unwritten, so the log never shows
644
+ // an answer that no run applied.
645
+ if (running.controller.signal.aborted || this.#closed) {
646
+ summary = notApplied("aborted", "the resume was stopped before it wrote its answers");
647
+ }
648
+ else {
649
+ written = true;
650
+ summary = resumedSummary(await this.#approvals.resolve(handle, resolutions, this.#turnHooks(session, running)));
651
+ }
652
+ }
653
+ }
654
+ finally {
655
+ await handle.close().catch(() => undefined);
656
+ }
657
+ }
658
+ catch (error) {
659
+ summary = written
660
+ ? summaryOf(undefined, error)
661
+ : notApplied("error", `the resume could not start (${error instanceof Error ? error.message : String(error)})`);
662
+ }
663
+ finally {
664
+ for (const [id] of answers)
665
+ opened.answers.delete(id);
666
+ opened.generation += 1;
667
+ this.#release(opened, running);
668
+ }
669
+ if (summary !== undefined)
670
+ this.settled(session, running.turn, summary);
671
+ running.finish();
672
+ this.#askAfterResume(session, opened, summary, answers);
673
+ this.#pump(session);
674
+ }
675
+ /**
676
+ * Asks again after a resume. A request the resume left waiting, such as one a quorum still needs, is asked again.
677
+ * One whose answer was never written, because the lock was held or the resume was stopped, is asked again too, at
678
+ * most `MAX_REASKS` times, so a lock another process holds can't make a loop. A resume that failed after it wrote
679
+ * its answers asks nothing, and a closed dispatcher asks nobody.
680
+ */
681
+ #askAfterResume(session, opened, summary, answers) {
682
+ if (summary === undefined || this.#closed)
683
+ return;
684
+ if (summary.error === undefined) {
685
+ for (const connection of this.#watchers(session))
686
+ void this.#armFor(connection, session);
687
+ return;
688
+ }
689
+ if (summary.error.kind !== NOT_APPLIED)
690
+ return;
691
+ const again = new Set();
692
+ for (const [id] of answers) {
693
+ const count = opened.reasks.get(id) ?? 0;
694
+ if (count >= MAX_REASKS)
695
+ continue;
696
+ opened.reasks.set(id, count + 1);
697
+ again.add(id);
698
+ }
699
+ if (again.size === 0)
700
+ return;
701
+ for (const connection of this.#watchers(session))
702
+ void this.#armFor(connection, session, again);
703
+ }
704
+ /**
705
+ * Runs a `client_request` tool's call by sending `tool/call` to the turn's owner, and resolves with its answer. A call
706
+ * never hangs on a client that is gone: with no owner, or once the owner closes, it resolves with an error result,
707
+ * and an abort withdraws the request with `$/cancelRequest` and rejects.
708
+ */
709
+ #clientTool(session, owner) {
710
+ return (call) => new Promise((resolve, reject) => {
711
+ if (call.signal.aborted) {
712
+ reject(call.signal.reason);
713
+ return;
714
+ }
715
+ if (owner === undefined || !owner.open || !owner.watching(session)) {
716
+ resolve(toolError(`no client is connected to run ${call.tool}`));
717
+ return;
718
+ }
719
+ const id = this.#requestId();
720
+ const onAbort = () => {
721
+ owner.withdraw(id);
722
+ reject(call.signal.reason);
723
+ };
724
+ call.signal.addEventListener("abort", onAbort, { once: true });
725
+ const settle = (result) => {
726
+ call.signal.removeEventListener("abort", onAbort);
727
+ resolve(result);
728
+ };
729
+ owner.ask({
730
+ jsonrpc: "2.0",
731
+ id,
732
+ method: "tool/call",
733
+ params: { session, callId: call.callId, tool: call.tool, input: call.input },
734
+ }, {
735
+ session,
736
+ answer: (answer) => settle("error" in answer
737
+ ? toolError(`the client could not run ${call.tool}: ${answer.error.message}`)
738
+ : toolResultOf(answer.result, call.tool)),
739
+ lost: () => settle(toolError(`the client closed before it answered the call to ${call.tool}`)),
740
+ });
741
+ });
742
+ }
743
+ async #branch(connection, command) {
744
+ const { session } = command.params;
745
+ const opened = this.#opened.get(session);
746
+ if (opened === undefined || !connection.watching(session)) {
747
+ throw failure(ErrorCodes.InvalidParams, `no session ${JSON.stringify(session)} is open`);
748
+ }
749
+ if (opened.running !== undefined || opened.branching === true) {
750
+ throw failure(ErrorCodes.SessionLocked, "a turn is running in this session");
751
+ }
752
+ if (this.#closed)
753
+ throw failure(ErrorCodes.InternalError, "the dispatcher is closed");
754
+ opened.branching = true;
755
+ try {
756
+ return await this.#branchLocked(connection, command, opened);
757
+ }
758
+ finally {
759
+ opened.branching = false;
760
+ this.#pump(session);
761
+ }
762
+ }
763
+ async #branchLocked(connection, command, opened) {
764
+ const { session, entryId } = command.params;
765
+ // A checkout is announced under its own session; a fork's entries belong to the new session, nobody watches yet.
766
+ const handle = command.method === "session/checkout"
767
+ ? await this.#lockedHandle(session)
768
+ : await openSession({
769
+ store: this.#options.store,
770
+ index: this.#options.index,
771
+ lock: this.#options.lock,
772
+ key: this.key(session),
773
+ });
774
+ try {
775
+ if (command.method === "session/checkout") {
776
+ await handle.checkout(entryId);
777
+ return { session, head: handle.head() };
778
+ }
779
+ const forked = await handle.fork(entryId);
780
+ try {
781
+ const id = forked.key.sessionId;
782
+ this.#opened.set(id, newOpened(opened.cwd));
783
+ connection.watch(id);
784
+ return { session: id, head: forked.head() };
785
+ }
786
+ finally {
787
+ // The change has landed; a lock that will not release must not turn it into an error.
788
+ await forked.close().catch(() => undefined);
789
+ }
790
+ }
791
+ finally {
792
+ await handle.close().catch(() => undefined);
793
+ }
794
+ }
795
+ }
796
+ /** Creates the dispatcher that serves `options.harness` over the protocol's commands. */
797
+ export function createDispatcher(options) {
798
+ return new HarnessDispatcher(options);
799
+ }
800
+ //# sourceMappingURL=dispatcher.js.map