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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +716 -2
  5. package/dist/ablation.d.ts +2 -0
  6. package/dist/ablation.js +3 -0
  7. package/dist/ablation.js.map +1 -0
  8. package/dist/completion/check.d.ts +64 -0
  9. package/dist/completion/check.js +152 -0
  10. package/dist/completion/check.js.map +1 -0
  11. package/dist/completion/checks.d.ts +45 -0
  12. package/dist/completion/checks.js +173 -0
  13. package/dist/completion/checks.js.map +1 -0
  14. package/dist/completion/flags.d.ts +25 -0
  15. package/dist/completion/flags.js +87 -0
  16. package/dist/completion/flags.js.map +1 -0
  17. package/dist/completion/index.d.ts +8 -0
  18. package/dist/completion/index.js +9 -0
  19. package/dist/completion/index.js.map +1 -0
  20. package/dist/completion/snapshot.d.ts +33 -0
  21. package/dist/completion/snapshot.js +83 -0
  22. package/dist/completion/snapshot.js.map +1 -0
  23. package/dist/context/cap.d.ts +32 -0
  24. package/dist/context/cap.js +50 -0
  25. package/dist/context/cap.js.map +1 -0
  26. package/dist/context/estimate.d.ts +18 -0
  27. package/dist/context/estimate.js +20 -0
  28. package/dist/context/estimate.js.map +1 -0
  29. package/dist/context/file-spill.d.ts +5 -0
  30. package/dist/context/file-spill.js +25 -0
  31. package/dist/context/file-spill.js.map +1 -0
  32. package/dist/context/index.d.ts +10 -0
  33. package/dist/context/index.js +10 -0
  34. package/dist/context/index.js.map +1 -0
  35. package/dist/context/mask.d.ts +27 -0
  36. package/dist/context/mask.js +71 -0
  37. package/dist/context/mask.js.map +1 -0
  38. package/dist/context/mid-turn.d.ts +40 -0
  39. package/dist/context/mid-turn.js +82 -0
  40. package/dist/context/mid-turn.js.map +1 -0
  41. package/dist/context/policy.d.ts +9 -0
  42. package/dist/context/policy.js +140 -0
  43. package/dist/context/policy.js.map +1 -0
  44. package/dist/context/spill-ledger.d.ts +25 -0
  45. package/dist/context/spill-ledger.js +54 -0
  46. package/dist/context/spill-ledger.js.map +1 -0
  47. package/dist/context/spill.d.ts +6 -0
  48. package/dist/context/spill.js +14 -0
  49. package/dist/context/spill.js.map +1 -0
  50. package/dist/context/summarize.d.ts +53 -0
  51. package/dist/context/summarize.js +204 -0
  52. package/dist/context/summarize.js.map +1 -0
  53. package/dist/context/summary-template.d.ts +29 -0
  54. package/dist/context/summary-template.js +69 -0
  55. package/dist/context/summary-template.js.map +1 -0
  56. package/dist/context/types.d.ts +150 -0
  57. package/dist/context/types.js +2 -0
  58. package/dist/context/types.js.map +1 -0
  59. package/dist/context/write-cap.d.ts +19 -0
  60. package/dist/context/write-cap.js +41 -0
  61. package/dist/context/write-cap.js.map +1 -0
  62. package/dist/create-harness.d.ts +7 -0
  63. package/dist/create-harness.js +21 -0
  64. package/dist/create-harness.js.map +1 -0
  65. package/dist/credentials/addresses.d.ts +14 -0
  66. package/dist/credentials/addresses.js +144 -0
  67. package/dist/credentials/addresses.js.map +1 -0
  68. package/dist/credentials/allowlist.d.ts +34 -0
  69. package/dist/credentials/allowlist.js +77 -0
  70. package/dist/credentials/allowlist.js.map +1 -0
  71. package/dist/credentials/egress-proxy.d.ts +70 -0
  72. package/dist/credentials/egress-proxy.js +482 -0
  73. package/dist/credentials/egress-proxy.js.map +1 -0
  74. package/dist/credentials/index.d.ts +9 -0
  75. package/dist/credentials/index.js +10 -0
  76. package/dist/credentials/index.js.map +1 -0
  77. package/dist/credentials/scrub.d.ts +16 -0
  78. package/dist/credentials/scrub.js +93 -0
  79. package/dist/credentials/scrub.js.map +1 -0
  80. package/dist/errors.d.ts +56 -0
  81. package/dist/errors.js +63 -0
  82. package/dist/errors.js.map +1 -0
  83. package/dist/extensions/compose.d.ts +27 -0
  84. package/dist/extensions/compose.js +83 -0
  85. package/dist/extensions/compose.js.map +1 -0
  86. package/dist/extensions/context-files-node.d.ts +28 -0
  87. package/dist/extensions/context-files-node.js +74 -0
  88. package/dist/extensions/context-files-node.js.map +1 -0
  89. package/dist/extensions/context-files.d.ts +68 -0
  90. package/dist/extensions/context-files.js +214 -0
  91. package/dist/extensions/context-files.js.map +1 -0
  92. package/dist/extensions/digest.d.ts +6 -0
  93. package/dist/extensions/digest.js +68 -0
  94. package/dist/extensions/digest.js.map +1 -0
  95. package/dist/extensions/index.d.ts +10 -0
  96. package/dist/extensions/index.js +10 -0
  97. package/dist/extensions/index.js.map +1 -0
  98. package/dist/extensions/load.d.ts +42 -0
  99. package/dist/extensions/load.js +211 -0
  100. package/dist/extensions/load.js.map +1 -0
  101. package/dist/extensions/lock.d.ts +8 -0
  102. package/dist/extensions/lock.js +95 -0
  103. package/dist/extensions/lock.js.map +1 -0
  104. package/dist/extensions/node.d.ts +10 -0
  105. package/dist/extensions/node.js +11 -0
  106. package/dist/extensions/node.js.map +1 -0
  107. package/dist/extensions/project-dirs.d.ts +24 -0
  108. package/dist/extensions/project-dirs.js +97 -0
  109. package/dist/extensions/project-dirs.js.map +1 -0
  110. package/dist/extensions/skills-node.d.ts +34 -0
  111. package/dist/extensions/skills-node.js +123 -0
  112. package/dist/extensions/skills-node.js.map +1 -0
  113. package/dist/extensions/skills.d.ts +51 -0
  114. package/dist/extensions/skills.js +175 -0
  115. package/dist/extensions/skills.js.map +1 -0
  116. package/dist/extensions/trust-file.d.ts +3 -0
  117. package/dist/extensions/trust-file.js +62 -0
  118. package/dist/extensions/trust-file.js.map +1 -0
  119. package/dist/extensions/trust-store-node.d.ts +10 -0
  120. package/dist/extensions/trust-store-node.js +33 -0
  121. package/dist/extensions/trust-store-node.js.map +1 -0
  122. package/dist/extensions/types.d.ts +42 -0
  123. package/dist/extensions/types.js +2 -0
  124. package/dist/extensions/types.js.map +1 -0
  125. package/dist/harness.d.ts +156 -0
  126. package/dist/harness.js +2 -0
  127. package/dist/harness.js.map +1 -0
  128. package/dist/index.d.ts +4 -0
  129. package/dist/index.js +5 -0
  130. package/dist/index.js.map +1 -0
  131. package/dist/mcp/connection.d.ts +22 -0
  132. package/dist/mcp/connection.js +267 -0
  133. package/dist/mcp/connection.js.map +1 -0
  134. package/dist/mcp/content.d.ts +27 -0
  135. package/dist/mcp/content.js +177 -0
  136. package/dist/mcp/content.js.map +1 -0
  137. package/dist/mcp/errors.d.ts +19 -0
  138. package/dist/mcp/errors.js +21 -0
  139. package/dist/mcp/errors.js.map +1 -0
  140. package/dist/mcp/index.d.ts +10 -0
  141. package/dist/mcp/index.js +10 -0
  142. package/dist/mcp/index.js.map +1 -0
  143. package/dist/mcp/manager.d.ts +7 -0
  144. package/dist/mcp/manager.js +173 -0
  145. package/dist/mcp/manager.js.map +1 -0
  146. package/dist/mcp/record.d.ts +7 -0
  147. package/dist/mcp/record.js +20 -0
  148. package/dist/mcp/record.js.map +1 -0
  149. package/dist/mcp/stdio.d.ts +39 -0
  150. package/dist/mcp/stdio.js +382 -0
  151. package/dist/mcp/stdio.js.map +1 -0
  152. package/dist/mcp/types.d.ts +172 -0
  153. package/dist/mcp/types.js +2 -0
  154. package/dist/mcp/types.js.map +1 -0
  155. package/dist/memory/index.d.ts +2 -0
  156. package/dist/memory/index.js +3 -0
  157. package/dist/memory/index.js.map +1 -0
  158. package/dist/permissions/default-rules.d.ts +7 -0
  159. package/dist/permissions/default-rules.js +42 -0
  160. package/dist/permissions/default-rules.js.map +1 -0
  161. package/dist/permissions/errors.d.ts +11 -0
  162. package/dist/permissions/errors.js +14 -0
  163. package/dist/permissions/errors.js.map +1 -0
  164. package/dist/permissions/index.d.ts +9 -0
  165. package/dist/permissions/index.js +9 -0
  166. package/dist/permissions/index.js.map +1 -0
  167. package/dist/permissions/match.d.ts +33 -0
  168. package/dist/permissions/match.js +287 -0
  169. package/dist/permissions/match.js.map +1 -0
  170. package/dist/permissions/pipeline.d.ts +9 -0
  171. package/dist/permissions/pipeline.js +235 -0
  172. package/dist/permissions/pipeline.js.map +1 -0
  173. package/dist/permissions/rules.d.ts +22 -0
  174. package/dist/permissions/rules.js +74 -0
  175. package/dist/permissions/rules.js.map +1 -0
  176. package/dist/permissions/shadow.d.ts +5 -0
  177. package/dist/permissions/shadow.js +22 -0
  178. package/dist/permissions/shadow.js.map +1 -0
  179. package/dist/permissions/types.d.ts +104 -0
  180. package/dist/permissions/types.js +2 -0
  181. package/dist/permissions/types.js.map +1 -0
  182. package/dist/sandbox/base.d.ts +35 -0
  183. package/dist/sandbox/base.js +60 -0
  184. package/dist/sandbox/base.js.map +1 -0
  185. package/dist/sandbox/docker/index.d.ts +35 -0
  186. package/dist/sandbox/docker/index.js +448 -0
  187. package/dist/sandbox/docker/index.js.map +1 -0
  188. package/dist/sandbox/errors.d.ts +16 -0
  189. package/dist/sandbox/errors.js +22 -0
  190. package/dist/sandbox/errors.js.map +1 -0
  191. package/dist/sandbox/host-files.d.ts +63 -0
  192. package/dist/sandbox/host-files.js +248 -0
  193. package/dist/sandbox/host-files.js.map +1 -0
  194. package/dist/sandbox/index.d.ts +8 -0
  195. package/dist/sandbox/index.js +8 -0
  196. package/dist/sandbox/index.js.map +1 -0
  197. package/dist/sandbox/none.d.ts +17 -0
  198. package/dist/sandbox/none.js +108 -0
  199. package/dist/sandbox/none.js.map +1 -0
  200. package/dist/sandbox/process.d.ts +61 -0
  201. package/dist/sandbox/process.js +253 -0
  202. package/dist/sandbox/process.js.map +1 -0
  203. package/dist/sandbox/spawn-env.d.ts +20 -0
  204. package/dist/sandbox/spawn-env.js +128 -0
  205. package/dist/sandbox/spawn-env.js.map +1 -0
  206. package/dist/sandbox/srt/index.d.ts +35 -0
  207. package/dist/sandbox/srt/index.js +264 -0
  208. package/dist/sandbox/srt/index.js.map +1 -0
  209. package/dist/sandbox/srt/settings.d.ts +48 -0
  210. package/dist/sandbox/srt/settings.js +31 -0
  211. package/dist/sandbox/srt/settings.js.map +1 -0
  212. package/dist/sandbox/types.d.ts +88 -0
  213. package/dist/sandbox/types.js +6 -0
  214. package/dist/sandbox/types.js.map +1 -0
  215. package/dist/server/answers.d.ts +16 -0
  216. package/dist/server/answers.js +43 -0
  217. package/dist/server/answers.js.map +1 -0
  218. package/dist/server/connection.d.ts +99 -0
  219. package/dist/server/connection.js +309 -0
  220. package/dist/server/connection.js.map +1 -0
  221. package/dist/server/dispatcher.d.ts +86 -0
  222. package/dist/server/dispatcher.js +800 -0
  223. package/dist/server/dispatcher.js.map +1 -0
  224. package/dist/server/index.d.ts +13 -0
  225. package/dist/server/index.js +12 -0
  226. package/dist/server/index.js.map +1 -0
  227. package/dist/server/local-transport.d.ts +44 -0
  228. package/dist/server/local-transport.js +103 -0
  229. package/dist/server/local-transport.js.map +1 -0
  230. package/dist/server/outbox.d.ts +31 -0
  231. package/dist/server/outbox.js +130 -0
  232. package/dist/server/outbox.js.map +1 -0
  233. package/dist/server/params.d.ts +25 -0
  234. package/dist/server/params.js +112 -0
  235. package/dist/server/params.js.map +1 -0
  236. package/dist/server/protocol.schema.json +2448 -0
  237. package/dist/server/rpc-session.d.ts +43 -0
  238. package/dist/server/rpc-session.js +167 -0
  239. package/dist/server/rpc-session.js.map +1 -0
  240. package/dist/server/stdio-streams.d.ts +67 -0
  241. package/dist/server/stdio-streams.js +218 -0
  242. package/dist/server/stdio-streams.js.map +1 -0
  243. package/dist/server/stdio.d.ts +59 -0
  244. package/dist/server/stdio.js +189 -0
  245. package/dist/server/stdio.js.map +1 -0
  246. package/dist/server/websocket.d.ts +106 -0
  247. package/dist/server/websocket.js +327 -0
  248. package/dist/server/websocket.js.map +1 -0
  249. package/dist/session/approvals.d.ts +81 -0
  250. package/dist/session/approvals.js +217 -0
  251. package/dist/session/approvals.js.map +1 -0
  252. package/dist/session/code-call-log.d.ts +42 -0
  253. package/dist/session/code-call-log.js +63 -0
  254. package/dist/session/code-call-log.js.map +1 -0
  255. package/dist/session/code-call-result.d.ts +19 -0
  256. package/dist/session/code-call-result.js +95 -0
  257. package/dist/session/code-call-result.js.map +1 -0
  258. package/dist/session/code-call.d.ts +49 -0
  259. package/dist/session/code-call.js +345 -0
  260. package/dist/session/code-call.js.map +1 -0
  261. package/dist/session/effect-scope.d.ts +11 -0
  262. package/dist/session/effect-scope.js +10 -0
  263. package/dist/session/effect-scope.js.map +1 -0
  264. package/dist/session/errors.d.ts +19 -0
  265. package/dist/session/errors.js +27 -0
  266. package/dist/session/errors.js.map +1 -0
  267. package/dist/session/file-index.d.ts +8 -0
  268. package/dist/session/file-index.js +70 -0
  269. package/dist/session/file-index.js.map +1 -0
  270. package/dist/session/file-key-store.d.ts +16 -0
  271. package/dist/session/file-key-store.js +169 -0
  272. package/dist/session/file-key-store.js.map +1 -0
  273. package/dist/session/file-lock.d.ts +52 -0
  274. package/dist/session/file-lock.js +324 -0
  275. package/dist/session/file-lock.js.map +1 -0
  276. package/dist/session/index.d.ts +22 -0
  277. package/dist/session/index.js +20 -0
  278. package/dist/session/index.js.map +1 -0
  279. package/dist/session/jsonl-store.d.ts +37 -0
  280. package/dist/session/jsonl-store.js +386 -0
  281. package/dist/session/jsonl-store.js.map +1 -0
  282. package/dist/session/jsonl.d.ts +9 -0
  283. package/dist/session/jsonl.js +10 -0
  284. package/dist/session/jsonl.js.map +1 -0
  285. package/dist/session/lock.d.ts +19 -0
  286. package/dist/session/lock.js +2 -0
  287. package/dist/session/lock.js.map +1 -0
  288. package/dist/session/memory-store.d.ts +12 -0
  289. package/dist/session/memory-store.js +60 -0
  290. package/dist/session/memory-store.js.map +1 -0
  291. package/dist/session/migrate.d.ts +41 -0
  292. package/dist/session/migrate.js +86 -0
  293. package/dist/session/migrate.js.map +1 -0
  294. package/dist/session/pointer.d.ts +15 -0
  295. package/dist/session/pointer.js +22 -0
  296. package/dist/session/pointer.js.map +1 -0
  297. package/dist/session/rebuild.d.ts +53 -0
  298. package/dist/session/rebuild.js +230 -0
  299. package/dist/session/rebuild.js.map +1 -0
  300. package/dist/session/resume.d.ts +26 -0
  301. package/dist/session/resume.js +128 -0
  302. package/dist/session/resume.js.map +1 -0
  303. package/dist/session/retention.d.ts +97 -0
  304. package/dist/session/retention.js +702 -0
  305. package/dist/session/retention.js.map +1 -0
  306. package/dist/session/runner.d.ts +156 -0
  307. package/dist/session/runner.js +656 -0
  308. package/dist/session/runner.js.map +1 -0
  309. package/dist/session/scheduler.d.ts +47 -0
  310. package/dist/session/scheduler.js +85 -0
  311. package/dist/session/scheduler.js.map +1 -0
  312. package/dist/session/secret-key-store.d.ts +47 -0
  313. package/dist/session/secret-key-store.js +79 -0
  314. package/dist/session/secret-key-store.js.map +1 -0
  315. package/dist/session/session.d.ts +106 -0
  316. package/dist/session/session.js +353 -0
  317. package/dist/session/session.js.map +1 -0
  318. package/dist/session/sticky.d.ts +48 -0
  319. package/dist/session/sticky.js +232 -0
  320. package/dist/session/sticky.js.map +1 -0
  321. package/dist/session/store.d.ts +108 -0
  322. package/dist/session/store.js +163 -0
  323. package/dist/session/store.js.map +1 -0
  324. package/dist/telemetry/index.d.ts +2 -0
  325. package/dist/telemetry/index.js +3 -0
  326. package/dist/telemetry/index.js.map +1 -0
  327. package/dist/testing/fake-sandbox.d.ts +34 -0
  328. package/dist/testing/fake-sandbox.js +221 -0
  329. package/dist/testing/fake-sandbox.js.map +1 -0
  330. package/dist/testing/index.d.ts +10 -0
  331. package/dist/testing/index.js +11 -0
  332. package/dist/testing/index.js.map +1 -0
  333. package/dist/testing/key-store-conformance.d.ts +22 -0
  334. package/dist/testing/key-store-conformance.js +97 -0
  335. package/dist/testing/key-store-conformance.js.map +1 -0
  336. package/dist/testing/run-cases.d.ts +21 -0
  337. package/dist/testing/run-cases.js +20 -0
  338. package/dist/testing/run-cases.js.map +1 -0
  339. package/dist/testing/sandbox-conformance.d.ts +64 -0
  340. package/dist/testing/sandbox-conformance.js +361 -0
  341. package/dist/testing/sandbox-conformance.js.map +1 -0
  342. package/dist/testing/scheduler-conformance.d.ts +32 -0
  343. package/dist/testing/scheduler-conformance.js +72 -0
  344. package/dist/testing/scheduler-conformance.js.map +1 -0
  345. package/dist/testing/store-conformance.d.ts +21 -0
  346. package/dist/testing/store-conformance.js +320 -0
  347. package/dist/testing/store-conformance.js.map +1 -0
  348. package/dist/tools/errors.d.ts +13 -0
  349. package/dist/tools/errors.js +17 -0
  350. package/dist/tools/errors.js.map +1 -0
  351. package/dist/tools/index.d.ts +8 -0
  352. package/dist/tools/index.js +8 -0
  353. package/dist/tools/index.js.map +1 -0
  354. package/dist/tools/registry.d.ts +3 -0
  355. package/dist/tools/registry.js +234 -0
  356. package/dist/tools/registry.js.map +1 -0
  357. package/dist/tools/tool-search.d.ts +30 -0
  358. package/dist/tools/tool-search.js +118 -0
  359. package/dist/tools/tool-search.js.map +1 -0
  360. package/dist/tools/types.d.ts +106 -0
  361. package/dist/tools/types.js +2 -0
  362. package/dist/tools/types.js.map +1 -0
  363. package/llms.txt +435 -0
  364. package/package.json +118 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../src/session/runner.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAA8D,MAAM,uBAAuB,CAAC;AACtH,OAAO,EAAE,cAAc,EAAkC,MAAM,wBAAwB,CAAC;AACxF,OAAO,EAEL,YAAY,EAEZ,mBAAmB,EACnB,WAAW,EACX,aAAa,EAOb,GAAG,EACH,WAAW,GAGZ,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAIL,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,GACd,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAItD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE/D,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AA2EzD,+GAA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M,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1D,0FAA0F;IAC1F,OAAO;QACL,GAAG,OAAO;QACV,KAAK,EAAE,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK;QAClC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC;QAC3C,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC;KACxC,CAAC;AACJ,CAAC;AAED,6FAA6F;AAC7F,SAAS,YAAY,CAAC,MAAkB;IACtC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,MAA0C,CAAC;IAC9E,OAAO,IAAkB,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * `runTurn()`: one SDK run, written into a session's log. The user entries are durable before the run starts, so a turn\n * that dies before its first model call leaves the question in the file. The run's own events then become entries\n * through one observer: a message's blocks and end when its call ends, a tool's result when the call ends, usage, and the\n * turn's end. Every write goes through one queue, so the permission pipeline's entries and the observer's never race for\n * the same parent.\n */\nimport { addCost, addUsage, type ContentBlock, type Message, type Model, type ModelRef } from \"@buildanagent/gateway\";\nimport { FORMAT_VERSION, type Origin, type SessionEntry } from \"@buildanagent/protocol\";\nimport {\n type AgentEvent,\n CAPABILITIES,\n type CallOptions,\n composeInterceptors,\n continueRun,\n DEFAULTS_HASH,\n type Interceptors,\n type Observer,\n type Recheck,\n type Resolution,\n type Run,\n type RunResult,\n run,\n SDK_VERSION,\n type ToolDefinition,\n type ToolResult,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport {\n type CompletionOutcome,\n type CompletionSettings,\n type CompletionStart,\n completionFailure,\n runCompletionCheck,\n snapshotStart,\n} from \"../completion/check.js\";\nimport type { ContextFill, TurnContext } from \"../context/types.js\";\nimport { HarnessError } from \"../errors.js\";\nimport { skillOfRead } from \"../extensions/skills.js\";\nimport type { Harness } from \"../harness.js\";\nimport type { PolicySession } from \"../permissions/types.js\";\nimport type { ToolWrapper } from \"../tools/types.js\";\nimport { contextOf } from \"./rebuild.js\";\nimport { settleOpenCalls, unansweredCalls } from \"./resume.js\";\nimport type { Session } from \"./session.js\";\nimport { findSticky, stickyDecision } from \"./sticky.js\";\nimport type { EntryInput } from \"./store.js\";\n\n/** One call to a `client_request` tool, as `TurnOptions.clientTool` receives it. */\nexport interface ClientToolCall {\n readonly callId: string;\n /** The tool's canonical name. */\n readonly tool: string;\n /** The input after the SDK validated it. */\n readonly input: unknown;\n /** Fires when the run is aborted, so the caller can withdraw the request it sent. */\n readonly signal: AbortSignal;\n}\n\n/** Runs a `client_request` tool's call by asking the client that holds the tool, and resolves with its result. */\nexport type ClientToolRunner = (call: ClientToolCall) => Promise<ToolResult>;\n\n/** The options of one turn. Anything left out takes the harness's setting. */\nexport interface TurnOptions<H = unknown> {\n readonly input: string | ContentBlock[];\n /** The `origin` of the input blocks: `operator` for text the host wrote, such as a scheduled prompt. Default `user`. */\n readonly inputOrigin?: \"user\" | \"operator\";\n readonly budgetUsd?: number;\n readonly signal?: AbortSignal;\n /** This turn's host context. A tool reads it as `ctx.app`; it reaches no schema, event or entry. */\n readonly hostContext?: H;\n readonly system?: string;\n /** The registered tools this turn may use, by name or alias. A name the registry lacks throws. Default every tool. */\n readonly tools?: readonly string[];\n readonly output?: ToolDefinition<unknown, unknown, unknown>;\n /** The model for this turn. A change from the session's last model is recorded as a `loadout` entry. */\n readonly model?: Model;\n readonly maxSteps?: number;\n /** How many times the loop re-issues a call that ended with a retryable error. Default none. */\n readonly turnRetries?: number;\n readonly modelOptions?: CallOptions;\n /** Called with the run as soon as it starts, so a caller can `steer()`, `followUp()` or abort it. */\n readonly onRun?: (run: Run<unknown>) => void;\n /** Called with how full the request view is after each model call's view is built, when the harness has a context policy. */\n readonly onContextFill?: (fill: ContextFill) => void;\n /** Called when the first run has ended because the request was too large and a retry may follow. */\n readonly onOverflowRetry?: () => void;\n /**\n * Checks the turn's completion. Before the model runs, the turn resolves the project's checks in this sandbox and\n * snapshots the workspace and the check config. A turn that ends `done` then runs those checks, diffs the workspace\n * and the config against the start, and writes a `completion_check` entry. The stop reason is unchanged: a failed\n * check, a flag or a check that could not run is recorded, never fatal. The result's `lastEntryId` is that entry.\n */\n readonly completion?: CompletionSettings;\n /** Called with the `completion_check` entry once it is written. */\n readonly onCompletionCheck?: (entry: SessionEntry) => void;\n /** Observers for this turn alone. Unlike `Run.on()`, they also see `run_start`. They run after the harness's own. */\n readonly observers?: readonly Observer[];\n /**\n * Runs the calls of every tool registered with the `client_request` pattern, in place of the tool's own `execute`.\n * The dispatcher sets it to send a `tool/call` request. Left out, the tool's own `execute` runs.\n */\n readonly clientTool?: ClientToolRunner;\n /**\n * The conversation so far. Left out, it is rebuilt from the session's log, so a turn in any process goes on from\n * what the log holds. Pass it only to run on a conversation the log doesn't hold.\n */\n readonly history?: readonly Message[];\n /** The clock of the entries and the run, for a test that needs the same bytes twice. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the ids of the entries and of the run, for a test that needs the same bytes twice. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/** What a turn returns: the SDK's result, and where the turn left the log. */\nexport type TurnResult = RunResult<unknown> & { sessionKey: string; lastEntryId: string };\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\ntype Body = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n\n/** Writes entries one at a time, each after the one before, so every entry's parent is the entry before it. */\nclass EntryWriter {\n readonly #session: Session;\n readonly #newId: () => string;\n readonly #now: () => Date;\n readonly #onFailure: () => void;\n #chain: Promise<unknown> = Promise.resolve();\n #failure: unknown;\n #failed = false;\n\n constructor(session: Session, newId: () => string, now: () => Date, onFailure: () => void) {\n this.#session = session;\n this.#newId = newId;\n this.#now = now;\n this.#onFailure = onFailure;\n }\n\n /** The first write that failed, once one has. */\n failure(): { readonly error: unknown } | undefined {\n return this.#failed ? { error: this.#failure } : undefined;\n }\n\n write(origin: Origin, body: Body): Promise<SessionEntry> {\n const next = this.#chain.then(async () => {\n if (this.#failed) throw this.#failure;\n const entry = {\n ...body,\n id: this.#newId(),\n parentId: this.#session.head(),\n timestamp: this.#now().toISOString(),\n origin,\n };\n const [stored] = await this.#session.append([entry as EntryInput]);\n return stored as SessionEntry;\n });\n this.#chain = next.catch((error) => {\n if (!this.#failed) {\n this.#failed = true;\n this.#failure = error;\n // A log that can't be written can't be trusted to hold the turn, so the run stops.\n this.#onFailure();\n }\n });\n return next;\n }\n\n /** Waits for every write queued so far. */\n settled(): Promise<unknown> {\n return this.#chain;\n }\n}\n\nconst refKey = (ref: ModelRef): string => `${ref.api}\\u0000${ref.provider}\\u0000${ref.id}`;\n\n/**\n * The harness's wrapper, with a `client_request` tool's `execute` sent to `clientTool` first, so a write cap or shadow\n * mode still wraps the call the client runs.\n */\nfunction wrapperOf<H>(harness: Harness<H>, clientTool: ClientToolRunner | undefined): ToolWrapper<H> | undefined {\n if (clientTool === undefined) return harness.wrap;\n const inner: ToolWrapper<H> = harness.wrap ?? ((tool) => tool.definition);\n return (tool, hostContext) => {\n if (tool.pattern !== \"client_request\") return inner(tool, hostContext);\n const definition: ToolDefinition<unknown, unknown, unknown> = {\n ...tool.definition,\n execute: (input, ctx) => clientTool({ callId: ctx.callId, tool: tool.canonicalName, input, signal: ctx.signal }),\n };\n return inner({ ...tool, definition }, hostContext);\n };\n}\n\n/** The turn's tools: the registry's definitions for this host context, cut to the allowlist. */\nfunction toolsOf<H>(\n harness: Harness<H>,\n options: Pick<TurnOptions<H>, \"tools\" | \"hostContext\" | \"clientTool\">,\n): ToolDefinition<unknown, unknown, unknown>[] {\n const all = harness.registry.definitions(wrapperOf(harness, options.clientTool), options.hostContext as H);\n if (options.tools === undefined) return all;\n const allowed = new Set<string>();\n for (const name of options.tools) {\n const tool = harness.registry.get(name);\n if (tool === undefined)\n throw new HarnessError(\n \"invalid_turn_options\",\n `the tool allowlist names \"${name}\", which no tool is registered under`,\n );\n allowed.add(tool.canonicalName);\n }\n return all.filter((definition) => allowed.has(definition.name));\n}\n\n/**\n * Writes what a new session starts with: its header when the path is empty, and its `env_stamp` when the path has\n * none. `write` appends one entry after the ones before it.\n */\nexport async function recordSessionStart<H>(\n harness: Harness<H>,\n write: (origin: \"harness\", body: Body) => Promise<unknown>,\n model: Model,\n started: readonly SessionEntry[],\n): Promise<void> {\n if (started.length === 0) {\n await write(\"harness\", {\n type: \"session_header\",\n formatVersion: FORMAT_VERSION,\n harnessVersion: harness.harnessVersion,\n sdkVersion: SDK_VERSION,\n defaultsHash: DEFAULTS_HASH,\n capabilities: [...CAPABILITIES],\n ablationHash: harness.ablationHash,\n });\n }\n if (!started.some((entry) => entry.type === \"env_stamp\")) {\n await write(\"harness\", { type: \"env_stamp\", ...harness.env, model: model.ref });\n }\n}\n\n/** Writes what a new session starts with, and a `loadout` when the tools or the model differ from the last one recorded. */\nasync function recordLoadout<H>(\n harness: Harness<H>,\n writer: EntryWriter,\n model: Model,\n tools: readonly ToolDefinition<unknown, unknown, unknown>[],\n started: readonly SessionEntry[],\n): Promise<void> {\n await recordSessionStart(harness, (origin, body) => writer.write(origin, body), model, started);\n const names = tools.map((tool) => tool.name);\n const last = started.findLast((entry) => entry.type === \"loadout\");\n const same =\n last?.type === \"loadout\" &&\n last.model !== undefined &&\n refKey(last.model) === refKey(model.ref) &&\n [...last.tools].sort().join() === [...names].sort().join();\n if (!same) await writer.write(\"harness\", { type: \"loadout\", tools: names, model: model.ref });\n const written = new Set<string>();\n for (const record of harness.extensionRecords ?? []) {\n const key = `${record.name}\\0${record.contentHash}`;\n const known =\n written.has(key) ||\n started.some(\n (entry) =>\n entry.type === \"extension_loaded\" && entry.name === record.name && entry.contentHash === record.contentHash,\n );\n if (known) continue;\n written.add(key);\n await writer.write(\"harness\", { ...record, type: \"extension_loaded\" });\n }\n}\n\nasync function writeInput(\n writer: EntryWriter,\n options: { input: string | ContentBlock[]; inputOrigin?: \"user\" | \"operator\" },\n newId: () => string,\n) {\n const blocks: ContentBlock[] =\n typeof options.input === \"string\" ? [{ type: \"text\", text: options.input }] : options.input;\n const messageId = newId();\n for (const [index, block] of blocks.entries()) {\n await writer.write(options.inputOrigin ?? \"user\", {\n type: \"message_block\",\n messageId,\n role: \"user\",\n index,\n block,\n delivery: \"input\",\n });\n }\n}\n\ntype ModelMessage = Extract<AgentEvent, { type: \"model_call_end\" }>[\"message\"];\n\n/** Turns the run's events into entries. It keeps the last model message back until the next event shows it was kept. */\nclass EventRecorder {\n readonly #writer: EntryWriter;\n readonly #harness: Harness<unknown>;\n readonly #system: string;\n readonly #newId: () => string;\n readonly #tools = new Map<string, string>();\n readonly #inputs = new Map<string, unknown>();\n #pending: ModelMessage | undefined;\n\n readonly #mode: \"run\" | \"continue\";\n readonly #spillOf: TurnContext[\"spillOf\"] | undefined;\n\n constructor(\n writer: EntryWriter,\n harness: Harness<unknown>,\n system: string,\n newId: () => string,\n mode: \"run\" | \"continue\" = \"run\",\n spillOf?: TurnContext[\"spillOf\"],\n ) {\n this.#spillOf = spillOf;\n this.#mode = mode;\n this.#writer = writer;\n this.#harness = harness;\n this.#system = system;\n this.#newId = newId;\n }\n\n /** Queues a write and returns at once. A failure is recorded by the writer and rethrown by `runTurn()`. */\n #queue(origin: Origin, body: Body): void {\n this.#writer.write(origin, body).catch(() => undefined);\n }\n\n #usage(message: ModelMessage): void {\n this.#queue(\"harness\", {\n type: \"usage\",\n source: \"model_call\",\n usage: message.usage,\n ...(message.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: message.lastAttemptUsage }),\n cost: message.cost,\n });\n }\n\n /**\n * Queues the held-back message: its blocks, its end and its usage. The gate calls it before it writes, so a call's\n * decision never lands ahead of the message that made the call.\n */\n flush(): void {\n const message = this.#pending;\n if (message === undefined) return;\n this.#pending = undefined;\n const messageId = this.#newId();\n for (const [index, block] of message.content.entries()) {\n this.#queue(\"model\", { type: \"message_block\", messageId, role: \"assistant\", index, block });\n }\n this.#queue(\"model\", {\n type: \"message_end\",\n messageId,\n model: message.model,\n stopReason: message.stopReason,\n ...(message.error === undefined ? {} : { error: message.error }),\n });\n this.#usage(message);\n }\n\n /** Handles an event without waiting for the store, so the observer is never behind and the SDK never drops it. */\n handle(event: AgentEvent): void {\n if (event.type === \"retry\" && event.layer === \"turn\" && this.#pending !== undefined) {\n // The call's message is superseded and not in the transcript, but the provider billed it.\n const superseded = this.#pending;\n this.#pending = undefined;\n this.#usage(superseded);\n return;\n }\n this.flush();\n this.#record(event);\n }\n\n #record(event: AgentEvent): void {\n switch (event.type) {\n case \"run_start\":\n this.#queue(\"harness\", {\n type: \"turn_start\",\n runId: event.runId,\n mode: this.#mode,\n system: this.#system,\n });\n return;\n case \"approval_request\":\n // The request is in the log before any client hears of it: the harness's own observers wait for the writes.\n this.#queue(\"harness\", { type: \"approval_requested\", request: event.request, input: event.input });\n return;\n case \"model_call_end\":\n this.#pending = event.message;\n // A call the SDK refuses to start (unknown tool, bad input) gets no tool_call_start, so its name comes from here.\n for (const block of event.message.content) {\n if (block.type === \"tool_call\") this.#tools.set(block.callId, block.name);\n }\n return;\n case \"tool_call_start\":\n this.#tools.set(event.callId, event.tool);\n this.#inputs.set(event.callId, event.input);\n return;\n case \"tool_call_end\":\n this.#toolResult(event);\n return;\n case \"steer_applied\":\n for (const [index, block] of event.receipt.message.entries()) {\n this.#queue(\"user\", {\n type: \"message_block\",\n messageId: event.receipt.id,\n role: \"user\",\n index,\n block,\n delivery: event.receipt.kind,\n });\n }\n return;\n case \"run_end\":\n this.#queue(\"harness\", {\n type: \"turn_end\",\n runId: event.runId,\n stopReason: event.result.stopReason,\n steps: event.result.steps,\n });\n return;\n default:\n }\n }\n\n #toolResult(event: Extract<AgentEvent, { type: \"tool_call_end\" }>): void {\n const tool = this.#tools.get(event.callId) ?? \"\";\n const trust = this.#harness.registry.get(tool)?.outputTrust ?? \"untrusted\";\n const { result } = event;\n const spill = this.#spillOf?.(event.callId);\n this.#queue(\"tool\", {\n type: \"tool_result\",\n callId: event.callId,\n tool,\n content: [...result.content],\n isError: result.isError === true,\n ...(result.details === undefined ? {} : { details: result.details }),\n ...(spill === undefined ? {} : { spill }),\n trust,\n });\n this.#skillLoaded(tool, event);\n }\n\n /** A `read` that opened a listed skill's `SKILL.md` and succeeded put the skill's instructions in the context. */\n #skillLoaded(tool: string, event: Extract<AgentEvent, { type: \"tool_call_end\" }>): void {\n const skills = this.#harness.skills;\n if (skills === undefined || tool !== \"read\" || event.result.isError === true) return;\n const input = event.input ?? this.#inputs.get(event.callId);\n const skill = skillOfRead(skills, this.#harness.env.cwd, input);\n if (skill !== undefined) this.#queue(\"harness\", { type: \"skill_loaded\", name: skill.name, path: skill.path });\n }\n}\n\n/** What the layers that write inside a run are given: the turn's writer, and a way to wait for the run's entries. */\nfunction attachment(writer: EntryWriter, recorder: EventRecorder) {\n return {\n append: (origin: Origin, body: Body) => writer.write(origin, body),\n settle: async () => {\n recorder.flush();\n await writer.settled();\n },\n };\n}\n\n/** The turn's context layers, when the harness has a policy. */\nfunction contextFor<H>(\n harness: Harness<H>,\n session: Session,\n model: Model,\n options: { readonly onContextFill?: (fill: ContextFill) => void; readonly history?: readonly Message[] },\n retry = false,\n): TurnContext | undefined {\n return harness.context?.forTurn({\n session,\n model,\n ownHistory: options.history !== undefined,\n ...(retry ? { midTurn: false } : {}),\n ...(options.onContextFill === undefined ? {} : { onFill: options.onContextFill }),\n });\n}\n\n/** The interceptors of a turn: the harness's, the pipeline's gate, and a guard that refuses a model change inside a turn. */\nfunction interceptorsOf<H>(\n harness: Harness<H>,\n session: Session,\n writer: EntryWriter,\n recorder: EventRecorder,\n hostContext: H | undefined,\n turnModel: Model,\n turnContext: TurnContext | undefined,\n): Interceptors {\n const policySession: PolicySession = { append: (entry) => writer.write(\"harness\", entry) };\n const pipelineGate = harness.pipeline?.gate(async () => {\n // The model's message and the earlier results are queued first, so the gate's entries follow them in the log.\n recorder.flush();\n await writer.settled();\n return { session: policySession, hostContext, entries: await session.path() };\n });\n const gate =\n pipelineGate === undefined ? undefined : withStickyAllowances(pipelineGate, harness, session, writer, recorder);\n // The context policy runs first, so it reads and indexes the run's own transcript, and the harness's hooks see its view.\n const composed = composeInterceptors(turnContext?.interceptors ?? {}, harness.interceptors ?? {}, gate ?? {});\n const inner = composed.beforeModelCall;\n return {\n ...composed,\n async beforeModelCall(event) {\n const patch = await inner?.(event);\n if (\n patch !== undefined &&\n \"model\" in patch &&\n patch.model !== undefined &&\n refKey(patch.model.ref) !== refKey(turnModel.ref)\n ) {\n throw new HarnessError(\n \"invalid_turn_options\",\n \"a hook changed the model inside a turn; set TurnOptions.model for the next turn so it is recorded\",\n );\n }\n return patch;\n },\n };\n}\n\n/**\n * The pipeline's gate with the sticky allowances applied: a call the pipeline would ask about, and that a person's\n * earlier sticky `allow` covers, runs. A deny stays a deny, and the pipeline's own entry for the ask stays in the log\n * beside the entry that records the allowance.\n */\nfunction withStickyAllowances<H>(\n gate: NonNullable<ReturnType<NonNullable<Harness<H>[\"pipeline\"]>[\"gate\"]>>,\n harness: Harness<H>,\n session: Session,\n writer: EntryWriter,\n recorder: EventRecorder,\n): Pick<Interceptors, \"beforeToolCall\"> {\n return {\n async beforeToolCall(event) {\n // The pipeline's gate always has a `beforeToolCall`; a gate without one has nothing to ask.\n const decision = (await gate.beforeToolCall?.(event)) ?? { decision: \"allow\" as const };\n if (decision.decision !== \"ask\") return decision;\n recorder.flush();\n await writer.settled();\n const covered = await findSticky(\n await session.path(),\n { tool: event.tool, input: event.input, policyVersion: decision.policyVersion },\n harness.registry,\n );\n if (covered === undefined) return decision;\n const tool = harness.registry.get(event.tool)?.canonicalName ?? event.tool;\n await writer.write(\n \"harness\",\n await stickyDecision({ callId: event.callId, tool, input: event.input }, covered, decision.policyVersion),\n );\n return { decision: \"allow\", reason: \"a sticky allowance a person gave earlier covers this call\" };\n },\n };\n}\n\n/**\n * The harness's own observers, each held back on an approval request until the entries written so far are durable. An\n * observer that hears of a request can therefore always find its `approval_requested` entry in the log.\n */\nfunction afterWrites(observers: readonly Observer[] | undefined, writer: EntryWriter): Observer[] {\n return (observers ?? []).map(\n (observer): Observer =>\n async (event) => {\n // Only a request needs its entry first, and `settled()` never rejects: a failed write is the writer's to report.\n if (event.type === \"approval_request\") await writer.settled();\n await observer(event);\n },\n );\n}\n\n/** The run options a turn sets only when it has a value, so a missing one leaves the SDK's default. */\ntype RunSettings<H> = Pick<\n TurnOptions<H>,\n | \"clock\"\n | \"newId\"\n | \"hostContext\"\n | \"output\"\n | \"maxSteps\"\n | \"turnRetries\"\n | \"modelOptions\"\n | \"budgetUsd\"\n | \"onContextFill\"\n>;\n\nfunction optionalRunOptions<H>(options: RunSettings<H>, harness: Harness<H>, history: readonly Message[]) {\n return {\n ...(history.length === 0 ? {} : { history }),\n ...(options.clock === undefined ? {} : { clock: options.clock }),\n ...(options.newId === undefined ? {} : { idGenerator: options.newId }),\n ...(options.hostContext === undefined ? {} : { app: options.hostContext }),\n ...(options.output === undefined ? {} : { output: options.output }),\n ...(options.maxSteps === undefined ? {} : { maxSteps: options.maxSteps }),\n ...(options.turnRetries === undefined ? {} : { turnRetries: options.turnRetries }),\n ...(options.modelOptions === undefined ? {} : { modelOptions: options.modelOptions }),\n ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }),\n ...(harness.signer === undefined ? {} : { signer: harness.signer }),\n };\n}\n\n/** Waits for the run and for every queued write, and returns the result with where the log ends. */\nasync function settleTurn(handle: Run<unknown>, writer: EntryWriter, session: Session): Promise<TurnResult> {\n let result: RunResult<unknown> | undefined;\n let runError: unknown;\n try {\n result = (await handle.result) as RunResult<unknown>;\n } catch (error) {\n runError = error;\n }\n await writer.settled();\n // A store failure is the cause of an aborted run, so it comes before the run's own error.\n const failed = writer.failure();\n if (failed !== undefined) throw failed.error;\n if (result === undefined) throw runError;\n return { ...result, sessionKey: session.key.sessionId, lastEntryId: session.head() as string };\n}\n\n/** What every turn and every resume needs: a writer whose failure aborts the run, the run's signal and its id source. */\nfunction turnPlumbing(session: Session, options: { signal?: AbortSignal; clock?: Clock; newId?: () => string }) {\n const stop = new AbortController();\n const signal = options.signal === undefined ? stop.signal : AbortSignal.any([options.signal, stop.signal]);\n const newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n const writer = new EntryWriter(\n session,\n newId,\n options.clock === undefined ? () => new Date() : () => new Date((options.clock as Clock).now()),\n () => stop.abort(),\n );\n return { signal, newId, writer };\n}\n\n/**\n * Runs one turn on a session and writes it to the log. The session must be open with a lock. The first turn of a new\n * session writes its header and `env_stamp`; a turn whose model or tools differ from the last recorded ones writes a\n * `loadout` first; the input blocks follow, and the run's events after them. The returned result is the SDK's, with the\n * session id and the id of the last entry the turn wrote. When the harness has a context policy and the run ends because\n * the provider said the request was too large, the policy compacts once and the turn goes on from the rebuilt context;\n * a second overflow ends the turn with that error.\n */\nexport async function runTurn<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const settings = options.completion;\n // The start state is taken before the turn writes anything, and with the turn's own signal, so an abort stops it.\n // It is taken for every turn, because whether the turn ends `done` is known only after the model has run.\n const start =\n settings === undefined ? undefined : await snapshotStart(settings, options.signal ?? new AbortController().signal);\n const result = await retryAfterOverflow(session, harness, options, await runTurnOnce(session, harness, options));\n if (settings === undefined || result.stopReason !== \"done\") return result;\n return recordCompletion(session, settings, start, options, result);\n}\n\n/**\n * Runs the completion check after a `done` turn and writes its entry. The result's stop reason is left as it is, and a\n * check that throws (a sandbox error, a disposed sandbox) is recorded as a failed entry instead of losing the result.\n */\nasync function recordCompletion<H>(\n session: Session,\n settings: CompletionSettings,\n start: CompletionStart | undefined,\n options: TurnOptions<H>,\n result: TurnResult,\n): Promise<TurnResult> {\n const signal = options.signal ?? new AbortController().signal;\n let outcome: CompletionOutcome;\n try {\n outcome = await runCompletionCheck(settings, start, signal);\n } catch (error) {\n outcome = { checks: [], passed: false, flagged: [...(start?.failures ?? []), completionFailure(error)] };\n }\n const { writer } = turnPlumbing(session, options);\n let entry: SessionEntry;\n try {\n entry = await writer.write(\"harness\", { type: \"completion_check\", ...outcome });\n } catch {\n // A failed append (a lost lock, a store conflict) must not turn a `done` turn into a rejection: the turn's own\n // entries are written, and the result stands without the check's entry.\n return result;\n }\n options.onCompletionCheck?.(entry);\n return { ...result, lastEntryId: entry.id };\n}\n\nasync function runTurnOnce<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const model = options.model ?? harness.model;\n const system = options.system ?? harness.system;\n const tools = toolsOf(harness, options);\n const { signal, newId, writer } = turnPlumbing(session, options);\n // What a crash left open is settled first, so the log reads as a whole and the context has no call without a result.\n let path = await session.path();\n const wrote = await settleOpenCalls(\n path,\n harness,\n (origin, body) => writer.write(origin, body as Body),\n !session.headMoved(),\n );\n if (wrote) path = await session.path();\n await recordLoadout(harness, writer, model, tools, path);\n const turnContext = contextFor(harness, session, model, options);\n const waiting = options.history === undefined ? unansweredCalls(path, true) : [];\n if (waiting.length > 0) {\n throw new HarnessError(\n \"invalid_turn_options\",\n `the session waits on tool calls with no result (${waiting.map((call) => call.callId).join(\", \")}); resolve them before another turn, or pass history`,\n );\n }\n // Between turns, before the input is written, the summary layer may replace an outgrown span with a summary. It\n // runs only once no call waits for a result, so a paused turn's own message is never in the span.\n if (\n options.history === undefined &&\n (await turnContext?.compact({ path, signal, append: (origin, body) => writer.write(origin, body) }))\n ) {\n path = await session.path();\n }\n const history = options.history ?? contextOf(path).messages;\n await writeInput(writer, options, newId);\n const recorder = new EventRecorder(writer, harness as Harness<unknown>, system, newId, \"run\", turnContext?.spillOf);\n turnContext?.attach(attachment(writer, recorder));\n const observer: Observer = (event) => recorder.handle(event);\n const handle = run({\n model,\n system,\n input: options.input,\n tools,\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [observer, ...afterWrites(harness.observers, writer), ...afterWrites(options.observers, writer)],\n ...optionalRunOptions(options, harness, history),\n });\n options.onRun?.(handle);\n return settleTurn(handle, writer, session);\n}\n\n/**\n * Re-runs from an entry: HEAD moves to `entryId` with a `checkout` entry, and a new turn follows it as a new branch of\n * the same log. The entries of the branch it left stay as they were. The entry must not leave a tool call without its\n * result, because that call never ran on the new branch.\n */\nexport async function rerunFrom<H = unknown>(\n session: Session,\n harness: Harness<H>,\n entryId: string,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const waiting = unansweredCalls(await session.path(entryId), true).map((call) => call.callId);\n if (waiting.length > 0) {\n throw new HarnessError(\n \"invalid_turn_options\",\n `entry ${entryId} follows tool calls with no result (${waiting.join(\", \")}), so a re-run from it would send calls that never ran`,\n );\n }\n await session.checkout(entryId);\n return runTurn(session, harness, options);\n}\n\n/** One `approval_resolved` entry as written: the answer, and what it covers beyond its own call. */\nexport interface ResolutionRecord {\n readonly resolution: Resolution;\n readonly sticky?: \"run\" | \"session\";\n readonly allowance?: { tool: string; inputHash?: string; commandPrefix?: string[]; policyVersion?: string };\n readonly groupId?: string;\n readonly quorum?: \"pending\";\n}\n\n/** What resuming a paused turn takes: the answers, and the same per-turn settings a turn has. */\nexport interface ResumeOptions<H = unknown> extends RunSettings<H> {\n /** The answers the SDK checks and applies: one per request whose answer is settled. */\n readonly resolutions: readonly Resolution[];\n /**\n * The `approval_resolved` entries to write before the run, with what each covers. Left out, each resolution is\n * written as it is. A request a quorum still waits on has a record here and no resolution.\n */\n readonly records?: readonly ResolutionRecord[];\n /**\n * The caller's app data. A request bound to app data when it paused runs only when the resume passes the same value,\n * so this is the caller's identity. The tools are the paused turn's, from the log. The model is the harness's, or\n * `model`, and one that differs from the paused turn's is recorded as a `loadout`. Pass the turn's `maxSteps`,\n * `output`, `turnRetries` and `modelOptions` again, because the log does not hold them.\n */\n readonly hostContext?: H;\n /** The model the resumed turn runs on, in place of the harness's. */\n readonly model?: Model;\n /** Aborts the resumed turn. */\n readonly signal?: AbortSignal;\n /** Called with the resumed run as soon as it starts, so a caller can `steer()`, `followUp()` or abort it. */\n readonly onRun?: (run: Run<unknown>) => void;\n /** Observers for this resume alone, as `TurnOptions.observers`. */\n readonly observers?: readonly Observer[];\n /** Runs the calls of `client_request` tools, as `TurnOptions.clientTool`. */\n readonly clientTool?: ClientToolRunner;\n}\n\n/** The resume's policy check: the pipeline decides the call again, so a deny written after the pause wins. */\nfunction recheckThrough<H>(\n session: Session,\n harness: Harness<H>,\n writer: EntryWriter,\n recorder: EventRecorder,\n hostContext: H | undefined,\n): Recheck {\n return async (pending, input) => {\n // The earlier results and decisions are queued first, so the pipeline reads a log that holds them.\n recorder.flush();\n await writer.settled();\n const decision = await harness.pipeline?.decide(\n { callId: pending.callId, tool: pending.tool, input, initiator: \"model\" },\n { session: { append: (entry) => writer.write(\"harness\", entry) }, hostContext, entries: await session.path() },\n );\n // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.\n return decision?.decision === \"deny\" ? { deny: decision.reason } : \"allow\";\n };\n}\n\n/**\n * Resumes a paused turn from the log alone. The context, with its waiting requests, is rebuilt before anything is\n * written; each resolution is then written as an `approval_resolved` entry, and `continueRun()` verifies the requests\n * against the harness's signer. Each approved call goes through the permission pipeline again first, and a deny now\n * turns the approval into a denial.\n */\nexport async function resumeTurn<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: ResumeOptions<H>,\n): Promise<TurnResult> {\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no approval can be checked\");\n }\n const { signal, newId, writer } = turnPlumbing(session, options);\n const path = await session.path();\n const context = contextOf(path);\n const waiting = new Set((context.pending ?? []).map((request) => request.id));\n const answered = new Set<string>();\n for (const resolution of options.resolutions) {\n if (answered.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `request ${resolution.requestId} is answered twice in one resume`);\n }\n answered.add(resolution.requestId);\n if (!waiting.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `no request ${resolution.requestId} is waiting in this session`);\n }\n }\n // The paused turn's tools: the latest `loadout` names them, and one the registry has lost stops the resume.\n const names = path.findLast((entry) => entry.type === \"loadout\");\n const tools = toolsOf(harness, {\n ...(names?.type === \"loadout\" ? { tools: names.tools } : {}),\n ...(options.hostContext === undefined ? {} : { hostContext: options.hostContext }),\n ...(options.clientTool === undefined ? {} : { clientTool: options.clientTool }),\n });\n const records = options.records ?? options.resolutions.map((resolution) => ({ resolution }));\n for (const record of records) await writer.write(\"user\", { type: \"approval_resolved\", ...record });\n const model = options.model ?? harness.model;\n await recordLoadout(harness, writer, model, tools, path);\n const turnContext = contextFor(harness, session, model, options);\n const recorder = new EventRecorder(\n writer,\n harness as Harness<unknown>,\n context.system,\n newId,\n \"continue\",\n turnContext?.spillOf,\n );\n turnContext?.attach(attachment(writer, recorder));\n const handle = continueRun(context, {\n model,\n tools,\n resolutions: [...options.resolutions],\n recheck: recheckThrough(session, harness, writer, recorder, options.hostContext),\n signer: harness.signer,\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [\n (event: AgentEvent) => recorder.handle(event),\n ...afterWrites(harness.observers, writer),\n ...afterWrites(options.observers, writer),\n ],\n ...optionalRunOptions(options, harness, []),\n });\n options.onRun?.(handle);\n return settleTurn(handle, writer, session);\n}\n\n/**\n * Layer 5: after a run that ended because the request was too large, asks the context policy to compact once and\n * goes on from the rebuilt context with `continueRun()`, which asks the model again because the gateway leaves the\n * failed response out of the request. Only one retry is made, so a second overflow is the turn's result.\n */\nasync function retryAfterOverflow<H>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n first: TurnResult,\n): Promise<TurnResult> {\n if (first.stopReason !== \"error\" || first.error.kind !== \"overflow\" || options.history !== undefined) return first;\n const model = options.model ?? harness.model;\n const turnContext = contextFor(harness, session, model, options, true);\n if (turnContext === undefined) return first;\n // The retry has what the first attempt left of `maxSteps`; with none left there is nothing to retry into.\n const stepsLeft = options.maxSteps === undefined ? undefined : options.maxSteps - first.steps;\n if (stepsLeft !== undefined && stepsLeft < 1) return first;\n const { signal, newId, writer } = turnPlumbing(session, options);\n // The first run has ended: a steer sent now waits for the retry's run.\n options.onOverflowRetry?.();\n let compacted: boolean;\n try {\n compacted = await turnContext.onOverflow({\n path: await session.path(),\n signal,\n append: (origin, body) => writer.write(origin, body),\n });\n } catch (error) {\n // An abort during the summary call ends the turn as aborted, not as the overflow it was trying to cure.\n if (signal.aborted) return { ...withoutError(first), stopReason: \"aborted\", lastEntryId: session.head() as string };\n throw error;\n }\n await writer.settled();\n // A summary call that was made and rejected wrote its usage entry, so the log ends later than the first result says.\n if (!compacted) return { ...first, lastEntryId: session.head() as string };\n const context = contextOf(await session.path());\n const recorder = new EventRecorder(\n writer,\n harness as Harness<unknown>,\n context.system,\n newId,\n \"continue\",\n turnContext.spillOf,\n );\n turnContext.attach(attachment(writer, recorder));\n const handle = continueRun(context, {\n model,\n tools: toolsOf(harness, options),\n resolutions: [],\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [\n (event: AgentEvent) => recorder.handle(event),\n ...afterWrites(harness.observers, writer),\n ...afterWrites(options.observers, writer),\n ],\n ...optionalRunOptions(stepsLeft === undefined ? options : { ...options, maxSteps: stepsLeft }, harness, []),\n });\n options.onRun?.(handle);\n const retried = await settleTurn(handle, writer, session);\n // The turn's result counts both attempts: what the first one spent and the steps it took.\n return {\n ...retried,\n steps: first.steps + retried.steps,\n usage: addUsage(first.usage, retried.usage),\n cost: addCost(first.cost, retried.cost),\n };\n}\n\n/** A result without its `error`, for a turn that was cut short before the error mattered. */\nfunction withoutError(result: TurnResult): TurnResult {\n const { error: _error, ...rest } = result as TurnResult & { error?: unknown };\n return rest as TurnResult;\n}\n"]}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The scheduler seam: a promise to call back for a session at a time. A host that cannot keep a timer alive between
3
+ * requests backs it with its own alarm, such as a Durable Object alarm, a delayed queue message or a workflow sleep.
4
+ * `processScheduler()` backs the seam with a timer, for a host that stays up. The seam carries a lock's renewals and any wake a
5
+ * run asks for, such as an approval deadline.
6
+ */
7
+ /**
8
+ * Promises a wake at a time. A wake is **at-least-once**: it can arrive more than once, and a caller must treat a second
9
+ * wake as harmless. It never arrives before `at`.
10
+ */
11
+ export interface Scheduler {
12
+ /**
13
+ * Asks for one wake of `sessionId` at `at`. A time in the past wakes at once. Asking twice for the same id and time is
14
+ * one wake. The id is only a key to the scheduler. A caller that wakes a session for a second purpose prefixes the id,
15
+ * as `fileLock()` does for its renewals, so the two ids never cancel each other.
16
+ */
17
+ wake(at: Date, sessionId: string): Promise<void>;
18
+ /** Drops every wake still pending for `sessionId`. A wake already delivered is not recalled, and an unknown id is fine. */
19
+ cancel(sessionId: string): Promise<void>;
20
+ }
21
+ /** What receives a wake: the id it was asked for and the time it was asked for. */
22
+ export type WakeHandler = (sessionId: string, at: Date) => void | Promise<void>;
23
+ /** A scheduler that delivers its wakes in this process, to handlers registered with `onWake()`. */
24
+ export interface ProcessScheduler extends Scheduler {
25
+ /** Calls `handler` for every wake as it comes due. The returned function stops it. */
26
+ onWake(handler: WakeHandler): () => void;
27
+ /** This scheduler's clock in milliseconds since the epoch. A caller that asks for a wake reads its time here. */
28
+ now(): number;
29
+ }
30
+ /** The options of `processScheduler()`. A test sets `now`, `setTimer` and `clearTimer` to drive time by hand. */
31
+ export interface ProcessSchedulerOptions {
32
+ /** The clock in milliseconds since the epoch. Default `Date.now`. */
33
+ readonly now?: () => number;
34
+ /** Starts a timer. Default `setTimeout`, unreferenced so a pending wake never keeps a process alive. */
35
+ readonly setTimer?: (callback: () => void, ms: number) => unknown;
36
+ /** Stops a timer `setTimer` started. Default `clearTimeout`. */
37
+ readonly clearTimer?: (timer: unknown) => void;
38
+ /** Receives an error a handler threw or rejected with, so one handler's failure never stops the others. Default ignores it. */
39
+ readonly onError?: (error: unknown, sessionId: string) => void;
40
+ }
41
+ /**
42
+ * A `Scheduler` for a host that stays up: each wake is a timer, and the handlers registered with `onWake()` receive it.
43
+ * Wakes do not survive the process, which is the point of the seam: a host that restarts supplies a scheduler that does.
44
+ * Wake times are wall-clock instants, so a clock that steps backward delays a wake by the same amount. A host that must
45
+ * wake on time despite clock changes supplies its own scheduler.
46
+ */
47
+ export declare function processScheduler(options?: ProcessSchedulerOptions): ProcessScheduler;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The scheduler seam: a promise to call back for a session at a time. A host that cannot keep a timer alive between
3
+ * requests backs it with its own alarm, such as a Durable Object alarm, a delayed queue message or a workflow sleep.
4
+ * `processScheduler()` backs the seam with a timer, for a host that stays up. The seam carries a lock's renewals and any wake a
5
+ * run asks for, such as an approval deadline.
6
+ */
7
+ // A timer's delay is a 32-bit number, so a farther wake sleeps in steps.
8
+ const MAX_DELAY_MS = 2 ** 31 - 1;
9
+ function defaultSetTimer(callback, ms) {
10
+ const timer = setTimeout(callback, ms);
11
+ timer.unref?.();
12
+ return timer;
13
+ }
14
+ /**
15
+ * A `Scheduler` for a host that stays up: each wake is a timer, and the handlers registered with `onWake()` receive it.
16
+ * Wakes do not survive the process, which is the point of the seam: a host that restarts supplies a scheduler that does.
17
+ * Wake times are wall-clock instants, so a clock that steps backward delays a wake by the same amount. A host that must
18
+ * wake on time despite clock changes supplies its own scheduler.
19
+ */
20
+ export function processScheduler(options = {}) {
21
+ const now = options.now ?? Date.now;
22
+ const setTimer = options.setTimer ?? defaultSetTimer;
23
+ const clearTimer = options.clearTimer ?? ((timer) => clearTimeout(timer));
24
+ const handlers = new Set();
25
+ const pending = new Map();
26
+ const key = (id, at) => `${at}:${id}`;
27
+ const deliver = async (id, at) => {
28
+ for (const handler of [...handlers]) {
29
+ try {
30
+ await handler(id, new Date(at));
31
+ }
32
+ catch (error) {
33
+ try {
34
+ options.onError?.(error, id);
35
+ }
36
+ catch {
37
+ // A reporter that throws must not stop the handlers after it.
38
+ }
39
+ }
40
+ }
41
+ };
42
+ const arm = (entry) => {
43
+ const remaining = entry.at - now();
44
+ entry.timer = setTimer(() => {
45
+ // A wake that a cancel already removed must not fire, even when its timer was already due.
46
+ if (pending.get(key(entry.id, entry.at)) !== entry)
47
+ return;
48
+ // A far wake sleeps in steps, and a timer can also fire a millisecond early, so both look at the clock again.
49
+ if (now() < entry.at)
50
+ return arm(entry);
51
+ pending.delete(key(entry.id, entry.at));
52
+ void deliver(entry.id, entry.at);
53
+ }, Math.min(MAX_DELAY_MS, Math.max(0, remaining)));
54
+ };
55
+ return {
56
+ wake(at, sessionId) {
57
+ const time = at.getTime();
58
+ if (Number.isNaN(time))
59
+ return Promise.reject(new TypeError("Scheduler.wake needs a valid date."));
60
+ if (!pending.has(key(sessionId, time))) {
61
+ const entry = { id: sessionId, at: time, timer: undefined };
62
+ pending.set(key(sessionId, time), entry);
63
+ arm(entry);
64
+ }
65
+ return Promise.resolve();
66
+ },
67
+ cancel(sessionId) {
68
+ for (const [name, entry] of pending) {
69
+ if (entry.id !== sessionId)
70
+ continue;
71
+ clearTimer(entry.timer);
72
+ pending.delete(name);
73
+ }
74
+ return Promise.resolve();
75
+ },
76
+ now,
77
+ onWake(handler) {
78
+ handlers.add(handler);
79
+ return () => {
80
+ handlers.delete(handler);
81
+ };
82
+ },
83
+ };
84
+ }
85
+ //# sourceMappingURL=scheduler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduler.js","sourceRoot":"","sources":["../../src/session/scheduler.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAwCH,yEAAyE;AACzE,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AAQjC,SAAS,eAAe,CAAC,QAAoB,EAAE,EAAU;IACvD,MAAM,KAAK,GAAG,UAAU,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IACtC,KAAgC,CAAC,KAAK,EAAE,EAAE,CAAC;IAC5C,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAA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BAAE,SAAS;gBACrC,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACxB,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACvB,CAAC;YACD,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;QAC3B,CAAC;QACD,GAAG;QACH,MAAM,CAAC,OAAO;YACZ,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;YACtB,OAAO,GAAG,EAAE;gBACV,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAC3B,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The scheduler seam: a promise to call back for a session at a time. A host that cannot keep a timer alive between\n * requests backs it with its own alarm, such as a Durable Object alarm, a delayed queue message or a workflow sleep.\n * `processScheduler()` backs the seam with a timer, for a host that stays up. The seam carries a lock's renewals and any wake a\n * run asks for, such as an approval deadline.\n */\n\n/**\n * Promises a wake at a time. A wake is **at-least-once**: it can arrive more than once, and a caller must treat a second\n * wake as harmless. It never arrives before `at`.\n */\nexport interface Scheduler {\n /**\n * Asks for one wake of `sessionId` at `at`. A time in the past wakes at once. Asking twice for the same id and time is\n * one wake. The id is only a key to the scheduler. A caller that wakes a session for a second purpose prefixes the id,\n * as `fileLock()` does for its renewals, so the two ids never cancel each other.\n */\n wake(at: Date, sessionId: string): Promise<void>;\n /** Drops every wake still pending for `sessionId`. A wake already delivered is not recalled, and an unknown id is fine. */\n cancel(sessionId: string): Promise<void>;\n}\n\n/** What receives a wake: the id it was asked for and the time it was asked for. */\nexport type WakeHandler = (sessionId: string, at: Date) => void | Promise<void>;\n\n/** A scheduler that delivers its wakes in this process, to handlers registered with `onWake()`. */\nexport interface ProcessScheduler extends Scheduler {\n /** Calls `handler` for every wake as it comes due. The returned function stops it. */\n onWake(handler: WakeHandler): () => void;\n /** This scheduler's clock in milliseconds since the epoch. A caller that asks for a wake reads its time here. */\n now(): number;\n}\n\n/** The options of `processScheduler()`. A test sets `now`, `setTimer` and `clearTimer` to drive time by hand. */\nexport interface ProcessSchedulerOptions {\n /** The clock in milliseconds since the epoch. Default `Date.now`. */\n readonly now?: () => number;\n /** Starts a timer. Default `setTimeout`, unreferenced so a pending wake never keeps a process alive. */\n readonly setTimer?: (callback: () => void, ms: number) => unknown;\n /** Stops a timer `setTimer` started. Default `clearTimeout`. */\n readonly clearTimer?: (timer: unknown) => void;\n /** Receives an error a handler threw or rejected with, so one handler's failure never stops the others. Default ignores it. */\n readonly onError?: (error: unknown, sessionId: string) => void;\n}\n\n// A timer's delay is a 32-bit number, so a farther wake sleeps in steps.\nconst MAX_DELAY_MS = 2 ** 31 - 1;\n\ninterface Pending {\n readonly id: string;\n readonly at: number;\n timer: unknown;\n}\n\nfunction defaultSetTimer(callback: () => void, ms: number): unknown {\n const timer = setTimeout(callback, ms);\n (timer as { unref?: () => void }).unref?.();\n return timer;\n}\n\n/**\n * A `Scheduler` for a host that stays up: each wake is a timer, and the handlers registered with `onWake()` receive it.\n * Wakes do not survive the process, which is the point of the seam: a host that restarts supplies a scheduler that does.\n * Wake times are wall-clock instants, so a clock that steps backward delays a wake by the same amount. A host that must\n * wake on time despite clock changes supplies its own scheduler.\n */\nexport function processScheduler(options: ProcessSchedulerOptions = {}): ProcessScheduler {\n const now = options.now ?? Date.now;\n const setTimer = options.setTimer ?? defaultSetTimer;\n const clearTimer = options.clearTimer ?? ((timer: unknown) => clearTimeout(timer as ReturnType<typeof setTimeout>));\n const handlers = new Set<WakeHandler>();\n const pending = new Map<string, Pending>();\n\n const key = (id: string, at: number) => `${at}:${id}`;\n\n const deliver = async (id: string, at: number): Promise<void> => {\n for (const handler of [...handlers]) {\n try {\n await handler(id, new Date(at));\n } catch (error) {\n try {\n options.onError?.(error, id);\n } catch {\n // A reporter that throws must not stop the handlers after it.\n }\n }\n }\n };\n\n const arm = (entry: Pending): void => {\n const remaining = entry.at - now();\n entry.timer = setTimer(\n () => {\n // A wake that a cancel already removed must not fire, even when its timer was already due.\n if (pending.get(key(entry.id, entry.at)) !== entry) return;\n // A far wake sleeps in steps, and a timer can also fire a millisecond early, so both look at the clock again.\n if (now() < entry.at) return arm(entry);\n pending.delete(key(entry.id, entry.at));\n void deliver(entry.id, entry.at);\n },\n Math.min(MAX_DELAY_MS, Math.max(0, remaining)),\n );\n };\n\n return {\n wake(at, sessionId) {\n const time = at.getTime();\n if (Number.isNaN(time)) return Promise.reject(new TypeError(\"Scheduler.wake needs a valid date.\"));\n if (!pending.has(key(sessionId, time))) {\n const entry: Pending = { id: sessionId, at: time, timer: undefined };\n pending.set(key(sessionId, time), entry);\n arm(entry);\n }\n return Promise.resolve();\n },\n cancel(sessionId) {\n for (const [name, entry] of pending) {\n if (entry.id !== sessionId) continue;\n clearTimer(entry.timer);\n pending.delete(name);\n }\n return Promise.resolve();\n },\n now,\n onWake(handler) {\n handlers.add(handler);\n return () => {\n handlers.delete(handler);\n };\n },\n };\n}\n"]}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * `secretKeyStore()`: a read-only `KeyStore` over a secret the host can read but not write, such as a Worker secret, a
3
+ * Secrets Manager value or a secret environment variable. The platform's own tooling rotates the secret, so the store
4
+ * has `load()` only (ADR 0035). `rotateKeys()` and `pruneKeys()` call a store's optional methods and, for a read-only
5
+ * store, reject with an error that names the tooling to use instead. This file imports no Node module.
6
+ */
7
+ import { type KeyStore } from "@buildanagent/agent-safety";
8
+ /** The options of `secretKeyStore()`. */
9
+ export interface SecretKeyStoreOptions {
10
+ /**
11
+ * Returns the secret's text: the JSON ring `parseKeyRing()` reads, such as
12
+ * `{"current":"2026-11","keys":{"2026-11":"<key>"}}`. It is called on every `load()`.
13
+ */
14
+ readonly read: () => string | Promise<string>;
15
+ }
16
+ /**
17
+ * A `KeyStore` whose `load()` calls `read()` and parses the text it returns. It reads the secret on every call and
18
+ * keeps no copy, so a ring the platform rotated takes effect at the next `load()`. It has no `rotate()` or `prune()`:
19
+ * rotate with the platform's secret tooling, and keep an old key in the ring until no unresolved pause names it.
20
+ *
21
+ * `load()` throws a `HarnessError`, code `invalid_key_store`, when `read()` fails or returns something that is not a
22
+ * usable ring: not JSON, a key that is not base64url or is shorter than 32 bytes, or a `current` the ring lacks. The
23
+ * error's message is fixed text and it has no cause, so it never holds the secret's text, a key id or a key, nor the
24
+ * error `read()` threw. Check the secret itself to find which rule it breaks.
25
+ */
26
+ export declare function secretKeyStore(options: SecretKeyStoreOptions): KeyStore;
27
+ /** Where a read-only store's error sends the owner when no hint is given. */
28
+ export declare const DEFAULT_PLATFORM_HINT = "your platform's secret tooling, such as wrangler secret put, aws secretsmanager put-secret-value or vercel env";
29
+ /** The options of `rotateKeys()` and `pruneKeys()`. */
30
+ export interface KeyChangeOptions {
31
+ /** The tool a read-only store's error names, such as `wrangler secret put`. Default `DEFAULT_PLATFORM_HINT`. */
32
+ readonly platformHint?: string;
33
+ }
34
+ /**
35
+ * Adds a new current key to `store` and returns its id. Rejects with a `HarnessError`, code `key_store_read_only`, when
36
+ * the store has no `rotate()`, with a message that names the platform tool to rotate with instead. An error the store's
37
+ * `rotate()` throws, even synchronously, becomes a rejection too.
38
+ */
39
+ export declare function rotateKeys(store: KeyStore, options?: KeyChangeOptions): Promise<string>;
40
+ /**
41
+ * Calls `store.prune(inUse)` and returns the ids it removed. Pass every key id that an unresolved pause names, or that
42
+ * pause fails closed. The store removes the keys not in `inUse` and keeps its current key; this helper adds no check of
43
+ * its own, and `keyStoreConformanceCases()` tests a store for both. Rejects with a `HarnessError`, code
44
+ * `key_store_read_only`, when the store has no `prune()`, with a message that names the platform tool to remove keys
45
+ * with instead. An error the store's `prune()` throws, even synchronously, becomes a rejection too.
46
+ */
47
+ export declare function pruneKeys(store: KeyStore, inUse: ReadonlySet<string>, options?: KeyChangeOptions): Promise<string[]>;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * `secretKeyStore()`: a read-only `KeyStore` over a secret the host can read but not write, such as a Worker secret, a
3
+ * Secrets Manager value or a secret environment variable. The platform's own tooling rotates the secret, so the store
4
+ * has `load()` only (ADR 0035). `rotateKeys()` and `pruneKeys()` call a store's optional methods and, for a read-only
5
+ * store, reject with an error that names the tooling to use instead. This file imports no Node module.
6
+ */
7
+ import { hmacSigner, parseKeyRing } from "@buildanagent/agent-safety";
8
+ import { HarnessError } from "../errors.js";
9
+ // No error built here carries a cause: a reader's error can quote the secret, as `JSON.parse` quotes its input, and a
10
+ // SafetyError repeats key ids as the ring spells them, so a ring with a key in an id position would put the key in the
11
+ // message. A fixed message is the only text that cannot hold key material.
12
+ const invalid = (message) => new HarnessError("invalid_key_store", message);
13
+ /**
14
+ * A `KeyStore` whose `load()` calls `read()` and parses the text it returns. It reads the secret on every call and
15
+ * keeps no copy, so a ring the platform rotated takes effect at the next `load()`. It has no `rotate()` or `prune()`:
16
+ * rotate with the platform's secret tooling, and keep an old key in the ring until no unresolved pause names it.
17
+ *
18
+ * `load()` throws a `HarnessError`, code `invalid_key_store`, when `read()` fails or returns something that is not a
19
+ * usable ring: not JSON, a key that is not base64url or is shorter than 32 bytes, or a `current` the ring lacks. The
20
+ * error's message is fixed text and it has no cause, so it never holds the secret's text, a key id or a key, nor the
21
+ * error `read()` threw. Check the secret itself to find which rule it breaks.
22
+ */
23
+ export function secretKeyStore(options) {
24
+ const { read } = options;
25
+ if (typeof read !== "function")
26
+ throw invalid("secretKeyStore() needs a read function that returns the secret");
27
+ return {
28
+ load: async () => {
29
+ let text;
30
+ try {
31
+ text = await read();
32
+ }
33
+ catch {
34
+ throw invalid("the key ring secret could not be read");
35
+ }
36
+ if (typeof text !== "string")
37
+ throw invalid("the key ring secret's reader must return a string");
38
+ try {
39
+ const ring = parseKeyRing(text);
40
+ // The signer checks what the parser leaves out: key lengths, key ids and that `current` is in the ring.
41
+ hmacSigner(ring);
42
+ return ring;
43
+ }
44
+ catch {
45
+ throw invalid("the key ring secret is not a usable key ring: it must be JSON with a current id and unpadded base64url keys " +
46
+ "of 32 or more bytes, and current must be one of the keys");
47
+ }
48
+ },
49
+ };
50
+ }
51
+ /** Where a read-only store's error sends the owner when no hint is given. */
52
+ export const DEFAULT_PLATFORM_HINT = "your platform's secret tooling, such as wrangler secret put, aws secretsmanager put-secret-value or vercel env";
53
+ function readOnly(action, options) {
54
+ const hint = options?.platformHint ?? DEFAULT_PLATFORM_HINT;
55
+ return new HarnessError("key_store_read_only", `this key store is read-only, so the harness cannot ${action}; change the secret with ${hint}`);
56
+ }
57
+ /**
58
+ * Adds a new current key to `store` and returns its id. Rejects with a `HarnessError`, code `key_store_read_only`, when
59
+ * the store has no `rotate()`, with a message that names the platform tool to rotate with instead. An error the store's
60
+ * `rotate()` throws, even synchronously, becomes a rejection too.
61
+ */
62
+ export async function rotateKeys(store, options) {
63
+ if (store.rotate === undefined)
64
+ throw readOnly("rotate keys", options);
65
+ return await store.rotate();
66
+ }
67
+ /**
68
+ * Calls `store.prune(inUse)` and returns the ids it removed. Pass every key id that an unresolved pause names, or that
69
+ * pause fails closed. The store removes the keys not in `inUse` and keeps its current key; this helper adds no check of
70
+ * its own, and `keyStoreConformanceCases()` tests a store for both. Rejects with a `HarnessError`, code
71
+ * `key_store_read_only`, when the store has no `prune()`, with a message that names the platform tool to remove keys
72
+ * with instead. An error the store's `prune()` throws, even synchronously, becomes a rejection too.
73
+ */
74
+ export async function pruneKeys(store, inUse, options) {
75
+ if (store.prune === undefined)
76
+ throw readOnly("prune keys", options);
77
+ return await store.prune(new Set(inUse));
78
+ }
79
+ //# sourceMappingURL=secret-key-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-key-store.js","sourceRoot":"","sources":["../../src/session/secret-key-store.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,UAAU,EAA+B,YAAY,EAAE,MAAM,4BAA4B,CAAC;AACnG,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAW5C,sHAAsH;AACtH,uHAAuH;AACvH,2EAA2E;AAC3E,MAAM,OAAO,GAAG,CAAC,OAAe,EAAE,E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AS;QAAE,MAAM,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;IACvE,OAAO,MAAM,KAAK,CAAC,MAAM,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,KAAe,EACf,KAA0B,EAC1B,OAA0B;IAE1B,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS;QAAE,MAAM,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IACrE,OAAO,MAAM,KAAK,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * `secretKeyStore()`: a read-only `KeyStore` over a secret the host can read but not write, such as a Worker secret, a\n * Secrets Manager value or a secret environment variable. The platform's own tooling rotates the secret, so the store\n * has `load()` only (ADR 0035). `rotateKeys()` and `pruneKeys()` call a store's optional methods and, for a read-only\n * store, reject with an error that names the tooling to use instead. This file imports no Node module.\n */\nimport { hmacSigner, type KeyRing, type KeyStore, parseKeyRing } from \"@buildanagent/agent-safety\";\nimport { HarnessError } from \"../errors.js\";\n\n/** The options of `secretKeyStore()`. */\nexport interface SecretKeyStoreOptions {\n /**\n * Returns the secret's text: the JSON ring `parseKeyRing()` reads, such as\n * `{\"current\":\"2026-11\",\"keys\":{\"2026-11\":\"<key>\"}}`. It is called on every `load()`.\n */\n readonly read: () => string | Promise<string>;\n}\n\n// No error built here carries a cause: a reader's error can quote the secret, as `JSON.parse` quotes its input, and a\n// SafetyError repeats key ids as the ring spells them, so a ring with a key in an id position would put the key in the\n// message. A fixed message is the only text that cannot hold key material.\nconst invalid = (message: string) => new HarnessError(\"invalid_key_store\", message);\n\n/**\n * A `KeyStore` whose `load()` calls `read()` and parses the text it returns. It reads the secret on every call and\n * keeps no copy, so a ring the platform rotated takes effect at the next `load()`. It has no `rotate()` or `prune()`:\n * rotate with the platform's secret tooling, and keep an old key in the ring until no unresolved pause names it.\n *\n * `load()` throws a `HarnessError`, code `invalid_key_store`, when `read()` fails or returns something that is not a\n * usable ring: not JSON, a key that is not base64url or is shorter than 32 bytes, or a `current` the ring lacks. The\n * error's message is fixed text and it has no cause, so it never holds the secret's text, a key id or a key, nor the\n * error `read()` threw. Check the secret itself to find which rule it breaks.\n */\nexport function secretKeyStore(options: SecretKeyStoreOptions): KeyStore {\n const { read } = options;\n if (typeof read !== \"function\") throw invalid(\"secretKeyStore() needs a read function that returns the secret\");\n return {\n load: async (): Promise<KeyRing> => {\n let text: unknown;\n try {\n text = await read();\n } catch {\n throw invalid(\"the key ring secret could not be read\");\n }\n if (typeof text !== \"string\") throw invalid(\"the key ring secret's reader must return a string\");\n try {\n const ring = parseKeyRing(text);\n // The signer checks what the parser leaves out: key lengths, key ids and that `current` is in the ring.\n hmacSigner(ring);\n return ring;\n } catch {\n throw invalid(\n \"the key ring secret is not a usable key ring: it must be JSON with a current id and unpadded base64url keys \" +\n \"of 32 or more bytes, and current must be one of the keys\",\n );\n }\n },\n };\n}\n\n/** Where a read-only store's error sends the owner when no hint is given. */\nexport const DEFAULT_PLATFORM_HINT =\n \"your platform's secret tooling, such as wrangler secret put, aws secretsmanager put-secret-value or vercel env\";\n\n/** The options of `rotateKeys()` and `pruneKeys()`. */\nexport interface KeyChangeOptions {\n /** The tool a read-only store's error names, such as `wrangler secret put`. Default `DEFAULT_PLATFORM_HINT`. */\n readonly platformHint?: string;\n}\n\nfunction readOnly(action: string, options: KeyChangeOptions | undefined): HarnessError {\n const hint = options?.platformHint ?? DEFAULT_PLATFORM_HINT;\n return new HarnessError(\n \"key_store_read_only\",\n `this key store is read-only, so the harness cannot ${action}; change the secret with ${hint}`,\n );\n}\n\n/**\n * Adds a new current key to `store` and returns its id. Rejects with a `HarnessError`, code `key_store_read_only`, when\n * the store has no `rotate()`, with a message that names the platform tool to rotate with instead. An error the store's\n * `rotate()` throws, even synchronously, becomes a rejection too.\n */\nexport async function rotateKeys(store: KeyStore, options?: KeyChangeOptions): Promise<string> {\n if (store.rotate === undefined) throw readOnly(\"rotate keys\", options);\n return await store.rotate();\n}\n\n/**\n * Calls `store.prune(inUse)` and returns the ids it removed. Pass every key id that an unresolved pause names, or that\n * pause fails closed. The store removes the keys not in `inUse` and keeps its current key; this helper adds no check of\n * its own, and `keyStoreConformanceCases()` tests a store for both. Rejects with a `HarnessError`, code\n * `key_store_read_only`, when the store has no `prune()`, with a message that names the platform tool to remove keys\n * with instead. An error the store's `prune()` throws, even synchronously, becomes a rejection too.\n */\nexport async function pruneKeys(\n store: KeyStore,\n inUse: ReadonlySet<string>,\n options?: KeyChangeOptions,\n): Promise<string[]> {\n if (store.prune === undefined) throw readOnly(\"prune keys\", options);\n return await store.prune(new Set(inUse));\n}\n"]}
@@ -0,0 +1,106 @@
1
+ /**
2
+ * `Session`: one session's log with its HEAD, and the operations that branch it. The log is an append-only tree of
3
+ * entries. HEAD is the entry the next append follows. A checkout, a fork and a revert write new entries or new files and
4
+ * never rewrite one, so the only mutable state is the pointer to the session's current file (`SessionIndex`).
5
+ */
6
+ import type { SessionEntry } from "@buildanagent/protocol";
7
+ import type { Context } from "@buildanagent/sdk";
8
+ import type { SessionLock } from "./lock.js";
9
+ import type { SessionIndex } from "./pointer.js";
10
+ import type { EntryInput, SessionKey, SessionStore, SessionSummary } from "./store.js";
11
+ /** The options of `openSession()`. */
12
+ export interface OpenSessionOptions {
13
+ readonly store: SessionStore;
14
+ readonly index: SessionIndex;
15
+ readonly key: SessionKey;
16
+ /** With a lock, the session takes it and may write. Without one, the session is read-only: readers never lock. */
17
+ readonly lock?: SessionLock;
18
+ /** The clock for the entries a session writes itself. Default `new Date()`. */
19
+ readonly now?: () => Date;
20
+ /** Makes the ids of the entries and files a session writes itself. Default `crypto.randomUUID()`. */
21
+ readonly newId?: () => string;
22
+ }
23
+ /** What links a child session to the session that started it: a tool call, or a workflow step. Give exactly one. */
24
+ export type ChildLink = {
25
+ readonly spawningCallId: string;
26
+ } | {
27
+ readonly stepId: string;
28
+ };
29
+ /**
30
+ * The prefix of the name of a file that holds part of a session, such as a revert's or a migration's file. A listing
31
+ * leaves such files out, because a person knows a session by its key.
32
+ */
33
+ export declare const DERIVED = "~";
34
+ /** Whether a file id names a derived file. */
35
+ export declare const isDerivedFile: (file: string) => boolean;
36
+ /** One session. Open it with `openSession()`. */
37
+ export declare class Session {
38
+ #private;
39
+ readonly key: SessionKey;
40
+ private constructor();
41
+ /** Reads the session's current file, and takes the writer lock when the options have a lock. */
42
+ static open(options: OpenSessionOptions): Promise<Session>;
43
+ /** The id of the entry the next append follows, or `null` for a session with no entries yet. */
44
+ head(): string | null;
45
+ /** The id of the file the session's log is in now. A revert or a migration changes it. */
46
+ file(): string;
47
+ /** Whether this session may write: it was opened with a lock, and still holds it. */
48
+ writable(): boolean;
49
+ /**
50
+ * Appends entries to the session's current file and moves HEAD. The caller sets each entry's `parentId`, normally
51
+ * `head()` for the first and the entry before it for the rest. The append is guarded by the end of the log this session
52
+ * has seen, so a writer that lost the lock can't extend it.
53
+ */
54
+ append(entries: readonly EntryInput[]): Promise<SessionEntry[]>;
55
+ /**
56
+ * The entries from the root to `headId` (default HEAD), following `parentId` and crossing into a parent file when a
57
+ * fork's entry follows one in it. A fork's own header is left out, and so are the `checkout` entries, which move HEAD
58
+ * and are not part of the conversation.
59
+ */
60
+ path(headId?: string | null): Promise<SessionEntry[]>;
61
+ /** Whether the log's last entry is a `checkout`, so HEAD was moved and the path's end is not where the log ends. */
62
+ headMoved(): boolean;
63
+ /**
64
+ * The name of the branch HEAD is on: the file the log is in, and, after a checkout, that checkout's id, so a re-run
65
+ * that replays a call id gets a branch of its own.
66
+ */
67
+ branch(): string;
68
+ /**
69
+ * The SDK context the entries from the root to `headId` (default HEAD) stand for: the messages in order, and the
70
+ * system prompt of the latest turn, which is the one the model saw. Pass it to `continueRun()`, in any process,
71
+ * after a JSON round trip. A call the log shows without a result is left open, so `runTurn()` settles it first.
72
+ */
73
+ toContext(headId?: string | null): Promise<Context>;
74
+ /**
75
+ * The entries from the root to `headId` (default HEAD), in order, as a stored session shows them. It reads the log
76
+ * and nothing else: no model, tool or hook runs, so a playback is the same on every machine.
77
+ */
78
+ playback(headId?: string | null): AsyncGenerator<SessionEntry>;
79
+ /** Moves HEAD to `entryId` by appending a `checkout` entry, so a reload finds HEAD where it was left. */
80
+ checkout(entryId: string): Promise<void>;
81
+ /**
82
+ * Starts a new session from `entryId`: a new file whose header names this session's file and that entry as its parent,
83
+ * so the fork's `path()` includes everything up to the entry without copying it. This session is unchanged. The
84
+ * returned session is opened with the same options under a new id.
85
+ */
86
+ fork(entryId: string): Promise<Session>;
87
+ /**
88
+ * Goes back to `entryId` in a new file and points the session at it. The new file's header names the old file as its
89
+ * parent, so nothing before the entry is lost, and the old file is not touched. A crash before the pointer moves
90
+ * leaves the old file in use. Returns this session, now on the new file.
91
+ */
92
+ revert(entryId: string): Promise<Session>;
93
+ /**
94
+ * Starts the log of a subagent or a workflow step, and records the link in this session with a `subagent_link` entry
95
+ * that carries `spawningCallId` or `stepId`, whichever was given, and never both. If the link can't be written, for
96
+ * example because the lock was lost, the child's file stays in the store as a session no one links to, which retention
97
+ * removes; the same holds for a fork that can't be opened.
98
+ */
99
+ child(link: ChildLink): Promise<Session>;
100
+ /** Gives up the writer lock, if the session holds one. */
101
+ close(): Promise<void>;
102
+ }
103
+ /** Opens a session. With a `lock` it is the session's one writer, and without one it can only read. */
104
+ export declare function openSession(options: OpenSessionOptions): Promise<Session>;
105
+ /** The user's sessions, oldest first, without the files that only hold part of a session (a revert's or a migration's). */
106
+ export declare function listSessions(store: SessionStore, userId: string): AsyncGenerator<SessionSummary>;