@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
package/README.md CHANGED
@@ -1,3 +1,717 @@
1
- # Temporary Holding Version
1
+ # @buildanagent/harness
2
+
3
+ The harness wraps the SDK's loop with what a coding agent needs around it: a session log that survives a crash, a context policy, tools, permissions, a sandbox and credentials kept out of it. Use it to run an agent whose every turn is recorded and can be resumed, checked and replayed.
4
+
5
+ Each removable component has its own subpath, so you import only what you use and an ablation can drop the rest. `session`, `context`, `tools`, `permissions`, `sandbox`, `credentials`, `extensions`, `mcp`, `server` and `testing` are built. `memory`, `telemetry` and `ablation` are empty stubs that hold their place until their components arrive.
6
+
7
+ ## Install the alpha with `pnpm add @buildanagent/harness@alpha`
8
+
9
+ The package needs Node 22.19 or later. npm serves every release under the `alpha` dist-tag until the first stable one:
10
+
11
+ ```sh
12
+ pnpm add @buildanagent/harness@alpha
13
+ ```
14
+
15
+ All six buildanagent packages share one version, and the harness depends on that exact version of the gateway, the SDK, the protocol and `@buildanagent/agent-safety`. Name the tag: a plain `pnpm add @buildanagent/harness` installs `0.0.0-bootstrap.0`, a deprecated placeholder, because `latest` stays on it until the first stable release.
16
+
17
+ ## The session log holds twenty-one entry types
18
+
19
+ `@buildanagent/harness/session` re-exports the entry union from `@buildanagent/protocol`, where the [stable fields and the JSON Schema](https://github.com/laudebugs/buildanagent/blob/main/packages/protocol/README.md#a-session-file-is-a-list-of-entries-one-per-line) are documented. Every entry carries `id`, `parentId`, `seq`, `timestamp`, `type` and `origin`. The [session format page](https://github.com/laudebugs/buildanagent/blob/main/packages/harness/docs/session-format.md) lists every field of every type and says which are stable, and a test checks it against the JSON Schema. The types, in the order of the union:
20
+
21
+ - `session_header`: the first entry of a file, with the format, harness and SDK versions, the defaults hash, the capabilities, the ablation hash and, optionally, the parent session and the product.
22
+ - `turn_start`: a run began, with the frozen system prompt.
23
+ - `message_block` and `message_end`: one content block of a message, and the close of the message with its model and stop reason.
24
+ - `tool_result`: what a tool returned, with whether its output is trusted.
25
+ - `code_call`: a tool call that the host's own code made with `invokeTool()`, with no model step, and the earlier code call it undoes, if any.
26
+ - `permission_decision`: the permission pipeline's verdict on one call.
27
+ - `usage`: the tokens and cost of a model call, a summary or a judge call.
28
+ - `turn_end`: a run ended, with its stop reason and step count.
29
+ - `checkout`: HEAD moved to another entry.
30
+ - `compaction`: a summary replaced older entries in the context.
31
+ - `env_stamp` and `loadout`: the environment a session ran in, and a change of tools or model.
32
+ - `completion_check`: the commands that checked a finished task, and whether they passed.
33
+ - `skill_loaded` and `extension_loaded`: a skill or an extension entered the session.
34
+ - `subagent_link`: a child session exists, and which call or step started it.
35
+ - `approval_requested` and `approval_resolved`: a call waits for a person (with its signed request and the input it would run with), and the person's answer.
36
+ - `shadow_call`: a call that shadow mode recorded and did not run.
37
+ - `product_record`: a record the product owns, under a namespaced name.
38
+
39
+ ## A sandbox says what it stops, and the host decides what it may touch
40
+
41
+ `./sandbox` defines `SandboxClient`, a backend that provisions a `Sandbox` for a workspace and a `SandboxPolicy`: the folders it may read and write, and the hosts it may reach. The policy is separate from the `ApprovalPolicy` that says when a denied action may be asked for again, and the model never changes either. A backend reports a `tier` and the `stops` it claims, and it claims a stop only when its tier and setup deliver it:
42
+
43
+ | Tier | Backend | Stops | What it is |
44
+ | --- | --- | --- | --- |
45
+ | `none` | `noneSandbox({ unsafe: true })` | nothing | A command runs as the user, with the machine's files and network. For a machine that is already disposable, and for tests of the rest of the harness |
46
+ | `os` | `srtSandbox()` | mistakes and exfiltration | An operating-system sandbox that shares the host's kernel, on Linux only |
47
+ | `container` | `dockerSandbox()` | mistakes and exfiltration, as far as its setup allows | A container with its capabilities dropped and no network, on Linux only |
48
+
49
+ `mistakes` are the agent's own errors, such as a write outside the workspace. `exfiltration` is sending data to a host that is not allowed. No backend claims to stop a `hostile_process`, because a sandbox that shares the host's kernel can't promise it. A backend that can't start throws `SandboxUnavailableError`, and the host must not run unconfined, so no backend falls back to `none`.
50
+
51
+ `noneSandbox()` needs `unsafe: true`: leaving it out is a type error, and a JavaScript caller gets a `HarnessError` with the code `unsafe_sandbox_not_acknowledged`. Each sandbox it provisions writes a warning to standard error, or to the `warn` option. It enforces no policy, which is what `stops: []` says.
52
+
53
+ The example below runs a project's tests in a workspace and prints the exit code, or why the command was refused:
54
+
55
+ ```ts
56
+ import { noneSandbox, spawnEnv } from "@buildanagent/harness/sandbox";
57
+
58
+ const sandbox = await noneSandbox({ unsafe: true }).provision({ root: "/work/repo" }, policy);
59
+ const result = await sandbox.exec(["pnpm", "test"], { env: spawnEnv([]), signal: controller.signal, timeoutMs: 120_000 });
60
+ console.log("denied" in result ? result.denied.reason : result.exitCode);
61
+ ```
62
+
63
+ `exec` takes an executable and its arguments, with no shell, and resolves with the exit code and output. A failing command is a result, not an error, and a command the policy refuses resolves with `{ denied }`. A command that runs past `timeoutMs` stops with exit code 124, and one the system can't find gives 127. A command that a signal killed gives 128 plus the signal's number, with `signal` naming it. Output past `maxOutputBytes` (8 MiB for each stream by default) is dropped, and the result says `truncated: true`.
64
+
65
+ The `none` backend starts each command in its own process group. A timeout, an abort or `dispose()` therefore kills the command and everything it started, and `exec` settles even when a background process still holds the output pipes.
66
+
67
+ Bad input is an error, not a result. A working directory that isn't an existing folder, a bad `timeoutMs` or a bad `maxOutputBytes` throws a `HarnessError`. An already aborted signal rejects before the command runs, and reading a missing file rejects with the code `sandbox_not_found`.
68
+
69
+ ## The srt backend confines each command with Anthropic's OS sandbox
70
+
71
+ `srtSandbox()` from `./sandbox/srt` runs each command under `srt`, Anthropic's sandbox runtime. It pins `@anthropic-ai/sandbox-runtime` 0.0.83 under the Apache-2.0 license. The package calls itself a "Beta Research Preview", and says its APIs and configuration formats may evolve (as of November 2026). `provision()` writes the settings file, so `./sandbox/srt` is the one place that knows that format.
72
+
73
+ The backend claims `mistakes` and `exfiltration` on Linux and nowhere else, because Linux is the only platform it is tested on. It needs `bwrap` (bubblewrap) and `socat` on the `PATH`. `provision()` starts `srt` once with a command that does nothing. A missing program, an unsupported platform or a host where `srt` can't start a command therefore throws `SandboxUnavailableError`, and nothing runs.
74
+
75
+ The policy maps to `srt`'s settings like this:
76
+
77
+ - **Reads.** `srt` denies every read, then allows the read roots, the write roots, the system folders a program needs to start (`/usr`, `/bin`, `/lib`, `/etc` and a few more) and `srt`'s own helper folders. Anything else, such as `/home`, is out of reach. `extraReadRoots` adds folders, such as a toolchain's.
78
+ - **Writes.** Only the write roots are writable. `denyWrite` keeps a folder read-only inside a write root, which is how the session's own log folder stays out of the agent's reach. `writeFile` refuses the same folders, and the files `srt` protects, such as `.bashrc`, `.claude` and `.git/hooks`.
79
+ - **Network.** The command has no network of its own. Its traffic goes through a proxy that allows only the policy's hosts. `parentProxy` sends allowed traffic through an upstream proxy for a host that sits behind one.
80
+
81
+ Every path is passed as a literal, so a folder named like a pattern is never read as one. The settings file and a run folder for `srt`'s proxy sockets live in a private folder that `dispose()` removes. A command can read the run folder and nothing else in it, so it can't read the settings file, which may hold a proxy address.
82
+
83
+ A command's environment holds the variables it was given, plus the proxy variables `srt` adds, which `SRT_ADDED_ENVIRONMENT` lists. `srt` itself starts with only a `PATH` and its own `TMPDIR`. The given variables pass through `env` inside the sandbox, so a variable such as `NODE_OPTIONS` can't make `srt`'s own Node load code outside it. The backend never copies the host's `process.env`. A command whose first word contains `=` resolves with exit code 127, as under `none`.
84
+
85
+ Four limits are worth knowing:
86
+
87
+ - **Shared kernel.** The sandbox is a set of Linux namespaces, so a process that is trying to escape is out of scope, and no `hostile_process` stop is claimed.
88
+ - **No TLS inspection.** The proxy allows or refuses a host by name and does not read what a command sends it.
89
+ - **File calls run in the host.** `readFile` and `writeFile` check each path by its real path, so a symlink that leads out is refused. They check the opened file again through `/proc`, though a hostile process could still win that race. They don't run under `srt`, because two `srt` processes in one workspace can disturb each other: each makes and removes empty protected files there. Commands that run at the same time in one workspace share that risk.
90
+ - **Cleanup depends on `srt`.** A stopped command gets a `SIGTERM` and two seconds before the `SIGKILL`, so `srt` removes its protected files. A `SIGKILL` from outside leaves them.
91
+
92
+ The package's opt-in sandbox tests run the conformance suite and the escape cases against the real `srt`, and they fail on a skipped case instead of skipping. They are opt-in because they start bubblewrap. Without `srt`, the other tests check the settings and the unavailable paths.
93
+
94
+ ## The Docker backend runs each command in a locked-down container
95
+
96
+ `dockerSandbox({ image })` from `./sandbox/docker` runs each command in its own container, made from an image that is already on the Docker host: `provision()` never pulls, and you should pin the image by digest. The container has all capabilities dropped, a read-only root file system, no network, no new privileges and no shared IPC.
97
+
98
+ The container also has a limit on processes (`pidsLimit`, 256 by default), CPUs (`cpus`, 1) and memory with no swap (`memoryMb`, 1024). It runs as your user and group, so the files it writes stay yours, and its only other writable place is a 64 MiB `/tmp` in memory.
99
+
100
+ The policy decides what is mounted, at the same path inside as outside. A write root is mounted writable, and it must exist. A read root and an `extraReadRoots` folder are mounted read-only. A `denyWrite` folder inside a write root is made if it is missing and mounted read-only on top, so the session log stays out of the agent's reach. A `denyWrite` path outside every write root is not mounted at all. The protected files that `srt` also guards, such as `.bashrc`, `.claude`, `.git/hooks` and `.git/config` at the top of a write root, are mounted read-only when they exist, and `writeFile` refuses them. Nothing else is mounted, so a path outside the roots does not exist in the container.
101
+
102
+ The workspace must lie inside a root. The backend never mounts the Docker socket: a root that resolves to `/`, or that holds the daemon's socket (`/var/run/docker.sock`, `/run/docker.sock` or the one `dockerHost` names), is refused.
103
+
104
+ The container has no network, so a command reaches a host only through `proxySocket`: a Unix socket on the host, mounted at `DOCKER_PROXY_SOCKET_PATH` (`/run/harness/proxy.sock`), that the credential proxy listens on. The program in the image has to speak to that socket itself. Without `proxySocket`, no host is reachable, including the ones the policy allows.
105
+
106
+ `provision()` starts the `docker` client with a clean environment: a `PATH`, a private empty `HOME`, and `DOCKER_HOST` when the option or the host sets one. It never copies the host's environment. A missing client, a daemon that doesn't answer or an image that isn't on the host throws `SandboxUnavailableError` and runs nothing.
107
+
108
+ A command's environment is exactly the one it was given. `env -i` clears the image's own variables, so the image needs an `env` that takes `-i` and `--`, as BusyBox and GNU coreutils do. It also clears `PATH`, and a program name is then looked up on the C library's default path, which differs between images. Pass a `PATH`, as `spawnEnv()` does, for a program that lives elsewhere, such as `/usr/local/bin/node` in a Debian image. A command whose first word contains `=` resolves with exit code 127, as under `none`.
109
+
110
+ Each command is created and then started. A timeout, an abort or `dispose()` kills the container by name, so nothing outlives the call, and `dispose()` also removes any container of this sandbox that a stopped client left behind.
111
+
112
+ Five limits are worth knowing:
113
+
114
+ - **Shared kernel.** A container shares the host's kernel, so a process that is trying to escape is out of scope, and no `hostile_process` stop is claimed.
115
+ - **Protected files made later.** A protected file that is missing when `provision()` runs, or one in a subfolder, is not protected inside the container, because a mount needs a file to cover. An agent could write `.git/hooks/pre-commit` there, and the host's next `git commit` would run it. Keep `.git/hooks` and `.git/config` in place, or list them in `denyWrite`.
116
+ - **Linux and a rootful daemon.** Only Linux was tested, against a rootful daemon. Rootless Docker mounts differently and was not tested.
117
+ - **File calls run in the host.** `readFile` and `writeFile` check each path by its real path and through `/proc`, as under `srt`, and `writeFile` refuses a `denyWrite` folder. A hostile process could still win that race.
118
+ - **The network lock rests on the daemon.** `--network none` is checked by inspecting the running container, because a test host with no bridge can't tell a closed network from a missing one.
119
+
120
+ The same opt-in tests run the conformance suite and the lock-down cases against a real daemon, with a pinned Node image, and fail on a skipped case. Without Docker, the other tests check the flags and the unavailable paths with a fake client.
121
+
122
+ ## The egress proxy keeps every credential outside the sandbox
123
+
124
+ `startEgressProxy({ allow, routes, log })` from `./credentials` starts a proxy on `127.0.0.1`, or on a Unix socket you give it (`socketPath`, which is what `dockerSandbox`'s `proxySocket` mounts). Nothing leaves the sandbox except through it. It refuses everything that isn't on its allowlist with a 403, and it writes one log record for each request: the host, the method, the status and the bytes, never a header or a body. Give the sandbox `proxy.url` as `HTTPS_PROXY`. On a Unix socket, `proxy.url` is `unix:<path>`, which is not a proxy URL, and the program inside the container connects to the socket itself.
125
+
126
+ A tunnel (`CONNECT`) goes only to an allowlisted name on an allowlisted port, which is 443 unless the entry says `:port`. An entry is a name, or `*.name` for every name under it. The proxy resolves the name itself, checks every address it gets, and refuses the whole request if any one is not public: loopback, link-local (which holds the cloud metadata address 169.254.169.254), private, shared, multicast and reserved ranges, for IPv4 and IPv6, and IPv6 addresses that wrap one of them. The refused ranges include the IANA special-purpose ones and the deprecated site-local and IPv4-translated forms.
127
+
128
+ The proxy then connects to the address it checked, so a name that answers differently a moment later can't redirect the connection. An address literal as a target, an HTTP proxy request in absolute form and a malformed target are refused without a lookup.
129
+
130
+ A tool that needs a credential uses a route. `routes` lists, for each one, a name, an HTTPS host, the methods it accepts, the header that carries the credential and a function that returns the real secret. The sandbox sends `http://127.0.0.1:<port>/<route>/path` and puts `proxy.sentinels[route]`, a random placeholder, where the credential goes, such as `Authorization: Bearer <sentinel>`. The proxy checks the route, the method and the sentinel, replaces the sentinel with the secret and forwards the request over HTTPS to the route's host, with the same address check.
131
+
132
+ The secret is read for each request, so a rotated key is used at once, and it never enters the sandbox's environment, a log record or a response from the proxy.
133
+
134
+ `proxy.fetch(input, init)` is for tools that run in the harness's own process, which a network sandbox doesn't confine. It applies the same allowlist, address check and pinned connection, and it rejects with `egress_denied` for a host that isn't allowed. It uses HTTPS only and doesn't follow redirects, so each hop is a new call that the allowlist checks. A URL under `proxy.url`, or under `http://egress.proxy`, which also works on a Unix socket, is a route request with the same injection. An aborted signal rejects with its reason.
135
+
136
+ `scrubSecrets(entry, secrets)` returns a copy of a session entry with each secret replaced by `[REDACTED]`, in every string and key at any depth, and also when the secret was percent-encoded, JSON-escaped or turned into base64, alone or inside a longer value such as a Basic authorization header. An entry's `type`, `id`, `parentId`, `seq`, `timestamp`, `origin` and `formatVersion` are never rewritten. Apply it before every append, with `await proxy.knownSecrets()` and the tokens and session URLs of any hosted-browser, CDP or OAuth connector tool, because the scrubber can only remove a secret it is told about.
137
+
138
+ Four limits are worth knowing:
139
+
140
+ - **An allowed credential can still act.** The sandbox holds a placeholder, not the secret, but it can ask the proxy to use the real one on that host and those methods. Scope each route to the host and methods the task needs.
141
+ - **A service that echoes the credential back reveals it.** The proxy doesn't read responses, so a route to a service that returns the request's headers hands the secret to the sandbox. Scrub the entry, and don't route to such a service.
142
+ - **No TLS inspection.** A tunnel is an opaque stream: the proxy knows the name, not what the tool sends. Only a route can add a credential, and only a route sees the request.
143
+ - **Local processes can reach it.** The proxy listens on loopback, so any process on the host can use its allowed tunnels. Only a process that knows a sentinel can use a route, and sentinels are random for each proxy. A Unix socket narrows access to the socket's file permissions.
144
+
145
+ The package's tests run the proxy against a real HTTPS server on loopback, with a self-signed certificate that only the test trusts and a table in place of DNS.
146
+
147
+ ## Every spawned process gets a cleared environment
148
+
149
+ `spawnEnv(allow, extra)` builds the whole environment for a spawned process. It returns `PATH`, a fresh temp `HOME`, `TMPDIR` and `LANG`, the parent variables that `allow` names and the parent has, and `extra`. Nothing else is copied, so a key set in the parent never reaches a child. The caller removes the temp `HOME` when the process is done; an `extra.HOME` replaces it and no folder is made. `PATH` is the parent's with every entry that isn't absolute removed, so a `.` can't run a program from the working directory, and `TMPDIR` is the shared system temp directory, not a private one.
150
+
151
+ A name that isn't a valid variable name, or a value with a NUL character, throws a `HarnessError` with the code `invalid_spawn_env`. `allow` also refuses three kinds of name:
152
+
153
+ - a reserved name, which is always set already;
154
+ - a name that makes a program load code, such as `NODE_OPTIONS` or `LD_PRELOAD`;
155
+ - a name that looks like a credential: one with a `_`-separated part such as `KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `PAT` or `AUTH`, or a connection string or proxy URL such as `DATABASE_URL` or `HTTPS_PROXY`. So `ANTHROPIC_API_KEY` is refused and `GIT_AUTHOR_NAME` isn't.
156
+
157
+ The check goes by name and can't catch a credential under an unremarkable one, so name only variables you know. A credential can reach a child only as an explicit `extra`, written in code, such as a dummy key for the credential proxy. That keeps credentials out of the sandbox.
158
+
159
+ ## Test a sandbox with the fake and the conformance suite
160
+
161
+ `./testing` has `fakeSandbox()`, a sandbox in memory that enforces the policy it is given and records every `exec`, but runs no program: it understands `echo`, `env`, `cat`, `write`, `true`, `false`, `sleep` and `net-probe`. It claims tier `os`, because it enforces file roots and the network allowlist, but it confines no real process.
162
+
163
+ `runSandboxConformance(factory)` pins the interface for every backend. Its cases check that a file reads back as written, that `exec` reports exit codes and output, that the environment holds only the variables given, that an aborted signal rejects and a timeout stops with 124, and that `dispose` ends the sandbox and any command still running. When the caller passes `processTree`, a case also checks that an abort or timeout ends the command's whole process tree. A backend that adds variables of its own, such as proxy settings, lists them in `addedEnvironment`, and the environment case accepts those and no others.
164
+
165
+ A case that needs enforcement runs only when the backend's `stops` claim it:
166
+
167
+ - a write or read outside the roots, and a path that climbs out with `..`;
168
+ - a symlink that points outside, where the factory passes a `symlink` function;
169
+ - a working directory outside the workspace;
170
+ - the network, where the caller passes two hosts it controls, such as two loopback listeners: the allowed one must be reached and the blocked one must not.
171
+
172
+ `none` passes the rest and skips those with a reason, and a backend that can't start skips every case with its reason and fails none. The suite tells errors apart by `isHarnessError()` and the error's `code`, so a backend bundled separately from the suite still passes. `sandboxConformanceCases(factory)` returns the same cases one by one, for a runner that wants a test for each.
173
+
174
+ ## One registry names, defers and wraps every tool
175
+
176
+ `@buildanagent/harness/tools` holds the tools of every source in one registry, so permission rules, tool search and the session log read one description of each. `createToolRegistry()` returns it, and `register()` adds a tool with its source: `builtin`, `extension`, `client` or `mcp:<server>`.
177
+
178
+ - **Names.** A tool's canonical name is checked once, at registration, against the SDK's rule of 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. An MCP tool is namespaced as `mcp__<server>__<tool>`. A second tool with a name already taken throws a `DuplicateToolError`, and an extension replaces a built-in only with `override: true`.
179
+ - **Hashes.** An MCP tool whose server or tool name needs cleaning, holds a double underscore, starts or ends with an underscore, or makes the name run past 64 characters gets `_` and an eight-digit hash of its source and name. A name therefore depends on its tool alone and never on what was registered before it.
180
+ - **Aliases.** A native or display alias stays apart from the canonical name. No alias may equal another tool's name or alias, in either order of registration, so a rule that matches either matches one tool.
181
+ - **All or none.** `registerAll(tools)` registers a list, or none of it: when one tool is refused, it removes the ones the list registered before it and throws the error.
182
+ - **Exposure.** Every source has an exposure that the registry writes to each tool's `exposure`: `deferred` for MCP tools and `direct` for the rest. `setExposure(source, exposure)` changes it for a source, now and for tools registered later. A run keeps the exposure `definitions()` gave its tools, so call `definitions()` again for the next run. `definitions()` returns the tools in registration order and keeps it, so the cached prefix does not move when a tool activates.
183
+ - **Tool search.** `toolSearchTool(registry, { activated })` is a `tool_search` tool, and `activated` is required. It matches a query against the `deferred` tools' names and descriptions, records the best matches in `activated` and names them to the model, with the description of a trusted tool. An untrusted tool's description, such as an MCP server's, counts as one matched word at most and is never quoted, and one untrusted source takes at most half the results. `toolSearchInterceptors(registry, activated)` sends the run's tools, including any from outside the registry, plus the activated ones. A deferred tool is therefore absent from each request until the model asks for it, and present in the next. The search ignores common words such as `the` and `for`, counts a repeated word once, and takes a `maxResults` of 1 or more. A `hidden` tool is never found, and `tool_search` itself is always sent, so a source set to `deferred` cannot leave the model with no way to find a tool. Register `tool_search` in the registry, because the interceptor sends it by that name and throws when the registry lacks it. Pass the same set to the tool and the interceptor, and a new one to each run.
184
+ - **Host context.** `definitions(wrap, hostContext)` runs each tool through `wrap`, which can bind a write cap, shadow mode, a sandbox or the turn's host context. The registry sets the result's name and exposure, so a wrapper cannot rename or expose a tool. The host context reaches `execute` by the wrapper's closure, never through a schema, so it is in no request, event or saved context.
185
+ - **Output trust.** A tool's `outputTrust` is `untrusted` for an MCP tool and for a tool registered with `remoteAgent: true`, `trusted` otherwise, and the value a registration declares wins. `approvalReuse` defaults to `both`, and `pattern` records whether the tool runs `in_process` or by a `client_request`.
186
+ - **Preamble size.** `preambleTokens({ system })` estimates the tokens a request carries before any message: the system prompt and every `direct` tool. A `deferred` tool adds nothing, which is why the default for MCP is `deferred`. A `RegisteredTool` that `register()` returns is a snapshot, so call `get()` after `setExposure()` to read the current exposure.
187
+
188
+ ## One pipeline decides every tool call, and a call no rule settles is denied when nobody can answer
189
+
190
+ `@buildanagent/harness/permissions` decides each tool call in one order: hooks, deny rules, ask rules, the mode, allow rules, the host callback, then the no-match default. A deny at any step ends the decision, so a deny rule beats every mode, `bypass` included, and a hook's deny beats everything. `createPermissionPipeline(config, registry)` returns a pipeline, and `pipeline.gate(context)` is the SDK's `beforeToolCall` gate, where `context` gives each call its session, host context and entries.
191
+
192
+ - **No match.** With no host callback, a call that no rule settles asks when `interactive` is `true` and is denied when it is `false`.
193
+ - **Hooks.** A hook returns a deny, an ask or nothing, and its type has no allow. A hook that returns an allow, or anything else, denies the call. A hook's ask stands unless a deny rule matches later, and a hook that throws denies. A classifier belongs in a hook, which can only restrict, or in the host callback, whose allows carry `by: "classifier:<id>"` in the log.
194
+ - **Rules.** A `Rule` names a tool by name, alias, a `*` pattern or a regular expression. It may add `paths`, globs matched against the input's path fields (`path`, `file_path`, `paths` and a few more, normalised so `./` and `..` do not slip past), and `commandPrefix`, the leading words of a shell command. A deny or ask rule matches when any path or any part of a chained command matches. A relative glob in such a rule matches below any directory, because the pipeline doesn't know the working directory. An allow rule needs every path inside its globs, counted from the workspace root, and every part of the chain covered by some allow rule, so `git status && rm -rf /` is not allowed by a rule for `git status`.
195
+ - **Shell parsing reads what a shell would run, to three levels.** For every rule it splits a command on `&&`, `||`, `;`, `|`, `&` and newlines outside quotes, and reads subshells, groups and the script of a shell given `-c`. For deny and ask rules it also reads `$( )`, backticks and `<( )`, and looks past a program's directory, `sudo -u root`, `env -i`, `timeout 5`, `xargs`, `eval`, `NAME=value` words, keywords such as `{` and `!`, and git's global options, as in `git -C dir rm`. A command given as a word list is read the same way.
196
+ - **Shell parsing fails closed.** A command with a substitution, or an `$'...'` word with an escape, is never allowed by a rule, because its parts can't all be read. An allow rule with a `commandPrefix` does not cover a redirection to or from a file, only a copy of one stream to another and a redirect to `/dev/null`. A command nested deeper than three levels, or carried in a field the parser doesn't know, counts as a match for every deny and ask rule that has a `commandPrefix` for the tool.
197
+ - **What it does not read.** The parser does not decode escapes or follow aliases, functions, variables, here-documents or a script the command writes first, and a deny or ask rule does not read a redirection's target as a path. Run untrusted commands in a sandbox as well.
198
+ - **Modes.** `default` adds nothing. `accept_edits` allows `editTools` (default `write`, `edit`, `multi_edit`, `apply_patch`). `read_only` allows `readOnlyTools` (default `read`, `grep`, `glob`) and denies every other tool, whatever allow rules, ask rules and hooks' asks say, because an approval must not widen a limit. `bypass` allows whatever no hook, deny rule or ask rule stopped. `shadow` allows the same calls and skips asks, because nothing runs. `pipeline.shadowWrapper(session)` gives `registry.definitions()` a wrapper that writes a `shadow_call` entry and returns a fixed result in place of each tool's `execute`, and a pipeline in `shadow` mode refuses every call until that wrapper has been taken.
199
+ - **A shadowed callback is a startup error.** An allow rule with no `paths` and no `commandPrefix`, for a registered tool, throws `PermissionConfigError` while a host callback is set, because the callback could never decide a call to that tool. Deny rules, hooks and a host callback with no allow rules start cleanly. A tool registered later is checked when a call reaches the rule, and the call is refused and logged.
200
+ - **Every decision is logged.** Each `decide()` appends one `permission_decision` entry, allows included, with the decision, the rule, who decided, the `policyVersion` and the hash of the input. The pipeline fails closed: an entry that can't be written rejects the decision and the gate denies the call, and an input with no canonical form is denied.
201
+ - **Default ask rules.** `defaultAskRules` asks for a change to a test file and to a hook, CI configuration or a rules file, and for `git rm`. They match by path, so they ask for every change to such a file and can't tell a deleted test from an edited one; a hook can.
202
+
203
+ ## A session belongs to a user, and every store call names both
204
+
205
+ `@buildanagent/harness/session` holds the `SessionStore` interface and `memoryStore()`, and `@buildanagent/harness/session/jsonl` holds `jsonlStore({ dir })` and `fileLock({ dir })`, which need Node's file system. A store keeps each session under a `SessionKey`, `{ userId, sessionId }`. `append`, `load` and `delete` take that key, and `list` takes the user, so no call finds a session by its id alone. A type test checks that a call with the id alone fails to compile. A session under another user looks exactly like one that doesn't exist: `load` yields nothing, `delete` does nothing and `list` leaves it out. A lookup must name the user even on a host that isolates users some other way, because adding the user later would change every caller.
206
+
207
+ - **Append assigns and returns.** `append(key, entries, { expectedLastId })` takes entries without `seq`, assigns each its sequence number and returns the stored entries. A session's first entry must be its `session_header`, and every entry must pass the protocol's `parseEntry()`.
208
+ - **Append is idempotent.** An entry already stored with the same content is not written again, and one stored with different content throws a `ConflictError`. A batch that is partly stored finishes on a retry. If another writer has extended the log since, the retry throws a `ConflictError`.
209
+ - **Append is a compare-and-swap.** `expectedLastId` names the entry the log must end with, so two writers can't extend one log. A stale tail throws a `ConflictError` and writes nothing, and `null` means the session must not exist yet. A batch is written whole or not at all.
210
+ - **Size.** An entry whose JSON is over 64 KiB, counted in bytes, throws an `EntryTooLargeError`. `maxEntryBytes` changes the bound. Spill large content to a file and keep a reference.
211
+ - **Load.** `load(key, { fromSeq, onTornLine })` yields the entries present when it began, in order. A last line that was never completed is skipped and reported once through `onTornLine`, and a bad line anywhere else throws a `HarnessError` with code `session_corrupt`.
212
+ - **The JSONL store survives a crash.** It writes `<dir>/<user>/<session>.jsonl`, one entry per line, each append as one write of whole lines followed by an `fsync`, so a crash leaves at most one unterminated last line. The next append cuts that line off.
213
+ - **File names cannot escape their folder.** Names are percent-encoded, capital letters and dots included, so no id can name `..`, reach another user's folder or collide with another id on a file system that ignores case.
214
+ - **One process is safe, and two need the writer lock.** The store caches the state of the 64 logs used last and rereads a log when the file's size has changed, so another process's write is seen on the next append. Two processes writing one session still need the writer lock. `list()` skips a file it can't read, so one bad file hides no other session. The `fsync` on every append costs time that a later timing run should measure.
215
+ - **Add a backend.** Pass a factory to `runStoreConformance(factory)` or `storeConformanceCases(factory)` from `@buildanagent/harness/testing`. A factory returns a fresh empty store, and optionally `tearLastLine(key)`, which leaves a log ending in a line that was never completed so the torn-line cases can run. The suite imports no test runner and no Node module. A backend that passes the cases follows the append, size and load rules above.
216
+
217
+ ## One writer holds a session's lock, and a lock outlives a crash only by its lease
218
+
219
+ `fileLock({ dir })` in `@buildanagent/harness/session/jsonl` is a `SessionLock` that keeps one lock file per session, `<dir>/<user>/<session>.lock`, keyed like the store. `acquire(key)` creates the file with the exclusive-create flag, writes `{ pid, host, token, leaseUntil }` and returns a handle, or returns `"would_block"` at once if another writer holds it. It never waits. Readers never lock.
220
+
221
+ - **Lease.** The holder renews every `renewMs` (default 10 seconds) for a `leaseMs` lease (default 30 seconds). The renewal overwrites the lock's fixed-size record in place through an open handle. It can't recreate a released lock, because the open fails, and it can't overwrite a successor's lock, because that is a different file. A renewal that finds the lock gone or another writer's token gives up, and `handle.held()` turns `false`. Any other error is retried on the next tick. A writer that sees `false` must stop writing.
222
+ - **Stale.** A lock is stale only when its lease has lapsed and, on the same host, its process no longer exists. A lock whose process is alive is never taken, and neither is one whose lease still runs. A lock from another host is never taken by `acquire()`, because this host can't tell whether that process lives. `unlockSession({ dir }, key)` removes any lock and says what it removed. It is the library behind `buildanagent session unlock --force`, and the caller decides that it is safe.
223
+ - **Takeover.** Taking a stale lock runs under a short-lived guard file, so two writers racing for one stale lock can't each delete the other's new lock. A lock file with no readable record blocks until it is older than a lease, because its writer may still be writing it.
224
+ - **Release.** `release()` stops the renewal, waits for one in progress, and removes the lock only if it still holds this handle's token, so a writer that lost its lock never frees the next holder's.
225
+ - **Local disk only.** An exclusive create is not reliable on a network file system, so NFS and similar are unsupported. Another host needs a different `SessionLock`, such as a lease row in a database.
226
+ - **Pid reuse.** If the system reuses a dead writer's pid, the stale lock stays until that process ends. The lease and the token make this a delay and never a corruption.
227
+ - **The crash test.** A test spawns a child that takes the lock and appends in a loop, kills it with `SIGKILL`, and requires a new writer to get the lock within one lease and every complete entry to load.
228
+
229
+ ## HEAD moves by entries, and a fork or a revert writes a new file and never edits an old one
230
+
231
+ `openSession({ store, index, key, lock })` returns a `Session`, one session's log with its HEAD. With a `lock` it takes the session's writer lock and may write, and without one it can only read. A session opened while another writer holds the lock throws `session_locked`, and one that has lost its lock must stop writing. The log is an append-only tree: each entry names the entry it follows, and `head()` is the entry the next append follows, or `null` before the first one.
232
+
233
+ - **HEAD is in the log.** Each appended entry moves HEAD to itself, and `checkout(id)` appends a `checkout` entry that moves it to `id`. A reload replays the entries, so HEAD comes back where it was left. An append after a checkout follows the entry checked out, so the other branch stays in the log.
234
+ - **Path.** `path(id)` lists the entries from the root to `id` (default HEAD) by following `parentId`. It leaves out `checkout` entries, which move HEAD and aren't part of the conversation.
235
+ - **Fork.** `fork(id)` starts a new session from `id`. Its new file holds a header that names this session's file and the entry as its parent, and a `checkout` of that entry. Its `path()` crosses into the parent file, so the prefix is shared and never copied, and only the entries up to the fork point are part of it. The returned session has a new id, and this one is unchanged.
236
+ - **Revert.** `revert(id)` writes the same kind of file and points this session at it, so the session goes on from `id`. The old file keeps every entry and is never touched, but the entries after `id` are no longer part of this session's tree: `path()` and `checkout()` reach only the entries from the root to `id` and the new file's own. A crash before the pointer moves leaves the old file in use.
237
+ - **The pointer.** The pointer to a session's current file is the only mutable state. `memoryIndex()` keeps it in memory, and `fileIndex({ dir })` in `@buildanagent/harness/session/jsonl` replaces a small JSON file by writing a temp file and renaming it.
238
+ - **Derived files.** The files a revert or a migration writes have names that start with `~`, and `listSessions()` leaves them out of a listing, because a session is known by its key.
239
+ - **Child.** `child({ spawningCallId })` or `child({ stepId })` starts the log of a subagent or a workflow step as its own session, and records the link in this session with a `subagent_link` entry that carries the one id given. Giving both or neither throws. The child's header names this session and the link entry as `parent` and the id as `spawn`, and its `path()` does not cross into this session, so a child never shares the parent's conversation.
240
+ - **Migration.** `migrateSession()` takes a log in an older format through the migrations it is given, writes the result as a new file in one append, which checks every entry against the current format, reads it back, and only then moves the pointer. The old file stays as it was. A log from a newer format is refused with `unsupported_format`, because only a newer harness can read it. `migrateSession()` takes the session's writer lock for the whole migration. It leaves a log that is already current alone, whatever its header names, and refuses to migrate a file whose header names a parent, because that parent would stay in the old format. It can't see forks that name this file as their parent, because a store has no index of dependents. Migrate only a session with no forks: an existing fork would still name the old-format file as its parent and become unreadable.
241
+ - **A file in another format is not corruption.** A store that finds a header it doesn't read throws `unsupported_format` and not `session_corrupt`, and offers `loadRaw()` so a migration can read the entries as they were written.
242
+
243
+ ## Nothing is deleted unless you set a retention period
244
+
245
+ `jsonlStore({ dir })` never deletes or moves a file. To expire old sessions, give it `retention: { days, action }`, or call `pruneSessions({ dir, userId, retention })` yourself, both from `@buildanagent/harness/session/jsonl`. A session expires when the newest entry in any of its files is more than `days` old. Its files count wherever they are, live or archived.
246
+
247
+ - **`archive`** gzips each of the session's live files into `<dir>/.archive/<user>/` and removes the original once the archive reads back to the same bytes. The pointer stays. `list()` and `load()` still find an archived session, and a write restores the file it writes to.
248
+ - **`purge`** deletes the session's files, live and archived, and then its pointer. A session that was archived before you switched to `purge` is deleted once it expires.
249
+ - **When in doubt, a file stays.** Before it removes anything, a run takes the lock of each session it means to expire, reads the folder again, and decides from that second read which sessions survive: the fresh ones, the locked ones, and the ones it can't read or date. A writer that appended just before the lock is judged on what it wrote. A purge keeps every expired session that a survivor continues, as a fork continues its parent, and removes a fork before its parent. A file the store wrote but the run can't read stops every purge for that user, because it could be a fork of any session; it is listed in `skipped`, and an archive still goes ahead.
250
+ - **Edge cases.** How a run stops part-way, fails on one session, treats a torn file and reads files is on the [session format page](docs/session-format.md#nothing-expires-unless-you-set-a-retention-period).
251
+ - **When it runs.** `pruneSessions()` runs it when you call it, and the `sessions prune` command will call it. A store with `retention` also runs it once per user per process, on its first `list`, `load`, `append` or `delete` for that user. It never runs on a timer. After one clean pass, the store does not expire that user's sessions again until the process restarts, so a long-running server must call `pruneSessions()` on a schedule of its own, with the lock its writers hold. The store passes each error of its pass to `onRetentionError`, ignores an error the callback throws, and runs a failed pass again on the first call at least a minute after it ended. A store call waits for a pass that is running, and a pass keeps any session with a store call already in flight, so a pass never moves a file under the store's own append or delete.
252
+ - **Locks.** Pass the session `lock`, and a session whose writer is running is kept. Without a lock, a writer in another process or another store is not protected from a run.
253
+ - **A delete leaves files behind.** `delete()` removes a session's first file and that file's archive, but not the files a revert or a migration made, nor the pointer. A run treats what is left as the deleted session: it expires on the dates of those files, a purge removes it and an archive moves it, and neither brings the deleted first file back.
254
+
255
+ ```ts
256
+ const store = jsonlStore({ dir, retention: { days: 30, action: "archive" }, lock });
257
+ const { archived, purged, kept, skipped, errors } = await pruneSessions({
258
+ dir,
259
+ userId: "ada",
260
+ retention: { days: 30, action: "purge" },
261
+ });
262
+ ```
263
+
264
+ The package sets no default period, and `days` must be a positive number or the call throws `invalid_retention`. The [session format page](docs/session-format.md#nothing-expires-unless-you-set-a-retention-period) says where the archive is, and it has the [disk-cost projection](docs/session-format.md#what-a-month-of-sessions-costs-on-disk).
265
+
266
+ ## `runTurn()` writes one SDK run into the log, and the user entry goes first
267
+
268
+ `runTurn(session, harness, options)` from `@buildanagent/harness/session` runs one turn of a `Harness` (built with `createHarness()` from `@buildanagent/harness/server`) on an open session. The input blocks are durable before `run()` starts, so a turn that dies before its first model call leaves the question in the file. A new session's first turn writes a `session_header`, which holds the SDK's version, defaults hash and capabilities, and an `env_stamp`. Any turn whose model or tool set differs from the last recorded one first writes a `loadout`, and a hook that swaps the model inside a turn is refused, so set `model` on the next turn instead. Every write goes through one queue, so the permission pipeline's `permission_decision` entries and the run's own never race for a parent. A failed write aborts the run, and `runTurn()` rethrows it.
269
+
270
+ | SDK event | Entry |
271
+ | --- | --- |
272
+ | input (before `run()`) | `message_block` with `delivery: "input"`, origin `user` or `operator` |
273
+ | `run_start` | `turn_start`, with the turn's exact system prompt |
274
+ | `model_call_end` | one `message_block` per block, a `message_end` and a `usage` |
275
+ | a turn-layer `retry` | a `usage` entry only |
276
+ | `tool_call_end` | `tool_result` with its own `callId` and the tool's declared output trust |
277
+ | `steer_applied` | `message_block` with `delivery: "steer"` or `"followUp"` |
278
+ | `run_end` | `turn_end` |
279
+
280
+ Call `runTurn()` once at a time per `Session`: its writes stay in order within one call, but two concurrent calls on one `Session` can interleave their entries. A turn may set `system`, `output`, `model`, `maxSteps`, `turnRetries`, `modelOptions`, `budgetUsd`, `signal`, `tools` and `hostContext`. `tools` is an allowlist of registered names, and an unknown name throws `invalid_turn_options`. `hostContext` reaches a tool as `ctx.app` and reaches no entry. `onRun` hands the caller the run, so it can `steer()` or `followUp()` it. `clientTool` runs every call to a tool registered with the `client_request` pattern in place of its own `execute`; the dispatcher sets it to send `tool/call`, and without it the tool's own `execute` runs.
281
+
282
+ ## One dispatcher answers every client, and a client in the same process needs no framing
283
+
284
+ `createDispatcher({ harness, store, index, lock, userId })` from `@buildanagent/harness/server` serves the protocol's commands over a harness. `inProcessTransport(dispatcher)` connects a client in the same process. Its `request(method, params)` resolves with the result, or rejects with an `RpcFailure` whose `rpc` field holds the error code and message. `onMessage()` listens for the server's notifications and requests. `respond(request, result)` and `fail(request, error)` answer a request, and `respond()` takes only the result type of that request's method, so an approval can't be answered with a tool result. `stdioTransport()` carries the same messages to a client in another process, one per line, as [its section](#stdiotransport-serves-one-client-over-a-pair-of-byte-streams) describes.
285
+
286
+ ```ts
287
+ const client = inProcessTransport(createDispatcher({ harness, store, index, lock, userId: "ada" }));
288
+ client.onMessage((message) => {
289
+ // "event" and "turn/settled" notifications, and the server's requests, which carry an id.
290
+ if ("id" in message && "method" in message && message.method === "approval/request") {
291
+ const { id: requestId } = message.params.request;
292
+ client.respond(message, { resolutions: [{ requestId, decision: "allow" }] });
293
+ }
294
+ });
295
+ await client.request("initialize", { clientInfo: { name: "cli", version: "1" }, capabilities: [] });
296
+ const { session } = await client.request("session/create", { cwd: "/work" });
297
+ const disposition = await client.request("turn/start", { session, input: [{ type: "text", text: "Hi" }] });
298
+ ```
299
+
300
+ `turn/start` answers with a disposition before anything else: `{ accepted: true, turn }`, or `{ accepted: false, reason }`. The reason is `busy` when this dispatcher already runs a turn (or a checkout or fork) in the session, `locked` when another process holds the session's lock, and `invalid` for a session the connection never created or opened. The turn's events follow as `event` notifications. When an event is an appended entry, its `seq` is that entry's sequence number; any other event carries the sequence of the latest entry written. Every turn ends with one `turn/settled`, sent after the turn's retries and after its last entry is written. A turn that throws settles with the stop reason `error`.
301
+
302
+ A steer or follow-up belongs to the turn its disposition names. One that arrives before the run exists waits for it, and if the turn fails before its run starts, the steer ends with the turn: `turn/settled` reports the failure, and the log holds no message for the steer.
303
+
304
+ The log, not the dispatcher, holds the state. The dispatcher takes the session's lock only while a turn, checkout, fork or resume runs, and a client can drive only the sessions it created or opened. It announces only the entries written to the session's current file, so a child session's header never appears in its parent's stream. `session/create` takes a `cwd`, which the dispatcher records for the session and does not yet pass to a turn. A closed dispatcher refuses new connections and answers `turn/start` on an open session with an error. `session/checkout` and `session/fork` are experimental: a client lists them in the `capabilities` of `initialize`, or the server answers `NotOptedIn`.
305
+
306
+ ### A request for a person goes to every watching client once its entry is durable, and the first answer wins
307
+
308
+ When a call needs a person, its turn ends `awaiting_approval` or `clarification_requested`, as [the approvals section](#a-call-that-needs-a-person-is-a-signed-pause-that-any-process-with-the-key-file-can-resume) describes. The dispatcher sends `approval/request` or `clarification/request` to every connection that watches the session, and only after the `approval_requested` entry's append has resolved. A client that hears of a request can therefore always find it in the log. Each request has a server id of the form `sr-<n>` and carries the signed request.
309
+
310
+ - **The answer.** A client answers with `{ resolutions: [resolution] }`: exactly one resolution, naming the signed request it was asked about. An approval takes `decision` `allow` or `deny` with an optional `reason`; a clarification takes `answer`. Either may carry `by`, which the dispatcher passes on unchecked, so the transport is where a host authenticates its clients.
311
+ - **The first answer wins.** The dispatcher withdraws the same question from every other connection with `$/cancelRequest`, and ignores a later answer, a second answer to the same id and an answer to an id it never sent or already withdrew.
312
+ - **A malformed answer** is asked again on the same connection under a new id. An error response leaves the request waiting in the log, and the client is asked again the next time it opens the session.
313
+ - **The resume.** The answer goes through `Approvals.resolve()`, by default `createApprovals(harness)` or the dispatcher's `approvals` option, as a turn of its own with a new turn id. It runs once the session is free, so an answer that arrives while the paused turn is still finishing waits for that turn's `turn/settled`. The resume streams its events and ends with its own `turn/settled`. Before it resolves, the dispatcher reads the log under the lock and drops an answer whose request no longer waits, because another process resolved it first. A resume with no answer left runs nothing and settles nothing.
314
+ - **An answer the resume could not apply.** When another process holds the lock, the lock can't be taken, or an interrupt stops the resume before it writes, the resume writes no answer. Its `turn/settled` then carries the error kind `answer_not_applied`, with the stop reason `error`, or `aborted` after an interrupt. The request still waits in the log, and the dispatcher asks every watching client again, at most three times per request, so a lock held elsewhere can't make a loop. After that, the client is asked again the next time it opens the session. A closed dispatcher asks nobody.
315
+ - **After the resume.** A request the resume left waiting, such as one a quorum still needs, is asked again. A resume that failed after it wrote its answers asks nothing. An answer that arrives while a `turn/start` holds the session waits for it, and still resumes when that turn fails to start.
316
+ - **Asking again on open.** The dispatcher reads the waiting requests from the log, and reads again if an answer was taken or applied during the read, so a client is never asked about a request someone else has just resolved.
317
+
318
+ Nothing holds a session open while a client thinks. The paused turn has already settled and released the lock, and the request lives in the log, so a client that never answers costs one entry in each connection's table of open requests until that connection closes.
319
+
320
+ ### A client tool's call goes to the client that started the turn
321
+
322
+ A tool registered with `pattern: "client_request"` runs on the client. The dispatcher sends `tool/call` with the session, the call id, the tool's canonical name and the validated input, to the connection that started the turn; for a resume, to the connection whose answer started it. The client answers with `{ content, isError }`, which becomes the call's result. The call never waits on a client that is gone. With no such connection, when the connection closes before answering, and for an error response or an answer that is not a tool result, the model gets an error result and the turn goes on. An abort of the turn withdraws the call with `$/cancelRequest`, and an answer that arrives after that is ignored.
323
+
324
+ ### Either side cancels its own request with `$/cancelRequest`
325
+
326
+ A client cancels a `turn/start` by sending `$/cancelRequest` with that request's id, at any time until the turn settles. A client that reuses the id for a later `turn/start` cancels the later turn. The dispatcher aborts the run, and the turn still ends with one `turn/settled`, with the stop reason `aborted`. In the in-process transport, pass `{ signal }` as the third argument of `request()`; aborting the signal after the disposition still cancels the turn. A cancel for any other request, or for an id the server does not know, does nothing, and that request is answered as usual. The server sends `$/cancelRequest` for its own requests: an approval someone else answered, and a tool call whose turn was aborted.
327
+
328
+ ### Each connection's queues are bounded at 128, and only events are dropped
329
+
330
+ `queueSize`, 128 by default, bounds two queues of each connection.
331
+
332
+ - **Commands.** A connection holds at most 128 unanswered commands. A command keeps its place until its response has gone out, not just until it is computed, so a client that sends faster than it reads is refused as soon as 128 commands wait. The 129th gets the error `QueueFull` (-32001), and a refused command takes no place. A refusal waits to go out like any response, so the refusals are bounded too: once 128 of them wait undelivered, the client is neither reading nor waiting, and the server closes the connection.
333
+ - **Events.** `connect(send)` takes a `send` that may return a promise, and the next message waits until that promise settles. While a slow client keeps messages waiting, at most 128 live events wait with them, and the server drops each event past that. An `events_dropped` event takes the place of a session's dropped events: its `count` says how many, and its `seq` is the last dropped event's. It goes out before the session's next message, or once the queue empties.
334
+ - **Never dropped.** Responses, server requests, `turn/settled`, `$/cancelRequest`, the `events_dropped` marker and replayed events always go out. What produces each of them bounds it: the command queue bounds the responses, the refusal bound bounds the `QueueFull` errors, the waiting requests bound the server requests, and each turn sends one `turn/settled`.
335
+
336
+ A client that takes each message at once, as the in-process transport does, never loses an event. A client told of a gap gets every dropped entry back from `session/open`. Live events go on after the marker, so the client sends a `fromSeq` one past the last `seq` it received before the marker, and drops by `seq` any entry it then gets twice.
337
+
338
+ ### `session/open` with `fromSeq` replays the entries a client missed
339
+
340
+ `fromSeq` is the first sequence number to replay, so a client that last saw `seq` N sends N + 1. The dispatcher reads the session's current file from that entry on and sends each entry as an `entry_appended` event, then the live stream. It holds the session's live events from the start of the open, so the response comes first, then the replay, then what happened meanwhile, and no entry is sent twice or lost. The log is the replay window. A `fromSeq` is therefore never too old, and a second process, or the same one after a restart, replays what the first wrote. Only entries are replayed. Streamed events such as text deltas are transient, and the entries that follow them hold the same content.
341
+
342
+ `fromSeq` must be a whole number of at least 0. A `fromSeq` one past the last entry replays nothing, and one further, which no client could have seen, is refused with `InvalidParams`. Replay follows the open's rules: only a connection that opens the session gets it, a failed open replays nothing, and a dispatcher serves only its own user's sessions. When a second open fails on a connection that already watched the session, that connection keeps its live stream. What the failed open held goes out, and a marker stands where the hold dropped anything. The marker counts only what the replay lacks, and its `seq` is never below the replay's last entry.
343
+
344
+ ### A client that reconnects finds its pending requests in `initialize` and is asked again on open
345
+
346
+ A request survives its client. `initialize` lists in `pending` every request still waiting in every readable session of the user, so a client that joins can re-arm them. `initialize` alone grants no access to a session, so the server sends the requests again, under new ids, only once the client opens the session with `session/open`. The id a closed connection held is stale, and an answer to it is ignored. A connection that dropped without closing still holds its old request. When someone else answers the question, the server withdraws it from that connection with `$/cancelRequest`.
347
+
348
+ ### `stdioTransport()` serves one client over a pair of byte streams
349
+
350
+ `stdioTransport(dispatcher, { input, output, log }, { maxLineBytes, signal, writeTimeoutMs })` connects one client and resolves when that client is done. `input` is a Node `Readable` such as `process.stdin` or a Web `ReadableStream`, and `output` is a Node `Writable` such as `process.stdout` or a Web `WritableStream`. `log` takes the transport's own diagnostics, one line each, and a host points it at stderr, because `output` carries protocol lines only. A diagnostic never quotes what the client sent. The transport's source, `stdio.ts`, imports no Node module, so the same function can serve a Worker's streams. The transport authenticates nobody: whoever holds `input` and `output` acts as the dispatcher's user, and the dispatcher passes `Resolution.by` on as the client sent it. Run it only where you trust every process that can reach the two streams; binding a client to an identity is not built yet. The [protocol README](https://github.com/laudebugs/buildanagent/blob/main/packages/protocol/README.md#over-stdio-each-message-is-one-line-and-stdout-carries-nothing-else) gives the wire rules: one message per line, an error for each bad line, and commands that may be answered out of order.
351
+
352
+ - **Backpressure.** The transport writes a message, and when `output` reports itself full, the connection's queue waits for `drain` before it hands over the next one. A client that stops reading therefore keeps the server's backlog near the stream's own buffer, and the dispatcher drops live events past `queueSize` instead of holding them. While `output` is full, every write shares one wait for room, so a long session adds no listener to the stream. `input` goes on being read meanwhile, and the connection's limit of 128 unanswered commands bounds what a client that sends without reading costs.
353
+ - **Bad lines.** The transport answers a line it can't read itself, outside the connection's queue. An answer the output takes at once costs nothing, so a client that reads can send any number of bad lines. Once 128 answers wait on a full output, the client is sending without reading, and the transport stops. A malformed response, one that carries `result` or `error`, is only logged, because JSON-RPC never answers a response; the server's request it meant to answer still waits for a good one.
354
+ - **A message JSON can't carry.** When `encode()` refuses a message the server built, such as a tool call whose input holds a `bigint`, the transport logs it. A response goes out as `InternalError`. A server request is answered back into the connection with `InternalError`, as if the client had failed it, so a tool call ends with an error result instead of waiting. A notification is dropped.
355
+ - **Shutdown.** When `input` ends, the transport waits until every command it read has its response queued and every line is written, then closes the connection and resolves. An `input` that fails is logged and handled as an end. Four events stop the transport at once: `output` fails, `output` closes, the dispatcher closes the connection, or `signal` aborts. It then closes the connection, logs why and resolves. The dispatcher closes a connection whose client leaves 128 refusals unread, and `connect()`'s `onClose` option reports that. A client that closes its input and never reads ends the wait after `writeTimeoutMs`, and a host that wants an earlier stop aborts `signal`. A transport that can't start, because the dispatcher is closed or a Web stream is already locked, rejects and leaves both streams as it found them.
356
+ - **The streams stay the host's.** The transport never ends, closes, destroys or cancels either stream. When it resolves, it has removed every listener it added, paused a Node `input` and released a Web stream's lock, so the host can go on using both and decides when its process exits.
357
+ - **What the transport does not check.** The transport checks each message's envelope with `decode()`. Before a handler runs, the dispatcher checks a command's params against the protocol schema. A command with malformed params gets `InvalidParams`, which names the method, the path of the failed field and the failed keyword, and never a value or a field name the client chose. A command with no `params` is checked as if it carried `{}`. The check covers `params` only, and `decode()` still checks the rest of the envelope.
358
+ - **A client that stops reading.** Once the input has ended, the transport waits for the output to take what is queued. The output must take each queued line within `writeTimeoutMs` (30,000 ms by default, `Infinity` to turn the check off), or the transport logs why and closes the connection. Each line the output takes restarts the wait, so a client that keeps reading is not cut off. A client that takes one very large line more slowly than the limit is cut off, so a host that serves such lines raises the limit. A value that is not a whole number from 1 to 2,147,483,647, or `Infinity`, rejects with `invalid_transport_options` before the transport connects.
359
+
360
+ `test/server/stdio.test.ts` runs the server in a child process spawned with `spawnEnv([])`. `test/server/stdio-transport.test.ts` drives the transport in process over streams it holds, for the stops, the bounds and the streams left behind. The child-process test checks that a client completes a turn, that stdout holds only protocol lines, that the end of stdin still gets every answer, and that a client that stops reading leaves at most 256 KiB waiting while 25,000 events stream. It also sets a variable in the parent and checks that the child's environment holds only `PATH`, `HOME`, `TMPDIR` and `LANG`.
361
+
362
+ ### `webSocketTransport()` serves one client on one WebSocket
363
+
364
+ `webSocketTransport(dispatcher, socket, { maxMessageBytes, maxBufferedBytes, writeTimeoutMs, signal, log })` connects one client to the dispatcher and resolves when that client is done. `socket` is any already-open object with the standard `WebSocket` methods. The global `WebSocket` of Node and browsers fits, and the transport needs no library and imports no Node module. One text frame holds one JSON-RPC message, with no trailing newline. The transport authenticates nobody. Whoever holds the socket acts as the dispatcher's user, and the dispatcher passes `Resolution.by` on as the client sent it. A host that exposes the socket must check the caller's identity and origin before it hands the socket over.
365
+
366
+ - **Bad frames.** A frame that is binary, empty, over `maxMessageBytes` (8 MiB, not counting one trailing newline), holds more than one line, even with blank lines around one message, or is a batch gets `ErrorCodes.InvalidRequest`. A frame that isn't JSON, or holds an unpaired surrogate, gets `ErrorCodes.ParseError`. Both error codes answer with a `null` id, as does a bad envelope whose id can't be read. A bad envelope with a readable id gets that id. A malformed response is only logged. A binary frame's size is read from its byte length without reading its data. After a frame over the bound, binary or text, the transport closes the socket with 1009.
367
+ - **Backpressure.** A socket reports no event when its send buffer empties, so while `bufferedAmount` is over `maxBufferedBytes` (1 MiB) the transport checks it every 25 ms and waits to send. The buffer can pass the bound by one frame. The transport closes the socket with 1008 and logs why when the buffer does not shrink for `writeTimeoutMs` (30,000 ms by default, `Infinity` to turn the check off) or when the client leaves 128 error answers or refusals unread. A socket whose `send` throws is closed with 1011, and the log gives the error's name and never its message. The global `WebSocket` refuses to close with 1008, 1009 or 1011, so when closing with one of them throws, the transport closes again with 4008, 4009 or 4011 and the same reason.
368
+ - **Shutdown.** A close from the peer ends the transport without a close of its own, and an error ends it too, closing the socket with 1011 if the socket is still open. Besides the 1008, 1009 and 1011 closes above, the transport closes the socket only when `signal` aborts, with 1000. The peer's close reason is never logged.
369
+ - **Reconnect.** The transport serves one socket. When a client's socket drops, the host serves the new socket with a new call on the same dispatcher, and the client sends `session/open` with the `fromSeq` after the last entry it saw, as in the `session/open` with `fromSeq` section above.
370
+
371
+ `test/server/websocket-transport.test.ts`, `websocket-reconnect.test.ts` and `websocket-framing.test.ts` run the transport over an in-memory socket pair.
372
+
373
+ ## The log is the only state, so a turn rebuilds its context from it
374
+
375
+ `session.toContext(headId?)` rebuilds the SDK's `Context` from the entries between the root and `headId` (default HEAD): the messages in order and the system prompt of the latest `turn_start`, byte for byte. It groups `message_block` entries by `messageId`, closes a message at its `message_end`, and takes its usage from the `usage` entry that follows. A `usage` entry anywhere else belongs to a call whose message a turn-layer retry superseded, and builds no message. The result deep-equals the `context` of the run that wrote the log, a paused run included, and `continueRun()` finishes a run from it after a JSON round trip. A turn that leaves out `history` takes it from `toContext()`, so a new process goes on from the log alone.
376
+
377
+ A request that still waits for a person is in `context.pending`, and the input its call would run with is in `context.pendingInputs`, both read from the `approval_requested` entries.
378
+
379
+ There are two ways to look at a stored session again, and neither calls a model:
380
+
381
+ - **Playback** is `session.playback(headId?)`, which yields the entries on the path in order and reads the log and nothing else.
382
+ - **Re-run** is `rerunFrom(session, harness, entryId, options)`: it appends a `checkout` to `entryId` and starts a new turn there, on a new branch of the same log. The entries of the branch it left don't change. It refuses an entry that follows an open call, because that call never ran on the new branch.
383
+
384
+ To get byte-identical logs, set `TurnOptions.clock` and `newId` to a fixed clock and sequential ids. Two identical scripted sessions then write identical JSONL files.
385
+
386
+ ### A crash leaves open calls, and the next turn settles them by what they could have done
387
+
388
+ An open call is a tool call whose result is not in the log. Before a turn writes anything, it settles the open calls a crash left:
389
+
390
+ - A message with blocks and no end is ended first, as `tool_calls` if it made calls and as `aborted` if not, so its calls count and the model is sent their results.
391
+ - A call to a tool that declares `effect: { kind: "write" }`, or to a tool the registry no longer has, gets an `unknown` write outcome with `retry: "reconcile_first"`, because the write may have taken effect. The model reads that it must check before it retries.
392
+ - A call to any other tool gets an error that says it was interrupted, which the model may retry.
393
+ - A turn with no `turn_end` gets one with stop reason `aborted`, unless a checkout moved HEAD there, since a turn left behind by a re-run was not interrupted.
394
+
395
+ A turn that ended `awaiting_approval` or `clarification_requested` leaves its calls open on purpose, for the approval that resolves them (below). A later turn that passes no `history` refuses to start with `invalid_turn_options` while any call is open, because the gateway would answer it with a made-up "missing result" error and the approval would then have nothing to resume.
396
+
397
+ When a tool has a business key, a model that proposes the same write again reaches the same effect key, so the write goes out once. `effectScope(session, harness, toolCallId)` builds the scope that key takes: the harness's `tenant` (default `local`), the session id, the branch and the call id. The branch is the log's file plus its latest checkout.
398
+
399
+ ## Two cheap layers keep a long run small: a write cap that spills, and masking in steps
400
+
401
+ `createContextPolicy()` from `@buildanagent/harness/context` builds the first two of the five context layers, and `createHarness({ ..., context })` applies it to every turn. Neither layer edits a stored entry. The write cap stores the cut text, so the model reads what the log holds, and masking changes only the request view.
402
+
403
+ ```ts
404
+ const context = createContextPolicy({ spill: fileSpillStore({ dir: ".sessions/spill" }) });
405
+ ```
406
+
407
+ **Layer 1, the write cap.** A tool result whose text is over the cap is cut before the model reads it, and the full text goes to the `spill` store. The model reads the first part and a line that names the file, and the `tool_result` entry stores the same cut text with `spill: { path, bytes }`. If the store cannot write, the text is still cut, and the notice says the rest was not kept.
408
+
409
+ The cap counts the bytes the entry takes in the log: JSON escaping, the result's details and other blocks, and 1 KiB for the entry's own fields. A capped entry therefore always fits the stores' 64 KiB entry bound. The default `writeCapBytes` of 65,536 leaves the model a little under 64 KiB of plain text, and less of a text full of newlines or quotes. `fileSpillStore({ dir })` from `@buildanagent/harness/context/file` writes one file per capped result, and `memorySpillStore()` serves tests. A file is named by the run id, a count within the run and the call id, because a provider may reuse a call id. A policy with the layer on and no `spill` throws `invalid_context_options`.
410
+
411
+ **Layer 2, stepped masking.** Before each model call, every tool result before a cutoff shrinks to its first 500 characters and a pointer line. The line names the spill file, or the log entry when the result was never spilled. A cut never leaves half of a surrogate pair. The cutoff is `floor((messages − 8) / 8) × 8`, so it moves once every eight messages. Between moves the view's prefix stays byte-identical, which keeps a provider's prompt cache hitting.
412
+
413
+ Signed thinking limits where the cutoff may stand. A model that checks each signed block against the earlier request rejects a block that follows an edited message, and a model that thinks in a tool loop needs that loop's own blocks back. So while the tool loop in progress holds signed thinking, the cutoff is computed as though the transcript ended where the loop began, and nothing in the loop is masked. The view also drops the signed reasoning of messages before the loop that follow the first masked result, and keeps the signed reasoning before that result and the loop's own.
414
+
415
+ Turn a layer off with `layers: { write_cap: false }` or `layers: { mask: false }`; `mask` takes `{ keepChars, stepMessages }`. After each view is built, the policy reports how full it estimates the view to be: `TurnOptions.onContextFill` receives `{ tokens, budget, window }`, and the dispatcher sends `tokens` and `budget` as a `context_fill` event. With a previous response, the estimate is that response's input and output tokens plus the view's growth since, counted as characters over four. Before any response, it is characters over four for the whole view. The other three layers follow.
416
+
417
+ ## A summary replaces an outgrown span between turns, and the log keeps every original
418
+
419
+ Layer 3 of the context policy runs at the start of a turn, before the turn's input is written. When the context is over the budget, the policy summarises everything before a verbatim tail and writes a `compaction` entry. The budget is `budgetTokens`, which defaults to the smaller of the model's window less 16,384 tokens and 200,000. The tail is the newest messages that add up to `summarize.tailTokens` (default 20,000), moved back until it starts with an assistant message, so a call is never split from its result and the summary is never followed by a second user message.
420
+
421
+ The policy below sets four options. It keeps the newest 20,000 tokens verbatim, asks the summary to keep the open bugs, caps the summary call at $5 and logs each written entry:
422
+
423
+ ```ts
424
+ const context = createContextPolicy({
425
+ spill,
426
+ summarize: { tailTokens: 20_000, focus: "open bugs", capUsd: 5 },
427
+ hooks: { afterCompact: async (entry) => audit(entry) },
428
+ });
429
+ ```
430
+
431
+ The summary call goes through `Model.complete()` with `cacheRetention: "none"`, on the turn's model or `summarize.model`. It reads the whole discarded span, with each tool result cut to `toolOutputChars` (default 2,000), and asks for the fixed sections of Pi's compaction prompt and its rule to keep exact paths, function names and error messages. The wording is versioned, and each entry records the version in `promptVersion` (`recall-v1`). The span begins with the earlier summary when there is one, so each summary updates the last. A `focus` hint is added to the request and recorded on the entry.
432
+
433
+ The call's cost goes in a `usage` entry with `source: "summary"`, written before the `compaction` entry that names it. When `summarize.capUsd` is set, the harness projects the call's cost with `projectCallCost()` before it runs. It skips the layer when the session's spend plus that projection would pass the cap, or when either figure is unknown. Spend counts the entries from the root to HEAD, so a branch left behind by a re-run is not counted. The cap guards the summary call only: it keeps no room for the turn's own next call. The request must also fit the summary model's window, less `summarize.maxOutputTokens`.
434
+
435
+ A failed summary never fails the turn, and `log` reports each failure. A skip before the call, for the cap or the window, writes nothing. A reply rejected after the call, such as one cut off at its output limit or empty, writes only its `usage` entry. A provider error or a throwing `beforeCompact` writes nothing. A throwing `afterCompact` is reported too, but the compaction stands because its entry is already written. An aborted turn still stops.
436
+
437
+ `hooks.beforeCompact` receives `{ span, tokens, focus? }` and may return `{ summary }`, which replaces the model's. No call is made, the cap is not checked, a zero-cost `usage` entry is written and the entry records `promptVersion: "hook"`. A missing or blank summary leaves the model to write it. `hooks.afterCompact` receives the written entry. `layers: { summarize: false }` turns the layer off.
438
+
439
+ No entry is edited or removed. `session.toContext()`, and every turn that rebuilds its context from the log, start from the latest compaction: its summary as a user message, then the kept tail, then everything written after it. The tail loses its signed reasoning blocks, because a block that follows the summarised span carries a signature the summary made stale; blocks written after the compaction stay. A re-run from an entry before the compaction rebuilds the original context from the file.
440
+
441
+ ## Two more triggers compact inside a turn: at 90% of a small window, and after a provider overflow
442
+
443
+ Layer 3 runs between turns. Layers 4 and 5 run inside one: layer 4 when a model call would fill most of a small window, layer 5 when the provider has already refused a request as too large. Both use layer 3's summary call, template, hooks, cap and `log`, and each writes a `compaction` entry whose `layer` is `mid_turn` or `overflow_retry`.
444
+
445
+ **Layer 4, mid-turn.** The SDK's loop keeps the run's whole transcript, so a compaction in the middle of a run cannot shorten it. It changes the view that every later model call of the run reads. The first call whose context would pass `midTurnRatio` (default 0.9) of the model's window summarises the span before the verbatim tail and writes the entry. From then on the run reads the summary, the tail and what the run adds, and later turns rebuild the same view from the log. A turn compacts mid-turn at most once.
446
+
447
+ The layer is on by default only for windows under 128,000 tokens, where a single turn can fill the window. Set `layers: { mid_turn: true }` to turn it on for a larger one. The estimate is the last response's input and output tokens plus a character count of what the view added since. The compaction drops the signed reasoning of the kept tail's older messages from the view, because the summary made their signatures stale, and keeps the thinking the run wrote after it.
448
+
449
+ **Layer 5, overflow retry.** When a run ends because the provider said the request was too large (`error.kind` `overflow`), `runTurn()` asks the policy to compact once, whatever the context's size, and goes on from the rebuilt context with `continueRun()`. That call asks the model again, because the gateway leaves the failed response out of the request. `onRun` is called again with the retry's run. The dispatcher holds a steer or follow-up sent in between until that run exists, and still sends one `turn/settled`. The turn's result adds the two attempts' steps, usage and cost, and the retry gets what the first attempt left of `maxSteps`. `layers: { overflow_retry: false }` turns the layer off.
450
+
451
+ Three cases end the turn with the overflow error as its result (`stopReason: "error"`) and no further attempt:
452
+
453
+ - A second overflow, because only one retry is made.
454
+ - Nothing before the tail to summarise, such as one message too large for the window.
455
+ - A turn given its own `history`, which has neither layer, because the log does not describe its context.
456
+
457
+ Four limits and interactions follow from this design:
458
+
459
+ - The retry gets the turn's `budgetUsd` again, not what the first attempt left.
460
+ - The retry does not compact mid-turn again.
461
+ - The context policy's interceptors run before the harness's own `interceptors` and the permission gate. A mid-turn compaction therefore indexes the run's own transcript, a harness `transformContext` or `beforeModelCall` hook sees the masked and compacted view, and a harness `afterToolCall` hook sees the capped result.
462
+ - A steer or follow-up accepted while the retry's summary call runs is delivered only if the retry goes ahead. When the summary is skipped or the turn is aborted, the message is dropped.
463
+
464
+ ## A turn that ends `done` runs the project's checks, and the diff flags are recorded, never fatal
465
+
466
+ A model's "done" is a claim, so a turn can check it in code. Pass `completion: { sandbox, env }` to `runTurn()`, where `sandbox` is the session's sandbox and `env` is the checks' whole environment, built with `spawnEnv()`. Before the model runs, the turn resolves the project's checks, reads the check config and takes a snapshot of the workspace. It does this for every turn, because whether a turn ends `done` is known only after the model has run, so expect up to 5,000 file reads before each turn. When the run ends `done`, the harness runs the checks it resolved at the start, takes a second snapshot, and writes one `completion_check` entry after `turn_end`. It also calls `onCompletionCheck` with that entry. The turn's stop reason is unchanged: a failed check or a flag is recorded for the CLI and the eval reports to show, and a turn that ends any other way runs no check. `lastEntryId` on the result is the new entry. A `done` turn from the dispatcher runs a check only when `createDispatcher()` is given `completion`, a function that takes a session's id and returns that session's `{ sandbox, env }` (or `undefined` for none).
467
+
468
+ **A turn resumed after an approval is never checked.** A resume through `createApprovals()` runs no completion check, because the start state is not kept across the pause. So in an agent that uses approvals, a turn that pauses for one and then ends `done` writes no `completion_check` entry, and its "done" goes unchecked.
469
+
470
+ **The checks are fixed before the model runs.** A turn can't change which commands run by editing `.agents/harness.json`, because they were resolved before it began. A package runner reads a script's body when it runs it, though, and `make` reads the `Makefile`, so a turn that rewrites the `test` script to `true` would still change what `npm run test` does. The harness therefore compares the check config at the end with the start and adds one flag for each part the turn changed:
471
+
472
+ - `check config changed: .agents/harness.json` for any edit to that file.
473
+ - `check config changed: package.json script <name>` for a changed body of `typecheck`, `test`, `check`, any script a check runs through `npm`, `pnpm`, `yarn` or `bun` (such as `npm run e2e`), or the `pre` and `post` hook of any of these, because npm and yarn run the hooks too.
474
+ - `check config changed: Makefile test target` when the `test` rule's target line or recipe changed.
475
+
476
+ A script no check runs is not tracked, and the Makefile comparison covers the `test` rule only, not the rules it depends on.
477
+
478
+ **A check that can't do its work is recorded, never thrown.** When the checks can't be resolved before the turn (a `.agents/harness.json` that is not valid JSON, say), the turn still runs, and its entry has no checks, `passed: false` and a flag `completion check failed: <message>`. A start snapshot that throws is recorded the same way, and the checks still run. A check that throws, such as one run in a disposed sandbox, gives an entry with no checks, `passed: false` and the same kind of flag. `runTurn()` never throws for a `done` turn because of its completion check, and that includes the append of the entry: when the store refuses it (a lost lock, a conflict), the result comes back without that entry, `lastEntryId` stays the turn's own last entry and `onCompletionCheck` is not called.
479
+
480
+ **Configure the checks in `.agents/harness.json`.** `completionChecks` is a list, and each item is a command string, split on spaces, or a list of an executable and its arguments. Neither goes through a shell, so write `["sh", "-c", "make lint && make test"]` for one that needs it. A configured list replaces discovery, and an empty list runs nothing:
481
+
482
+ ```json
483
+ { "completionChecks": ["pnpm run typecheck", "pnpm run test", ["make", "e2e"]] }
484
+ ```
485
+
486
+ Without the key, the harness runs the `package.json` scripts `typecheck`, `test` and `check`, in that order, when they exist, with `pnpm` or `yarn` when the project has that lockfile and `npm` otherwise. When no script matches, it runs `make test` if the `Makefile` has a `test` target, alone or in a list such as `all test:`; a variable named `test` does not count. `resolveChecks()` shows what a sandbox would run. A file that is not JSON, or a `completionChecks` that is not a list of commands, makes `resolveChecks()` throw `HarnessError` with code `invalid_completion_config`; in a turn, that becomes the failed entry described above.
487
+
488
+ **What the entry holds.** Every check runs, even after one fails, with `timeoutMs` (default 10 minutes) each. `checks` lists each command with its exit code: 124 for a timeout, 126 when the sandbox's policy refused it, and 130 when the turn's signal aborted it. The check running at the abort and each one after it gets 130 and a flag. A check the signal aborted counts as aborted even when the sandbox returned a result for it, such as exit 143. Once the signal has aborted, no further check is started and no diff is taken. `passed` is true when every exit code is 0, so it is also true for a project with no checks, where `checks` is empty. `flagged` holds, in order, any `completion check failed` flags, the refusals and aborts, the `check config changed` flags, and one sentence for each diff pattern:
489
+
490
+ - an added skip marker: `.skip(`, `xit(` or `@pytest.mark.skip`
491
+ - an added placeholder: `TODO` or `FIXME` in capitals (`todo` is not flagged), or "not implemented" in any case
492
+ - a new file whose name has `mock`, `stub` or `fake` in it
493
+ - a deleted test file
494
+ - a test file with fewer assertion lines (`expect(`, `assert(`, `assert.x(`, `assertEqual(` and Python `assert` statements) than before
495
+
496
+ A test file is a code file (such as `.ts`, `.js`, `.py`, `.go`, `.rs`, `.java` or `.rb`) in a `test`, `tests` or `__tests__` folder, or a file named `*.test.*`, `*.spec.*`, `*_test.*` or `test_*.py` anywhere. A fixture or snapshot in a test folder, such as `test/fixtures/sample.json`, is not one, so deleting it raises no flag. A line counts as added when the file has more copies of it than before, so moving a line flags nothing. These patterns have honest causes, which is why they never stop a run: expect false positives, and read a flag as a prompt to look.
497
+
498
+ **The diff needs a way to snapshot the workspace.** The default, `gitSnapshotter`, lists `git ls-files --cached --others --exclude-standard` in the sandbox and reads each file up to 256 KiB as UTF-8 text, at most 5,000 files. The second snapshot reads the first one's paths again and adds the new ones. A file left out for its size, its encoding or the cap, or one it could not read for any reason but its absence (a policy refusal, a sandbox error), is ignored by the diff, so none is reported as deleted. The listing and each read stop after 60 seconds (`SNAPSHOT_TIMEOUT_MS`), and a read that times out is skipped. In a workspace that is no repository, or when the listing times out, it returns nothing, and the entry then has checks and no diff flags. Pass `snapshotter` in `completion` to diff another way.
499
+
500
+ ## An extension adds hooks and tools in the harness's own process, and project trust only gates loading
501
+
502
+ An `Extension` from `@buildanagent/harness/extensions` is a name, a version, and any of `interceptors`, `observers` and `tools`. It runs in the harness's process with the harness's permissions, so loading one is a trust decision and nothing more: **trust is not a sandbox.** The permission pipeline still decides every call an extension's tool makes, and an extension's own hooks can do anything the process can.
503
+
504
+ This audit extension asks a person before every shell command and hands every event to a log. The harness runs it before another extension, `other`, and records both:
505
+
506
+ ```ts
507
+ /** A harness that runs the audit extension first, then `other`, with both extensions' tools in `registry`. */
508
+ export async function auditedHarness(
509
+ registry: ToolRegistry,
510
+ model: Model,
511
+ log: (e: AgentEvent) => void,
512
+ other: Extension,
513
+ ) {
514
+ const audit: Extension = {
515
+ name: "audit",
516
+ version: "1.0.0",
517
+ interceptors: { beforeToolCall: (event) => (event.tool === "bash" ? { decision: "ask" } : { decision: "allow" }) },
518
+ observers: [(event) => log(event)],
519
+ };
520
+ const { interceptors, observers } = composeExtensions([audit, other]);
521
+ registerExtensionTools(registry, [audit, other]);
522
+ const extensionRecords = await recordsOf([audit, other]);
523
+ return createHarness({ registry, model, system: SYSTEM, interceptors, observers, extensionRecords });
524
+ }
525
+ ```
526
+
527
+ `composeExtensions()` joins the hooks in the order given, by the SDK's rules. `transformContext`, `beforeModelCall` and `afterToolCall` chain in registration order. `beforeToolCall` is a gate: the first deny wins and any ask asks. `afterModelCall` passes the message on, so the last override stands. `shouldStop` lets any stop win. Observers run in order and change nothing. A hook that throws fails the moment it belongs to, so a gate that fails closed fails the whole gate closed. `composeExtensions()` and `registerExtensionTools()` refuse two extensions with one name, or one with no name or version, with `invalid_extension`. `registerExtensionTools()` registers each extension's tools with source `extension`; an `override: true` tool replaces a built-in of the same name and nothing else. A turn writes an `extension_loaded` entry for each of `extensionRecords` whose name and hash the session's log does not hold yet.
528
+
529
+ A project can supply its own extensions, and trust decides whether they load. `@buildanagent/harness/extensions/node` loads them from `.agents/extensions/<folder>/`, each with an `index.mjs` or `index.js` whose default export is an `Extension`, or a function returning one. When a project has extensions, `loadProjectExtensions(root, { trust, headless })` loads none of them and returns a notice saying why if the run is headless or the project is not in the `TrustStore`. A headless run loads a trusted project's extensions only with `loadInHeadless: true`. `fileTrustStore(path)` keeps trusted folders in a 0600 JSON file. The loaders ask a store only about a project's real path, never the spelling the host wrote, because a link can be pointed at another folder after it was trusted: trusting `/work/current` must not trust the clone it points at tomorrow. Two stores in memory serve tests and hosts that decide trust themselves. `memoryTrustStore()`, from the portable `@buildanagent/harness/extensions`, touches no file system and compares paths as written, so give it real paths. `realPathTrustStore()`, from `@buildanagent/harness/extensions/node`, resolves each folder to its real path when the store is built or when its `trust` method adds it. A host that trusts `/tmp/proj`, where `/tmp` is a link to `/private/tmp` as on macOS, therefore gets that project trusted, and a link pointed elsewhere later takes no trust with it. The result of a load holds the `extensions`, the `records` for `extensionRecords` and the `notices`.
530
+
531
+ Pins keep a trusted project from changing under you. `pinProjectExtensions(root)` writes `.agents/extensions.lock.json`, one SHA-256 per extension folder. The hash covers every file in the folder, in sorted order, each by its path and its own digest. Once a lock file exists, the loader refuses a folder whose hash differs, or that the file does not list, or that the file lists and the project no longer holds, with `extension_hash_mismatch`, and none of the project's extensions load. With no lock file they load and a notice says they are unpinned.
532
+
533
+ The loader hashes and checks every folder before it imports any, so a refusal runs none of the project's code. Node caches modules for the life of a process, so a folder that changed after the process imported it is refused until the process restarts. An extension folder may not hold a symlink.
534
+
535
+ Two limits remain. The pin covers the files inside each folder and nothing an extension imports from outside it, such as a relative path that leaves the folder or a package from the project's `node_modules`. And the lock file sits inside the project it pins, so anyone who can edit the project can pin their own changes: the pin catches a change nobody meant, not an attacker who holds the project. Pin a project only after you have read its extensions.
536
+
537
+ ## MCP servers connect side by side, each in its own era, and their tools wait behind tool search
538
+
539
+ `@buildanagent/harness/mcp` is the MCP client, built on `@modelcontextprotocol/client` 2.4.0 and kept behind its own `McpConnection` interface, so the registry never sees the library. `createMcpManager({ servers, registry })` checks every server's config, and that the registry has `register()`, `registerAll()` and `list()`, when you create it, and starts nothing until `connect()`. That call connects each server on its own, so one slow or broken server never holds back the rest, and it resolves with one status per server: `connected` with the server's era and its tools' canonical names, or `failed` with the error. This example connects one server over stdio:
540
+
541
+ ```ts
542
+ export async function connectDocs(registry: ToolRegistry, command: string, args: string[], token: string) {
543
+ const manager = createMcpManager({
544
+ registry,
545
+ servers: [
546
+ {
547
+ name: "docs",
548
+ transport: { kind: "stdio", command, args, env: ["DOCS_REGION"], setEnv: { DOCS_TOKEN: token } },
549
+ requestTimeoutMs: 30_000,
550
+ },
551
+ ],
552
+ });
553
+ const [status] = await manager.connect();
554
+ if (status?.status === "failed") throw status.error;
555
+ return { manager, era: status?.era, tools: status?.tools ?? [] };
556
+ }
557
+ ```
558
+
559
+ A stdio server gets `spawnEnv()`'s environment and nothing else from the parent: `PATH`, a fresh temp `HOME`, `TMPDIR` and `LANG`, plus the parent variables that `env` names and the values that `setEnv` sets. The harness spawns the child itself, because the library's own stdio transport adds the parent's `HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM` and `USER` to the environment it is given. `env` follows `spawnEnv()`'s rules, so a name such as `GITHUB_TOKEN` is refused there, and the token goes in `setEnv` with a value the host read from its own secret store. A clean environment is not a sandbox: a stdio server runs on the host as the harness's own user, outside any sandbox, so it can read whatever that user can, `~/.ssh` included. Connect only servers you would run yourself. A server named in `transport: { kind: "in_process", channel }` runs in the harness's process instead, over a channel such as the `InMemoryTransport` of `@modelcontextprotocol/server`, and needs no Node.
560
+
561
+ **Each server negotiates its own era.** The client sends `server/discover` first, and a server that answers it connects in the 2026-07-28 era. A server that refuses the probe, or stays silent past `probeTimeoutMs`, gets `initialize` and connects as `legacy`. The probe waits 5,000 ms by default, or half of `connectTimeoutMs` when that is shorter, and a `probeTimeoutMs` as long as `connectTimeoutMs` is refused, so a silent server always has time to fall back. A stdio server that exits cleanly after the probe, as servers on some older SDKs do, is started once more and spoken to as legacy from the start. A server that crashes starts once, and the whole connect, a restart included, takes at most `connectTimeoutMs`. `connection.era` and `connection.protocolVersion` record the outcome, so a 2026-07-28 server and a legacy one sit side by side in one harness.
562
+
563
+ **The tools are registered all or none.** A server's tools take the source `mcp:<name>`, so the registry names them `mcp__<name>__<tool>` and defers them until tool search names them; `exposure` in the config changes that. A server name is 1 to 32 characters from `A-Z`, `a-z`, `0-9` and `-`, and two servers can't share one in any letter case, so no server can take another's prefix or a built-in's name. The manager registers the list through the registry's `registerAll()`, which removes what it added when any tool is refused, so a clash with a tool already registered, even one another manager added a moment before, leaves none of the server's tools behind. It refuses a whole list, registers none of it and closes the server, with an `McpError` of code `mcp_tool_list_refused`, when the list breaks a rule:
564
+
565
+ - it holds more than `maxTools` tools (default 256), or its pages run past eight;
566
+ - a name is over 128 characters or holds a control character;
567
+ - an input schema is not an object schema, or is over 64 KiB;
568
+ - two names match once normalised to NFKC and lower case, such as `Search` and `search`.
569
+
570
+ The harness reads the list one page at a time and stops at the page that passes `maxTools`, so a server can make it hold at most one page beyond the limit. A description over 4,096 characters is cut, never inside a character, and the registry hashes a name that needs cleaning.
571
+
572
+ **A server's schema runs no regular expression.** The SDK checks a call's input against the tool's schema before the permission gate decides the call, and it runs a schema's patterns on a backtracking engine, so a pattern such as `^(a+)+$` could freeze the harness with one crafted input. The harness therefore removes `pattern`, `patternProperties` and `format` from every server's input schema, at any depth, before the tool is defined, and refuses a schema nested deeper than 64 levels. The model reads the schema without them, and the server still checks its own input. The registry builds each tool's definition again for every turn, so a schema is compiled once per turn.
573
+
574
+ **The server's hints change nothing.** Every MCP tool is registered as not first-party and as a write, whatever its `readOnlyHint` says, so the loop never runs its calls together or runs one again after a crash because of a server's claim. `listTools()` keeps the hints for display only. The tools run through the turn's own tool pipeline, so the permission pipeline decides every call before it is sent, and a denied call never reaches the server. The write cap applies to every result, as to any tool.
575
+
576
+ **A server's output and descriptions are untrusted.** Each result's entry is stored with `trust: "untrusted"`. That mark is a record only: nothing in a request tells the model which results are untrusted yet, which waits on HD16. Tool search never quotes an MCP tool's description in its own result, which the log stores as trusted; it names the tool, and the description reaches the model with the tool's definition. It scores an MCP tool on its name, counts its description as one word at most, and gives one server at most half the slots, so a description stuffed with keywords can't crowd out the other tools.
577
+
578
+ **The client gives a server nothing to ask for and nothing to run.** The harness reads a result's content and never its structured content, so it gives the client a validator that compiles no output schema. The client declares no capabilities: a legacy server's sampling, roots and elicitation requests get error -32601, and a 2026-07-28 client drops a server's requests unanswered. No resource link or embedded resource URI is ever fetched.
579
+
580
+ **Every failure is bounded.** A call fails with an `McpError` of code `mcp_call_failed`, whose `failure` says why:
581
+
582
+ - `closed`: the server exited or crashed, or the connection closed.
583
+ - `timeout`: no answer came within `requestTimeoutMs` (default 60,000 ms).
584
+ - `aborted`: the turn's signal fired.
585
+ - `input_required`: the server asked for input from the user, which this harness does not supply yet.
586
+ - `server_error`: the server answered with an error, and its message is cut to 500 characters.
587
+
588
+ A server that fails to start, or to finish its handshake within `connectTimeoutMs` (default 30,000 ms), fails to connect with `mcp_connect_failed`. A stdio server's line over `maxLineBytes` (default 8 MiB) closes the connection, and a line that is not a JSON object is dropped and logged. Only the newest `maxStderrBytes` (default 64 KiB) of its standard error are kept, for `connection.stderr()`, and they never reach the model.
589
+
590
+ **Closing ends the server's process group.** `manager.close()` first aborts every handshake still running, so a server that hangs can't hold up the others. It then ends each server's input, waits `closeGraceMs` (default 2,000 ms), sends `SIGTERM`, waits again and then kills the group, so a server that ignores the close, and whatever it started inside its group, still ends. A descendant that leaves the group, by `setsid` or a detached spawn, survives, and on Windows, which has no process groups here, only the server itself is killed. The temp `HOME` is removed, and a tool of a closed server fails when called.
591
+
592
+ **A signal ends the servers only if the host opts in.** If the harness's process exits without closing, an exit handler kills every group still running. A signal whose default action ends the process emits no exit event, though, and a server's group never gets the terminal's `SIGINT`. The harness adds no signal listener by default, because a listener changes what a signal does to the host. A server that exits when its input ends, as most do, still goes with the host; one that ignores its closed input outlives a signalled host. A host whose process those signals end calls `killMcpServersOnSignal()` once: on the first `SIGINT`, `SIGTERM` or `SIGHUP`, the harness kills every group, removes its listeners and raises the signal again, so the process ends as it would have, and a library such as `signal-exit`, which re-raises only when it is alone, still sees itself alone. A host that handles `SIGINT` to cancel a turn should not opt in, since the first `SIGINT` would end its servers; such a host calls `manager.close()` when it stops. A `SIGKILL` gives the harness no chance to clean up.
593
+
594
+ **One switch turns MCP off.** With `createMcpManager({ ..., mcp: false })`, `connect()` resolves with an empty list, starts no server and registers nothing.
595
+
596
+ **A session records which servers ran.** `manager.records()` gives one `extension_loaded` record of tier `mcp` per connected server, in config order; pass them in `extensionRecords` to `createHarness()`, and a turn writes an entry for each record its session's log does not hold yet. A record holds the server's name, the transport kind, the era, and two hashes: one of the command and its args, for a stdio server, and one of the tools as registered, each tool's name, description and input schema, sorted by name. It never holds an argument or an environment value, because either can carry a token, and a server that failed to connect has no record. The command hash is not salted, so anyone who reads the log can check a guess at an argument, such as a short PIN or a token of a known format, by hashing it; put every secret in `setEnv`, never in `args`. Every hash is `sha256:` and the SHA-256 of canonical JSON, so an unchanged server records the same hashes on every connect.
597
+
598
+ Three limits remain. A server's notice that its tool list changed is logged through `log`, and its tools stay as registered at connect. A server's request for user input fails the call: a server-supplied prompt is untrusted text a person would read as the harness's own, and the owner chose on 2026-11-22 to fail such calls until the connectors work gives a pause a safe form. And the manager takes configs only from host code; a project's own MCP config, which needs project trust, is todo N54.
599
+
600
+ ## A skill is a file the model reads, and only its name, description and path are in the prompt
601
+
602
+ A skill is a folder under `.agents/skills/` with a `SKILL.md` whose frontmatter has a `name` and a `description`. `discoverSkills(cwd, { trust })` from `@buildanagent/harness/extensions/node` finds them in `cwd` and in every folder above it up to the repository root, which is the first folder with a `.git`. A `cwd` in no repository searches only itself. It returns the `skills`, the `records` for `extensionRecords` (tier `skill`, the SHA-256 of each `SKILL.md`'s bytes as stored) and the `notices`. The nearer folder wins when two skills share a name, and a file that is not a skill is skipped with a notice. The loader also skips three things, each with a notice: a `SKILL.md` that is a link leaving the project, a `SKILL.md` past 256 KiB (a limit we chose so that every record's hash covers a whole file), and a folder whose name holds a control character or, on POSIX, a `\`.
603
+
604
+ ```ts
605
+ const { skills, records } = await discoverSkills(cwd, { trust: fileTrustStore(trustFile), headless: false });
606
+ const system = withSkills("You help.", skills);
607
+ const harness = createHarness({ registry, model, system, skills, extensionRecords: records, env: { cwd } });
608
+ ```
609
+
610
+ `withSkills()` adds a `## Skills` section that lists each skill's name, description and path and never its body. The model loads a skill by reading its `SKILL.md` with the `read` tool, and the turn then writes a `skill_loaded` entry with the skill's name and path. A harness records one entry for each successful `read` whose `path` or `file_path` input names a listed skill's own `SKILL.md`, once per read, because a compaction can drop the body and a second read loads it again. A read of another file in the skill's folder, one that failed, or one that asks for part of the file with an `offset` or a `limit` writes none. To record loads, pass `skills` to `createHarness()`, and pass the same `cwd` you gave `discoverSkills()` as `env.cwd`. The turn matches each read against `skills` and takes a relative path from `env.cwd`. If you leave `env.cwd` out, it is `/`, and a relative read such as `.agents/skills/triage/SKILL.md` matches no skill. A skill whose path starts with a drive such as `C:\` matches Windows reads, where `\` separates folders as `/` does; any other skill path is a POSIX one, where only `/` does.
611
+
612
+ The frontmatter checks follow Pi's skills documentation. A name is lowercase letters, digits and single hyphens, at most 64 characters, and a description is at most 1,024; a file past either limit, or with no description, is not listed. A skill's name should match its folder's, and one that differs loads with a notice. The frontmatter reader handles a small subset of YAML: `key: value` lines, quoted or plain, with a value that continues on indented lines or is a `>` or `|` block.
613
+
614
+ Skills are inside the project-trust gate, as the guide says, and `trust` is required, as it is for `loadProjectExtensions()`: a skill's name and description go into the system prompt, so an untrusted checkout must not reach it by a caller leaving the store out. An untrusted project, or a headless run without `loadInHeadless: true`, lists no skills and returns one notice saying why. A host that trusts every project it opens passes a store that says so. As with extensions, trust decides what loads and nothing more: a loaded skill is text the model may follow, and no sandbox comes with it.
615
+
616
+ ## `AGENTS.md`, `CLAUDE.md` and the plan files lead every request, labelled untrusted
617
+
618
+ `contextFiles(cwd)` reads `AGENTS.md` and then `CLAUDE.md` in each folder from the repository root down to `cwd`, so the file nearest the work comes last. A `CLAUDE.md` that is a link to the `AGENTS.md` beside it is read once. Context files load whether or not the project is trusted, because they are text and not code, and `contextFiles()` takes no trust store. Each file is cut at 64 KiB: no more than that is read, however long the file, and the cut falls between characters. `contextFiles()` returns every file it read, and `projectContext()` holds them together to 128 KiB (`CONTEXT_FILES_MAX_TOTAL_BYTES`), because the block is added after the context policy has counted the request, so compaction can't shrink it. Past that limit the outermost files are left out first, so the ones nearest the work stay, and the block names those it left out, so the model knows they exist. A link that leaves the project is skipped with a notice, so a cloned repository cannot point `AGENTS.md` at `~/.ssh/id_rsa` and send it to the model provider.
619
+
620
+ ```ts
621
+ const { files } = await contextFiles(cwd);
622
+ const context = projectContext({ files, plan: planFileSource(cwd) });
623
+ const { interceptors } = composeExtensions([context]);
624
+ const harness = createHarness({ registry, model, system: withPlanConvention(system), interceptors });
625
+ ```
626
+
627
+ `projectContext()` returns an extension whose `transformContext` hook puts the files at the start of the first user message of every request, as one text block whose bytes never change, followed by a second block for the plan files. Each file sits in an `<untrusted-project-context-TOKEN source="…">` section under a note that says the text is the project's and not the user's. The token is the first 16 hex digits of the SHA-256 of the file's path and text, and the section ends only at `</untrusted-project-context-TOKEN>` with the same token. A file would have to hold its own hash to close its section early, and the token stays the same while the file does, so the block's bytes still never change. As a second guard, every spelling of the label's tag in a file is escaped. The match runs on a folded copy of the text: white space and format characters are removed, and the rest is normalised to NFKC and lower case. It therefore catches fullwidth brackets, a tag name split across lines, and entities for `<` with or without their `;`. The text is rebuilt from the files for each request and is not written to the log, so a compaction that replaces the early messages with a summary can't remove it: the first request after a compaction holds the `AGENTS.md` text again, beside the summary. The cost is that the log doesn't hold the context files' text, so a replay needs the same files.
628
+
629
+ A long task keeps its state in two files under the project's `.agents/` folder: `plan.md` (Markdown: the goal, the steps, which are done) and `progress.json` (JSON: what is done and what is next). `withPlanConvention()` adds a paragraph to the system prompt that tells the model to keep and update them. `planFileSource(root)` reads both files from disk. `projectContext()` asks the source at the first model call of every run, whether the run is a new turn or a resume, so the first request of a resumed session holds what the last process left. The same text is sent for the rest of the run, so the model's own edits during a run show in the next run, and the run's later calls read the prompt cache. A plan edit is not free, though. The plan sits in the first message, and a provider caches a prompt by its prefix, so the first call of the run after an edit reads none of the conversation from the cache: everything after the system prompt and tools is sent uncached once, and later calls read it from the cache again. Putting the plan in its own block after the context files keeps their text unchanged but does not avoid that pass. The gateway puts cache breakpoints on the system prompt, the tools and the newest message, never between the two blocks. A file that doesn't exist is left out, and a `progress.json` that isn't valid JSON, which a crash can leave, is shown as written with a notice. The harness only reads these files; the model writes them with its ordinary tools.
630
+
631
+ ## A call that needs a person is a signed pause that any process with the key file can resume
632
+
633
+ When the permission pipeline's gate returns `ask`, the turn ends `awaiting_approval`, and the signed request is the log's `approval_requested` entry, written before any observer of the harness sees the event. A client that listens on the run's own handle, not on the harness's observers, can hear of a request a moment before the log has it. The harness never blocks on an approval, so a restart loses nothing. The entry holds the SDK's request unchanged, with the input the call would run with. It names its key by id and holds no key bytes.
634
+
635
+ `createApprovals(harness)` from `@buildanagent/harness/session` reads and answers the pauses:
636
+
637
+ - `pending(session)` lists the requests whose call has no result yet, each with its input. A request stays listed after an answer until its call runs.
638
+ - `resolve(session, resolutions, options?)` throws `approval_not_pending` for a request that doesn't wait, and `approval_unavailable` when the harness has no `signer`. It writes each answer as an `approval_resolved` entry, lets the quorum policy decide each request, then calls `continueRun()` with the harness's signer for the requests the policy settled. The SDK verifies each request's signature, call and input, so a tampered request runs nothing, writes a new `approval_requested` entry and asks again.
639
+ - Each approved call goes through the permission pipeline once more before it runs. A deny rule added after the pause turns the approval into a denial result, and a question the pipeline would ask again does not stop a call a person approved.
640
+ - `options` takes the same settings as a turn: `budgetUsd`, `signal`, `hostContext`, `clock`, `newId`, `maxSteps`, `output`, `turnRetries` and `modelOptions`, plus `model`. The log holds none of the settings except the tools, so the host passes them again.
641
+ - The tools are the paused turn's, read from the log. A `model` that differs from the paused turn's is recorded as a `loadout`.
642
+ - A request bound to a `hostContext` when it paused runs only when the resume passes the same value, so that value is the caller's identity. The resumed turn starts with a `turn_start` of mode `continue`.
643
+
644
+ The host fills `Resolution.by` only after it has authenticated the approver. An answer never ends a wait by itself: a request waits until its call has a result, so a resume the SDK refuses leaves the pause as it was. A second answer for the same request is appended after the first, and the later resume uses it. If a resume dies after it was given an allow, the call may have run. The next turn settles that call as a crash and does not ask again, even when the run died before it reached the call.
645
+
646
+ ### One answer can cover more than its call, and a quorum can ask for several
647
+
648
+ `resolve()` takes four more options (`sticky`, `commandPrefix`, `group` and `requesterId`), and `createApprovals(harness, { quorum, secrets })` takes a quorum policy and a secret list.
649
+
650
+ - **Sticky allowances.** `sticky: "run"` or `"session"` makes an `allow` cover the same call again. The `approval_resolved` entry carries the `sticky` scope and an `allowance`: the tool and the call's input hash or, with `commandPrefix`, a command prefix, and the policy version it was given under. When the pipeline would ask about a call that an allowance covers, the call runs, and a `permission_decision` entry with `by: "sticky"` records why. A deny rule still wins, because the allowance only answers an ask. A `run` allowance lasts until the next turn starts, resumes included. A `session` allowance counts from the start of the session's own file, so a fork never inherits it. It is ignored once the permission policy's version changes, because a person approved it under the earlier policy.
651
+ - **Never covered.** A command whose first word, by any path, is a shell, an interpreter, a package runner or a wrapper such as `env`, `sudo` or `xargs` throws `sticky_refused`. That includes the listed prefixes (`bash -c`, `sh -c`, `sh -lc`, `zsh -c`, `node -e`, `python -c`, `bun run`, `npx`, `uvx`), `/bin/sh -c`, `env bash -c` and `python3 -c`. So does a call whose input holds a value that `secrets()` returns, whether the secret appears as plain text or as JSON would escape it, and any sticky answer under a custom quorum policy, because one approver's click would then skip the quorum on every later call.
652
+ - **Prefix rules.** A command prefix must be a non-empty start of the approved command, on a call that has a `command`, and it covers only a simple command: one with no operator, quote, glob, expansion, substitution or line break. A `git status` prefix covers `git status -s` and not `git status && curl x | sh`.
653
+ - **Reuse.** `approvalReuse` is `both` (the default), `sticky`, `group` or `none`, and a tool takes only the kinds it names. A refused answer throws `approval_reuse_refused` before anything is written, and the call asks again next time.
654
+ - **Grouped answers.** With `group: true`, an answer reaches every waiting request of the step with the same tool and the same whole input; for a shell command the spaces outside quotes are normalised first, and a field such as `cwd` still tells two commands apart. The entries share a `groupId`, and each counts as that approver's answer on its request, so a quorum above one still needs more approvers. Only a group that joins more than one request needs its tool to allow grouping.
655
+ - **Quorum policy.** A `QuorumPolicy` has one method, `evaluate(request, resolutions)`, that returns `met`, `pending`, `rejected` or `expired`. `oneResolution` is the default and follows the latest answer. `quorumOf(n)` needs `n` distinct approvers named in `Resolution.by`, counts only allows, and refuses an `n` that is not a whole number of at least one. `met` runs the call, `rejected` and `expired` turn it into a denial result, and `pending` leaves it waiting: the turn ends `awaiting_approval` again. Calling `resolve(session, [])` asks the policy about every request of a paused turn, which is how a policy that keeps its own clock expires an old one. It leaves a code call's request waiting: the policy decides that call when it is next answered, so a late allow for an expired call comes back `denied`.
656
+ - **What the log keeps.** A denial by the policy, not a person, is written with `by: "policy"`. A pending answer is marked `quorum: "pending"` so that crash detection does not read it as an answer a run received.
657
+ - **Requester.** `requesterId` names who asked, and an approver equal to it throws `approver_is_requester`. The host authenticates approvers and fills `Resolution.by`; the harness trusts what it is given.
658
+
659
+ ### Code runs a side effect through the same pipeline and pause as the model, with no model call
660
+
661
+ `harness.invokeTool(session, { tool, input, hostContext })` runs one tool call that your code chose, such as an approved reply or a refund. The call goes through the same permission pipeline, signed pause and log as a call the model makes, and the model is never called. The session must be open with its lock.
662
+
663
+ ```ts
664
+ const call = { tool: "refund", input: { orderId: "o1" }, hostContext: { user: "ada" } };
665
+ const result = await harness.invokeTool(session, call);
666
+ if (result.status === "awaiting_approval") {
667
+ await createApprovals(harness).resolve(session, [{ requestId: result.pending.id, decision: "allow", by: "grace" }], { hostContext: call.hostContext });
668
+ }
669
+ ```
670
+
671
+ The call's own entries start with a `code_call` entry, which holds the call's `callId`, the tool's canonical name, the input and its hash. The entry's id is the call id. Before it, `invokeTool()` writes what the session still lacks: a new session's `session_header` and `env_stamp`, and a `tool_result` for each earlier code call that a crash left open. The pipeline then decides the call with `initiator: "code"` and writes its `permission_decision`, and the call ends one of three ways:
672
+
673
+ - **`done`.** An allow runs the tool through the harness's `wrap` with the call's host context, and writes its `tool_result`. A sticky allowance covers a code call as it covers a model call. `result` holds the whole of what the tool returned, even when the stored entry is capped.
674
+ - **`denied`.** A deny writes an error `tool_result` and returns the reason. The tool never runs.
675
+ - **`awaiting_approval`.** An ask signs the request with `createPendingRequest()` and the harness's signer, and writes it as an `approval_requested` entry before the result returns. The request signs a MAC of `hostContext` when one is given, so only the same host context can resolve it. `Approvals.pending(session)` lists a paused turn's requests first and this request after them.
676
+
677
+ The stored result is capped as a model call's is. The harness's context policy caps it and spills the full text. A result still over the store's entry bound is cut to fit, with its outcome kept at the front, so a call that ran always gets its result. A tool that throws gets an error result; for a write, its outcome is `unknown`, because the write may have taken effect.
678
+
679
+ `resolve()` routes an answer by its request. An answer to a code call's request resolves that call on its own and returns a `CodeCallResult`, so it can't share a `resolve()` with any other answer (`invalid_code_call`). Before anything is written, the answer is checked against the request: the signature under a key in the ring, the bound host context, the call and the tool, and the input, which must hash to the signed hash in the `code_call` entry, the `approval_requested` entry and the request alike. A request that fails throws `approval_refused` with the cause, writes nothing and runs nothing. The answer is then written, and the quorum policy decides. `met` decides the call again with the pipeline, so a deny rule added after the pause wins, and then runs the tool with `options.hostContext` and `options.signal`. `rejected` and `expired` deny the call, and `pending` returns `awaiting_approval`. A code call's expiry is enforced when it is next answered, because `resolve(session, [])` leaves its request waiting. `sticky`, `group` and `requesterId` apply as they do for a turn, and `approvalReuse` refuses a sticky or grouped answer the same way. A code call has no step, so a grouped answer covers only its own call. `budgetUsd` and the model settings don't apply, because no model is called.
680
+
681
+ Every result except `denied` carries `effectKey`, the call's effect identity. It comes from the tool's business key (`effect.businessKey`) when the tool declares one, and otherwise from `effectScope(session, harness, callId)`, whose call id is the `code_call` entry's id. A tool that builds its own key with `effectScope(session, harness, ctx.callId)` therefore gets the same key, and a resolution in another process finds it again.
682
+
683
+ A code call is the host's, so the model never reads it or its result. Each code call runs at most once, even across a crash. Two terms carry the rule. A call *starts* once its log holds the entry that clears it to run: the pipeline's allow, a sticky allowance, or, after a person's allow, the pipeline's fresh decision when it is not a deny. The tool starts right after that entry. To *settle* a call is to write the result it lacks, for a call that crashed, never ran or was interrupted. The next `invokeTool()` on the session settles every call a crash left open:
684
+
685
+ | The call | What its log holds | What the next `invokeTool()` does |
686
+ | --- | --- | --- |
687
+ | Has a result | A `tool_result` | Nothing. The call no longer waits, so a replayed answer throws `approval_not_pending`. |
688
+ | Started, no result | The entry that cleared it, and no `tool_result` | Settles it with the result an interrupted model call gets, and never runs it again, because it may have taken effect. |
689
+ | Answered or never asked, never started | No entry that cleared it, and either a final answer or no request | Settles it with an error that says it never ran, so a compensation that names it is refused. |
690
+
691
+ A call that asked and has no final answer is not open: it still waits.
692
+
693
+ Within one process, one code call of a session runs at a time.
694
+
695
+ A code call runs no turn, so the harness's `interceptors` and `observers` don't see it: they are the hooks and events of a model step. A `beforeToolCall` may replace the input or ask through the run's own pause, neither of which fits a call whose input is recorded and hashed before it is decided. What applies to a code call is the permission pipeline, whose `hooks` see `initiator: "code"`; the harness's `wrap`, which can guard or redact around the tool; and the context policy's write cap. Put a guard that must cover code calls in the pipeline's `hooks` or in `wrap`.
696
+
697
+ `compensates` names the call id of an earlier code call that this one undoes, such as a refund reversal after a refund. The earlier call must have run, and the compensation must reach an effect key of its own, or `invokeTool()` throws `invalid_code_call`. The compensation's `code_call` entry records the link.
698
+
699
+ `invokeTool()` throws before it writes anything:
700
+
701
+ - `invalid_code_call`: a tool the registry lacks or that runs on the client, an input or host context with no canonical JSON form, a business key that fails, a harness with no pipeline, or a compensation that fails its check.
702
+ - `approval_unavailable`: a harness with no signer.
703
+ - An aborted signal throws its reason.
704
+
705
+ It does not check the input against the tool's schema, because your code, not a model, chose it.
706
+
707
+ ### The key ring is a 0600 file outside the log and the sandbox
708
+
709
+ `fileKeyStore(path?)` from `@buildanagent/harness/session/jsonl` is a `KeyStore` over one file, by default `$XDG_STATE_HOME/buildanagent/keys.json` (or `~/.local/state/buildanagent/keys.json`). `load()` creates a ring with one random 256-bit key when the file is missing, in a folder of mode `0700`, and refuses a file that group or others can read, that belongs to another user, or that is a symbolic link. Pass the loaded ring to `hmacSigner()` and give the signer to `createHarness({ signer })`; the SDK reads the key by the id a request names, so a request signed with an older key still verifies. `rotate()` adds a new current key, and `prune(inUse)` removes every key not in `inUse` except the current one, so pass the `keyId` of every request that still waits. `rotate()` and `prune()` take a lock file beside the ring, so two processes that change it together keep both changes. A tool or sandbox sees none of this: the ring is in the host's files, and a spawned process gets [a cleared environment](#every-spawned-process-gets-a-cleared-environment).
710
+
711
+ ### A read-only secret can hold the key ring instead
712
+
713
+ On a serverless host the harness can read its key but not write it, so `secretKeyStore({ read })` from `@buildanagent/harness/session` is a `KeyStore` with `load()` only. `read()` returns the secret's text, the JSON ring that `parseKeyRing()` reads, such as `{"current":"2026-11","keys":{"2026-11":"<key>"}}` with each key at least 32 random bytes in unpadded base64url. `load()` calls `read()` every time and keeps no copy, so a ring the platform rotated takes effect at the next load. `load()` throws `invalid_key_store` for a `read()` that fails or returns a non-string, and for a ring that is not JSON, holds a key that is not base64url or is shorter than 32 bytes, or names a `current` it lacks. The error's message is fixed text and the error has no cause, so it never holds the secret's text, a key id, a key or the error `read()` threw. To find which rule a ring breaks, check the secret itself. The store imports no Node module, so a Cloudflare, AWS or Vercel adapter only has to supply `read` (N46a, N47a and N48a build those).
714
+
715
+ The owner rotates such a ring with the platform's own tooling: add a new key and make it current, then remove an old key once no waiting request names it. `rotateKeys(store)` and `pruneKeys(store, inUse)` call a store's `rotate()` and `prune()` when it has them. On a store without them they reject with `key_store_read_only`, whose message names the platform's secret tooling (by default "such as wrangler secret put, aws secretsmanager put-secret-value or vercel env"; pass `platformHint` for your own text).
716
+ `keyStoreConformanceCases(factory)` and `runKeyStoreConformance(factory)` in `@buildanagent/harness/testing` check a store with five cases. `load()` returns a usable ring, returns the same ring twice, and gives a ring that signs and verifies through `hmacSigner()`. `rotate()` keeps the old key loadable, and `prune()` keeps the current and in-use keys and returns the ids it removed. The rotate and prune cases skip with a reason when a store leaves the methods out. Run `runKeyStoreConformance(factory)` against any store you write.
2
717
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.