@buildanagent/harness 0.0.0-bootstrap.0 → 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 +717 -0
  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 +119 -5
@@ -0,0 +1,43 @@
1
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
+ const optionalText = (value) => value === undefined || typeof value === "string";
3
+ /**
4
+ * The one resolution an answer to `approval/request` or `clarification/request` gives for `request`, or `undefined` when
5
+ * the answer is malformed, names another request, or gives more than one. An approval takes `allow` or `deny` with an
6
+ * optional `reason`; a clarification takes an `answer`. Either may carry `by`.
7
+ */
8
+ export function resolutionOf(result, request) {
9
+ if (!isObject(result) || !Array.isArray(result.resolutions) || result.resolutions.length !== 1)
10
+ return undefined;
11
+ const [given] = result.resolutions;
12
+ if (!isObject(given) || given.requestId !== request.id || !optionalText(given.by))
13
+ return undefined;
14
+ const by = given.by === undefined ? {} : { by: given.by };
15
+ if (request.kind === "clarification") {
16
+ return typeof given.answer === "string" && given.decision === undefined
17
+ ? { requestId: request.id, answer: given.answer, ...by }
18
+ : undefined;
19
+ }
20
+ if ((given.decision !== "allow" && given.decision !== "deny") || given.answer !== undefined)
21
+ return undefined;
22
+ if (!optionalText(given.reason))
23
+ return undefined;
24
+ return {
25
+ requestId: request.id,
26
+ decision: given.decision,
27
+ ...(given.reason === undefined ? {} : { reason: given.reason }),
28
+ ...by,
29
+ };
30
+ }
31
+ /** An error result the model reads, for a tool call the client could not run. */
32
+ export function toolError(text) {
33
+ return { content: [{ type: "text", text }], isError: true };
34
+ }
35
+ /** The tool result a client's answer to `tool/call` gives, or an error result when the answer is not one. */
36
+ export function toolResultOf(result, tool) {
37
+ if (!isObject(result) || !Array.isArray(result.content) || typeof result.isError !== "boolean") {
38
+ return toolError(`the client's answer to the call to ${tool} is not a tool result`);
39
+ }
40
+ // The SDK checks each block, so a block of the wrong kind becomes an error result there.
41
+ return { content: result.content, isError: result.isError };
42
+ }
43
+ //# sourceMappingURL=answers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"answers.js","sourceRoot":"","sources":["../../src/server/answers.ts"],"names":[],"mappings":"AAOA,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoC,EAAE,CACpE,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEvE,MAAM,YAAY,GAAG,CAAC,KAAc,EAAW,EAAE,CAAC,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AAEnG;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,MAAe,EAAE,OAA6B;IACzE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,MAAM,CAAC,WAAW,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACjH,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,WAAwB,CAAC;IAChD,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,SAAS,KAAK,OAAO,CAAC,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;QAAE,OAAO,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,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QAC/F,OAAO,SAAS,CAAC,sCAAsC,IAAI,uBAAuB,CAAC,CAAC;IACtF,CAAC;IACD,yFAAyF;IACzF,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAgC,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;AACvF,CAAC","sourcesContent":["/**\n * Reads a client's answers to the server's requests. An answer is checked before it reaches the approvals or a tool\n * call, because it comes from outside the process: an approval answer must name the request it was asked about and\n * nothing else, and a tool result must have the shape the SDK takes.\n */\nimport type { Resolution, SignedPendingRequest, ToolResult } from \"@buildanagent/sdk\";\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst optionalText = (value: unknown): boolean => value === undefined || typeof value === \"string\";\n\n/**\n * The one resolution an answer to `approval/request` or `clarification/request` gives for `request`, or `undefined` when\n * the answer is malformed, names another request, or gives more than one. An approval takes `allow` or `deny` with an\n * optional `reason`; a clarification takes an `answer`. Either may carry `by`.\n */\nexport function resolutionOf(result: unknown, request: SignedPendingRequest): Resolution | undefined {\n if (!isObject(result) || !Array.isArray(result.resolutions) || result.resolutions.length !== 1) return undefined;\n const [given] = result.resolutions as unknown[];\n if (!isObject(given) || given.requestId !== request.id || !optionalText(given.by)) return undefined;\n const by = given.by === undefined ? {} : { by: given.by as string };\n if (request.kind === \"clarification\") {\n return typeof given.answer === \"string\" && given.decision === undefined\n ? { requestId: request.id, answer: given.answer, ...by }\n : undefined;\n }\n if ((given.decision !== \"allow\" && given.decision !== \"deny\") || given.answer !== undefined) return undefined;\n if (!optionalText(given.reason)) return undefined;\n return {\n requestId: request.id,\n decision: given.decision,\n ...(given.reason === undefined ? {} : { reason: given.reason as string }),\n ...by,\n };\n}\n\n/** An error result the model reads, for a tool call the client could not run. */\nexport function toolError(text: string): ToolResult {\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n/** The tool result a client's answer to `tool/call` gives, or an error result when the answer is not one. */\nexport function toolResultOf(result: unknown, tool: string): ToolResult {\n if (!isObject(result) || !Array.isArray(result.content) || typeof result.isError !== \"boolean\") {\n return toolError(`the client's answer to the call to ${tool} is not a tool result`);\n }\n // The SDK checks each block, so a block of the wrong kind becomes an error result there.\n return { content: result.content as ToolResult[\"content\"], isError: result.isError };\n}\n"]}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * One client's end of the dispatcher: what it may see, what it has asked, and what the server has asked it. A
3
+ * connection receives only the events of the sessions it created or opened. It holds at most `limit` commands at a
4
+ * time, counting each until its response has gone out, so a client that sends faster than it reads is refused with
5
+ * `QueueFull` instead of growing the queue. At most `limit` refusals wait to go out, and past that the connection is
6
+ * closed, because a client that neither reads nor waits would otherwise grow the queue with refusals. What waits also
7
+ * bounds the server requests the connection holds: one per pending approval or clarification of a session it watches,
8
+ * and one per `client_request` tool call that a turn it started makes.
9
+ */
10
+ import { type ClientCommand, type ClientMessage, type Id, type RpcError, type ServerMessage, type ServerNotification, type ServerRequest } from "@buildanagent/protocol";
11
+ import { type Deliver } from "./outbox.js";
12
+ /** A client's answer to a server request: its result, or the error it sent instead. */
13
+ export type ServerAnswer = {
14
+ readonly result: unknown;
15
+ } | {
16
+ readonly error: RpcError;
17
+ };
18
+ /** A server request the client has not answered yet. */
19
+ export interface Asked {
20
+ readonly session: string;
21
+ /** For an approval or a clarification, the id of the signed request it asks about. */
22
+ readonly pendingId?: string;
23
+ /** Called once with the client's answer. */
24
+ answer(answer: ServerAnswer): void;
25
+ /** Called once if the connection closes before an answer. */
26
+ lost(): void;
27
+ }
28
+ /** What a connection asks of the dispatcher it belongs to. */
29
+ export interface ConnectionHost {
30
+ /** Runs one command and returns its result, with what to do once the response has gone out. */
31
+ dispatch(connection: ServerConnection, command: ClientCommand & {
32
+ id: Id;
33
+ }): Promise<Dispatched>;
34
+ /** Forgets a connection that closed. */
35
+ detach(connection: ServerConnection): void;
36
+ }
37
+ /** A command's outcome: its result, and what runs right after its response has been queued. */
38
+ export interface Dispatched {
39
+ readonly result: unknown;
40
+ readonly after?: () => void;
41
+ }
42
+ /** An error the dispatcher answers a command with. */
43
+ export declare class Failure extends Error {
44
+ readonly rpc: RpcError;
45
+ constructor(code: number, message: string);
46
+ }
47
+ type EventMessage = Extract<ServerNotification, {
48
+ method: "event";
49
+ }>;
50
+ type SettledMessage = Extract<ServerNotification, {
51
+ method: "turn/settled";
52
+ }>;
53
+ /** One client's connection to the dispatcher, as the module comment describes. */
54
+ export declare class ServerConnection {
55
+ #private;
56
+ constructor(host: ConnectionHost, deliver: Deliver, limit: number, onClose?: () => void);
57
+ /** Whether the client is still connected. */
58
+ get open(): boolean;
59
+ /** Sends a message that belongs to no session's stream: a response or a cancel. */
60
+ send(message: ServerMessage): void;
61
+ /** Sends a session's `turn/settled` to a connection that watches it, after any replay that is being prepared. */
62
+ settled(message: SettledMessage): void;
63
+ /** Sends a live event of a session this connection watches, or holds it while the session is being opened. */
64
+ event(message: EventMessage): void;
65
+ watch(session: string): void;
66
+ /** Whether this connection created or opened the session. */
67
+ watching(session: string): boolean;
68
+ /** Starts holding a session's live events, so none is lost or sent early while its log is read. False if one is already held. */
69
+ hold(session: string): boolean;
70
+ /**
71
+ * Ends the hold of a failed open, and leaves the session as watched or unwatched as it was. A connection that
72
+ * already watched the session still gets what was held, because those messages are its live stream; one that did
73
+ * not gets nothing.
74
+ */
75
+ unhold(session: string): void;
76
+ /**
77
+ * Watches the session: sends `replay`, which is never dropped, then what was held since `hold()`, leaving out an
78
+ * appended entry whose `seq` is at or before `replayedTo` because the replay already carried it.
79
+ */
80
+ release(session: string, replay: readonly EventMessage[], replayedTo: number): void;
81
+ optIn(methods: readonly string[]): void;
82
+ optedIn(method: string): boolean;
83
+ /** Sends a server request and remembers it until the client answers, the server withdraws it, or the connection closes. */
84
+ ask(request: ServerRequest, asked: Asked): void;
85
+ /** Whether an approval or clarification about this signed request waits for this client's answer. */
86
+ asking(pendingId: string): boolean;
87
+ /** Withdraws a server request with `$/cancelRequest`. Returns false when it was already answered or withdrawn. */
88
+ withdraw(id: string): boolean;
89
+ /** Withdraws every request this client holds about one signed request, because someone else answered it. */
90
+ withdrawPending(pendingId: string): void;
91
+ /** Lets the client cancel its own `turn/start` by id until the turn settles. */
92
+ trackTurn(id: Id, cancel: () => void): void;
93
+ /** Stops tracking a turn, unless a later `turn/start` that reused the id has replaced its canceller. */
94
+ untrackTurn(id: Id, cancel: () => void): void;
95
+ close(): void;
96
+ /** Handles one message from the client, and resolves once its response, if it has one, is queued. */
97
+ receive(message: ClientMessage): Promise<void>;
98
+ }
99
+ export {};
@@ -0,0 +1,309 @@
1
+ /**
2
+ * One client's end of the dispatcher: what it may see, what it has asked, and what the server has asked it. A
3
+ * connection receives only the events of the sessions it created or opened. It holds at most `limit` commands at a
4
+ * time, counting each until its response has gone out, so a client that sends faster than it reads is refused with
5
+ * `QueueFull` instead of growing the queue. At most `limit` refusals wait to go out, and past that the connection is
6
+ * closed, because a client that neither reads nor waits would otherwise grow the queue with refusals. What waits also
7
+ * bounds the server requests the connection holds: one per pending approval or clarification of a session it watches,
8
+ * and one per `client_request` tool call that a turn it started makes.
9
+ */
10
+ import { ErrorCodes, } from "@buildanagent/protocol";
11
+ import { isHarnessError } from "../errors.js";
12
+ import { Outbox } from "./outbox.js";
13
+ /** An error the dispatcher answers a command with. */
14
+ export class Failure extends Error {
15
+ rpc;
16
+ constructor(code, message) {
17
+ super(message);
18
+ this.rpc = { code, message };
19
+ }
20
+ }
21
+ const isId = (value) => typeof value === "string" || (typeof value === "number" && Number.isFinite(value));
22
+ /** One client's connection to the dispatcher, as the module comment describes. */
23
+ export class ServerConnection {
24
+ #host;
25
+ #outbox;
26
+ #limit;
27
+ #watching = new Set();
28
+ #held = new Map();
29
+ #optedIn = new Set();
30
+ #asked = new Map();
31
+ #turns = new Map();
32
+ #inFlight = 0;
33
+ #refusals = 0;
34
+ #open = true;
35
+ #onClose;
36
+ constructor(host, deliver, limit, onClose) {
37
+ this.#host = host;
38
+ this.#outbox = new Outbox(deliver, limit);
39
+ this.#limit = limit;
40
+ this.#onClose = onClose;
41
+ }
42
+ /** Whether the client is still connected. */
43
+ get open() {
44
+ return this.#open;
45
+ }
46
+ /** Sends a message that belongs to no session's stream: a response or a cancel. */
47
+ send(message) {
48
+ this.#outbox.push(message);
49
+ }
50
+ /** Sends a session's `turn/settled` to a connection that watches it, after any replay that is being prepared. */
51
+ settled(message) {
52
+ const held = this.#held.get(message.params.session);
53
+ if (held !== undefined)
54
+ held.messages.push(message);
55
+ else if (this.#watching.has(message.params.session))
56
+ this.#outbox.push(message);
57
+ }
58
+ /** Sends a live event of a session this connection watches, or holds it while the session is being opened. */
59
+ event(message) {
60
+ const held = this.#held.get(message.params.session);
61
+ if (held === undefined) {
62
+ if (this.#watching.has(message.params.session))
63
+ this.#outbox.push(message);
64
+ return;
65
+ }
66
+ // A hold lasts one read of the log, and is bounded as the queue is: past the bound, events are counted as dropped.
67
+ if (held.events < this.#limit) {
68
+ held.messages.push(message);
69
+ held.events += 1;
70
+ }
71
+ else {
72
+ held.gapAt ??= held.messages.length;
73
+ const { seq } = message.params;
74
+ if (message.params.event.type === "entry_appended") {
75
+ held.droppedEntries = { first: held.droppedEntries?.first ?? seq, last: seq };
76
+ }
77
+ else {
78
+ held.dropped += 1;
79
+ held.lastDroppedSeq = Math.max(held.lastDroppedSeq, seq);
80
+ }
81
+ }
82
+ }
83
+ watch(session) {
84
+ this.#watching.add(session);
85
+ }
86
+ /** Whether this connection created or opened the session. */
87
+ watching(session) {
88
+ return this.#watching.has(session);
89
+ }
90
+ /** Starts holding a session's live events, so none is lost or sent early while its log is read. False if one is already held. */
91
+ hold(session) {
92
+ if (this.#held.has(session))
93
+ return false;
94
+ this.#held.set(session, {
95
+ messages: [],
96
+ events: 0,
97
+ dropped: 0,
98
+ lastDroppedSeq: -1,
99
+ droppedEntries: undefined,
100
+ gapAt: undefined,
101
+ });
102
+ return true;
103
+ }
104
+ /**
105
+ * Ends the hold of a failed open, and leaves the session as watched or unwatched as it was. A connection that
106
+ * already watched the session still gets what was held, because those messages are its live stream; one that did
107
+ * not gets nothing.
108
+ */
109
+ unhold(session) {
110
+ if (this.#watching.has(session))
111
+ this.release(session, [], -1);
112
+ else
113
+ this.#held.delete(session);
114
+ }
115
+ /**
116
+ * Watches the session: sends `replay`, which is never dropped, then what was held since `hold()`, leaving out an
117
+ * appended entry whose `seq` is at or before `replayedTo` because the replay already carried it.
118
+ */
119
+ release(session, replay, replayedTo) {
120
+ const held = this.#held.get(session);
121
+ this.#held.delete(session);
122
+ this.#watching.add(session);
123
+ for (const message of replay)
124
+ this.#outbox.push(message, { keep: true });
125
+ const marker = () => {
126
+ const gap = held === undefined ? undefined : gapOf(held, replayedTo);
127
+ if (gap !== undefined)
128
+ this.#outbox.pushGap(session, gap.count, gap.seq);
129
+ };
130
+ for (const [index, message] of (held?.messages ?? []).entries()) {
131
+ // The drops began once the hold was full, so their marker goes out before what was held after them.
132
+ if (index === held?.gapAt)
133
+ marker();
134
+ if (message.method === "event" && message.params.event.type === "entry_appended") {
135
+ if (message.params.seq <= replayedTo)
136
+ continue;
137
+ }
138
+ this.#outbox.push(message);
139
+ }
140
+ if (held?.gapAt !== undefined && held.gapAt >= held.messages.length)
141
+ marker();
142
+ }
143
+ optIn(methods) {
144
+ for (const method of methods)
145
+ this.#optedIn.add(method);
146
+ }
147
+ optedIn(method) {
148
+ return this.#optedIn.has(method);
149
+ }
150
+ /** Sends a server request and remembers it until the client answers, the server withdraws it, or the connection closes. */
151
+ ask(request, asked) {
152
+ if (!this.#open) {
153
+ asked.lost();
154
+ return;
155
+ }
156
+ this.#asked.set(request.id, asked);
157
+ this.#outbox.push(request);
158
+ }
159
+ /** Whether an approval or clarification about this signed request waits for this client's answer. */
160
+ asking(pendingId) {
161
+ for (const asked of this.#asked.values())
162
+ if (asked.pendingId === pendingId)
163
+ return true;
164
+ return false;
165
+ }
166
+ /** Withdraws a server request with `$/cancelRequest`. Returns false when it was already answered or withdrawn. */
167
+ withdraw(id) {
168
+ if (!this.#asked.delete(id))
169
+ return false;
170
+ if (this.#open)
171
+ this.send({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
172
+ return true;
173
+ }
174
+ /** Withdraws every request this client holds about one signed request, because someone else answered it. */
175
+ withdrawPending(pendingId) {
176
+ for (const [id, asked] of [...this.#asked])
177
+ if (asked.pendingId === pendingId)
178
+ this.withdraw(id);
179
+ }
180
+ /** Lets the client cancel its own `turn/start` by id until the turn settles. */
181
+ trackTurn(id, cancel) {
182
+ this.#turns.set(id, cancel);
183
+ }
184
+ /** Stops tracking a turn, unless a later `turn/start` that reused the id has replaced its canceller. */
185
+ untrackTurn(id, cancel) {
186
+ if (this.#turns.get(id) === cancel)
187
+ this.#turns.delete(id);
188
+ }
189
+ close() {
190
+ if (!this.#open)
191
+ return;
192
+ this.#open = false;
193
+ this.#outbox.close();
194
+ const asked = [...this.#asked.values()];
195
+ this.#asked.clear();
196
+ this.#turns.clear();
197
+ this.#held.clear();
198
+ this.#host.detach(this);
199
+ for (const request of asked)
200
+ request.lost();
201
+ // The transport learns of a close it did not ask for, such as one for refusals left unread.
202
+ try {
203
+ this.#onClose?.();
204
+ }
205
+ catch {
206
+ // A transport's own failure must not stop the close.
207
+ }
208
+ }
209
+ /** Handles one message from the client, and resolves once its response, if it has one, is queued. */
210
+ async receive(message) {
211
+ if (!this.#open)
212
+ return;
213
+ if (!("method" in message)) {
214
+ this.#answered(message);
215
+ return;
216
+ }
217
+ if (!("id" in message)) {
218
+ if (message.method === "$/cancelRequest")
219
+ this.#cancel(message.params?.id);
220
+ return;
221
+ }
222
+ await this.#command(message);
223
+ }
224
+ /**
225
+ * Answers a command the full queue can't take with `QueueFull`. The refusal takes no command's place, but it waits to
226
+ * go out like any response, so a client that keeps sending without reading would grow the queue: once `limit`
227
+ * refusals wait, the server closes the connection instead.
228
+ */
229
+ #refuse(id) {
230
+ if (this.#refusals >= this.#limit) {
231
+ this.close();
232
+ return;
233
+ }
234
+ this.#refusals += 1;
235
+ this.#outbox.push({
236
+ jsonrpc: "2.0",
237
+ id,
238
+ error: { code: ErrorCodes.QueueFull, message: `the queue holds ${this.#limit} commands; send again later` },
239
+ }, {
240
+ onSent: () => {
241
+ this.#refusals -= 1;
242
+ },
243
+ });
244
+ }
245
+ /** A client's answer to a server request. One with an id this connection is not waiting on is ignored. */
246
+ #answered(message) {
247
+ if (typeof message.id !== "string")
248
+ return;
249
+ const asked = this.#asked.get(message.id);
250
+ if (asked === undefined)
251
+ return;
252
+ this.#asked.delete(message.id);
253
+ asked.answer("error" in message ? { error: message.error } : { result: message.result });
254
+ }
255
+ #cancel(id) {
256
+ if (isId(id))
257
+ this.#turns.get(id)?.();
258
+ }
259
+ async #command(command) {
260
+ if (this.#inFlight >= this.#limit) {
261
+ this.#refuse(command.id);
262
+ return;
263
+ }
264
+ this.#inFlight += 1;
265
+ // The command holds its place until its response has gone out, so a client that doesn't read is refused soon.
266
+ const onSent = () => {
267
+ this.#inFlight -= 1;
268
+ };
269
+ let after;
270
+ try {
271
+ const outcome = await this.#host.dispatch(this, command);
272
+ after = outcome.after;
273
+ this.#outbox.push({ jsonrpc: "2.0", id: command.id, result: outcome.result }, { onSent });
274
+ }
275
+ catch (error) {
276
+ this.#outbox.push({ jsonrpc: "2.0", id: command.id, error: rpcErrorOf(error) }, { onSent });
277
+ }
278
+ finally {
279
+ // A closed outbox drops the response, so it never calls back.
280
+ if (!this.#open)
281
+ this.#inFlight = 0;
282
+ after?.();
283
+ }
284
+ }
285
+ }
286
+ /**
287
+ * What a hold really lost: its dropped events, less the entries the replay carried up to `replayedTo`. The marker's
288
+ * `seq` is never below `replayedTo`, because the client has everything up to there. `undefined` when nothing was lost.
289
+ */
290
+ function gapOf(held, replayedTo) {
291
+ const entries = held.droppedEntries;
292
+ const lostEntries = entries === undefined ? 0 : Math.max(0, entries.last - Math.max(entries.first, replayedTo + 1) + 1);
293
+ const count = held.dropped + lostEntries;
294
+ if (count === 0)
295
+ return undefined;
296
+ return { count, seq: Math.max(held.lastDroppedSeq, entries?.last ?? -1, replayedTo) };
297
+ }
298
+ /** The error a failed command answers with. */
299
+ function rpcErrorOf(error) {
300
+ if (error instanceof Failure)
301
+ return error.rpc;
302
+ const message = error instanceof Error ? error.message : String(error);
303
+ if (isHarnessError(error) && error.code === "entry_not_found")
304
+ return { code: ErrorCodes.InvalidParams, message };
305
+ if (isHarnessError(error) && error.code === "session_locked")
306
+ return { code: ErrorCodes.SessionLocked, message };
307
+ return { code: ErrorCodes.InternalError, message };
308
+ }
309
+ //# sourceMappingURL=connection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/server/connection.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAGL,UAAU,GAMX,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAgB,MAAM,EAAE,MAAM,aAAa,CAAC;AA8BnD,sDAAsD;AACtD,MAAM,OAAO,OAAQ,SAAQ,KAAK;IACvB,GAAG,CAAW;IACvB,YAAY,IAAY,EAAE,OAAe;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,GAAG,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC/B,CAAC;CACF;AAyBD,MAAM,IAAI,GAAG,CAAC,KAAc,EAAe,EAAE,CAC3C,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;AAErF,kFAAkF;AAClF,MAAM,OAAO,gBAAgB;IAClB,KAAK,CAAiB;IACtB,OAAO,CAAS;IAChB,MAAM,CAAS;IACf,SAAS,GAAG,I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CAAC;IACtG,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC;IACzC,IAAI,KAAK,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAClC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,CAAC,EAAE,UAAU,CAAC,EAAE,CAAC;AACxF,CAAC;AAED,+CAA+C;AAC/C,SAAS,UAAU,CAAC,KAAc;IAChC,IAAI,KAAK,YAAY,OAAO;QAAE,OAAO,KAAK,CAAC,GAAG,CAAC;IAC/C,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,IAAI,cAAc,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,iBAAiB;QAAE,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,aAAa,EAAE,OAAO,EAAE,CAAC;IAClH,IAAI,cAAc,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB;QAAE,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,aAAa,EAAE,OAAO,EAAE,CAAC;IACjH,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,aAAa,EAAE,OAAO,EAAE,CAAC;AACrD,CAAC","sourcesContent":["/**\n * One client's end of the dispatcher: what it may see, what it has asked, and what the server has asked it. A\n * connection receives only the events of the sessions it created or opened. It holds at most `limit` commands at a\n * time, counting each until its response has gone out, so a client that sends faster than it reads is refused with\n * `QueueFull` instead of growing the queue. At most `limit` refusals wait to go out, and past that the connection is\n * closed, because a client that neither reads nor waits would otherwise grow the queue with refusals. What waits also\n * bounds the server requests the connection holds: one per pending approval or clarification of a session it watches,\n * and one per `client_request` tool call that a turn it started makes.\n */\nimport {\n type ClientCommand,\n type ClientMessage,\n ErrorCodes,\n type Id,\n type RpcError,\n type ServerMessage,\n type ServerNotification,\n type ServerRequest,\n} from \"@buildanagent/protocol\";\nimport { isHarnessError } from \"../errors.js\";\nimport { type Deliver, Outbox } from \"./outbox.js\";\n\n/** A client's answer to a server request: its result, or the error it sent instead. */\nexport type ServerAnswer = { readonly result: unknown } | { readonly error: RpcError };\n\n/** A server request the client has not answered yet. */\nexport interface Asked {\n readonly session: string;\n /** For an approval or a clarification, the id of the signed request it asks about. */\n readonly pendingId?: string;\n /** Called once with the client's answer. */\n answer(answer: ServerAnswer): void;\n /** Called once if the connection closes before an answer. */\n lost(): void;\n}\n\n/** What a connection asks of the dispatcher it belongs to. */\nexport interface ConnectionHost {\n /** Runs one command and returns its result, with what to do once the response has gone out. */\n dispatch(connection: ServerConnection, command: ClientCommand & { id: Id }): Promise<Dispatched>;\n /** Forgets a connection that closed. */\n detach(connection: ServerConnection): void;\n}\n\n/** A command's outcome: its result, and what runs right after its response has been queued. */\nexport interface Dispatched {\n readonly result: unknown;\n readonly after?: () => void;\n}\n\n/** An error the dispatcher answers a command with. */\nexport class Failure extends Error {\n readonly rpc: RpcError;\n constructor(code: number, message: string) {\n super(message);\n this.rpc = { code, message };\n }\n}\n\ntype EventMessage = Extract<ServerNotification, { method: \"event\" }>;\ntype SettledMessage = Extract<ServerNotification, { method: \"turn/settled\" }>;\n\n/**\n * What a session sent while a `session/open` was reading its log, waiting to go out after the replay. Events count\n * against the bound. A `turn/settled` is always kept, and needs no bound of its own: the session runs one turn at a\n * time, so one read of the log sees few of them.\n */\ninterface Held {\n readonly messages: (EventMessage | SettledMessage)[];\n events: number;\n /** Dropped events that are not entries, and the latest `seq` among them. */\n dropped: number;\n lastDroppedSeq: number;\n /**\n * The first and last `seq` of the dropped entries. Once the hold is full every later entry is dropped, so the range\n * has no hole, and the replay may already carry its start.\n */\n droppedEntries: { first: number; last: number } | undefined;\n /** How many of `messages` came before the first drop, so the marker goes out where the drops were. */\n gapAt: number | undefined;\n}\n\nconst isId = (value: unknown): value is Id =>\n typeof value === \"string\" || (typeof value === \"number\" && Number.isFinite(value));\n\n/** One client's connection to the dispatcher, as the module comment describes. */\nexport class ServerConnection {\n readonly #host: ConnectionHost;\n readonly #outbox: Outbox;\n readonly #limit: number;\n readonly #watching = new Set<string>();\n readonly #held = new Map<string, Held>();\n readonly #optedIn = new Set<string>();\n readonly #asked = new Map<string, Asked>();\n readonly #turns = new Map<Id, () => void>();\n #inFlight = 0;\n #refusals = 0;\n #open = true;\n readonly #onClose: (() => void) | undefined;\n\n constructor(host: ConnectionHost, deliver: Deliver, limit: number, onClose?: () => void) {\n this.#host = host;\n this.#outbox = new Outbox(deliver, limit);\n this.#limit = limit;\n this.#onClose = onClose;\n }\n\n /** Whether the client is still connected. */\n get open(): boolean {\n return this.#open;\n }\n\n /** Sends a message that belongs to no session's stream: a response or a cancel. */\n send(message: ServerMessage): void {\n this.#outbox.push(message);\n }\n\n /** Sends a session's `turn/settled` to a connection that watches it, after any replay that is being prepared. */\n settled(message: SettledMessage): void {\n const held = this.#held.get(message.params.session);\n if (held !== undefined) held.messages.push(message);\n else if (this.#watching.has(message.params.session)) this.#outbox.push(message);\n }\n\n /** Sends a live event of a session this connection watches, or holds it while the session is being opened. */\n event(message: EventMessage): void {\n const held = this.#held.get(message.params.session);\n if (held === undefined) {\n if (this.#watching.has(message.params.session)) this.#outbox.push(message);\n return;\n }\n // A hold lasts one read of the log, and is bounded as the queue is: past the bound, events are counted as dropped.\n if (held.events < this.#limit) {\n held.messages.push(message);\n held.events += 1;\n } else {\n held.gapAt ??= held.messages.length;\n const { seq } = message.params;\n if (message.params.event.type === \"entry_appended\") {\n held.droppedEntries = { first: held.droppedEntries?.first ?? seq, last: seq };\n } else {\n held.dropped += 1;\n held.lastDroppedSeq = Math.max(held.lastDroppedSeq, seq);\n }\n }\n }\n\n watch(session: string): void {\n this.#watching.add(session);\n }\n\n /** Whether this connection created or opened the session. */\n watching(session: string): boolean {\n return this.#watching.has(session);\n }\n\n /** Starts holding a session's live events, so none is lost or sent early while its log is read. False if one is already held. */\n hold(session: string): boolean {\n if (this.#held.has(session)) return false;\n this.#held.set(session, {\n messages: [],\n events: 0,\n dropped: 0,\n lastDroppedSeq: -1,\n droppedEntries: undefined,\n gapAt: undefined,\n });\n return true;\n }\n\n /**\n * Ends the hold of a failed open, and leaves the session as watched or unwatched as it was. A connection that\n * already watched the session still gets what was held, because those messages are its live stream; one that did\n * not gets nothing.\n */\n unhold(session: string): void {\n if (this.#watching.has(session)) this.release(session, [], -1);\n else this.#held.delete(session);\n }\n\n /**\n * Watches the session: sends `replay`, which is never dropped, then what was held since `hold()`, leaving out an\n * appended entry whose `seq` is at or before `replayedTo` because the replay already carried it.\n */\n release(session: string, replay: readonly EventMessage[], replayedTo: number): void {\n const held = this.#held.get(session);\n this.#held.delete(session);\n this.#watching.add(session);\n for (const message of replay) this.#outbox.push(message, { keep: true });\n const marker = () => {\n const gap = held === undefined ? undefined : gapOf(held, replayedTo);\n if (gap !== undefined) this.#outbox.pushGap(session, gap.count, gap.seq);\n };\n for (const [index, message] of (held?.messages ?? []).entries()) {\n // The drops began once the hold was full, so their marker goes out before what was held after them.\n if (index === held?.gapAt) marker();\n if (message.method === \"event\" && message.params.event.type === \"entry_appended\") {\n if (message.params.seq <= replayedTo) continue;\n }\n this.#outbox.push(message);\n }\n if (held?.gapAt !== undefined && held.gapAt >= held.messages.length) marker();\n }\n\n optIn(methods: readonly string[]): void {\n for (const method of methods) this.#optedIn.add(method);\n }\n\n optedIn(method: string): boolean {\n return this.#optedIn.has(method);\n }\n\n /** Sends a server request and remembers it until the client answers, the server withdraws it, or the connection closes. */\n ask(request: ServerRequest, asked: Asked): void {\n if (!this.#open) {\n asked.lost();\n return;\n }\n this.#asked.set(request.id, asked);\n this.#outbox.push(request);\n }\n\n /** Whether an approval or clarification about this signed request waits for this client's answer. */\n asking(pendingId: string): boolean {\n for (const asked of this.#asked.values()) if (asked.pendingId === pendingId) return true;\n return false;\n }\n\n /** Withdraws a server request with `$/cancelRequest`. Returns false when it was already answered or withdrawn. */\n withdraw(id: string): boolean {\n if (!this.#asked.delete(id)) return false;\n if (this.#open) this.send({ jsonrpc: \"2.0\", method: \"$/cancelRequest\", params: { id } });\n return true;\n }\n\n /** Withdraws every request this client holds about one signed request, because someone else answered it. */\n withdrawPending(pendingId: string): void {\n for (const [id, asked] of [...this.#asked]) if (asked.pendingId === pendingId) this.withdraw(id);\n }\n\n /** Lets the client cancel its own `turn/start` by id until the turn settles. */\n trackTurn(id: Id, cancel: () => void): void {\n this.#turns.set(id, cancel);\n }\n\n /** Stops tracking a turn, unless a later `turn/start` that reused the id has replaced its canceller. */\n untrackTurn(id: Id, cancel: () => void): void {\n if (this.#turns.get(id) === cancel) this.#turns.delete(id);\n }\n\n close(): void {\n if (!this.#open) return;\n this.#open = false;\n this.#outbox.close();\n const asked = [...this.#asked.values()];\n this.#asked.clear();\n this.#turns.clear();\n this.#held.clear();\n this.#host.detach(this);\n for (const request of asked) request.lost();\n // The transport learns of a close it did not ask for, such as one for refusals left unread.\n try {\n this.#onClose?.();\n } catch {\n // A transport's own failure must not stop the close.\n }\n }\n\n /** Handles one message from the client, and resolves once its response, if it has one, is queued. */\n async receive(message: ClientMessage): Promise<void> {\n if (!this.#open) return;\n if (!(\"method\" in message)) {\n this.#answered(message);\n return;\n }\n if (!(\"id\" in message)) {\n if (message.method === \"$/cancelRequest\") this.#cancel(message.params?.id);\n return;\n }\n await this.#command(message as ClientCommand & { id: Id });\n }\n\n /**\n * Answers a command the full queue can't take with `QueueFull`. The refusal takes no command's place, but it waits to\n * go out like any response, so a client that keeps sending without reading would grow the queue: once `limit`\n * refusals wait, the server closes the connection instead.\n */\n #refuse(id: Id): void {\n if (this.#refusals >= this.#limit) {\n this.close();\n return;\n }\n this.#refusals += 1;\n this.#outbox.push(\n {\n jsonrpc: \"2.0\",\n id,\n error: { code: ErrorCodes.QueueFull, message: `the queue holds ${this.#limit} commands; send again later` },\n },\n {\n onSent: () => {\n this.#refusals -= 1;\n },\n },\n );\n }\n\n /** A client's answer to a server request. One with an id this connection is not waiting on is ignored. */\n #answered(message: Exclude<ClientMessage, ClientCommand>): void {\n if (typeof message.id !== \"string\") return;\n const asked = this.#asked.get(message.id);\n if (asked === undefined) return;\n this.#asked.delete(message.id);\n asked.answer(\"error\" in message ? { error: message.error } : { result: message.result });\n }\n\n #cancel(id: unknown): void {\n if (isId(id)) this.#turns.get(id)?.();\n }\n\n async #command(command: ClientCommand & { id: Id }): Promise<void> {\n if (this.#inFlight >= this.#limit) {\n this.#refuse(command.id);\n return;\n }\n this.#inFlight += 1;\n // The command holds its place until its response has gone out, so a client that doesn't read is refused soon.\n const onSent = () => {\n this.#inFlight -= 1;\n };\n let after: (() => void) | undefined;\n try {\n const outcome = await this.#host.dispatch(this, command);\n after = outcome.after;\n this.#outbox.push({ jsonrpc: \"2.0\", id: command.id, result: outcome.result as never }, { onSent });\n } catch (error) {\n this.#outbox.push({ jsonrpc: \"2.0\", id: command.id, error: rpcErrorOf(error) }, { onSent });\n } finally {\n // A closed outbox drops the response, so it never calls back.\n if (!this.#open) this.#inFlight = 0;\n after?.();\n }\n }\n}\n\n/**\n * What a hold really lost: its dropped events, less the entries the replay carried up to `replayedTo`. The marker's\n * `seq` is never below `replayedTo`, because the client has everything up to there. `undefined` when nothing was lost.\n */\nfunction gapOf(held: Held, replayedTo: number): { count: number; seq: number } | undefined {\n const entries = held.droppedEntries;\n const lostEntries =\n entries === undefined ? 0 : Math.max(0, entries.last - Math.max(entries.first, replayedTo + 1) + 1);\n const count = held.dropped + lostEntries;\n if (count === 0) return undefined;\n return { count, seq: Math.max(held.lastDroppedSeq, entries?.last ?? -1, replayedTo) };\n}\n\n/** The error a failed command answers with. */\nfunction rpcErrorOf(error: unknown): RpcError {\n if (error instanceof Failure) return error.rpc;\n const message = error instanceof Error ? error.message : String(error);\n if (isHarnessError(error) && error.code === \"entry_not_found\") return { code: ErrorCodes.InvalidParams, message };\n if (isHarnessError(error) && error.code === \"session_locked\") return { code: ErrorCodes.SessionLocked, message };\n return { code: ErrorCodes.InternalError, message };\n}\n"]}
@@ -0,0 +1,86 @@
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 { type ClientMessage } from "@buildanagent/protocol";
15
+ import type { CompletionSettings } from "../completion/check.js";
16
+ import type { Harness } from "../harness.js";
17
+ import { type Approvals } from "../session/approvals.js";
18
+ import type { SessionLock } from "../session/lock.js";
19
+ import type { SessionIndex } from "../session/pointer.js";
20
+ import { type TurnOptions } from "../session/runner.js";
21
+ import type { SessionStore } from "../session/store.js";
22
+ import type { Deliver } from "./outbox.js";
23
+ /** The methods a client must opt into, by listing each in the `capabilities` of its `initialize`. */
24
+ export declare const EXPERIMENTAL_METHODS: readonly ["session/checkout", "session/fork"];
25
+ /** The settings of `createDispatcher()`. */
26
+ export interface DispatcherOptions<H = unknown> {
27
+ readonly harness: Harness<H>;
28
+ readonly store: SessionStore;
29
+ readonly index: SessionIndex;
30
+ /** The writer lock a turn takes while it runs. Two dispatchers over one lock serve one session at a time. */
31
+ readonly lock: SessionLock;
32
+ /** Whose sessions this dispatcher serves. Every store call names this user. */
33
+ readonly userId: string;
34
+ /** What the harness adds to the SDK's capabilities in `initialize`. Default none. */
35
+ readonly capabilities?: readonly string[];
36
+ /** The name `initialize` reports. Default `buildanagent-harness`. */
37
+ readonly serverName?: string;
38
+ /** Settings every turn takes besides its input, resumes included. */
39
+ readonly turn?: Pick<TurnOptions<H>, "maxSteps" | "turnRetries" | "budgetUsd" | "modelOptions">;
40
+ /**
41
+ * The completion check for a session's turns, given the session's id. It returns the session's sandbox and
42
+ * environment, because one sandbox never serves every session, or `undefined` for a session with no check. Each
43
+ * `turn/start` calls it once. Default: no turn checks its completion.
44
+ */
45
+ readonly completion?: (session: string) => CompletionSettings | undefined;
46
+ /** Makes session and turn ids. Default `crypto.randomUUID()`. */
47
+ readonly newId?: () => string;
48
+ /**
49
+ * How many commands each connection may have unanswered, and how many events may wait for a slow client before
50
+ * the server drops them. A whole number of at least 1. Default 128.
51
+ */
52
+ readonly queueSize?: number;
53
+ /** The approvals a client's answers go through. Default `createApprovals(harness)`. */
54
+ readonly approvals?: Approvals<H>;
55
+ }
56
+ /** One client's end of the dispatcher: send it messages, and it calls back with what the server sends. */
57
+ export interface Connection {
58
+ /** Handles one message and resolves once its response, if it has one, is queued to go out. */
59
+ receive(message: ClientMessage): Promise<void>;
60
+ /**
61
+ * Stops delivering to this client. A turn it started goes on, and a tool call that waits on this client gets an
62
+ * error result. A request for a person stays in the log for the next client.
63
+ */
64
+ close(): void;
65
+ }
66
+ /** What `Dispatcher.connect()` takes besides `send`. */
67
+ export interface ConnectOptions {
68
+ /**
69
+ * Called once when the connection closes, whether the caller closed it with `close()` or the server did. The server
70
+ * closes a connection for a client that leaves 128 refusals unread. A transport uses it to stop serving a connection that is gone.
71
+ */
72
+ readonly onClose?: () => void;
73
+ }
74
+ /** The dispatcher `createDispatcher()` returns. */
75
+ export interface Dispatcher {
76
+ /**
77
+ * Adds a client. `send` gets every message the server sends it, one at a time and in order. A `send` that returns a
78
+ * promise holds the next message until it settles; while it waits, events past the queue size are dropped and an
79
+ * `events_dropped` event stands in for them.
80
+ */
81
+ connect(send: Deliver, options?: ConnectOptions): Connection;
82
+ /** Interrupts every running turn and waits for each to settle. */
83
+ close(): Promise<void>;
84
+ }
85
+ /** Creates the dispatcher that serves `options.harness` over the protocol's commands. */
86
+ export declare function createDispatcher<H = unknown>(options: DispatcherOptions<H>): Dispatcher;