@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,232 @@
1
+ /**
2
+ * Sticky allowances and grouped approvals: what a person's `allow` may cover beyond the one call. A sticky allowance
3
+ * covers the same call again for a run or a session, matched by the tool and the call's input hash or, for a shell tool,
4
+ * by a command prefix. It never covers a command run through a shell, an interpreter or a wrapper, which would let any
5
+ * script through. It never covers anything that holds a secret, or a tool whose `approvalReuse` says each call needs a
6
+ * person. A prefix covers only a simple command, with no operator that starts a second one. A group is the requests of
7
+ * one step that share a tool and an input, answered once.
8
+ */
9
+ import { canonicalInputHash } from "@buildanagent/sdk";
10
+ import { HarnessError } from "../errors.js";
11
+ /** The command prefixes no sticky allowance may cover: each runs whatever text follows it. */
12
+ export const INTERPRETER_PREFIXES = [
13
+ ["bash", "-c"],
14
+ ["sh", "-c"],
15
+ ["sh", "-lc"],
16
+ ["zsh", "-c"],
17
+ ["node", "-e"],
18
+ ["python", "-c"],
19
+ ["bun", "run"],
20
+ ["npx"],
21
+ ["uvx"],
22
+ ];
23
+ // Programs that run other code, whatever their flags: shells, interpreters, package runners, and wrappers that start a
24
+ // program named in their arguments. A sticky allowance never covers a command whose first word is one of them, by any
25
+ // path, so `/bin/sh -c`, `env bash -c` and `python3 -c` are refused with the listed prefixes.
26
+ const RUNS_OTHER_CODE = new Set([
27
+ "bash",
28
+ "sh",
29
+ "zsh",
30
+ "dash",
31
+ "ksh",
32
+ "fish",
33
+ "csh",
34
+ "tcsh",
35
+ "node",
36
+ "deno",
37
+ "bun",
38
+ "python",
39
+ "python2",
40
+ "python3",
41
+ "perl",
42
+ "ruby",
43
+ "php",
44
+ "lua",
45
+ "osascript",
46
+ "npx",
47
+ "pnpx",
48
+ "bunx",
49
+ "uvx",
50
+ "pipx",
51
+ "npm",
52
+ "pnpm",
53
+ "yarn",
54
+ "env",
55
+ "sudo",
56
+ "doas",
57
+ "xargs",
58
+ "nice",
59
+ "nohup",
60
+ "timeout",
61
+ "command",
62
+ "exec",
63
+ "time",
64
+ "stdbuf",
65
+ "ionice",
66
+ "watch",
67
+ "eval",
68
+ "source",
69
+ ".",
70
+ "find",
71
+ "awk",
72
+ "gawk",
73
+ "make",
74
+ "busybox",
75
+ "setsid",
76
+ "su",
77
+ "ssh",
78
+ "script",
79
+ "unshare",
80
+ "chroot",
81
+ ]);
82
+ const wordsOf = (command) => command
83
+ .trim()
84
+ .split(/\s+/)
85
+ .filter((word) => word !== "");
86
+ /** The program a command starts with, without its folder: `/bin/sh` is `sh`. */
87
+ const programOf = (word) => (word ?? "").split("/").at(-1) ?? "";
88
+ // The text that starts a second command or hides one: a list or pipe operator, a redirection, a substitution, a
89
+ // subshell, an expansion or a line break. A prefix allowance covers a command with none of them.
90
+ const SHELL_SYNTAX = /[;&|<>`$()\n\r"'\\*?[\]{}!#]/;
91
+ /** Whether the command is a single simple command, so a prefix says what it runs. */
92
+ export const isSimpleCommand = (command) => !SHELL_SYNTAX.test(command);
93
+ /** A shell command with its spaces normalised outside quotes, so two spellings of one command hash alike. */
94
+ export const normalisedCommand = (command) => /["']/.test(command) ? command.trim() : wordsOf(command).join(" ");
95
+ const commandOf = (input) => typeof input === "object" && input !== null && typeof input.command === "string"
96
+ ? input.command
97
+ : undefined;
98
+ const startsWith = (words, prefix) => prefix.length <= words.length && prefix.every((word, index) => words[index] === word);
99
+ /**
100
+ * Returns the listed interpreter prefix that `words` begin with or are the start of, or the first word's program when it
101
+ * runs other code. Returns `undefined` otherwise.
102
+ */
103
+ function runsOtherCode(words) {
104
+ if (words.length === 0)
105
+ return undefined;
106
+ const first = words[0];
107
+ // A leading assignment, quote, escape or glob can hide the program, so it is refused instead of read.
108
+ if (/[="'\\*?[\]{}$`!~]/.test(first))
109
+ return first;
110
+ if (programOf(first) === "git" && words.some((word) => word === "-c" || word.startsWith("--config-env")))
111
+ return "git -c";
112
+ const listed = INTERPRETER_PREFIXES.find((prefix) => startsWith(words, prefix) || startsWith(prefix, words));
113
+ if (listed !== undefined)
114
+ return listed.join(" ");
115
+ const program = programOf(words[0]);
116
+ return RUNS_OTHER_CODE.has(program) ? program : undefined;
117
+ }
118
+ /** What a sticky or grouped answer on a tool needs the tool to allow. */
119
+ const allows = (reuse, kind) => reuse === "both" || reuse === kind;
120
+ /** Throws `approval_reuse_refused` unless the tool's `approvalReuse` lets one answer cover more than one call. */
121
+ export function checkReuse(tool, reuse, kind) {
122
+ if (!allows(reuse, kind)) {
123
+ throw new HarnessError("approval_reuse_refused", `the tool "${tool}" sets approvalReuse "${reuse}", which forbids a ${kind} answer: each call needs a person`);
124
+ }
125
+ }
126
+ const refused = (why) => new HarnessError("sticky_refused", why);
127
+ /** Every string inside a value, so a secret is found as it is and not as JSON escapes it. */
128
+ function stringsIn(value, found = []) {
129
+ if (typeof value === "string")
130
+ found.push(value);
131
+ else if (Array.isArray(value))
132
+ for (const item of value)
133
+ stringsIn(item, found);
134
+ else if (typeof value === "object" && value !== null)
135
+ for (const item of Object.values(value))
136
+ stringsIn(item, found);
137
+ return found;
138
+ }
139
+ /** Throws `sticky_refused` unless the command prefix is a non-empty start of a simple command a person approved. */
140
+ function checkPrefix(command, commandPrefix) {
141
+ if (commandPrefix.length === 0 || commandPrefix.some((word) => word === "")) {
142
+ throw refused("a command prefix needs at least one word");
143
+ }
144
+ if (command === undefined || !isSimpleCommand(command)) {
145
+ throw refused("a command prefix covers only a simple command: no operator, redirection or substitution");
146
+ }
147
+ if (!startsWith(wordsOf(command), commandPrefix)) {
148
+ throw refused("the command prefix is not the start of the command a person approved");
149
+ }
150
+ }
151
+ /**
152
+ * Throws `sticky_refused` when an allowance on this call would cover code run through a shell, an interpreter or a
153
+ * wrapper, a prefix that is empty or that doesn't start the approved command, a command prefix on a call with no
154
+ * simple command, or a secret. `secrets` are the values the host's credential store knows.
155
+ */
156
+ export function checkSticky(input, commandPrefix, secrets) {
157
+ const command = commandOf(input);
158
+ for (const words of [command === undefined ? [] : wordsOf(command), commandPrefix ?? []]) {
159
+ const found = runsOtherCode(words);
160
+ if (found !== undefined)
161
+ throw refused(`a sticky allowance may not cover "${found}", which runs other code`);
162
+ }
163
+ if (commandPrefix !== undefined)
164
+ checkPrefix(command, commandPrefix);
165
+ const texts = [...stringsIn(input), ...(commandPrefix ?? []), JSON.stringify(input) ?? ""];
166
+ if (secrets.some((secret) => secret !== "" && texts.some((text) => text.includes(secret)))) {
167
+ throw refused("a sticky allowance may not cover a call that holds a secret the credential store knows");
168
+ }
169
+ }
170
+ /** The id a request's group shares: the tool and the whole input, with a shell command's spaces normalised. */
171
+ export async function groupIdOf(tool, input, inputHash) {
172
+ const command = commandOf(input);
173
+ const key = command === undefined
174
+ ? inputHash
175
+ : await canonicalInputHash({ ...input, command: normalisedCommand(command) });
176
+ return `grp-${(await canonicalInputHash({ tool, key })).slice(0, 16)}`;
177
+ }
178
+ /** Whether an allowance matches the call's input: the same hash, or a prefix of a simple command. */
179
+ function matchesInput(allowance, hash, command) {
180
+ if (allowance.inputHash === hash)
181
+ return true;
182
+ if (allowance.commandPrefix === undefined || command === undefined)
183
+ return false;
184
+ return isSimpleCommand(command) && startsWith(wordsOf(command), allowance.commandPrefix);
185
+ }
186
+ /** Whether a sticky entry's allowance covers a call under the policy version that asks about it now. */
187
+ function covers(entry, name, hash, command, version) {
188
+ if (entry.type !== "approval_resolved" || entry.quorum !== undefined)
189
+ return false;
190
+ if (entry.allowance === undefined || entry.allowance.tool !== name)
191
+ return false;
192
+ if (entry.allowance.policyVersion !== undefined && entry.allowance.policyVersion !== version)
193
+ return false;
194
+ return matchesInput(entry.allowance, hash, command);
195
+ }
196
+ /**
197
+ * The id of the sticky `approval_resolved` entry that covers this call, if one does. A `run` allowance counts from the
198
+ * latest turn that started a run, so its resumes share it; a `session` allowance counts from the start of this
199
+ * session's own file, so a fork never inherits its parent's. An allowance given under another policy version is
200
+ * ignored, because the policy that asked is no longer the one a person approved under.
201
+ */
202
+ export async function findSticky(path, call, registry) {
203
+ const tool = registry.get(call.tool);
204
+ if (tool !== undefined && !allows(tool.approvalReuse, "sticky"))
205
+ return undefined;
206
+ const fileStart = path.findLastIndex((entry) => entry.type === "session_header");
207
+ const runStart = Math.max(fileStart, path.findLastIndex((entry) => entry.type === "turn_start" && entry.mode === "run"));
208
+ const hash = await canonicalInputHash(call.input);
209
+ const command = typeof call.input === "object" && call.input !== null ? commandOf(call.input) : undefined;
210
+ const name = tool?.canonicalName ?? call.tool;
211
+ const live = path.filter((entry, index) => entry.type === "approval_resolved" && index >= (entry.sticky === "run" ? runStart : fileStart));
212
+ return live.findLast((entry) => entry.type === "approval_resolved" &&
213
+ entry.sticky !== undefined &&
214
+ covers(entry, name, hash, command, call.policyVersion))?.id;
215
+ }
216
+ /**
217
+ * The `permission_decision` entry that records a sticky allowance letting a call run: an allow by `sticky`, naming the
218
+ * `approval_resolved` entry that covers the call. The pipeline's own entry for the ask stays in the log beside it.
219
+ */
220
+ export async function stickyDecision(call, coveredBy, policyVersion) {
221
+ return {
222
+ type: "permission_decision",
223
+ callId: call.callId,
224
+ tool: call.tool,
225
+ decision: "allow",
226
+ rule: `sticky:${coveredBy}`,
227
+ by: "sticky",
228
+ policyVersion: policyVersion ?? "",
229
+ inputHash: await canonicalInputHash(call.input),
230
+ };
231
+ }
232
+ //# sourceMappingURL=sticky.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sticky.js","sourceRoot":"","sources":["../../src/session/sticky.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,8FAA8F;AAC9F,MAAM,CAAC,MAAM,oBAAoB,GAAmC;IAClE,CAAC,MAAM,EAAE,IAAI,CAAC;IACd,CAAC,IAAI,EAAE,IAAI,CAAC;IACZ,CAAC,IAAI,EAAE,KAAK,CAAC;IACb,CAAC,KAAK,EAAE,IAAI,CAAC;IACb,CAAC,MAAM,EAAE,IAAI,CAAC;IACd,CAAC,QAAQ,EAAE,IAAI,CAAC;IAChB,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,KAAK,CAAC;IACP,CAAC,KAAK,CAAC;CACR,CAAC;AAEF,uHAAuH;AACvH,sHAAsH;AACtH,8FAA8F;AAC9F,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,MAAM;IACN,IAAI;IACJ,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,MAAM;IACN,KAAK;IACL,QAAQ;IACR,SAAS;IACT,SAAS;IACT,MAAM;IACN,MAAM;IACN,KAAK;IACL,KAAK;IACL,WAAW;IACX,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,SAAS;IACT,SAAS;IACT,MAAM;IACN,MAAM;IACN,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,MAAM;IACN,QAAQ;IACR,GAAG;IACH,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,SAAS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KAAK,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,CAAC,MAAM,KAAK,SAAS;QAC1B,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,CACzD,EAAE,EAAE,CAAC;AACR,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,IAAiF,EACjF,SAAiB,EACjB,aAAiC;IAEjC,OAAO;QACL,IAAI,EAAE,qBAAqB;QAC3B,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,QAAQ,EAAE,OAAO;QACjB,IAAI,EAAE,UAAU,SAAS,EAAE;QAC3B,EAAE,EAAE,QAAQ;QACZ,aAAa,EAAE,aAAa,IAAI,EAAE;QAClC,SAAS,EAAE,MAAM,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC;KAChD,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Sticky allowances and grouped approvals: what a person's `allow` may cover beyond the one call. A sticky allowance\n * covers the same call again for a run or a session, matched by the tool and the call's input hash or, for a shell tool,\n * by a command prefix. It never covers a command run through a shell, an interpreter or a wrapper, which would let any\n * script through. It never covers anything that holds a secret, or a tool whose `approvalReuse` says each call needs a\n * person. A prefix covers only a simple command, with no operator that starts a second one. A group is the requests of\n * one step that share a tool and an input, answered once.\n */\n\nimport type { PermissionDecisionEntry, SessionEntry } from \"@buildanagent/protocol\";\nimport { canonicalInputHash } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { ApprovalReuse, ToolRegistry } from \"../tools/types.js\";\n\n/** The command prefixes no sticky allowance may cover: each runs whatever text follows it. */\nexport const INTERPRETER_PREFIXES: readonly (readonly string[])[] = [\n [\"bash\", \"-c\"],\n [\"sh\", \"-c\"],\n [\"sh\", \"-lc\"],\n [\"zsh\", \"-c\"],\n [\"node\", \"-e\"],\n [\"python\", \"-c\"],\n [\"bun\", \"run\"],\n [\"npx\"],\n [\"uvx\"],\n];\n\n// Programs that run other code, whatever their flags: shells, interpreters, package runners, and wrappers that start a\n// program named in their arguments. A sticky allowance never covers a command whose first word is one of them, by any\n// path, so `/bin/sh -c`, `env bash -c` and `python3 -c` are refused with the listed prefixes.\nconst RUNS_OTHER_CODE = new Set([\n \"bash\",\n \"sh\",\n \"zsh\",\n \"dash\",\n \"ksh\",\n \"fish\",\n \"csh\",\n \"tcsh\",\n \"node\",\n \"deno\",\n \"bun\",\n \"python\",\n \"python2\",\n \"python3\",\n \"perl\",\n \"ruby\",\n \"php\",\n \"lua\",\n \"osascript\",\n \"npx\",\n \"pnpx\",\n \"bunx\",\n \"uvx\",\n \"pipx\",\n \"npm\",\n \"pnpm\",\n \"yarn\",\n \"env\",\n \"sudo\",\n \"doas\",\n \"xargs\",\n \"nice\",\n \"nohup\",\n \"timeout\",\n \"command\",\n \"exec\",\n \"time\",\n \"stdbuf\",\n \"ionice\",\n \"watch\",\n \"eval\",\n \"source\",\n \".\",\n \"find\",\n \"awk\",\n \"gawk\",\n \"make\",\n \"busybox\",\n \"setsid\",\n \"su\",\n \"ssh\",\n \"script\",\n \"unshare\",\n \"chroot\",\n]);\n\nconst wordsOf = (command: string): string[] =>\n command\n .trim()\n .split(/\\s+/)\n .filter((word) => word !== \"\");\n\n/** The program a command starts with, without its folder: `/bin/sh` is `sh`. */\nconst programOf = (word: string | undefined): string => (word ?? \"\").split(\"/\").at(-1) ?? \"\";\n\n// The text that starts a second command or hides one: a list or pipe operator, a redirection, a substitution, a\n// subshell, an expansion or a line break. A prefix allowance covers a command with none of them.\nconst SHELL_SYNTAX = /[;&|<>`$()\\n\\r\"'\\\\*?[\\]{}!#]/;\n\n/** Whether the command is a single simple command, so a prefix says what it runs. */\nexport const isSimpleCommand = (command: string): boolean => !SHELL_SYNTAX.test(command);\n\n/** A shell command with its spaces normalised outside quotes, so two spellings of one command hash alike. */\nexport const normalisedCommand = (command: string): string =>\n /[\"']/.test(command) ? command.trim() : wordsOf(command).join(\" \");\n\nconst commandOf = (input: unknown): string | undefined =>\n typeof input === \"object\" && input !== null && typeof (input as { command?: unknown }).command === \"string\"\n ? (input as { command: string }).command\n : undefined;\n\nconst startsWith = (words: readonly string[], prefix: readonly string[]): boolean =>\n prefix.length <= words.length && prefix.every((word, index) => words[index] === word);\n\n/**\n * Returns the listed interpreter prefix that `words` begin with or are the start of, or the first word's program when it\n * runs other code. Returns `undefined` otherwise.\n */\nfunction runsOtherCode(words: readonly string[]): string | undefined {\n if (words.length === 0) return undefined;\n const first = words[0] as string;\n // A leading assignment, quote, escape or glob can hide the program, so it is refused instead of read.\n if (/[=\"'\\\\*?[\\]{}$`!~]/.test(first)) return first;\n if (programOf(first) === \"git\" && words.some((word) => word === \"-c\" || word.startsWith(\"--config-env\")))\n return \"git -c\";\n const listed = INTERPRETER_PREFIXES.find((prefix) => startsWith(words, prefix) || startsWith(prefix, words));\n if (listed !== undefined) return listed.join(\" \");\n const program = programOf(words[0]);\n return RUNS_OTHER_CODE.has(program) ? program : undefined;\n}\n\n/** What a sticky or grouped answer on a tool needs the tool to allow. */\nconst allows = (reuse: ApprovalReuse, kind: \"sticky\" | \"group\"): boolean => reuse === \"both\" || reuse === kind;\n\n/** Throws `approval_reuse_refused` unless the tool's `approvalReuse` lets one answer cover more than one call. */\nexport function checkReuse(tool: string, reuse: ApprovalReuse, kind: \"sticky\" | \"group\"): void {\n if (!allows(reuse, kind)) {\n throw new HarnessError(\n \"approval_reuse_refused\",\n `the tool \"${tool}\" sets approvalReuse \"${reuse}\", which forbids a ${kind} answer: each call needs a person`,\n );\n }\n}\n\nconst refused = (why: string) => new HarnessError(\"sticky_refused\", why);\n\n/** Every string inside a value, so a secret is found as it is and not as JSON escapes it. */\nfunction stringsIn(value: unknown, found: string[] = []): string[] {\n if (typeof value === \"string\") found.push(value);\n else if (Array.isArray(value)) for (const item of value) stringsIn(item, found);\n else if (typeof value === \"object\" && value !== null) for (const item of Object.values(value)) stringsIn(item, found);\n return found;\n}\n\n/** Throws `sticky_refused` unless the command prefix is a non-empty start of a simple command a person approved. */\nfunction checkPrefix(command: string | undefined, commandPrefix: readonly string[]): void {\n if (commandPrefix.length === 0 || commandPrefix.some((word) => word === \"\")) {\n throw refused(\"a command prefix needs at least one word\");\n }\n if (command === undefined || !isSimpleCommand(command)) {\n throw refused(\"a command prefix covers only a simple command: no operator, redirection or substitution\");\n }\n if (!startsWith(wordsOf(command), commandPrefix)) {\n throw refused(\"the command prefix is not the start of the command a person approved\");\n }\n}\n\n/**\n * Throws `sticky_refused` when an allowance on this call would cover code run through a shell, an interpreter or a\n * wrapper, a prefix that is empty or that doesn't start the approved command, a command prefix on a call with no\n * simple command, or a secret. `secrets` are the values the host's credential store knows.\n */\nexport function checkSticky(\n input: unknown,\n commandPrefix: readonly string[] | undefined,\n secrets: readonly string[],\n): void {\n const command = commandOf(input);\n for (const words of [command === undefined ? [] : wordsOf(command), commandPrefix ?? []]) {\n const found = runsOtherCode(words);\n if (found !== undefined) throw refused(`a sticky allowance may not cover \"${found}\", which runs other code`);\n }\n if (commandPrefix !== undefined) checkPrefix(command, commandPrefix);\n const texts = [...stringsIn(input), ...(commandPrefix ?? []), JSON.stringify(input) ?? \"\"];\n if (secrets.some((secret) => secret !== \"\" && texts.some((text) => text.includes(secret)))) {\n throw refused(\"a sticky allowance may not cover a call that holds a secret the credential store knows\");\n }\n}\n\n/** The id a request's group shares: the tool and the whole input, with a shell command's spaces normalised. */\nexport async function groupIdOf(tool: string, input: unknown, inputHash: string): Promise<string> {\n const command = commandOf(input);\n const key =\n command === undefined\n ? inputHash\n : await canonicalInputHash({ ...(input as object), command: normalisedCommand(command) });\n return `grp-${(await canonicalInputHash({ tool, key })).slice(0, 16)}`;\n}\n\n/** What `findSticky()` needs to know about the call: its tool, input and the policy version that asks about it. */\nexport interface StickyCall {\n readonly tool: string;\n readonly input: unknown;\n readonly policyVersion?: string | undefined;\n}\n\n/** Whether an allowance matches the call's input: the same hash, or a prefix of a simple command. */\nfunction matchesInput(\n allowance: { inputHash?: string; commandPrefix?: string[] },\n hash: string,\n command: string | undefined,\n): boolean {\n if (allowance.inputHash === hash) return true;\n if (allowance.commandPrefix === undefined || command === undefined) return false;\n return isSimpleCommand(command) && startsWith(wordsOf(command), allowance.commandPrefix);\n}\n\n/** Whether a sticky entry's allowance covers a call under the policy version that asks about it now. */\nfunction covers(\n entry: SessionEntry,\n name: string,\n hash: string,\n command: string | undefined,\n version?: string,\n): boolean {\n if (entry.type !== \"approval_resolved\" || entry.quorum !== undefined) return false;\n if (entry.allowance === undefined || entry.allowance.tool !== name) return false;\n if (entry.allowance.policyVersion !== undefined && entry.allowance.policyVersion !== version) return false;\n return matchesInput(entry.allowance, hash, command);\n}\n\n/**\n * The id of the sticky `approval_resolved` entry that covers this call, if one does. A `run` allowance counts from the\n * latest turn that started a run, so its resumes share it; a `session` allowance counts from the start of this\n * session's own file, so a fork never inherits its parent's. An allowance given under another policy version is\n * ignored, because the policy that asked is no longer the one a person approved under.\n */\nexport async function findSticky(\n path: readonly SessionEntry[],\n call: StickyCall,\n registry: ToolRegistry,\n): Promise<string | undefined> {\n const tool = registry.get(call.tool);\n if (tool !== undefined && !allows(tool.approvalReuse, \"sticky\")) return undefined;\n const fileStart = path.findLastIndex((entry) => entry.type === \"session_header\");\n const runStart = Math.max(\n fileStart,\n path.findLastIndex((entry) => entry.type === \"turn_start\" && entry.mode === \"run\"),\n );\n const hash = await canonicalInputHash(call.input);\n const command = typeof call.input === \"object\" && call.input !== null ? commandOf(call.input) : undefined;\n const name = tool?.canonicalName ?? call.tool;\n const live = path.filter(\n (entry, index) => entry.type === \"approval_resolved\" && index >= (entry.sticky === \"run\" ? runStart : fileStart),\n );\n return live.findLast(\n (entry) =>\n entry.type === \"approval_resolved\" &&\n entry.sticky !== undefined &&\n covers(entry, name, hash, command, call.policyVersion),\n )?.id;\n}\n\n/**\n * The `permission_decision` entry that records a sticky allowance letting a call run: an allow by `sticky`, naming the\n * `approval_resolved` entry that covers the call. The pipeline's own entry for the ask stays in the log beside it.\n */\nexport async function stickyDecision(\n call: { readonly callId: string; readonly tool: string; readonly input: unknown },\n coveredBy: string,\n policyVersion: string | undefined,\n): Promise<PermissionDecisionEntry> {\n return {\n type: \"permission_decision\",\n callId: call.callId,\n tool: call.tool,\n decision: \"allow\",\n rule: `sticky:${coveredBy}`,\n by: \"sticky\",\n policyVersion: policyVersion ?? \"\",\n inputHash: await canonicalInputHash(call.input),\n };\n}\n"]}
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The session store's interface and the rules every backend shares. A session belongs to a user: every method names
3
+ * the user, and a session under another user looks exactly like one that doesn't exist, so no caller can forget the
4
+ * owner check. `planAppend()` holds the append rules once, so the memory and JSONL backends cannot drift apart.
5
+ */
6
+ import { type SessionEntry, type SessionHeaderEntry } from "@buildanagent/protocol";
7
+ /** The default bound on one entry's JSON, in bytes. */
8
+ export declare const DEFAULT_MAX_ENTRY_BYTES: number;
9
+ /** Which session: its user and its id. No method finds a session by its id alone. */
10
+ export interface SessionKey {
11
+ readonly userId: string;
12
+ readonly sessionId: string;
13
+ }
14
+ type OmitSeq<T> = T extends unknown ? Omit<T, "seq"> : never;
15
+ /** An entry as a caller writes it. The store assigns `seq`, so the caller never has to count. */
16
+ export type EntryInput = OmitSeq<SessionEntry>;
17
+ /** What `list()` says about a session, read from its header and its last entry. */
18
+ export interface SessionSummary {
19
+ readonly sessionId: string;
20
+ /** The header's timestamp. */
21
+ readonly startedAt: string;
22
+ /** The timestamp of the last entry. */
23
+ readonly lastEntryAt: string;
24
+ readonly entryCount: number;
25
+ readonly harnessVersion: string;
26
+ readonly sdkVersion: string;
27
+ readonly parent?: SessionHeaderEntry["parent"];
28
+ /** Set on a spawned subagent or workflow step, whose `parent` is the session that started it and not a fork point. */
29
+ readonly spawn?: SessionHeaderEntry["spawn"];
30
+ readonly product?: SessionHeaderEntry["product"];
31
+ }
32
+ /** The options of `append()`. */
33
+ export interface AppendOptions {
34
+ /**
35
+ * The id of the entry the log must end with, or `null` for a session that doesn't exist yet. A different tail throws
36
+ * a `ConflictError` and writes nothing, so two writers can't both extend the same log. A batch that is already
37
+ * stored, in whole or in part, is a retry and skips this check. A partly stored batch still throws a `ConflictError`
38
+ * if its stored part is no longer the end of the log.
39
+ */
40
+ readonly expectedLastId?: string | null;
41
+ }
42
+ /** The options of `load()`. */
43
+ export interface LoadOptions {
44
+ /** The first sequence number to yield. Default 0. */
45
+ readonly fromSeq?: number;
46
+ /** Called once if the log ends in a line that was never completed, which `load()` skips. */
47
+ readonly onTornLine?: (line: {
48
+ readonly bytes: number;
49
+ }) => void;
50
+ }
51
+ /** Where a session's entries live. Every method names the user. */
52
+ export interface SessionStore {
53
+ /**
54
+ * Appends entries, assigns each its `seq` and returns them as stored. It is idempotent by entry id: an entry already
55
+ * stored with the same content is not written again, and one stored with different content throws a
56
+ * `ConflictError`. A new session's first entry must be a `session_header`. It throws an `EntryTooLargeError` above
57
+ * the size bound, a `ConflictError` when `expectedLastId` is stale, and a `HarnessError` for an entry that is not
58
+ * valid. A failed append writes none of its batch.
59
+ */
60
+ append(key: SessionKey, entries: readonly EntryInput[], options?: AppendOptions): Promise<SessionEntry[]>;
61
+ /** The entries from `fromSeq` on, in order. A session that doesn't exist, or belongs to another user, yields none. */
62
+ load(key: SessionKey, options?: LoadOptions): AsyncIterable<SessionEntry>;
63
+ /** The user's sessions only, oldest first. */
64
+ list(userId: string): AsyncIterable<SessionSummary>;
65
+ /** Deletes the session. A session that doesn't exist, or belongs to another user, is left alone and is no error. */
66
+ delete(key: SessionKey): Promise<void>;
67
+ /**
68
+ * The entries as they were written, without the protocol's format check, so a migration can read a log from a format
69
+ * this harness no longer reads. A store that can't leave the check out doesn't offer this method, and `migrateSession()` refuses to migrate a session
70
+ * in such a store.
71
+ */
72
+ loadRaw?(key: SessionKey): AsyncIterable<unknown>;
73
+ }
74
+ /**
75
+ * A user or session id as a file name: every byte outside `[a-z0-9_-]` becomes `%XX`, capital letters and dots
76
+ * included, so no id can name `..`, climb out of its folder, or collide with another id on a file system that ignores case.
77
+ */
78
+ export declare function encodeName(part: string): string;
79
+ /**
80
+ * Throws a `HarnessError` with code `invalid_session_key` unless `userId` and `sessionId` are each 1 to 64 characters
81
+ * with no control characters or lone surrogates and fit in a file name once encoded. Both backends apply this rule.
82
+ */
83
+ export declare function checkKey(key: SessionKey): void;
84
+ /** The log as a backend holds it: its entries by id, and where it ends. */
85
+ export interface LogState {
86
+ readonly byId: Map<string, SessionEntry>;
87
+ readonly lastId: string | null;
88
+ readonly lastSeq: number;
89
+ }
90
+ /** What an append will do: the entries it returns, and the ones to write. */
91
+ export interface AppendPlan {
92
+ readonly result: SessionEntry[];
93
+ readonly fresh: SessionEntry[];
94
+ }
95
+ /**
96
+ * Applies the append rules to a log and a batch, without writing: idempotency by id, the expected tail, the header
97
+ * first, validation and the size bound. Throws before anything is written, so a backend writes `fresh` or nothing.
98
+ */
99
+ export declare function planAppend(log: LogState, inputs: readonly EntryInput[], options: AppendOptions | undefined, maxBytes: number): AppendPlan;
100
+ /** The state after `fresh` was written, which extends the map in place, so an append costs the batch and not the log. */
101
+ export declare function extendState(state: LogState, fresh: readonly SessionEntry[]): LogState;
102
+ /** The log's state after `entries`, a copy that a backend can keep. */
103
+ export declare function stateOf(entries: readonly SessionEntry[]): LogState;
104
+ /** A summary from a log's entries, or `undefined` for a log with no header. */
105
+ export declare function summaryOf(sessionId: string, entries: readonly SessionEntry[]): SessionSummary | undefined;
106
+ /** The order `list()` uses: oldest first, then by id. */
107
+ export declare function byAge(a: SessionSummary, b: SessionSummary): number;
108
+ export {};
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The session store's interface and the rules every backend shares. A session belongs to a user: every method names
3
+ * the user, and a session under another user looks exactly like one that doesn't exist, so no caller can forget the
4
+ * owner check. `planAppend()` holds the append rules once, so the memory and JSONL backends cannot drift apart.
5
+ */
6
+ import { parseEntry } from "@buildanagent/protocol";
7
+ import { HarnessError } from "../errors.js";
8
+ import { ConflictError, EntryTooLargeError } from "./errors.js";
9
+ /** The default bound on one entry's JSON, in bytes. */
10
+ export const DEFAULT_MAX_ENTRY_BYTES = 64 * 1024;
11
+ const MAX_KEY_PART = 64;
12
+ /**
13
+ * A user or session id as a file name: every byte outside `[a-z0-9_-]` becomes `%XX`, capital letters and dots
14
+ * included, so no id can name `..`, climb out of its folder, or collide with another id on a file system that ignores case.
15
+ */
16
+ export function encodeName(part) {
17
+ return [...new TextEncoder().encode(part)]
18
+ .map((byte) => {
19
+ const char = String.fromCharCode(byte);
20
+ return /[a-z0-9_-]/.test(char) ? char : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
21
+ })
22
+ .join("");
23
+ }
24
+ const MAX_NAME_BYTES = 200;
25
+ /**
26
+ * Throws a `HarnessError` with code `invalid_session_key` unless `userId` and `sessionId` are each 1 to 64 characters
27
+ * with no control characters or lone surrogates and fit in a file name once encoded. Both backends apply this rule.
28
+ */
29
+ export function checkKey(key) {
30
+ for (const [label, value] of [
31
+ ["userId", key?.userId],
32
+ ["sessionId", key?.sessionId],
33
+ ]) {
34
+ if (typeof value !== "string" ||
35
+ value === "" ||
36
+ [...value].length > MAX_KEY_PART ||
37
+ !value.isWellFormed() ||
38
+ [...value].some((char) => char.charCodeAt(0) < 32) ||
39
+ encodeName(value).length > MAX_NAME_BYTES) {
40
+ throw new HarnessError("invalid_session_key", `a session ${label} must be 1 to ${MAX_KEY_PART} characters with no control characters or lone surrogates, and fit in a file name once encoded`);
41
+ }
42
+ }
43
+ }
44
+ // Key order and `undefined` fields must not make two equal entries look different.
45
+ function stable(value) {
46
+ if (Array.isArray(value))
47
+ return `[${value.map(stable).join(",")}]`;
48
+ if (typeof value !== "object" || value === null)
49
+ return JSON.stringify(value) ?? "null";
50
+ const record = value;
51
+ const fields = Object.keys(record)
52
+ .filter((name) => record[name] !== undefined)
53
+ .sort()
54
+ .map((name) => `${JSON.stringify(name)}:${stable(record[name])}`);
55
+ return `{${fields.join(",")}}`;
56
+ }
57
+ const sameContent = (a, b) => {
58
+ const { seq: _a, ...left } = a;
59
+ const { seq: _b, ...right } = b;
60
+ return stable(left) === stable(right);
61
+ };
62
+ /** The bytes of an entry's JSON, which is what the size bound counts. */
63
+ function entryBytes(entry) {
64
+ return new TextEncoder().encode(JSON.stringify(entry)).length;
65
+ }
66
+ function invalidEntry(why, cause) {
67
+ throw new HarnessError("invalid_session_entry", why, cause === undefined ? undefined : { cause });
68
+ }
69
+ /** Validates an entry with its assigned `seq`, through the protocol's own parser. */
70
+ function validated(input, seq) {
71
+ try {
72
+ return parseEntry(structuredClone({ ...input, seq }));
73
+ }
74
+ catch (cause) {
75
+ return invalidEntry(`an entry is not valid: ${cause instanceof Error ? cause.message : String(cause)}`, cause);
76
+ }
77
+ }
78
+ /** The entries of a batch that are already stored. They must be the batch's first entries, in order, and equal. */
79
+ function storedPrefix(log, inputs) {
80
+ const stored = [];
81
+ for (const [index, input] of inputs.entries()) {
82
+ const existing = log.byId.get(input.id);
83
+ if (existing === undefined) {
84
+ if (inputs.slice(index + 1).some((later) => log.byId.has(later.id))) {
85
+ throw new ConflictError("a batch is partly stored, and not as its first entries");
86
+ }
87
+ break;
88
+ }
89
+ // The stored entry went through the protocol parser, so the retry does too, or a normalised field would differ.
90
+ if (!sameContent(existing, validated(input, existing.seq))) {
91
+ throw new ConflictError(`entry "${input.id}" is already stored with different content`);
92
+ }
93
+ stored.push(existing);
94
+ }
95
+ return stored;
96
+ }
97
+ /**
98
+ * Applies the append rules to a log and a batch, without writing: idempotency by id, the expected tail, the header
99
+ * first, validation and the size bound. Throws before anything is written, so a backend writes `fresh` or nothing.
100
+ */
101
+ export function planAppend(log, inputs, options, maxBytes) {
102
+ if (new Set(inputs.map((input) => input.id)).size !== inputs.length)
103
+ invalidEntry("a batch repeats an entry id");
104
+ const stored = storedPrefix(log, inputs);
105
+ if (stored.length > 0 && stored.length < inputs.length && stored.at(-1)?.id !== log.lastId) {
106
+ throw new ConflictError("the stored part of this batch is no longer the end of the log");
107
+ }
108
+ if (stored.length === 0 && options?.expectedLastId !== undefined && options.expectedLastId !== log.lastId) {
109
+ throw new ConflictError(`the log ends at ${JSON.stringify(log.lastId)}, not ${JSON.stringify(options.expectedLastId)}`);
110
+ }
111
+ const fresh = inputs.slice(stored.length).map((input, offset) => validated(input, log.lastSeq + 1 + offset));
112
+ for (const [offset, entry] of fresh.entries()) {
113
+ const first = log.lastSeq < 0 && offset === 0;
114
+ if (first !== (entry.type === "session_header")) {
115
+ invalidEntry(first
116
+ ? "a session's first entry must be a session_header"
117
+ : "only a session's first entry may be a session_header");
118
+ }
119
+ const bytes = entryBytes(entry);
120
+ if (bytes > maxBytes)
121
+ throw new EntryTooLargeError(entry.id, bytes, maxBytes);
122
+ }
123
+ return { result: [...stored, ...fresh], fresh };
124
+ }
125
+ /** The state after `fresh` was written, which extends the map in place, so an append costs the batch and not the log. */
126
+ export function extendState(state, fresh) {
127
+ for (const entry of fresh)
128
+ state.byId.set(entry.id, entry);
129
+ const last = fresh.at(-1);
130
+ return last === undefined ? state : { byId: state.byId, lastId: last.id, lastSeq: last.seq };
131
+ }
132
+ /** The log's state after `entries`, a copy that a backend can keep. */
133
+ export function stateOf(entries) {
134
+ const last = entries.at(-1);
135
+ return {
136
+ byId: new Map(entries.map((entry) => [entry.id, entry])),
137
+ lastId: last?.id ?? null,
138
+ lastSeq: last?.seq ?? -1,
139
+ };
140
+ }
141
+ /** A summary from a log's entries, or `undefined` for a log with no header. */
142
+ export function summaryOf(sessionId, entries) {
143
+ const header = entries[0];
144
+ const last = entries.at(-1);
145
+ if (header?.type !== "session_header" || last === undefined)
146
+ return undefined;
147
+ return {
148
+ sessionId,
149
+ startedAt: header.timestamp,
150
+ lastEntryAt: last.timestamp,
151
+ entryCount: entries.length,
152
+ harnessVersion: header.harnessVersion,
153
+ sdkVersion: header.sdkVersion,
154
+ ...(header.parent === undefined ? {} : { parent: header.parent }),
155
+ ...(header.spawn === undefined ? {} : { spawn: header.spawn }),
156
+ ...(header.product === undefined ? {} : { product: header.product }),
157
+ };
158
+ }
159
+ /** The order `list()` uses: oldest first, then by id. */
160
+ export function byAge(a, b) {
161
+ return a.startedAt === b.startedAt ? a.sessionId.localeCompare(b.sessionId) : a.startedAt.localeCompare(b.startedAt);
162
+ }
163
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/session/store.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAA8C,MAAM,wBAAwB,CAAC;AAChG,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEhE,uDAAuD;AACvD,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,GAAG,IAAI,CAAC;AACjD,MAAM,YAAY,GAAG,EAAE,CAAC;AAwExB;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,OAAO,CAAC,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;SACvC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACZ,MAAM,IAAI,GAAG,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QACvC,OAAO,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;IACjG,CAAC,CAAC;SACD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B;;;GAGG;AACH,MAAM,UAAU,QAAQ,CAAC,GAAe;IACtC,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,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AAI,MAAM,EAAE,IAAI,KAAK,gBAAgB,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC9E,OAAO;QACL,SAAS;QACT,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,WAAW,EAAE,IAAI,CAAC,SAAS;QAC3B,UAAU,EAAE,OAAO,CAAC,MAAM;QAC1B,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,GAAG,CAAC,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC;QACjE,GAAG,CAAC,MAAM,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;QAC9D,GAAG,CAAC,MAAM,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;KACrE,CAAC;AACJ,CAAC;AAED,yDAAyD;AACzD,MAAM,UAAU,KAAK,CAAC,CAAiB,EAAE,CAAiB;IACxD,OAAO,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AACvH,CAAC","sourcesContent":["/**\n * The session store's interface and the rules every backend shares. A session belongs to a user: every method names\n * the user, and a session under another user looks exactly like one that doesn't exist, so no caller can forget the\n * owner check. `planAppend()` holds the append rules once, so the memory and JSONL backends cannot drift apart.\n */\nimport { parseEntry, type SessionEntry, type SessionHeaderEntry } from \"@buildanagent/protocol\";\nimport { HarnessError } from \"../errors.js\";\nimport { ConflictError, EntryTooLargeError } from \"./errors.js\";\n\n/** The default bound on one entry's JSON, in bytes. */\nexport const DEFAULT_MAX_ENTRY_BYTES = 64 * 1024;\nconst MAX_KEY_PART = 64;\n\n/** Which session: its user and its id. No method finds a session by its id alone. */\nexport interface SessionKey {\n readonly userId: string;\n readonly sessionId: string;\n}\n\ntype OmitSeq<T> = T extends unknown ? Omit<T, \"seq\"> : never;\n\n/** An entry as a caller writes it. The store assigns `seq`, so the caller never has to count. */\nexport type EntryInput = OmitSeq<SessionEntry>;\n\n/** What `list()` says about a session, read from its header and its last entry. */\nexport interface SessionSummary {\n readonly sessionId: string;\n /** The header's timestamp. */\n readonly startedAt: string;\n /** The timestamp of the last entry. */\n readonly lastEntryAt: string;\n readonly entryCount: number;\n readonly harnessVersion: string;\n readonly sdkVersion: string;\n readonly parent?: SessionHeaderEntry[\"parent\"];\n /** Set on a spawned subagent or workflow step, whose `parent` is the session that started it and not a fork point. */\n readonly spawn?: SessionHeaderEntry[\"spawn\"];\n readonly product?: SessionHeaderEntry[\"product\"];\n}\n\n/** The options of `append()`. */\nexport interface AppendOptions {\n /**\n * The id of the entry the log must end with, or `null` for a session that doesn't exist yet. A different tail throws\n * a `ConflictError` and writes nothing, so two writers can't both extend the same log. A batch that is already\n * stored, in whole or in part, is a retry and skips this check. A partly stored batch still throws a `ConflictError`\n * if its stored part is no longer the end of the log.\n */\n readonly expectedLastId?: string | null;\n}\n\n/** The options of `load()`. */\nexport interface LoadOptions {\n /** The first sequence number to yield. Default 0. */\n readonly fromSeq?: number;\n /** Called once if the log ends in a line that was never completed, which `load()` skips. */\n readonly onTornLine?: (line: { readonly bytes: number }) => void;\n}\n\n/** Where a session's entries live. Every method names the user. */\nexport interface SessionStore {\n /**\n * Appends entries, assigns each its `seq` and returns them as stored. It is idempotent by entry id: an entry already\n * stored with the same content is not written again, and one stored with different content throws a\n * `ConflictError`. A new session's first entry must be a `session_header`. It throws an `EntryTooLargeError` above\n * the size bound, a `ConflictError` when `expectedLastId` is stale, and a `HarnessError` for an entry that is not\n * valid. A failed append writes none of its batch.\n */\n append(key: SessionKey, entries: readonly EntryInput[], options?: AppendOptions): Promise<SessionEntry[]>;\n /** The entries from `fromSeq` on, in order. A session that doesn't exist, or belongs to another user, yields none. */\n load(key: SessionKey, options?: LoadOptions): AsyncIterable<SessionEntry>;\n /** The user's sessions only, oldest first. */\n list(userId: string): AsyncIterable<SessionSummary>;\n /** Deletes the session. A session that doesn't exist, or belongs to another user, is left alone and is no error. */\n delete(key: SessionKey): Promise<void>;\n /**\n * The entries as they were written, without the protocol's format check, so a migration can read a log from a format\n * this harness no longer reads. A store that can't leave the check out doesn't offer this method, and `migrateSession()` refuses to migrate a session\n * in such a store.\n */\n loadRaw?(key: SessionKey): AsyncIterable<unknown>;\n}\n\n/**\n * A user or session id as a file name: every byte outside `[a-z0-9_-]` becomes `%XX`, capital letters and dots\n * included, so no id can name `..`, climb out of its folder, or collide with another id on a file system that ignores case.\n */\nexport function encodeName(part: string): string {\n return [...new TextEncoder().encode(part)]\n .map((byte) => {\n const char = String.fromCharCode(byte);\n return /[a-z0-9_-]/.test(char) ? char : `%${byte.toString(16).toUpperCase().padStart(2, \"0\")}`;\n })\n .join(\"\");\n}\n\nconst MAX_NAME_BYTES = 200;\n\n/**\n * Throws a `HarnessError` with code `invalid_session_key` unless `userId` and `sessionId` are each 1 to 64 characters\n * with no control characters or lone surrogates and fit in a file name once encoded. Both backends apply this rule.\n */\nexport function checkKey(key: SessionKey): void {\n for (const [label, value] of [\n [\"userId\", key?.userId],\n [\"sessionId\", key?.sessionId],\n ] as const) {\n if (\n typeof value !== \"string\" ||\n value === \"\" ||\n [...value].length > MAX_KEY_PART ||\n !value.isWellFormed() ||\n [...value].some((char) => char.charCodeAt(0) < 32) ||\n encodeName(value).length > MAX_NAME_BYTES\n ) {\n throw new HarnessError(\n \"invalid_session_key\",\n `a session ${label} must be 1 to ${MAX_KEY_PART} characters with no control characters or lone surrogates, and fit in a file name once encoded`,\n );\n }\n }\n}\n\n/** The log as a backend holds it: its entries by id, and where it ends. */\nexport interface LogState {\n readonly byId: Map<string, SessionEntry>;\n readonly lastId: string | null;\n readonly lastSeq: number;\n}\n\n// Key order and `undefined` fields must not make two equal entries look different.\nfunction stable(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stable).join(\",\")}]`;\n if (typeof value !== \"object\" || value === null) return JSON.stringify(value) ?? \"null\";\n const record = value as Record<string, unknown>;\n const fields = Object.keys(record)\n .filter((name) => record[name] !== undefined)\n .sort()\n .map((name) => `${JSON.stringify(name)}:${stable(record[name])}`);\n return `{${fields.join(\",\")}}`;\n}\n\nconst sameContent = (a: SessionEntry, b: SessionEntry): boolean => {\n const { seq: _a, ...left } = a;\n const { seq: _b, ...right } = b;\n return stable(left) === stable(right);\n};\n\n/** The bytes of an entry's JSON, which is what the size bound counts. */\nfunction entryBytes(entry: SessionEntry): number {\n return new TextEncoder().encode(JSON.stringify(entry)).length;\n}\n\nfunction invalidEntry(why: string, cause?: unknown): never {\n throw new HarnessError(\"invalid_session_entry\", why, cause === undefined ? undefined : { cause });\n}\n\n/** Validates an entry with its assigned `seq`, through the protocol's own parser. */\nfunction validated(input: EntryInput, seq: number): SessionEntry {\n try {\n return parseEntry(structuredClone({ ...input, seq }));\n } catch (cause) {\n return invalidEntry(`an entry is not valid: ${cause instanceof Error ? cause.message : String(cause)}`, cause);\n }\n}\n\n/** The entries of a batch that are already stored. They must be the batch's first entries, in order, and equal. */\nfunction storedPrefix(log: LogState, inputs: readonly EntryInput[]): SessionEntry[] {\n const stored: SessionEntry[] = [];\n for (const [index, input] of inputs.entries()) {\n const existing = log.byId.get(input.id);\n if (existing === undefined) {\n if (inputs.slice(index + 1).some((later) => log.byId.has(later.id))) {\n throw new ConflictError(\"a batch is partly stored, and not as its first entries\");\n }\n break;\n }\n // The stored entry went through the protocol parser, so the retry does too, or a normalised field would differ.\n if (!sameContent(existing, validated(input, existing.seq))) {\n throw new ConflictError(`entry \"${input.id}\" is already stored with different content`);\n }\n stored.push(existing);\n }\n return stored;\n}\n\n/** What an append will do: the entries it returns, and the ones to write. */\nexport interface AppendPlan {\n readonly result: SessionEntry[];\n readonly fresh: SessionEntry[];\n}\n\n/**\n * Applies the append rules to a log and a batch, without writing: idempotency by id, the expected tail, the header\n * first, validation and the size bound. Throws before anything is written, so a backend writes `fresh` or nothing.\n */\nexport function planAppend(\n log: LogState,\n inputs: readonly EntryInput[],\n options: AppendOptions | undefined,\n maxBytes: number,\n): AppendPlan {\n if (new Set(inputs.map((input) => input.id)).size !== inputs.length) invalidEntry(\"a batch repeats an entry id\");\n const stored = storedPrefix(log, inputs);\n if (stored.length > 0 && stored.length < inputs.length && stored.at(-1)?.id !== log.lastId) {\n throw new ConflictError(\"the stored part of this batch is no longer the end of the log\");\n }\n if (stored.length === 0 && options?.expectedLastId !== undefined && options.expectedLastId !== log.lastId) {\n throw new ConflictError(\n `the log ends at ${JSON.stringify(log.lastId)}, not ${JSON.stringify(options.expectedLastId)}`,\n );\n }\n const fresh = inputs.slice(stored.length).map((input, offset) => validated(input, log.lastSeq + 1 + offset));\n for (const [offset, entry] of fresh.entries()) {\n const first = log.lastSeq < 0 && offset === 0;\n if (first !== (entry.type === \"session_header\")) {\n invalidEntry(\n first\n ? \"a session's first entry must be a session_header\"\n : \"only a session's first entry may be a session_header\",\n );\n }\n const bytes = entryBytes(entry);\n if (bytes > maxBytes) throw new EntryTooLargeError(entry.id, bytes, maxBytes);\n }\n return { result: [...stored, ...fresh], fresh };\n}\n\n/** The state after `fresh` was written, which extends the map in place, so an append costs the batch and not the log. */\nexport function extendState(state: LogState, fresh: readonly SessionEntry[]): LogState {\n for (const entry of fresh) state.byId.set(entry.id, entry);\n const last = fresh.at(-1);\n return last === undefined ? state : { byId: state.byId, lastId: last.id, lastSeq: last.seq };\n}\n\n/** The log's state after `entries`, a copy that a backend can keep. */\nexport function stateOf(entries: readonly SessionEntry[]): LogState {\n const last = entries.at(-1);\n return {\n byId: new Map(entries.map((entry) => [entry.id, entry])),\n lastId: last?.id ?? null,\n lastSeq: last?.seq ?? -1,\n };\n}\n\n/** A summary from a log's entries, or `undefined` for a log with no header. */\nexport function summaryOf(sessionId: string, entries: readonly SessionEntry[]): SessionSummary | undefined {\n const header = entries[0];\n const last = entries.at(-1);\n if (header?.type !== \"session_header\" || last === undefined) return undefined;\n return {\n sessionId,\n startedAt: header.timestamp,\n lastEntryAt: last.timestamp,\n entryCount: entries.length,\n harnessVersion: header.harnessVersion,\n sdkVersion: header.sdkVersion,\n ...(header.parent === undefined ? {} : { parent: header.parent }),\n ...(header.spawn === undefined ? {} : { spawn: header.spawn }),\n ...(header.product === undefined ? {} : { product: header.product }),\n };\n}\n\n/** The order `list()` uses: oldest first, then by id. */\nexport function byAge(a: SessionSummary, b: SessionSummary): number {\n return a.startedAt === b.startedAt ? a.sessionId.localeCompare(b.sessionId) : a.startedAt.localeCompare(b.startedAt);\n}\n"]}
@@ -0,0 +1,2 @@
1
+ /** `@buildanagent/harness/telemetry`: a stub that holds the entry's place until its component is built. */
2
+ export {};
@@ -0,0 +1,3 @@
1
+ /** `@buildanagent/harness/telemetry`: a stub that holds the entry's place until its component is built. */
2
+ export {};
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/telemetry/index.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,OAAO,EAAE,CAAC","sourcesContent":["/** `@buildanagent/harness/telemetry`: a stub that holds the entry's place until its component is built. */\nexport {};\n"]}
@@ -0,0 +1,34 @@
1
+ import type { SandboxClient } from "../sandbox/types.js";
2
+ /** The options of `fakeSandbox()`. */
3
+ export interface FakeSandboxOptions {
4
+ /** Makes `provision()` throw `SandboxUnavailableError` with this reason, as a backend that can't start does. */
5
+ readonly unavailable?: string;
6
+ }
7
+ /** One command the fake received, with what the caller passed. */
8
+ export interface RecordedExec {
9
+ readonly command: readonly string[];
10
+ readonly cwd: string | undefined;
11
+ readonly env: Readonly<Record<string, string>>;
12
+ readonly timeoutMs: number | undefined;
13
+ }
14
+ /** A fake backend, and what it has seen. */
15
+ export interface FakeSandboxClient extends SandboxClient {
16
+ /** Every command run through any sandbox this client provisioned, in order. */
17
+ readonly execs: readonly RecordedExec[];
18
+ /** The files of the latest sandbox, by absolute path. */
19
+ files(): ReadonlyMap<string, Uint8Array>;
20
+ /** Makes `link` an absolute path that stands for `target` in the latest sandbox, as a symlink does. */
21
+ symlink(link: string, target: string): void;
22
+ }
23
+ /**
24
+ * The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the
25
+ * environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,
26
+ * `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and
27
+ * `net-probe <host>` reaches a host only if the policy allows it. Any other command exits with 127.
28
+ */
29
+ export declare const FAKE_COMMANDS: readonly string[];
30
+ /**
31
+ * Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the
32
+ * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none.
33
+ */
34
+ export declare function fakeSandbox(options?: FakeSandboxOptions): FakeSandboxClient;