@buildanagent/harness 0.0.0-bootstrap.0 → 0.1.0-alpha.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +717 -0
  5. package/dist/ablation.d.ts +2 -0
  6. package/dist/ablation.js +3 -0
  7. package/dist/ablation.js.map +1 -0
  8. package/dist/completion/check.d.ts +64 -0
  9. package/dist/completion/check.js +152 -0
  10. package/dist/completion/check.js.map +1 -0
  11. package/dist/completion/checks.d.ts +45 -0
  12. package/dist/completion/checks.js +173 -0
  13. package/dist/completion/checks.js.map +1 -0
  14. package/dist/completion/flags.d.ts +25 -0
  15. package/dist/completion/flags.js +87 -0
  16. package/dist/completion/flags.js.map +1 -0
  17. package/dist/completion/index.d.ts +8 -0
  18. package/dist/completion/index.js +9 -0
  19. package/dist/completion/index.js.map +1 -0
  20. package/dist/completion/snapshot.d.ts +33 -0
  21. package/dist/completion/snapshot.js +83 -0
  22. package/dist/completion/snapshot.js.map +1 -0
  23. package/dist/context/cap.d.ts +32 -0
  24. package/dist/context/cap.js +50 -0
  25. package/dist/context/cap.js.map +1 -0
  26. package/dist/context/estimate.d.ts +18 -0
  27. package/dist/context/estimate.js +20 -0
  28. package/dist/context/estimate.js.map +1 -0
  29. package/dist/context/file-spill.d.ts +5 -0
  30. package/dist/context/file-spill.js +25 -0
  31. package/dist/context/file-spill.js.map +1 -0
  32. package/dist/context/index.d.ts +10 -0
  33. package/dist/context/index.js +10 -0
  34. package/dist/context/index.js.map +1 -0
  35. package/dist/context/mask.d.ts +27 -0
  36. package/dist/context/mask.js +71 -0
  37. package/dist/context/mask.js.map +1 -0
  38. package/dist/context/mid-turn.d.ts +40 -0
  39. package/dist/context/mid-turn.js +82 -0
  40. package/dist/context/mid-turn.js.map +1 -0
  41. package/dist/context/policy.d.ts +9 -0
  42. package/dist/context/policy.js +140 -0
  43. package/dist/context/policy.js.map +1 -0
  44. package/dist/context/spill-ledger.d.ts +25 -0
  45. package/dist/context/spill-ledger.js +54 -0
  46. package/dist/context/spill-ledger.js.map +1 -0
  47. package/dist/context/spill.d.ts +6 -0
  48. package/dist/context/spill.js +14 -0
  49. package/dist/context/spill.js.map +1 -0
  50. package/dist/context/summarize.d.ts +53 -0
  51. package/dist/context/summarize.js +204 -0
  52. package/dist/context/summarize.js.map +1 -0
  53. package/dist/context/summary-template.d.ts +29 -0
  54. package/dist/context/summary-template.js +69 -0
  55. package/dist/context/summary-template.js.map +1 -0
  56. package/dist/context/types.d.ts +150 -0
  57. package/dist/context/types.js +2 -0
  58. package/dist/context/types.js.map +1 -0
  59. package/dist/context/write-cap.d.ts +19 -0
  60. package/dist/context/write-cap.js +41 -0
  61. package/dist/context/write-cap.js.map +1 -0
  62. package/dist/create-harness.d.ts +7 -0
  63. package/dist/create-harness.js +21 -0
  64. package/dist/create-harness.js.map +1 -0
  65. package/dist/credentials/addresses.d.ts +14 -0
  66. package/dist/credentials/addresses.js +144 -0
  67. package/dist/credentials/addresses.js.map +1 -0
  68. package/dist/credentials/allowlist.d.ts +34 -0
  69. package/dist/credentials/allowlist.js +77 -0
  70. package/dist/credentials/allowlist.js.map +1 -0
  71. package/dist/credentials/egress-proxy.d.ts +70 -0
  72. package/dist/credentials/egress-proxy.js +482 -0
  73. package/dist/credentials/egress-proxy.js.map +1 -0
  74. package/dist/credentials/index.d.ts +9 -0
  75. package/dist/credentials/index.js +10 -0
  76. package/dist/credentials/index.js.map +1 -0
  77. package/dist/credentials/scrub.d.ts +16 -0
  78. package/dist/credentials/scrub.js +93 -0
  79. package/dist/credentials/scrub.js.map +1 -0
  80. package/dist/errors.d.ts +56 -0
  81. package/dist/errors.js +63 -0
  82. package/dist/errors.js.map +1 -0
  83. package/dist/extensions/compose.d.ts +27 -0
  84. package/dist/extensions/compose.js +83 -0
  85. package/dist/extensions/compose.js.map +1 -0
  86. package/dist/extensions/context-files-node.d.ts +28 -0
  87. package/dist/extensions/context-files-node.js +74 -0
  88. package/dist/extensions/context-files-node.js.map +1 -0
  89. package/dist/extensions/context-files.d.ts +68 -0
  90. package/dist/extensions/context-files.js +214 -0
  91. package/dist/extensions/context-files.js.map +1 -0
  92. package/dist/extensions/digest.d.ts +6 -0
  93. package/dist/extensions/digest.js +68 -0
  94. package/dist/extensions/digest.js.map +1 -0
  95. package/dist/extensions/index.d.ts +10 -0
  96. package/dist/extensions/index.js +10 -0
  97. package/dist/extensions/index.js.map +1 -0
  98. package/dist/extensions/load.d.ts +42 -0
  99. package/dist/extensions/load.js +211 -0
  100. package/dist/extensions/load.js.map +1 -0
  101. package/dist/extensions/lock.d.ts +8 -0
  102. package/dist/extensions/lock.js +95 -0
  103. package/dist/extensions/lock.js.map +1 -0
  104. package/dist/extensions/node.d.ts +10 -0
  105. package/dist/extensions/node.js +11 -0
  106. package/dist/extensions/node.js.map +1 -0
  107. package/dist/extensions/project-dirs.d.ts +24 -0
  108. package/dist/extensions/project-dirs.js +97 -0
  109. package/dist/extensions/project-dirs.js.map +1 -0
  110. package/dist/extensions/skills-node.d.ts +34 -0
  111. package/dist/extensions/skills-node.js +123 -0
  112. package/dist/extensions/skills-node.js.map +1 -0
  113. package/dist/extensions/skills.d.ts +51 -0
  114. package/dist/extensions/skills.js +175 -0
  115. package/dist/extensions/skills.js.map +1 -0
  116. package/dist/extensions/trust-file.d.ts +3 -0
  117. package/dist/extensions/trust-file.js +62 -0
  118. package/dist/extensions/trust-file.js.map +1 -0
  119. package/dist/extensions/trust-store-node.d.ts +10 -0
  120. package/dist/extensions/trust-store-node.js +33 -0
  121. package/dist/extensions/trust-store-node.js.map +1 -0
  122. package/dist/extensions/types.d.ts +42 -0
  123. package/dist/extensions/types.js +2 -0
  124. package/dist/extensions/types.js.map +1 -0
  125. package/dist/harness.d.ts +156 -0
  126. package/dist/harness.js +2 -0
  127. package/dist/harness.js.map +1 -0
  128. package/dist/index.d.ts +4 -0
  129. package/dist/index.js +5 -0
  130. package/dist/index.js.map +1 -0
  131. package/dist/mcp/connection.d.ts +22 -0
  132. package/dist/mcp/connection.js +267 -0
  133. package/dist/mcp/connection.js.map +1 -0
  134. package/dist/mcp/content.d.ts +27 -0
  135. package/dist/mcp/content.js +177 -0
  136. package/dist/mcp/content.js.map +1 -0
  137. package/dist/mcp/errors.d.ts +19 -0
  138. package/dist/mcp/errors.js +21 -0
  139. package/dist/mcp/errors.js.map +1 -0
  140. package/dist/mcp/index.d.ts +10 -0
  141. package/dist/mcp/index.js +10 -0
  142. package/dist/mcp/index.js.map +1 -0
  143. package/dist/mcp/manager.d.ts +7 -0
  144. package/dist/mcp/manager.js +173 -0
  145. package/dist/mcp/manager.js.map +1 -0
  146. package/dist/mcp/record.d.ts +7 -0
  147. package/dist/mcp/record.js +20 -0
  148. package/dist/mcp/record.js.map +1 -0
  149. package/dist/mcp/stdio.d.ts +39 -0
  150. package/dist/mcp/stdio.js +382 -0
  151. package/dist/mcp/stdio.js.map +1 -0
  152. package/dist/mcp/types.d.ts +172 -0
  153. package/dist/mcp/types.js +2 -0
  154. package/dist/mcp/types.js.map +1 -0
  155. package/dist/memory/index.d.ts +2 -0
  156. package/dist/memory/index.js +3 -0
  157. package/dist/memory/index.js.map +1 -0
  158. package/dist/permissions/default-rules.d.ts +7 -0
  159. package/dist/permissions/default-rules.js +42 -0
  160. package/dist/permissions/default-rules.js.map +1 -0
  161. package/dist/permissions/errors.d.ts +11 -0
  162. package/dist/permissions/errors.js +14 -0
  163. package/dist/permissions/errors.js.map +1 -0
  164. package/dist/permissions/index.d.ts +9 -0
  165. package/dist/permissions/index.js +9 -0
  166. package/dist/permissions/index.js.map +1 -0
  167. package/dist/permissions/match.d.ts +33 -0
  168. package/dist/permissions/match.js +287 -0
  169. package/dist/permissions/match.js.map +1 -0
  170. package/dist/permissions/pipeline.d.ts +9 -0
  171. package/dist/permissions/pipeline.js +235 -0
  172. package/dist/permissions/pipeline.js.map +1 -0
  173. package/dist/permissions/rules.d.ts +22 -0
  174. package/dist/permissions/rules.js +74 -0
  175. package/dist/permissions/rules.js.map +1 -0
  176. package/dist/permissions/shadow.d.ts +5 -0
  177. package/dist/permissions/shadow.js +22 -0
  178. package/dist/permissions/shadow.js.map +1 -0
  179. package/dist/permissions/types.d.ts +104 -0
  180. package/dist/permissions/types.js +2 -0
  181. package/dist/permissions/types.js.map +1 -0
  182. package/dist/sandbox/base.d.ts +35 -0
  183. package/dist/sandbox/base.js +60 -0
  184. package/dist/sandbox/base.js.map +1 -0
  185. package/dist/sandbox/docker/index.d.ts +35 -0
  186. package/dist/sandbox/docker/index.js +448 -0
  187. package/dist/sandbox/docker/index.js.map +1 -0
  188. package/dist/sandbox/errors.d.ts +16 -0
  189. package/dist/sandbox/errors.js +22 -0
  190. package/dist/sandbox/errors.js.map +1 -0
  191. package/dist/sandbox/host-files.d.ts +63 -0
  192. package/dist/sandbox/host-files.js +248 -0
  193. package/dist/sandbox/host-files.js.map +1 -0
  194. package/dist/sandbox/index.d.ts +8 -0
  195. package/dist/sandbox/index.js +8 -0
  196. package/dist/sandbox/index.js.map +1 -0
  197. package/dist/sandbox/none.d.ts +17 -0
  198. package/dist/sandbox/none.js +108 -0
  199. package/dist/sandbox/none.js.map +1 -0
  200. package/dist/sandbox/process.d.ts +61 -0
  201. package/dist/sandbox/process.js +253 -0
  202. package/dist/sandbox/process.js.map +1 -0
  203. package/dist/sandbox/spawn-env.d.ts +20 -0
  204. package/dist/sandbox/spawn-env.js +128 -0
  205. package/dist/sandbox/spawn-env.js.map +1 -0
  206. package/dist/sandbox/srt/index.d.ts +35 -0
  207. package/dist/sandbox/srt/index.js +264 -0
  208. package/dist/sandbox/srt/index.js.map +1 -0
  209. package/dist/sandbox/srt/settings.d.ts +48 -0
  210. package/dist/sandbox/srt/settings.js +31 -0
  211. package/dist/sandbox/srt/settings.js.map +1 -0
  212. package/dist/sandbox/types.d.ts +88 -0
  213. package/dist/sandbox/types.js +6 -0
  214. package/dist/sandbox/types.js.map +1 -0
  215. package/dist/server/answers.d.ts +16 -0
  216. package/dist/server/answers.js +43 -0
  217. package/dist/server/answers.js.map +1 -0
  218. package/dist/server/connection.d.ts +99 -0
  219. package/dist/server/connection.js +309 -0
  220. package/dist/server/connection.js.map +1 -0
  221. package/dist/server/dispatcher.d.ts +86 -0
  222. package/dist/server/dispatcher.js +800 -0
  223. package/dist/server/dispatcher.js.map +1 -0
  224. package/dist/server/index.d.ts +13 -0
  225. package/dist/server/index.js +12 -0
  226. package/dist/server/index.js.map +1 -0
  227. package/dist/server/local-transport.d.ts +44 -0
  228. package/dist/server/local-transport.js +103 -0
  229. package/dist/server/local-transport.js.map +1 -0
  230. package/dist/server/outbox.d.ts +31 -0
  231. package/dist/server/outbox.js +130 -0
  232. package/dist/server/outbox.js.map +1 -0
  233. package/dist/server/params.d.ts +25 -0
  234. package/dist/server/params.js +112 -0
  235. package/dist/server/params.js.map +1 -0
  236. package/dist/server/protocol.schema.json +2448 -0
  237. package/dist/server/rpc-session.d.ts +43 -0
  238. package/dist/server/rpc-session.js +167 -0
  239. package/dist/server/rpc-session.js.map +1 -0
  240. package/dist/server/stdio-streams.d.ts +67 -0
  241. package/dist/server/stdio-streams.js +218 -0
  242. package/dist/server/stdio-streams.js.map +1 -0
  243. package/dist/server/stdio.d.ts +59 -0
  244. package/dist/server/stdio.js +189 -0
  245. package/dist/server/stdio.js.map +1 -0
  246. package/dist/server/websocket.d.ts +106 -0
  247. package/dist/server/websocket.js +327 -0
  248. package/dist/server/websocket.js.map +1 -0
  249. package/dist/session/approvals.d.ts +81 -0
  250. package/dist/session/approvals.js +217 -0
  251. package/dist/session/approvals.js.map +1 -0
  252. package/dist/session/code-call-log.d.ts +42 -0
  253. package/dist/session/code-call-log.js +63 -0
  254. package/dist/session/code-call-log.js.map +1 -0
  255. package/dist/session/code-call-result.d.ts +19 -0
  256. package/dist/session/code-call-result.js +95 -0
  257. package/dist/session/code-call-result.js.map +1 -0
  258. package/dist/session/code-call.d.ts +49 -0
  259. package/dist/session/code-call.js +345 -0
  260. package/dist/session/code-call.js.map +1 -0
  261. package/dist/session/effect-scope.d.ts +11 -0
  262. package/dist/session/effect-scope.js +10 -0
  263. package/dist/session/effect-scope.js.map +1 -0
  264. package/dist/session/errors.d.ts +19 -0
  265. package/dist/session/errors.js +27 -0
  266. package/dist/session/errors.js.map +1 -0
  267. package/dist/session/file-index.d.ts +8 -0
  268. package/dist/session/file-index.js +70 -0
  269. package/dist/session/file-index.js.map +1 -0
  270. package/dist/session/file-key-store.d.ts +16 -0
  271. package/dist/session/file-key-store.js +169 -0
  272. package/dist/session/file-key-store.js.map +1 -0
  273. package/dist/session/file-lock.d.ts +52 -0
  274. package/dist/session/file-lock.js +324 -0
  275. package/dist/session/file-lock.js.map +1 -0
  276. package/dist/session/index.d.ts +22 -0
  277. package/dist/session/index.js +20 -0
  278. package/dist/session/index.js.map +1 -0
  279. package/dist/session/jsonl-store.d.ts +37 -0
  280. package/dist/session/jsonl-store.js +386 -0
  281. package/dist/session/jsonl-store.js.map +1 -0
  282. package/dist/session/jsonl.d.ts +9 -0
  283. package/dist/session/jsonl.js +10 -0
  284. package/dist/session/jsonl.js.map +1 -0
  285. package/dist/session/lock.d.ts +19 -0
  286. package/dist/session/lock.js +2 -0
  287. package/dist/session/lock.js.map +1 -0
  288. package/dist/session/memory-store.d.ts +12 -0
  289. package/dist/session/memory-store.js +60 -0
  290. package/dist/session/memory-store.js.map +1 -0
  291. package/dist/session/migrate.d.ts +41 -0
  292. package/dist/session/migrate.js +86 -0
  293. package/dist/session/migrate.js.map +1 -0
  294. package/dist/session/pointer.d.ts +15 -0
  295. package/dist/session/pointer.js +22 -0
  296. package/dist/session/pointer.js.map +1 -0
  297. package/dist/session/rebuild.d.ts +53 -0
  298. package/dist/session/rebuild.js +230 -0
  299. package/dist/session/rebuild.js.map +1 -0
  300. package/dist/session/resume.d.ts +26 -0
  301. package/dist/session/resume.js +128 -0
  302. package/dist/session/resume.js.map +1 -0
  303. package/dist/session/retention.d.ts +97 -0
  304. package/dist/session/retention.js +702 -0
  305. package/dist/session/retention.js.map +1 -0
  306. package/dist/session/runner.d.ts +156 -0
  307. package/dist/session/runner.js +656 -0
  308. package/dist/session/runner.js.map +1 -0
  309. package/dist/session/scheduler.d.ts +47 -0
  310. package/dist/session/scheduler.js +85 -0
  311. package/dist/session/scheduler.js.map +1 -0
  312. package/dist/session/secret-key-store.d.ts +47 -0
  313. package/dist/session/secret-key-store.js +79 -0
  314. package/dist/session/secret-key-store.js.map +1 -0
  315. package/dist/session/session.d.ts +106 -0
  316. package/dist/session/session.js +353 -0
  317. package/dist/session/session.js.map +1 -0
  318. package/dist/session/sticky.d.ts +48 -0
  319. package/dist/session/sticky.js +232 -0
  320. package/dist/session/sticky.js.map +1 -0
  321. package/dist/session/store.d.ts +108 -0
  322. package/dist/session/store.js +163 -0
  323. package/dist/session/store.js.map +1 -0
  324. package/dist/telemetry/index.d.ts +2 -0
  325. package/dist/telemetry/index.js +3 -0
  326. package/dist/telemetry/index.js.map +1 -0
  327. package/dist/testing/fake-sandbox.d.ts +34 -0
  328. package/dist/testing/fake-sandbox.js +221 -0
  329. package/dist/testing/fake-sandbox.js.map +1 -0
  330. package/dist/testing/index.d.ts +10 -0
  331. package/dist/testing/index.js +11 -0
  332. package/dist/testing/index.js.map +1 -0
  333. package/dist/testing/key-store-conformance.d.ts +22 -0
  334. package/dist/testing/key-store-conformance.js +97 -0
  335. package/dist/testing/key-store-conformance.js.map +1 -0
  336. package/dist/testing/run-cases.d.ts +21 -0
  337. package/dist/testing/run-cases.js +20 -0
  338. package/dist/testing/run-cases.js.map +1 -0
  339. package/dist/testing/sandbox-conformance.d.ts +64 -0
  340. package/dist/testing/sandbox-conformance.js +361 -0
  341. package/dist/testing/sandbox-conformance.js.map +1 -0
  342. package/dist/testing/scheduler-conformance.d.ts +32 -0
  343. package/dist/testing/scheduler-conformance.js +72 -0
  344. package/dist/testing/scheduler-conformance.js.map +1 -0
  345. package/dist/testing/store-conformance.d.ts +21 -0
  346. package/dist/testing/store-conformance.js +320 -0
  347. package/dist/testing/store-conformance.js.map +1 -0
  348. package/dist/tools/errors.d.ts +13 -0
  349. package/dist/tools/errors.js +17 -0
  350. package/dist/tools/errors.js.map +1 -0
  351. package/dist/tools/index.d.ts +8 -0
  352. package/dist/tools/index.js +8 -0
  353. package/dist/tools/index.js.map +1 -0
  354. package/dist/tools/registry.d.ts +3 -0
  355. package/dist/tools/registry.js +234 -0
  356. package/dist/tools/registry.js.map +1 -0
  357. package/dist/tools/tool-search.d.ts +30 -0
  358. package/dist/tools/tool-search.js +118 -0
  359. package/dist/tools/tool-search.js.map +1 -0
  360. package/dist/tools/types.d.ts +106 -0
  361. package/dist/tools/types.js +2 -0
  362. package/dist/tools/types.js.map +1 -0
  363. package/llms.txt +435 -0
  364. package/package.json +119 -5
@@ -0,0 +1,95 @@
1
+ import { capResult } from "../context/cap.js";
2
+ import { EntryTooLargeError } from "./errors.js";
3
+ /**
4
+ * The result as the context policy's write cap leaves it, with the spill that holds its full text. A cap that fails
5
+ * leaves the result whole, and the store's bound still holds it to size when it is written.
6
+ */
7
+ async function cappedByContext(harness, writer, call, result) {
8
+ const whole = { content: result.content, details: result.details };
9
+ // The call's history is not a turn's, so the policy is told not to compact in the middle of it.
10
+ const turn = harness.context?.forTurn({ session: writer.session, model: harness.model, ownHistory: true });
11
+ const hook = turn?.interceptors.afterToolCall;
12
+ if (turn === undefined || hook === undefined)
13
+ return whole;
14
+ try {
15
+ const patch = await hook({
16
+ runId: call.callId,
17
+ stepIndex: 0,
18
+ callId: call.callId,
19
+ signal: writer.signal,
20
+ timestamp: writer.now(),
21
+ tool: call.tool,
22
+ input: call.input,
23
+ result: result,
24
+ });
25
+ const spill = turn.spillOf(call.callId);
26
+ return {
27
+ content: patch?.content ?? whole.content,
28
+ details: patch !== undefined && "details" in patch ? patch.details : whole.details,
29
+ ...(spill === undefined ? {} : { spill }),
30
+ };
31
+ }
32
+ catch {
33
+ return whole;
34
+ }
35
+ }
36
+ /** The stored result cut to fit `cap` bytes, or `undefined` when its content already fits that cap. */
37
+ async function cut(stored, call, cap) {
38
+ const capped = await capResult({
39
+ content: stored.content,
40
+ details: stored.details,
41
+ cap,
42
+ name: call.callId,
43
+ // The context policy's spill store is its own, so what is cut here is not kept; the host's result still holds it.
44
+ write: () => Promise.reject(new Error("no spill store for a code call's result")),
45
+ });
46
+ if (capped === undefined)
47
+ return undefined;
48
+ return {
49
+ content: capped.patch.content ?? stored.content,
50
+ details: "details" in capped.patch ? capped.patch.details : stored.details,
51
+ ...(stored.spill === undefined ? {} : { spill: stored.spill }),
52
+ };
53
+ }
54
+ /**
55
+ * Writes the call's `tool_result` from what the tool returned. A result over the store's bound is cut to fit and
56
+ * written again, once at the bound and once at a quarter of it, so the call keeps its result and its outcome. Any other
57
+ * failure of the store is thrown: the call then has no result, and the next code call settles it as one that may have
58
+ * taken effect.
59
+ */
60
+ export async function writeCodeCallResult(harness, writer, tool, call, result) {
61
+ const entry = (stored) => writer.write({
62
+ type: "tool_result",
63
+ callId: call.callId,
64
+ tool: call.tool,
65
+ content: [...stored.content],
66
+ isError: result.isError === true,
67
+ ...(stored.details === undefined ? {} : { details: stored.details }),
68
+ ...(stored.spill === undefined ? {} : { spill: stored.spill }),
69
+ trust: tool.outputTrust,
70
+ });
71
+ const stored = await cappedByContext(harness, writer, call, result);
72
+ let refused;
73
+ try {
74
+ return await entry(stored);
75
+ }
76
+ catch (error) {
77
+ if (!(error instanceof EntryTooLargeError))
78
+ throw error;
79
+ refused = error;
80
+ }
81
+ for (const cap of [refused.maxBytes, refused.maxBytes >> 2]) {
82
+ const fitted = await cut(stored, call, cap);
83
+ if (fitted === undefined)
84
+ continue;
85
+ try {
86
+ return await entry(fitted);
87
+ }
88
+ catch (error) {
89
+ if (!(error instanceof EntryTooLargeError))
90
+ throw error;
91
+ }
92
+ }
93
+ throw refused;
94
+ }
95
+ //# sourceMappingURL=code-call-result.js.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AM,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,CAAC,KAAK,YAAY,kBAAkB,CAAC;gBAAE,MAAM,KAAK,CAAC;QAC1D,CAAC;IACH,CAAC;IACD,MAAM,OAAO,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Writing a code call's `tool_result`. The tool has already run when this is called, so the entry must land: an entry\n * the store refuses would leave a call that was let run with no result, and the next code call would settle it as a\n * write that may have taken effect although it finished. The harness's context policy caps the result first, as it caps\n * a model call's, and a result still over the store's bound is cut to fit, keeping the write outcome at its front.\n */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport type { CodeCallEntry, SessionEntry, ToolResultEntry } from \"@buildanagent/protocol\";\nimport type { ToolResult } from \"@buildanagent/sdk\";\nimport { capResult } from \"../context/cap.js\";\nimport type { Harness } from \"../harness.js\";\nimport type { RegisteredTool } from \"../tools/types.js\";\nimport { EntryTooLargeError } from \"./errors.js\";\nimport type { Session } from \"./session.js\";\n\n/** What a `tool_result` entry stores of a result. */\ninterface Stored {\n readonly content: readonly ModelContent[];\n readonly details: unknown;\n readonly spill?: { readonly path: string; readonly bytes: number };\n}\n\n/** What writing the result needs: the session, the clock's time, the signal and the writer of one entry. */\nexport interface ResultWriter {\n readonly session: Session;\n readonly now: () => string;\n readonly signal: AbortSignal;\n readonly write: (body: ToolResultEntry) => Promise<SessionEntry>;\n}\n\n/**\n * The result as the context policy's write cap leaves it, with the spill that holds its full text. A cap that fails\n * leaves the result whole, and the store's bound still holds it to size when it is written.\n */\nasync function cappedByContext<H>(\n harness: Harness<H>,\n writer: ResultWriter,\n call: CodeCallEntry,\n result: ToolResult<unknown>,\n): Promise<Stored> {\n const whole: Stored = { content: result.content, details: result.details };\n // The call's history is not a turn's, so the policy is told not to compact in the middle of it.\n const turn = harness.context?.forTurn({ session: writer.session, model: harness.model, ownHistory: true });\n const hook = turn?.interceptors.afterToolCall;\n if (turn === undefined || hook === undefined) return whole;\n try {\n const patch = await hook({\n runId: call.callId,\n stepIndex: 0,\n callId: call.callId,\n signal: writer.signal,\n timestamp: writer.now(),\n tool: call.tool,\n input: call.input,\n result: result as ToolResult,\n });\n const spill = turn.spillOf(call.callId);\n return {\n content: patch?.content ?? whole.content,\n details: patch !== undefined && \"details\" in patch ? patch.details : whole.details,\n ...(spill === undefined ? {} : { spill }),\n };\n } catch {\n return whole;\n }\n}\n\n/** The stored result cut to fit `cap` bytes, or `undefined` when its content already fits that cap. */\nasync function cut(stored: Stored, call: CodeCallEntry, cap: number): Promise<Stored | undefined> {\n const capped = await capResult({\n content: stored.content,\n details: stored.details,\n cap,\n name: call.callId,\n // The context policy's spill store is its own, so what is cut here is not kept; the host's result still holds it.\n write: () => Promise.reject(new Error(\"no spill store for a code call's result\")),\n });\n if (capped === undefined) return undefined;\n return {\n content: capped.patch.content ?? stored.content,\n details: \"details\" in capped.patch ? capped.patch.details : stored.details,\n ...(stored.spill === undefined ? {} : { spill: stored.spill }),\n };\n}\n\n/**\n * Writes the call's `tool_result` from what the tool returned. A result over the store's bound is cut to fit and\n * written again, once at the bound and once at a quarter of it, so the call keeps its result and its outcome. Any other\n * failure of the store is thrown: the call then has no result, and the next code call settles it as one that may have\n * taken effect.\n */\nexport async function writeCodeCallResult<H>(\n harness: Harness<H>,\n writer: ResultWriter,\n tool: RegisteredTool,\n call: CodeCallEntry,\n result: ToolResult<unknown>,\n): Promise<SessionEntry> {\n const entry = (stored: Stored) =>\n writer.write({\n type: \"tool_result\",\n callId: call.callId,\n tool: call.tool,\n content: [...stored.content],\n isError: result.isError === true,\n ...(stored.details === undefined ? {} : { details: stored.details }),\n ...(stored.spill === undefined ? {} : { spill: stored.spill }),\n trust: tool.outputTrust,\n });\n const stored = await cappedByContext(harness, writer, call, result);\n let refused: EntryTooLargeError;\n try {\n return await entry(stored);\n } catch (error) {\n if (!(error instanceof EntryTooLargeError)) throw error;\n refused = error;\n }\n for (const cap of [refused.maxBytes, refused.maxBytes >> 2]) {\n const fitted = await cut(stored, call, cap);\n if (fitted === undefined) continue;\n try {\n return await entry(fitted);\n } catch (error) {\n if (!(error instanceof EntryTooLargeError)) throw error;\n }\n }\n throw refused;\n}\n"]}
@@ -0,0 +1,49 @@
1
+ import { type Resolution } from "@buildanagent/sdk";
2
+ import type { Clock } from "@buildanagent/sdk/testing";
3
+ import type { CodeCall, CodeCallResult, Harness } from "../harness.js";
4
+ import type { RegisteredTool } from "../tools/types.js";
5
+ import { type WaitingCodeCall } from "./code-call-log.js";
6
+ import { type ResolutionRecord } from "./runner.js";
7
+ import type { Session } from "./session.js";
8
+ /** The settings both a call and its resolution take: where its ids and time come from. */
9
+ interface IoOptions {
10
+ readonly clock?: Clock;
11
+ readonly newId?: () => string;
12
+ }
13
+ /** What running a code call needs besides the tool: its host context and its signal. */
14
+ interface RunOptions<H> extends IoOptions {
15
+ readonly hostContext?: H;
16
+ readonly signal?: AbortSignal;
17
+ }
18
+ /** Runs `task` after every code call of `session` that this process started before it. */
19
+ export declare function inCodeCallQueue<T>(session: Session, task: () => Promise<T>): Promise<T>;
20
+ /**
21
+ * The call's effect key: from the tool's business key when it declares one, and from the scope of `callId` otherwise.
22
+ * A tool the registry no longer has gets the scope's key.
23
+ */
24
+ export declare function codeCallEffectKey<H>(session: Session, harness: Harness<H>, tool: RegisteredTool | undefined, call: {
25
+ readonly callId: string;
26
+ readonly input: unknown;
27
+ }): Promise<string>;
28
+ /** `Harness.invokeTool()`: see its documentation. */
29
+ export declare function invokeCodeCall<H>(harness: Harness<H>, session: Session, call: CodeCall<H>): Promise<CodeCallResult>;
30
+ /**
31
+ * Checks a resolution against the waiting call's signed request before anything is written: the signature under a key
32
+ * the signer holds, the host context the request binds, the call and tool, and the input, which must hash to the signed
33
+ * hash in the `code_call` entry, in the `approval_requested` entry and in the request alike. Throws `approval_refused`
34
+ * with the cause, which names no key, signature or input.
35
+ */
36
+ export declare function checkCodeCallRequest<H>(harness: Harness<H>, waiting: WaitingCodeCall, resolution: Resolution, hostContext: H | undefined): Promise<void>;
37
+ /** What the resolution of a code call is given: the answer the quorum settled on, if any, and the entries to write. */
38
+ export interface SettledCodeCall {
39
+ readonly forRun: Resolution | undefined;
40
+ readonly records: readonly ResolutionRecord[];
41
+ readonly effectKey: string;
42
+ }
43
+ /**
44
+ * Applies a code call's settled resolution: it writes the answers, then leaves the call waiting when the quorum still
45
+ * waits, denies it for a person's or the policy's refusal, and otherwise decides it again with the pipeline, so a deny
46
+ * written since the pause wins, and runs the tool itself, with no model step.
47
+ */
48
+ export declare function finishCodeCall<H>(harness: Harness<H>, session: Session, waiting: WaitingCodeCall, settled: SettledCodeCall, options: RunOptions<H>): Promise<CodeCallResult>;
49
+ export {};
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Code-initiated tool calls: a side effect the host's own code chose, run through the same permission pipeline, signed
3
+ * pause and log as a call the model makes, with no model step. The `code_call` entry is written before anything else
4
+ * of the call, and its id is the call id, so the effect key is fixed before the tool can run and a resume finds it.
5
+ * A call starts once its log holds the entry that clears it to run; one that started with no result is never rerun.
6
+ */
7
+ import { effectKey, renderOutcome, writeOutcome } from "@buildanagent/agent-safety";
8
+ import { canonicalInputHash, createPendingRequest, verifyResolution, } from "@buildanagent/sdk";
9
+ import { HarnessError } from "../errors.js";
10
+ import { codeCallsOf } from "./code-call-log.js";
11
+ import { writeCodeCallResult } from "./code-call-result.js";
12
+ import { effectScope } from "./effect-scope.js";
13
+ import { interruptedResult } from "./resume.js";
14
+ import { recordSessionStart } from "./runner.js";
15
+ import { findSticky, stickyDecision } from "./sticky.js";
16
+ // The SDK's default nesting cap, so a tool that starts an agent from a code call nests as it would in a run.
17
+ const MAX_DEPTH = 2;
18
+ function ioOf(session, options) {
19
+ const newId = options.newId ?? (() => globalThis.crypto.randomUUID());
20
+ const clock = options.clock ?? { now: () => new Date().toISOString() };
21
+ return {
22
+ session,
23
+ newId,
24
+ clock,
25
+ async write(origin, body, id = newId()) {
26
+ const entry = { ...body, id, parentId: session.head(), timestamp: clock.now(), origin };
27
+ const [stored] = await session.append([entry]);
28
+ return stored;
29
+ },
30
+ };
31
+ }
32
+ const invalid = (message, cause) => new HarnessError("invalid_code_call", message, cause === undefined ? {} : { cause });
33
+ const describe = (error) => (error instanceof Error ? error.message : String(error));
34
+ // One code call of a session runs at a time in a process: a second one would read the first one's open call as a crash.
35
+ // Another process is kept out by the session's lock.
36
+ const queues = new WeakMap();
37
+ /** Runs `task` after every code call of `session` that this process started before it. */
38
+ export function inCodeCallQueue(session, task) {
39
+ const next = (queues.get(session) ?? Promise.resolve()).then(task, task);
40
+ queues.set(session, next.catch(() => undefined));
41
+ return next;
42
+ }
43
+ /** The registered tool a code call names, refused when the registry lacks it or only a client can run it. */
44
+ function toolFor(harness, name) {
45
+ const tool = harness.registry.get(name);
46
+ if (tool === undefined)
47
+ throw invalid(`no tool "${name}" is registered, so the code call can't run`);
48
+ if (tool.pattern === "client_request") {
49
+ throw invalid(`the tool "${tool.canonicalName}" runs on the client, which a code call has no way to reach`);
50
+ }
51
+ return tool;
52
+ }
53
+ async function hashOf(value, what) {
54
+ try {
55
+ return await canonicalInputHash(value);
56
+ }
57
+ catch (error) {
58
+ throw invalid(`the code call's ${what} has no canonical JSON form`, error);
59
+ }
60
+ }
61
+ /**
62
+ * The call's effect key: from the tool's business key when it declares one, and from the scope of `callId` otherwise.
63
+ * A tool the registry no longer has gets the scope's key.
64
+ */
65
+ export async function codeCallEffectKey(session, harness, tool, call) {
66
+ const businessKey = tool?.definition.effect?.businessKey;
67
+ try {
68
+ return await effectKey(effectScope(session, harness, call.callId), businessKey?.(call.input));
69
+ }
70
+ catch (error) {
71
+ throw invalid(`the effect key of the call to "${tool?.canonicalName}" could not be made`, error);
72
+ }
73
+ }
74
+ /** Refuses a harness that can't decide or sign a code call, before anything is written. */
75
+ function checkHarness(harness) {
76
+ if (harness.pipeline === undefined) {
77
+ throw invalid("the harness has no permission pipeline, so no code call can be decided");
78
+ }
79
+ if (harness.signer === undefined) {
80
+ throw new HarnessError("approval_unavailable", "the harness has no signer, so a code call could not ask anyone");
81
+ }
82
+ }
83
+ /**
84
+ * Settles each code call a crash left open: writes the result it lacks. A call that started may have taken effect, so
85
+ * it gets the result an interrupted model call gets. A call that never started never ran, so it gets an error that says
86
+ * so: one that stopped before it could run or ask anyone, and one whose answer was written but which stopped, or was
87
+ * refused, before it started. A call that asked and has no final answer still waits.
88
+ */
89
+ async function settleCodeCalls(path, harness, io) {
90
+ for (const { call, result, requested, answered, letRun } of codeCallsOf(path).values()) {
91
+ if (result !== undefined || (requested !== undefined && !answered && !letRun))
92
+ continue;
93
+ const body = letRun
94
+ ? { origin: "tool", ...interruptedResult(harness, call.tool) }
95
+ : { origin: "harness", ...notRun(answered ? NOT_RUN_ANSWERED : NOT_RUN_EARLY) };
96
+ const { origin, ...fields } = body;
97
+ await io.write(origin, { type: "tool_result", callId: call.callId, tool: call.tool, ...fields });
98
+ }
99
+ }
100
+ const NOT_RUN_EARLY = "The code call stopped before it could run or ask anyone, so it never ran.";
101
+ const NOT_RUN_ANSWERED = "The code call stopped after its answer was written and before it could run, so it never ran.";
102
+ const notRun = (text) => ({
103
+ content: [{ type: "text", text }],
104
+ isError: true,
105
+ trust: "trusted",
106
+ });
107
+ /** Refuses a compensation that names no code call that ran, or that would share that call's effect key. */
108
+ async function checkCompensation(session, harness, records, compensated, ownKey) {
109
+ const target = records.get(compensated);
110
+ // A denial is the harness's own result. A result from the tool, a crash's result, or a call let run that has no
111
+ // result yet means the call ran or may have run.
112
+ const ran = target?.result === undefined ? target?.letRun === true : target.result.origin === "tool";
113
+ if (target === undefined || !ran) {
114
+ throw invalid(`a compensation must name a code call that ran, and "${compensated}" names none`);
115
+ }
116
+ const theirs = await codeCallEffectKey(session, harness, harness.registry.get(target.call.tool), target.call);
117
+ if (theirs === ownKey) {
118
+ throw invalid("a compensation needs an effect key of its own, and this one has the key of the call it undoes");
119
+ }
120
+ }
121
+ /** Writes an error result for a call that does not run, and returns the denial. */
122
+ async function deny(io, call, reason) {
123
+ const entry = await io.write("harness", {
124
+ type: "tool_result",
125
+ callId: call.callId,
126
+ tool: call.tool,
127
+ ...notRun(reason),
128
+ });
129
+ return { status: "denied", callId: call.callId, reason, entryId: entry.id };
130
+ }
131
+ /** Decides the call with the pipeline, which writes its `permission_decision`, and keeps the policy version it used. */
132
+ async function decide(harness, session, io, call, hostContext) {
133
+ let policyVersion;
134
+ const policySession = {
135
+ append(entry) {
136
+ if (entry.type === "permission_decision")
137
+ policyVersion = entry.policyVersion;
138
+ return io.write("harness", entry);
139
+ },
140
+ };
141
+ // checkHarness() refused a harness without a pipeline before anything was written.
142
+ const pipeline = harness.pipeline;
143
+ const decision = await pipeline.decide({ callId: call.callId, tool: call.tool, input: call.input, initiator: "code" }, { session: policySession, hostContext, entries: await session.path() });
144
+ return { decision, policyVersion: policyVersion === "" ? undefined : policyVersion };
145
+ }
146
+ const isContentList = (content) => Array.isArray(content) &&
147
+ content.every((block) => (block?.type === "text" && typeof block.text === "string") ||
148
+ (block?.type === "image" && typeof block.mediaType === "string" && typeof block.data === "string"));
149
+ /** A result with its write outcome's sentence in front of its content, as the model would read it. */
150
+ function withOutcome(result) {
151
+ if (!isContentList(result?.content))
152
+ throw new TypeError("the tool returned content that is not text and images");
153
+ if (result.outcome === undefined)
154
+ return result;
155
+ const rendered = renderOutcome(result.outcome);
156
+ return {
157
+ ...result,
158
+ content: [
159
+ { type: "text", text: rendered.text },
160
+ { type: "text", text: JSON.stringify({ outcome: rendered.payload }) },
161
+ ...result.content,
162
+ ],
163
+ isError: result.isError === true || rendered.isError,
164
+ };
165
+ }
166
+ /** The result of a tool that threw or returned something unusable: a write's outcome is unknown, since it may have run. */
167
+ function thrownResult(tool, error) {
168
+ const text = tool.definition.redactErrors === true ? "The tool failed." : `The tool failed: ${describe(error)}`;
169
+ if (tool.definition.effect?.kind !== "write")
170
+ return { content: [{ type: "text", text }], isError: true };
171
+ const rendered = renderOutcome(writeOutcome({
172
+ kind: "unknown",
173
+ operation: tool.canonicalName,
174
+ retry: "reconcile_first",
175
+ reason: "WRITE_FAILED",
176
+ currentState: "The tool failed before it returned, so the write may have taken effect.",
177
+ next: "Check whether it took effect before you do anything else.",
178
+ }));
179
+ return {
180
+ content: [
181
+ { type: "text", text: rendered.text },
182
+ { type: "text", text: JSON.stringify({ outcome: rendered.payload }) },
183
+ { type: "text", text },
184
+ ],
185
+ isError: true,
186
+ details: { outcome: rendered.payload },
187
+ };
188
+ }
189
+ /**
190
+ * Runs the tool through the harness's wrapper with the host context, and writes its result. The harness's interceptors
191
+ * and observers belong to a turn's model step, so they don't run here; the pipeline already decided the call.
192
+ */
193
+ async function runTool(harness, io, tool, call, options) {
194
+ const ctx = {
195
+ runId: call.callId,
196
+ callId: call.callId,
197
+ signal: options.signal ?? new AbortController().signal,
198
+ depth: 0,
199
+ maxDepth: MAX_DEPTH,
200
+ clock: io.clock,
201
+ app: options.hostContext,
202
+ update: () => undefined,
203
+ };
204
+ let result;
205
+ // A wrapper that throws is recorded like a tool that throws, so the call that was let run still gets a result.
206
+ try {
207
+ const definition = harness.wrap === undefined ? tool.definition : harness.wrap(tool, options.hostContext);
208
+ result = withOutcome(await definition.execute(call.input, ctx));
209
+ }
210
+ catch (error) {
211
+ result = thrownResult(tool, error);
212
+ }
213
+ const writer = {
214
+ session: io.session,
215
+ now: io.clock.now,
216
+ signal: ctx.signal,
217
+ write: (body) => io.write("tool", body),
218
+ };
219
+ const entry = await writeCodeCallResult(harness, writer, tool, call, result);
220
+ return { status: "done", callId: call.callId, result, entryId: entry.id, effectKey: options.effectKey };
221
+ }
222
+ /** Signs the request for a call the pipeline asks about, and writes it before anyone can hear of it. */
223
+ async function ask(harness, io, call, decision) {
224
+ const { reason, policyVersion, hostContext } = decision;
225
+ const pending = await createPendingRequest({
226
+ kind: "approval",
227
+ callId: call.callId,
228
+ tool: call.tool,
229
+ input: call.input,
230
+ ...(policyVersion === undefined ? {} : { policyVersion }),
231
+ ...(reason === "" ? {} : { reason }),
232
+ ...(hostContext === undefined ? {} : { app: hostContext }),
233
+ },
234
+ // checkHarness() refused a harness without a signer before anything was written.
235
+ harness.signer, { generateId: io.newId, now: () => new Date(io.clock.now()) });
236
+ await io.write("harness", { type: "approval_requested", request: pending, input: call.input });
237
+ return { status: "awaiting_approval", callId: call.callId, pending, effectKey: decision.effectKey };
238
+ }
239
+ /** Checks everything a code call needs before its first entry, and returns its tool, input hash and effect key. */
240
+ async function prepare(harness, session, call, callId) {
241
+ checkHarness(harness);
242
+ const tool = toolFor(harness, call.tool);
243
+ const inputHash = await hashOf(call.input, "input");
244
+ if (call.hostContext !== undefined)
245
+ await hashOf(call.hostContext, "host context");
246
+ const key = await codeCallEffectKey(session, harness, tool, { callId, input: call.input });
247
+ return { tool, inputHash, key };
248
+ }
249
+ /** `Harness.invokeTool()`: see its documentation. */
250
+ export async function invokeCodeCall(harness, session, call) {
251
+ // Checked before the queue too, so an aborted call never waits behind another.
252
+ call.signal?.throwIfAborted();
253
+ return inCodeCallQueue(session, () => invokeQueued(harness, session, call));
254
+ }
255
+ async function invokeQueued(harness, session, call) {
256
+ const io = ioOf(session, call);
257
+ const callId = io.newId();
258
+ const { tool, inputHash, key } = await prepare(harness, session, call, callId);
259
+ const path = await session.path();
260
+ if (call.compensates !== undefined) {
261
+ await checkCompensation(session, harness, codeCallsOf(path), call.compensates, key);
262
+ }
263
+ call.signal?.throwIfAborted();
264
+ await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, path);
265
+ await settleCodeCalls(await session.path(), harness, io);
266
+ const entry = {
267
+ type: "code_call",
268
+ callId,
269
+ tool: tool.canonicalName,
270
+ input: call.input,
271
+ inputHash,
272
+ ...(call.compensates === undefined ? {} : { compensates: call.compensates }),
273
+ };
274
+ await io.write("harness", entry, callId);
275
+ const { decision, policyVersion } = await decide(harness, session, io, entry, call.hostContext);
276
+ if (decision.decision === "deny")
277
+ return deny(io, entry, decision.reason);
278
+ const run = { ...call, effectKey: key };
279
+ if (decision.decision === "allow")
280
+ return runTool(harness, io, tool, entry, run);
281
+ const covered = await findSticky(await session.path(), { ...entry, policyVersion }, harness.registry);
282
+ if (covered === undefined) {
283
+ return ask(harness, io, entry, {
284
+ reason: decision.reason,
285
+ policyVersion,
286
+ hostContext: call.hostContext,
287
+ effectKey: key,
288
+ });
289
+ }
290
+ await io.write("harness", await stickyDecision(entry, covered, policyVersion));
291
+ return runTool(harness, io, tool, entry, run);
292
+ }
293
+ /**
294
+ * Checks a resolution against the waiting call's signed request before anything is written: the signature under a key
295
+ * the signer holds, the host context the request binds, the call and tool, and the input, which must hash to the signed
296
+ * hash in the `code_call` entry, in the `approval_requested` entry and in the request alike. Throws `approval_refused`
297
+ * with the cause, which names no key, signature or input.
298
+ */
299
+ export async function checkCodeCallRequest(harness, waiting, resolution, hostContext) {
300
+ const { call, request, input } = waiting;
301
+ const check = await verifyResolution(request, resolution, {
302
+ signer: harness.signer,
303
+ call: { callId: call.callId, tool: call.tool, input: call.input },
304
+ ...(hostContext === undefined ? {} : { app: hostContext }),
305
+ });
306
+ const cause = check.ok ? await inputCause(call, input) : check.cause;
307
+ if (cause !== undefined) {
308
+ throw new HarnessError("approval_refused", `the request for code call ${call.callId} failed its check (${cause}), so nothing ran and nothing was written`);
309
+ }
310
+ }
311
+ /** `input_changed` unless the recorded input and the input shown to the approver both hash to the recorded hash. */
312
+ async function inputCause(call, shown) {
313
+ const hash = async (value) => canonicalInputHash(value).catch(() => undefined);
314
+ const [recorded, asked] = await Promise.all([hash(call.input), hash(shown)]);
315
+ return recorded === call.inputHash && asked === call.inputHash ? undefined : "input_changed";
316
+ }
317
+ /**
318
+ * Applies a code call's settled resolution: it writes the answers, then leaves the call waiting when the quorum still
319
+ * waits, denies it for a person's or the policy's refusal, and otherwise decides it again with the pipeline, so a deny
320
+ * written since the pause wins, and runs the tool itself, with no model step.
321
+ */
322
+ export async function finishCodeCall(harness, session, waiting, settled, options) {
323
+ options.signal?.throwIfAborted();
324
+ const io = ioOf(session, options);
325
+ for (const record of settled.records)
326
+ await io.write("user", { type: "approval_resolved", ...record });
327
+ const { call } = waiting;
328
+ const { forRun, effectKey: key } = settled;
329
+ if (forRun === undefined) {
330
+ return { status: "awaiting_approval", callId: call.callId, pending: waiting.request, effectKey: key };
331
+ }
332
+ if (!("decision" in forRun) || forRun.decision !== "allow") {
333
+ return deny(io, call, ("reason" in forRun ? forRun.reason : undefined) ?? "A person denied the call.");
334
+ }
335
+ const tool = harness.registry.get(call.tool);
336
+ if (tool?.canonicalName !== call.tool || tool.pattern !== "in_process") {
337
+ return deny(io, call, `The tool "${call.tool}" is no longer registered for code calls, so the call did not run.`);
338
+ }
339
+ const { decision } = await decide(harness, session, io, call, options.hostContext);
340
+ // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.
341
+ if (decision.decision === "deny")
342
+ return deny(io, call, decision.reason);
343
+ return runTool(harness, io, tool, call, { ...options, effectKey: key });
344
+ }
345
+ //# sourceMappingURL=code-call.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-call.js","sourceRoot":"","sources":["../../src/session/code-call.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAGpF,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EAIpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAI5C,OAAO,EAAuB,WAAW,EAAwB,MAAM,oBAAoB,CAAC;AAC5F,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAExE,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,M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AAI,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * Code-initiated tool calls: a side effect the host's own code chose, run through the same permission pipeline, signed\n * pause and log as a call the model makes, with no model step. The `code_call` entry is written before anything else\n * of the call, and its id is the call id, so the effect key is fixed before the tool can run and a resume finds it.\n * A call starts once its log holds the entry that clears it to run; one that started with no result is never rerun.\n */\nimport { effectKey, renderOutcome, writeOutcome } from \"@buildanagent/agent-safety\";\nimport type { ContentBlock } from \"@buildanagent/gateway\";\nimport type { CodeCallEntry, Origin, SessionEntry } from \"@buildanagent/protocol\";\nimport {\n canonicalInputHash,\n createPendingRequest,\n type Resolution,\n type ToolContext,\n type ToolResult,\n verifyResolution,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCall, CodeCallResult, Harness } from \"../harness.js\";\nimport type { Decision, PolicySession } from \"../permissions/types.js\";\nimport type { RegisteredTool } from \"../tools/types.js\";\nimport { type CodeCallRecord, codeCallsOf, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { writeCodeCallResult } from \"./code-call-result.js\";\nimport { effectScope } from \"./effect-scope.js\";\nimport { interruptedResult } from \"./resume.js\";\nimport { type ResolutionRecord, recordSessionStart } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { findSticky, stickyDecision } from \"./sticky.js\";\nimport type { EntryInput } from \"./store.js\";\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\ntype Body = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n\n/** How a code call writes: one entry at a time after the one before, with its ids and clock. */\ninterface Io {\n readonly session: Session;\n write(origin: Origin, body: Body, id?: string): Promise<SessionEntry>;\n readonly newId: () => string;\n readonly clock: Clock;\n}\n\n/** The settings both a call and its resolution take: where its ids and time come from. */\ninterface IoOptions {\n readonly clock?: Clock;\n readonly newId?: () => string;\n}\n\n/** What running a code call needs besides the tool: its host context and its signal. */\ninterface RunOptions<H> extends IoOptions {\n readonly hostContext?: H;\n readonly signal?: AbortSignal;\n}\n\n// The SDK's default nesting cap, so a tool that starts an agent from a code call nests as it would in a run.\nconst MAX_DEPTH = 2;\n\nfunction ioOf(session: Session, options: IoOptions): Io {\n const newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n const clock = options.clock ?? { now: () => new Date().toISOString() };\n return {\n session,\n newId,\n clock,\n async write(origin, body, id = newId()) {\n const entry = { ...body, id, parentId: session.head(), timestamp: clock.now(), origin } as EntryInput;\n const [stored] = await session.append([entry]);\n return stored as SessionEntry;\n },\n };\n}\n\nconst invalid = (message: string, cause?: unknown) =>\n new HarnessError(\"invalid_code_call\", message, cause === undefined ? {} : { cause });\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// One code call of a session runs at a time in a process: a second one would read the first one's open call as a crash.\n// Another process is kept out by the session's lock.\nconst queues = new WeakMap<Session, Promise<unknown>>();\n\n/** Runs `task` after every code call of `session` that this process started before it. */\nexport function inCodeCallQueue<T>(session: Session, task: () => Promise<T>): Promise<T> {\n const next = (queues.get(session) ?? Promise.resolve()).then(task, task);\n queues.set(\n session,\n next.catch(() => undefined),\n );\n return next;\n}\n\n/** The registered tool a code call names, refused when the registry lacks it or only a client can run it. */\nfunction toolFor<H>(harness: Harness<H>, name: string): RegisteredTool {\n const tool = harness.registry.get(name);\n if (tool === undefined) throw invalid(`no tool \"${name}\" is registered, so the code call can't run`);\n if (tool.pattern === \"client_request\") {\n throw invalid(`the tool \"${tool.canonicalName}\" runs on the client, which a code call has no way to reach`);\n }\n return tool;\n}\n\nasync function hashOf(value: unknown, what: string): Promise<string> {\n try {\n return await canonicalInputHash(value);\n } catch (error) {\n throw invalid(`the code call's ${what} has no canonical JSON form`, error);\n }\n}\n\n/**\n * The call's effect key: from the tool's business key when it declares one, and from the scope of `callId` otherwise.\n * A tool the registry no longer has gets the scope's key.\n */\nexport async function codeCallEffectKey<H>(\n session: Session,\n harness: Harness<H>,\n tool: RegisteredTool | undefined,\n call: { readonly callId: string; readonly input: unknown },\n): Promise<string> {\n const businessKey = tool?.definition.effect?.businessKey;\n try {\n return await effectKey(effectScope(session, harness, call.callId), businessKey?.(call.input));\n } catch (error) {\n throw invalid(`the effect key of the call to \"${tool?.canonicalName}\" could not be made`, error);\n }\n}\n\n/** Refuses a harness that can't decide or sign a code call, before anything is written. */\nfunction checkHarness<H>(harness: Harness<H>): void {\n if (harness.pipeline === undefined) {\n throw invalid(\"the harness has no permission pipeline, so no code call can be decided\");\n }\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so a code call could not ask anyone\");\n }\n}\n\n/**\n * Settles each code call a crash left open: writes the result it lacks. A call that started may have taken effect, so\n * it gets the result an interrupted model call gets. A call that never started never ran, so it gets an error that says\n * so: one that stopped before it could run or ask anyone, and one whose answer was written but which stopped, or was\n * refused, before it started. A call that asked and has no final answer still waits.\n */\nasync function settleCodeCalls<H>(path: readonly SessionEntry[], harness: Harness<H>, io: Io): Promise<void> {\n for (const { call, result, requested, answered, letRun } of codeCallsOf(path).values()) {\n if (result !== undefined || (requested !== undefined && !answered && !letRun)) continue;\n const body = letRun\n ? { origin: \"tool\" as const, ...interruptedResult(harness, call.tool) }\n : { origin: \"harness\" as const, ...notRun(answered ? NOT_RUN_ANSWERED : NOT_RUN_EARLY) };\n const { origin, ...fields } = body;\n await io.write(origin, { type: \"tool_result\", callId: call.callId, tool: call.tool, ...fields });\n }\n}\n\nconst NOT_RUN_EARLY = \"The code call stopped before it could run or ask anyone, so it never ran.\";\nconst NOT_RUN_ANSWERED = \"The code call stopped after its answer was written and before it could run, so it never ran.\";\n\nconst notRun = (text: string) => ({\n content: [{ type: \"text\" as const, text }],\n isError: true,\n trust: \"trusted\" as const,\n});\n\n/** Refuses a compensation that names no code call that ran, or that would share that call's effect key. */\nasync function checkCompensation<H>(\n session: Session,\n harness: Harness<H>,\n records: ReadonlyMap<string, CodeCallRecord>,\n compensated: string,\n ownKey: string,\n): Promise<void> {\n const target = records.get(compensated);\n // A denial is the harness's own result. A result from the tool, a crash's result, or a call let run that has no\n // result yet means the call ran or may have run.\n const ran = target?.result === undefined ? target?.letRun === true : target.result.origin === \"tool\";\n if (target === undefined || !ran) {\n throw invalid(`a compensation must name a code call that ran, and \"${compensated}\" names none`);\n }\n const theirs = await codeCallEffectKey(session, harness, harness.registry.get(target.call.tool), target.call);\n if (theirs === ownKey) {\n throw invalid(\"a compensation needs an effect key of its own, and this one has the key of the call it undoes\");\n }\n}\n\n/** Writes an error result for a call that does not run, and returns the denial. */\nasync function deny(io: Io, call: CodeCallEntry, reason: string): Promise<CodeCallResult> {\n const entry = await io.write(\"harness\", {\n type: \"tool_result\",\n callId: call.callId,\n tool: call.tool,\n ...notRun(reason),\n });\n return { status: \"denied\", callId: call.callId, reason, entryId: entry.id };\n}\n\n/** Decides the call with the pipeline, which writes its `permission_decision`, and keeps the policy version it used. */\nasync function decide<H>(\n harness: Harness<H>,\n session: Session,\n io: Io,\n call: CodeCallEntry,\n hostContext: H | undefined,\n): Promise<{ decision: Decision; policyVersion: string | undefined }> {\n let policyVersion: string | undefined;\n const policySession: PolicySession = {\n append(entry) {\n if (entry.type === \"permission_decision\") policyVersion = entry.policyVersion;\n return io.write(\"harness\", entry);\n },\n };\n // checkHarness() refused a harness without a pipeline before anything was written.\n const pipeline = harness.pipeline as NonNullable<Harness<H>[\"pipeline\"]>;\n const decision = await pipeline.decide(\n { callId: call.callId, tool: call.tool, input: call.input, initiator: \"code\" },\n { session: policySession, hostContext, entries: await session.path() },\n );\n return { decision, policyVersion: policyVersion === \"\" ? undefined : policyVersion };\n}\n\nconst isContentList = (content: unknown): content is ToolResult[\"content\"] =>\n Array.isArray(content) &&\n content.every(\n (block: Partial<ContentBlock> | null) =>\n (block?.type === \"text\" && typeof block.text === \"string\") ||\n (block?.type === \"image\" && typeof block.mediaType === \"string\" && typeof block.data === \"string\"),\n );\n\n/** A result with its write outcome's sentence in front of its content, as the model would read it. */\nfunction withOutcome(result: ToolResult<unknown>): ToolResult<unknown> {\n if (!isContentList(result?.content)) throw new TypeError(\"the tool returned content that is not text and images\");\n if (result.outcome === undefined) return result;\n const rendered = renderOutcome(result.outcome);\n return {\n ...result,\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n ...result.content,\n ],\n isError: result.isError === true || rendered.isError,\n };\n}\n\n/** The result of a tool that threw or returned something unusable: a write's outcome is unknown, since it may have run. */\nfunction thrownResult(tool: RegisteredTool, error: unknown): ToolResult<unknown> {\n const text = tool.definition.redactErrors === true ? \"The tool failed.\" : `The tool failed: ${describe(error)}`;\n if (tool.definition.effect?.kind !== \"write\") return { content: [{ type: \"text\", text }], isError: true };\n const rendered = renderOutcome(\n writeOutcome({\n kind: \"unknown\",\n operation: tool.canonicalName,\n retry: \"reconcile_first\",\n reason: \"WRITE_FAILED\",\n currentState: \"The tool failed before it returned, so the write may have taken effect.\",\n next: \"Check whether it took effect before you do anything else.\",\n }),\n );\n return {\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n { type: \"text\", text },\n ],\n isError: true,\n details: { outcome: rendered.payload },\n };\n}\n\n/**\n * Runs the tool through the harness's wrapper with the host context, and writes its result. The harness's interceptors\n * and observers belong to a turn's model step, so they don't run here; the pipeline already decided the call.\n */\nasync function runTool<H>(\n harness: Harness<H>,\n io: Io,\n tool: RegisteredTool,\n call: CodeCallEntry,\n options: RunOptions<H> & { readonly effectKey: string },\n): Promise<CodeCallResult> {\n const ctx: ToolContext<unknown> = {\n runId: call.callId,\n callId: call.callId,\n signal: options.signal ?? new AbortController().signal,\n depth: 0,\n maxDepth: MAX_DEPTH,\n clock: io.clock,\n app: options.hostContext,\n update: () => undefined,\n };\n let result: ToolResult<unknown>;\n // A wrapper that throws is recorded like a tool that throws, so the call that was let run still gets a result.\n try {\n const definition = harness.wrap === undefined ? tool.definition : harness.wrap(tool, options.hostContext as H);\n result = withOutcome(await definition.execute(call.input, ctx));\n } catch (error) {\n result = thrownResult(tool, error);\n }\n const writer = {\n session: io.session,\n now: io.clock.now,\n signal: ctx.signal,\n write: (body: Body) => io.write(\"tool\", body),\n };\n const entry = await writeCodeCallResult(harness, writer, tool, call, result);\n return { status: \"done\", callId: call.callId, result, entryId: entry.id, effectKey: options.effectKey };\n}\n\n/** Signs the request for a call the pipeline asks about, and writes it before anyone can hear of it. */\nasync function ask<H>(\n harness: Harness<H>,\n io: Io,\n call: CodeCallEntry,\n decision: { reason: string; policyVersion: string | undefined; hostContext: H | undefined; effectKey: string },\n): Promise<CodeCallResult> {\n const { reason, policyVersion, hostContext } = decision;\n const pending = await createPendingRequest(\n {\n kind: \"approval\",\n callId: call.callId,\n tool: call.tool,\n input: call.input,\n ...(policyVersion === undefined ? {} : { policyVersion }),\n ...(reason === \"\" ? {} : { reason }),\n ...(hostContext === undefined ? {} : { app: hostContext }),\n },\n // checkHarness() refused a harness without a signer before anything was written.\n harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n { generateId: io.newId, now: () => new Date(io.clock.now()) },\n );\n await io.write(\"harness\", { type: \"approval_requested\", request: pending, input: call.input });\n return { status: \"awaiting_approval\", callId: call.callId, pending, effectKey: decision.effectKey };\n}\n\n/** Checks everything a code call needs before its first entry, and returns its tool, input hash and effect key. */\nasync function prepare<H>(harness: Harness<H>, session: Session, call: CodeCall<H>, callId: string) {\n checkHarness(harness);\n const tool = toolFor(harness, call.tool);\n const inputHash = await hashOf(call.input, \"input\");\n if (call.hostContext !== undefined) await hashOf(call.hostContext, \"host context\");\n const key = await codeCallEffectKey(session, harness, tool, { callId, input: call.input });\n return { tool, inputHash, key };\n}\n\n/** `Harness.invokeTool()`: see its documentation. */\nexport async function invokeCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n call: CodeCall<H>,\n): Promise<CodeCallResult> {\n // Checked before the queue too, so an aborted call never waits behind another.\n call.signal?.throwIfAborted();\n return inCodeCallQueue(session, () => invokeQueued(harness, session, call));\n}\n\nasync function invokeQueued<H>(harness: Harness<H>, session: Session, call: CodeCall<H>): Promise<CodeCallResult> {\n const io = ioOf(session, call);\n const callId = io.newId();\n const { tool, inputHash, key } = await prepare(harness, session, call, callId);\n const path = await session.path();\n if (call.compensates !== undefined) {\n await checkCompensation(session, harness, codeCallsOf(path), call.compensates, key);\n }\n call.signal?.throwIfAborted();\n await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, path);\n await settleCodeCalls(await session.path(), harness, io);\n const entry: CodeCallEntry = {\n type: \"code_call\",\n callId,\n tool: tool.canonicalName,\n input: call.input,\n inputHash,\n ...(call.compensates === undefined ? {} : { compensates: call.compensates }),\n };\n await io.write(\"harness\", entry, callId);\n const { decision, policyVersion } = await decide(harness, session, io, entry, call.hostContext);\n if (decision.decision === \"deny\") return deny(io, entry, decision.reason);\n const run = { ...call, effectKey: key };\n if (decision.decision === \"allow\") return runTool(harness, io, tool, entry, run);\n const covered = await findSticky(await session.path(), { ...entry, policyVersion }, harness.registry);\n if (covered === undefined) {\n return ask(harness, io, entry, {\n reason: decision.reason,\n policyVersion,\n hostContext: call.hostContext,\n effectKey: key,\n });\n }\n await io.write(\"harness\", await stickyDecision(entry, covered, policyVersion));\n return runTool(harness, io, tool, entry, run);\n}\n\n/**\n * Checks a resolution against the waiting call's signed request before anything is written: the signature under a key\n * the signer holds, the host context the request binds, the call and tool, and the input, which must hash to the signed\n * hash in the `code_call` entry, in the `approval_requested` entry and in the request alike. Throws `approval_refused`\n * with the cause, which names no key, signature or input.\n */\nexport async function checkCodeCallRequest<H>(\n harness: Harness<H>,\n waiting: WaitingCodeCall,\n resolution: Resolution,\n hostContext: H | undefined,\n): Promise<void> {\n const { call, request, input } = waiting;\n const check = await verifyResolution(request, resolution, {\n signer: harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n call: { callId: call.callId, tool: call.tool, input: call.input },\n ...(hostContext === undefined ? {} : { app: hostContext }),\n });\n const cause = check.ok ? await inputCause(call, input) : check.cause;\n if (cause !== undefined) {\n throw new HarnessError(\n \"approval_refused\",\n `the request for code call ${call.callId} failed its check (${cause}), so nothing ran and nothing was written`,\n );\n }\n}\n\n/** `input_changed` unless the recorded input and the input shown to the approver both hash to the recorded hash. */\nasync function inputCause(call: CodeCallEntry, shown: unknown): Promise<\"input_changed\" | undefined> {\n const hash = async (value: unknown) => canonicalInputHash(value).catch(() => undefined);\n const [recorded, asked] = await Promise.all([hash(call.input), hash(shown)]);\n return recorded === call.inputHash && asked === call.inputHash ? undefined : \"input_changed\";\n}\n\n/** What the resolution of a code call is given: the answer the quorum settled on, if any, and the entries to write. */\nexport interface SettledCodeCall {\n readonly forRun: Resolution | undefined;\n readonly records: readonly ResolutionRecord[];\n readonly effectKey: string;\n}\n\n/**\n * Applies a code call's settled resolution: it writes the answers, then leaves the call waiting when the quorum still\n * waits, denies it for a person's or the policy's refusal, and otherwise decides it again with the pipeline, so a deny\n * written since the pause wins, and runs the tool itself, with no model step.\n */\nexport async function finishCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n waiting: WaitingCodeCall,\n settled: SettledCodeCall,\n options: RunOptions<H>,\n): Promise<CodeCallResult> {\n options.signal?.throwIfAborted();\n const io = ioOf(session, options);\n for (const record of settled.records) await io.write(\"user\", { type: \"approval_resolved\", ...record });\n const { call } = waiting;\n const { forRun, effectKey: key } = settled;\n if (forRun === undefined) {\n return { status: \"awaiting_approval\", callId: call.callId, pending: waiting.request, effectKey: key };\n }\n if (!(\"decision\" in forRun) || forRun.decision !== \"allow\") {\n return deny(io, call, (\"reason\" in forRun ? forRun.reason : undefined) ?? \"A person denied the call.\");\n }\n const tool = harness.registry.get(call.tool);\n if (tool?.canonicalName !== call.tool || tool.pattern !== \"in_process\") {\n return deny(io, call, `The tool \"${call.tool}\" is no longer registered for code calls, so the call did not run.`);\n }\n const { decision } = await decide(harness, session, io, call, options.hostContext);\n // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.\n if (decision.decision === \"deny\") return deny(io, call, decision.reason);\n return runTool(harness, io, tool, call, { ...options, effectKey: key });\n}\n"]}
@@ -0,0 +1,11 @@
1
+ /** The scope of a write: who it acts for, in which session and branch, and which tool call asked for it. */
2
+ import type { EffectScope } from "@buildanagent/agent-safety";
3
+ import type { Harness } from "../harness.js";
4
+ import type { Session } from "./session.js";
5
+ /**
6
+ * The `EffectScope` a guarded write takes for `toolCallId`. The tenant is the harness's, the session is the session's
7
+ * id, and the branch is the file the log is in plus its latest checkout, which a fork, a revert or a re-run changes, so a
8
+ * branch that replays a call id gets its own key. A write with a business key shares one key across all of them, which is what makes a
9
+ * resumed run's repeated write recognisable.
10
+ */
11
+ export declare function effectScope(session: Session, harness: Pick<Harness, "tenant">, toolCallId: string): EffectScope;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The `EffectScope` a guarded write takes for `toolCallId`. The tenant is the harness's, the session is the session's
3
+ * id, and the branch is the file the log is in plus its latest checkout, which a fork, a revert or a re-run changes, so a
4
+ * branch that replays a call id gets its own key. A write with a business key shares one key across all of them, which is what makes a
5
+ * resumed run's repeated write recognisable.
6
+ */
7
+ export function effectScope(session, harness, toolCallId) {
8
+ return { tenant: harness.tenant, session: session.key.sessionId, branch: session.branch(), toolCallId };
9
+ }
10
+ //# sourceMappingURL=effect-scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effect-scope.js","sourceRoot":"","sources":["../../src/session/effect-scope.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,OAAgB,EAAE,OAAgC,EAAE,UAAkB;IAChG,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,EAAE,UAAU,EAAE,CAAC;AAC1G,CAAC","sourcesContent":["/** The scope of a write: who it acts for, in which session and branch, and which tool call asked for it. */\nimport type { EffectScope } from \"@buildanagent/agent-safety\";\nimport type { Harness } from \"../harness.js\";\nimport type { Session } from \"./session.js\";\n\n/**\n * The `EffectScope` a guarded write takes for `toolCallId`. The tenant is the harness's, the session is the session's\n * id, and the branch is the file the log is in plus its latest checkout, which a fork, a revert or a re-run changes, so a\n * branch that replays a call id gets its own key. A write with a business key shares one key across all of them, which is what makes a\n * resumed run's repeated write recognisable.\n */\nexport function effectScope(session: Session, harness: Pick<Harness, \"tenant\">, toolCallId: string): EffectScope {\n return { tenant: harness.tenant, session: session.key.sessionId, branch: session.branch(), toolCallId };\n}\n"]}