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

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 (397) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +822 -2
  5. package/dist/ablation.d.ts +2 -0
  6. package/dist/ablation.js +3 -0
  7. package/dist/ablation.js.map +1 -0
  8. package/dist/completion/check.d.ts +64 -0
  9. package/dist/completion/check.js +152 -0
  10. package/dist/completion/check.js.map +1 -0
  11. package/dist/completion/checks.d.ts +45 -0
  12. package/dist/completion/checks.js +173 -0
  13. package/dist/completion/checks.js.map +1 -0
  14. package/dist/completion/flags.d.ts +25 -0
  15. package/dist/completion/flags.js +87 -0
  16. package/dist/completion/flags.js.map +1 -0
  17. package/dist/completion/index.d.ts +8 -0
  18. package/dist/completion/index.js +9 -0
  19. package/dist/completion/index.js.map +1 -0
  20. package/dist/completion/snapshot.d.ts +33 -0
  21. package/dist/completion/snapshot.js +83 -0
  22. package/dist/completion/snapshot.js.map +1 -0
  23. package/dist/context/cap.d.ts +32 -0
  24. package/dist/context/cap.js +50 -0
  25. package/dist/context/cap.js.map +1 -0
  26. package/dist/context/estimate.d.ts +18 -0
  27. package/dist/context/estimate.js +20 -0
  28. package/dist/context/estimate.js.map +1 -0
  29. package/dist/context/file-spill.d.ts +15 -0
  30. package/dist/context/file-spill.js +40 -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 +10 -0
  48. package/dist/context/spill.js +18 -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 +54 -0
  69. package/dist/credentials/allowlist.js +134 -0
  70. package/dist/credentials/allowlist.js.map +1 -0
  71. package/dist/credentials/egress-policy.d.ts +69 -0
  72. package/dist/credentials/egress-policy.js +170 -0
  73. package/dist/credentials/egress-policy.js.map +1 -0
  74. package/dist/credentials/egress-proxy.d.ts +82 -0
  75. package/dist/credentials/egress-proxy.js +650 -0
  76. package/dist/credentials/egress-proxy.js.map +1 -0
  77. package/dist/credentials/git-route.d.ts +68 -0
  78. package/dist/credentials/git-route.js +288 -0
  79. package/dist/credentials/git-route.js.map +1 -0
  80. package/dist/credentials/index.d.ts +13 -0
  81. package/dist/credentials/index.js +14 -0
  82. package/dist/credentials/index.js.map +1 -0
  83. package/dist/credentials/scrub.d.ts +23 -0
  84. package/dist/credentials/scrub.js +115 -0
  85. package/dist/credentials/scrub.js.map +1 -0
  86. package/dist/errors.d.ts +60 -0
  87. package/dist/errors.js +67 -0
  88. package/dist/errors.js.map +1 -0
  89. package/dist/extensions/compose.d.ts +27 -0
  90. package/dist/extensions/compose.js +83 -0
  91. package/dist/extensions/compose.js.map +1 -0
  92. package/dist/extensions/context-files-node.d.ts +28 -0
  93. package/dist/extensions/context-files-node.js +74 -0
  94. package/dist/extensions/context-files-node.js.map +1 -0
  95. package/dist/extensions/context-files.d.ts +68 -0
  96. package/dist/extensions/context-files.js +214 -0
  97. package/dist/extensions/context-files.js.map +1 -0
  98. package/dist/extensions/digest.d.ts +6 -0
  99. package/dist/extensions/digest.js +68 -0
  100. package/dist/extensions/digest.js.map +1 -0
  101. package/dist/extensions/index.d.ts +10 -0
  102. package/dist/extensions/index.js +10 -0
  103. package/dist/extensions/index.js.map +1 -0
  104. package/dist/extensions/load.d.ts +42 -0
  105. package/dist/extensions/load.js +211 -0
  106. package/dist/extensions/load.js.map +1 -0
  107. package/dist/extensions/lock.d.ts +8 -0
  108. package/dist/extensions/lock.js +95 -0
  109. package/dist/extensions/lock.js.map +1 -0
  110. package/dist/extensions/node.d.ts +10 -0
  111. package/dist/extensions/node.js +11 -0
  112. package/dist/extensions/node.js.map +1 -0
  113. package/dist/extensions/project-dirs.d.ts +24 -0
  114. package/dist/extensions/project-dirs.js +97 -0
  115. package/dist/extensions/project-dirs.js.map +1 -0
  116. package/dist/extensions/skills-node.d.ts +34 -0
  117. package/dist/extensions/skills-node.js +123 -0
  118. package/dist/extensions/skills-node.js.map +1 -0
  119. package/dist/extensions/skills.d.ts +51 -0
  120. package/dist/extensions/skills.js +175 -0
  121. package/dist/extensions/skills.js.map +1 -0
  122. package/dist/extensions/trust-file.d.ts +3 -0
  123. package/dist/extensions/trust-file.js +62 -0
  124. package/dist/extensions/trust-file.js.map +1 -0
  125. package/dist/extensions/trust-store-node.d.ts +10 -0
  126. package/dist/extensions/trust-store-node.js +33 -0
  127. package/dist/extensions/trust-store-node.js.map +1 -0
  128. package/dist/extensions/types.d.ts +42 -0
  129. package/dist/extensions/types.js +2 -0
  130. package/dist/extensions/types.js.map +1 -0
  131. package/dist/harness.d.ts +156 -0
  132. package/dist/harness.js +2 -0
  133. package/dist/harness.js.map +1 -0
  134. package/dist/index.d.ts +4 -0
  135. package/dist/index.js +5 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/mcp/connection.d.ts +22 -0
  138. package/dist/mcp/connection.js +267 -0
  139. package/dist/mcp/connection.js.map +1 -0
  140. package/dist/mcp/content.d.ts +27 -0
  141. package/dist/mcp/content.js +177 -0
  142. package/dist/mcp/content.js.map +1 -0
  143. package/dist/mcp/errors.d.ts +19 -0
  144. package/dist/mcp/errors.js +21 -0
  145. package/dist/mcp/errors.js.map +1 -0
  146. package/dist/mcp/index.d.ts +10 -0
  147. package/dist/mcp/index.js +10 -0
  148. package/dist/mcp/index.js.map +1 -0
  149. package/dist/mcp/manager.d.ts +7 -0
  150. package/dist/mcp/manager.js +173 -0
  151. package/dist/mcp/manager.js.map +1 -0
  152. package/dist/mcp/record.d.ts +7 -0
  153. package/dist/mcp/record.js +20 -0
  154. package/dist/mcp/record.js.map +1 -0
  155. package/dist/mcp/stdio.d.ts +39 -0
  156. package/dist/mcp/stdio.js +382 -0
  157. package/dist/mcp/stdio.js.map +1 -0
  158. package/dist/mcp/types.d.ts +172 -0
  159. package/dist/mcp/types.js +2 -0
  160. package/dist/mcp/types.js.map +1 -0
  161. package/dist/memory/index.d.ts +2 -0
  162. package/dist/memory/index.js +3 -0
  163. package/dist/memory/index.js.map +1 -0
  164. package/dist/permissions/default-rules.d.ts +7 -0
  165. package/dist/permissions/default-rules.js +42 -0
  166. package/dist/permissions/default-rules.js.map +1 -0
  167. package/dist/permissions/errors.d.ts +11 -0
  168. package/dist/permissions/errors.js +14 -0
  169. package/dist/permissions/errors.js.map +1 -0
  170. package/dist/permissions/index.d.ts +9 -0
  171. package/dist/permissions/index.js +9 -0
  172. package/dist/permissions/index.js.map +1 -0
  173. package/dist/permissions/match.d.ts +33 -0
  174. package/dist/permissions/match.js +287 -0
  175. package/dist/permissions/match.js.map +1 -0
  176. package/dist/permissions/pipeline.d.ts +9 -0
  177. package/dist/permissions/pipeline.js +235 -0
  178. package/dist/permissions/pipeline.js.map +1 -0
  179. package/dist/permissions/rules.d.ts +22 -0
  180. package/dist/permissions/rules.js +74 -0
  181. package/dist/permissions/rules.js.map +1 -0
  182. package/dist/permissions/shadow.d.ts +5 -0
  183. package/dist/permissions/shadow.js +22 -0
  184. package/dist/permissions/shadow.js.map +1 -0
  185. package/dist/permissions/types.d.ts +104 -0
  186. package/dist/permissions/types.js +2 -0
  187. package/dist/permissions/types.js.map +1 -0
  188. package/dist/sandbox/base.d.ts +45 -0
  189. package/dist/sandbox/base.js +74 -0
  190. package/dist/sandbox/base.js.map +1 -0
  191. package/dist/sandbox/docker/index.d.ts +41 -0
  192. package/dist/sandbox/docker/index.js +497 -0
  193. package/dist/sandbox/docker/index.js.map +1 -0
  194. package/dist/sandbox/errors.d.ts +44 -0
  195. package/dist/sandbox/errors.js +57 -0
  196. package/dist/sandbox/errors.js.map +1 -0
  197. package/dist/sandbox/host-files.d.ts +65 -0
  198. package/dist/sandbox/host-files.js +258 -0
  199. package/dist/sandbox/host-files.js.map +1 -0
  200. package/dist/sandbox/index.d.ts +10 -0
  201. package/dist/sandbox/index.js +10 -0
  202. package/dist/sandbox/index.js.map +1 -0
  203. package/dist/sandbox/none.d.ts +17 -0
  204. package/dist/sandbox/none.js +108 -0
  205. package/dist/sandbox/none.js.map +1 -0
  206. package/dist/sandbox/policy.d.ts +49 -0
  207. package/dist/sandbox/policy.js +149 -0
  208. package/dist/sandbox/policy.js.map +1 -0
  209. package/dist/sandbox/process.d.ts +61 -0
  210. package/dist/sandbox/process.js +253 -0
  211. package/dist/sandbox/process.js.map +1 -0
  212. package/dist/sandbox/spawn-env.d.ts +20 -0
  213. package/dist/sandbox/spawn-env.js +128 -0
  214. package/dist/sandbox/spawn-env.js.map +1 -0
  215. package/dist/sandbox/srt/index.d.ts +38 -0
  216. package/dist/sandbox/srt/index.js +283 -0
  217. package/dist/sandbox/srt/index.js.map +1 -0
  218. package/dist/sandbox/srt/settings.d.ts +60 -0
  219. package/dist/sandbox/srt/settings.js +84 -0
  220. package/dist/sandbox/srt/settings.js.map +1 -0
  221. package/dist/sandbox/types.d.ts +125 -0
  222. package/dist/sandbox/types.js +6 -0
  223. package/dist/sandbox/types.js.map +1 -0
  224. package/dist/server/answers.d.ts +16 -0
  225. package/dist/server/answers.js +43 -0
  226. package/dist/server/answers.js.map +1 -0
  227. package/dist/server/connection.d.ts +99 -0
  228. package/dist/server/connection.js +309 -0
  229. package/dist/server/connection.js.map +1 -0
  230. package/dist/server/dispatcher.d.ts +86 -0
  231. package/dist/server/dispatcher.js +800 -0
  232. package/dist/server/dispatcher.js.map +1 -0
  233. package/dist/server/index.d.ts +13 -0
  234. package/dist/server/index.js +12 -0
  235. package/dist/server/index.js.map +1 -0
  236. package/dist/server/local-transport.d.ts +44 -0
  237. package/dist/server/local-transport.js +103 -0
  238. package/dist/server/local-transport.js.map +1 -0
  239. package/dist/server/outbox.d.ts +31 -0
  240. package/dist/server/outbox.js +130 -0
  241. package/dist/server/outbox.js.map +1 -0
  242. package/dist/server/params.d.ts +25 -0
  243. package/dist/server/params.js +112 -0
  244. package/dist/server/params.js.map +1 -0
  245. package/dist/server/protocol.schema.json +2448 -0
  246. package/dist/server/rpc-session.d.ts +43 -0
  247. package/dist/server/rpc-session.js +167 -0
  248. package/dist/server/rpc-session.js.map +1 -0
  249. package/dist/server/stdio-streams.d.ts +67 -0
  250. package/dist/server/stdio-streams.js +218 -0
  251. package/dist/server/stdio-streams.js.map +1 -0
  252. package/dist/server/stdio.d.ts +59 -0
  253. package/dist/server/stdio.js +189 -0
  254. package/dist/server/stdio.js.map +1 -0
  255. package/dist/server/websocket.d.ts +106 -0
  256. package/dist/server/websocket.js +327 -0
  257. package/dist/server/websocket.js.map +1 -0
  258. package/dist/session/approvals.d.ts +81 -0
  259. package/dist/session/approvals.js +217 -0
  260. package/dist/session/approvals.js.map +1 -0
  261. package/dist/session/code-call-log.d.ts +42 -0
  262. package/dist/session/code-call-log.js +63 -0
  263. package/dist/session/code-call-log.js.map +1 -0
  264. package/dist/session/code-call-result.d.ts +19 -0
  265. package/dist/session/code-call-result.js +95 -0
  266. package/dist/session/code-call-result.js.map +1 -0
  267. package/dist/session/code-call.d.ts +49 -0
  268. package/dist/session/code-call.js +345 -0
  269. package/dist/session/code-call.js.map +1 -0
  270. package/dist/session/effect-scope.d.ts +11 -0
  271. package/dist/session/effect-scope.js +10 -0
  272. package/dist/session/effect-scope.js.map +1 -0
  273. package/dist/session/errors.d.ts +19 -0
  274. package/dist/session/errors.js +27 -0
  275. package/dist/session/errors.js.map +1 -0
  276. package/dist/session/file-index.d.ts +8 -0
  277. package/dist/session/file-index.js +70 -0
  278. package/dist/session/file-index.js.map +1 -0
  279. package/dist/session/file-key-store.d.ts +16 -0
  280. package/dist/session/file-key-store.js +169 -0
  281. package/dist/session/file-key-store.js.map +1 -0
  282. package/dist/session/file-lock.d.ts +52 -0
  283. package/dist/session/file-lock.js +324 -0
  284. package/dist/session/file-lock.js.map +1 -0
  285. package/dist/session/index.d.ts +22 -0
  286. package/dist/session/index.js +20 -0
  287. package/dist/session/index.js.map +1 -0
  288. package/dist/session/jsonl-store.d.ts +37 -0
  289. package/dist/session/jsonl-store.js +386 -0
  290. package/dist/session/jsonl-store.js.map +1 -0
  291. package/dist/session/jsonl.d.ts +9 -0
  292. package/dist/session/jsonl.js +10 -0
  293. package/dist/session/jsonl.js.map +1 -0
  294. package/dist/session/lock.d.ts +19 -0
  295. package/dist/session/lock.js +2 -0
  296. package/dist/session/lock.js.map +1 -0
  297. package/dist/session/memory-store.d.ts +12 -0
  298. package/dist/session/memory-store.js +60 -0
  299. package/dist/session/memory-store.js.map +1 -0
  300. package/dist/session/migrate.d.ts +41 -0
  301. package/dist/session/migrate.js +86 -0
  302. package/dist/session/migrate.js.map +1 -0
  303. package/dist/session/pointer.d.ts +15 -0
  304. package/dist/session/pointer.js +22 -0
  305. package/dist/session/pointer.js.map +1 -0
  306. package/dist/session/rebuild.d.ts +53 -0
  307. package/dist/session/rebuild.js +230 -0
  308. package/dist/session/rebuild.js.map +1 -0
  309. package/dist/session/resume.d.ts +26 -0
  310. package/dist/session/resume.js +128 -0
  311. package/dist/session/resume.js.map +1 -0
  312. package/dist/session/retention.d.ts +97 -0
  313. package/dist/session/retention.js +702 -0
  314. package/dist/session/retention.js.map +1 -0
  315. package/dist/session/runner.d.ts +156 -0
  316. package/dist/session/runner.js +656 -0
  317. package/dist/session/runner.js.map +1 -0
  318. package/dist/session/scheduler.d.ts +47 -0
  319. package/dist/session/scheduler.js +85 -0
  320. package/dist/session/scheduler.js.map +1 -0
  321. package/dist/session/secret-key-store.d.ts +47 -0
  322. package/dist/session/secret-key-store.js +79 -0
  323. package/dist/session/secret-key-store.js.map +1 -0
  324. package/dist/session/session.d.ts +106 -0
  325. package/dist/session/session.js +353 -0
  326. package/dist/session/session.js.map +1 -0
  327. package/dist/session/sticky.d.ts +48 -0
  328. package/dist/session/sticky.js +232 -0
  329. package/dist/session/sticky.js.map +1 -0
  330. package/dist/session/store.d.ts +108 -0
  331. package/dist/session/store.js +163 -0
  332. package/dist/session/store.js.map +1 -0
  333. package/dist/telemetry/index.d.ts +2 -0
  334. package/dist/telemetry/index.js +3 -0
  335. package/dist/telemetry/index.js.map +1 -0
  336. package/dist/testing/fake-sandbox.d.ts +52 -0
  337. package/dist/testing/fake-sandbox.js +370 -0
  338. package/dist/testing/fake-sandbox.js.map +1 -0
  339. package/dist/testing/index.d.ts +10 -0
  340. package/dist/testing/index.js +11 -0
  341. package/dist/testing/index.js.map +1 -0
  342. package/dist/testing/key-store-conformance.d.ts +22 -0
  343. package/dist/testing/key-store-conformance.js +97 -0
  344. package/dist/testing/key-store-conformance.js.map +1 -0
  345. package/dist/testing/run-cases.d.ts +21 -0
  346. package/dist/testing/run-cases.js +20 -0
  347. package/dist/testing/run-cases.js.map +1 -0
  348. package/dist/testing/sandbox-conformance.d.ts +64 -0
  349. package/dist/testing/sandbox-conformance.js +468 -0
  350. package/dist/testing/sandbox-conformance.js.map +1 -0
  351. package/dist/testing/scheduler-conformance.d.ts +32 -0
  352. package/dist/testing/scheduler-conformance.js +72 -0
  353. package/dist/testing/scheduler-conformance.js.map +1 -0
  354. package/dist/testing/store-conformance.d.ts +21 -0
  355. package/dist/testing/store-conformance.js +320 -0
  356. package/dist/testing/store-conformance.js.map +1 -0
  357. package/dist/tools/builtins/bash.d.ts +9 -0
  358. package/dist/tools/builtins/bash.js +75 -0
  359. package/dist/tools/builtins/bash.js.map +1 -0
  360. package/dist/tools/builtins/builtins.d.ts +38 -0
  361. package/dist/tools/builtins/builtins.js +48 -0
  362. package/dist/tools/builtins/builtins.js.map +1 -0
  363. package/dist/tools/builtins/descriptions.d.ts +69 -0
  364. package/dist/tools/builtins/descriptions.js +94 -0
  365. package/dist/tools/builtins/descriptions.js.map +1 -0
  366. package/dist/tools/builtins/fetch.d.ts +12 -0
  367. package/dist/tools/builtins/fetch.js +157 -0
  368. package/dist/tools/builtins/fetch.js.map +1 -0
  369. package/dist/tools/builtins/files.d.ts +27 -0
  370. package/dist/tools/builtins/files.js +274 -0
  371. package/dist/tools/builtins/files.js.map +1 -0
  372. package/dist/tools/builtins/paths.d.ts +30 -0
  373. package/dist/tools/builtins/paths.js +62 -0
  374. package/dist/tools/builtins/paths.js.map +1 -0
  375. package/dist/tools/builtins/results.d.ts +15 -0
  376. package/dist/tools/builtins/results.js +31 -0
  377. package/dist/tools/builtins/results.js.map +1 -0
  378. package/dist/tools/builtins/search.d.ts +18 -0
  379. package/dist/tools/builtins/search.js +217 -0
  380. package/dist/tools/builtins/search.js.map +1 -0
  381. package/dist/tools/errors.d.ts +13 -0
  382. package/dist/tools/errors.js +17 -0
  383. package/dist/tools/errors.js.map +1 -0
  384. package/dist/tools/index.d.ts +12 -0
  385. package/dist/tools/index.js +11 -0
  386. package/dist/tools/index.js.map +1 -0
  387. package/dist/tools/registry.d.ts +3 -0
  388. package/dist/tools/registry.js +234 -0
  389. package/dist/tools/registry.js.map +1 -0
  390. package/dist/tools/tool-search.d.ts +30 -0
  391. package/dist/tools/tool-search.js +118 -0
  392. package/dist/tools/tool-search.js.map +1 -0
  393. package/dist/tools/types.d.ts +106 -0
  394. package/dist/tools/types.js +2 -0
  395. package/dist/tools/types.js.map +1 -0
  396. package/llms.txt +469 -0
  397. package/package.json +118 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flags.js","sourceRoot":"","sources":["../../src/completion/flags.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAUH,sFAAsF;AACtF,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,CAAC;AAE7B,MAAM,WAAW,GAAG,sCAAsC,CAAC;AAC3D,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAChD,MAAM,eAAe,GAAG,kBAAkB,CAAC;AAC3C,MAAM,SAAS,GAAG,iBAAiB,CAAC;AACpC,MAAM,cAAc,GAAG,gCAAgC,CAAC;AACxD,sHAAsH;AACtH,MAAM,SAAS,GAAG,2EAA2E,CAAC;AAC9F,MAAM,SAAS,GAAG,0DAA0D,CAAC;AAC7E,wHAAwH;AACxH,MAAM,SAAS,GAAG,+CAA+C,CAAC;AAClE,MAAM,UAAU,GAAG,EAAE,CAAC;AAEtB,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAU,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;AAEjF;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAA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AAG,KAAK,CAAC,MAAM,GAAG,SAAS,wBAAwB,CAAC,CAAC;AAC7F,CAAC","sourcesContent":["/**\n * The diff flags: patterns in what a turn changed that suggest the checks were gamed instead of met. A flag is a\n * sentence for a person to read, never a verdict, because every pattern has honest causes.\n */\n\n/** What the workspace held at one moment. */\nexport interface WorkspaceSnapshot {\n /** The text of each file, by path relative to the workspace root. */\n readonly files: ReadonlyMap<string, string>;\n /** Paths left out for their size, their encoding or the file cap. The diff ignores them, so none counts as deleted. */\n readonly skipped: ReadonlySet<string>;\n}\n\n/** The most flags one check records. The last entry says how many more there were. */\nexport const MAX_FLAGS = 100;\n\nconst SKIP_MARKER = /\\.skip\\(|\\bxit\\(|@pytest\\.mark\\.skip/;\nconst PLACEHOLDER_MARKER = /\\b(?:TODO|FIXME)\\b/;\nconst NOT_IMPLEMENTED = /not implemented/i;\nconst FAKE_NAME = /mock|stub|fake/i;\nconst TEST_DIRECTORY = /(?:^|\\/)(?:tests?|__tests__)\\//;\n// Only code in a test folder counts, so a fixture or snapshot there (`test/fixtures/sample.json`) is not a test file.\nconst CODE_FILE = /\\.(?:[cm]?[jt]sx?|py|go|rs|java|kt|rb|php|cs|swift|scala|c|cc|cpp|h|hpp)$/;\nconst TEST_NAME = /(?:\\.(?:test|spec)\\.[a-z]+|_test\\.[a-z]+)$|^test_.*\\.py$/;\n// An assertion line: `expect(`, `assert(`, `assert.x(`, `assertEqual(`, `self.assertX(` or a Python `assert` statement.\nconst ASSERTION = /\\bexpect\\s*\\(|\\bassert\\w*\\s*[.(]|^\\s*assert\\s/;\nconst LINE_LIMIT = 80;\n\nconst baseName = (path: string): string => path.slice(path.lastIndexOf(\"/\") + 1);\n\n/**\n * Whether a path looks like a test file: a code file (by its extension, such as `.ts`, `.py` or `.go`) in a `test`,\n * `tests` or `__tests__` folder, or a file named as a test anywhere. A data file in a test folder is not one.\n */\nexport function isTestFile(path: string): boolean {\n return (TEST_DIRECTORY.test(path) && CODE_FILE.test(path)) || TEST_NAME.test(baseName(path));\n}\n\nconst clip = (line: string): string => {\n const text = line.trim();\n return text.length > LINE_LIMIT ? `${text.slice(0, LINE_LIMIT)}...` : text;\n};\n\n/** The lines of `after` that `before` lacks, counting repeats, so a moved line is not an added one. */\nfunction addedLines(before: string, after: string): string[] {\n const seen = new Map<string, number>();\n for (const line of before.split(\"\\n\")) seen.set(line, (seen.get(line) ?? 0) + 1);\n const added: string[] = [];\n for (const line of after.split(\"\\n\")) {\n const left = seen.get(line) ?? 0;\n if (left > 0) seen.set(line, left - 1);\n else added.push(line);\n }\n return added;\n}\n\nconst countAssertions = (text: string): number => text.split(\"\\n\").filter((line) => ASSERTION.test(line)).length;\n\n/** The flags for the lines a modified or new file added: skip markers and placeholders. */\nfunction lineFlags(path: string, before: string | undefined, after: string): string[] {\n const flags: string[] = [];\n for (const line of addedLines(before ?? \"\", after)) {\n if (SKIP_MARKER.test(line)) flags.push(`skip marker added: ${path}: ${clip(line)}`);\n if (PLACEHOLDER_MARKER.test(line) || NOT_IMPLEMENTED.test(line))\n flags.push(`placeholder added: ${path}: ${clip(line)}`);\n }\n return flags;\n}\n\nfunction assertionFlags(path: string, before: string, after: string): string[] {\n if (!isTestFile(path)) return [];\n const was = countAssertions(before);\n const now = countAssertions(after);\n return now < was ? [`fewer assertion lines in ${path}: ${was} before, ${now} after`] : [];\n}\n\nfunction flagsForFile(path: string, before: string | undefined, after: string | undefined): string[] {\n if (after === undefined) return before !== undefined && isTestFile(path) ? [`test file deleted: ${path}`] : [];\n const flags =\n before === undefined && FAKE_NAME.test(baseName(path)) ? [`mock, stub or fake file added: ${path}`] : [];\n flags.push(...lineFlags(path, before, after));\n if (before !== undefined) flags.push(...assertionFlags(path, before, after));\n return flags;\n}\n\n/**\n * Compares the workspace at the start of a turn with the end, and returns one sentence for each pattern the plan names:\n * an added skip marker (`.skip(`, `xit(` or `@pytest.mark.skip`), an added placeholder (`TODO` or `FIXME` in capitals, or\n * \"not implemented\" in any case), a new file whose name has `mock`, `stub` or `fake` in it, a deleted test file, and a test file with\n * fewer assertion lines than before. Paths come out in sorted order, so the same change gives the same flags.\n */\nexport function flagChanges(before: WorkspaceSnapshot, after: WorkspaceSnapshot): string[] {\n const ignored = (path: string): boolean => before.skipped.has(path) || after.skipped.has(path);\n const paths = [...new Set([...before.files.keys(), ...after.files.keys()])].sort().filter((path) => !ignored(path));\n const flags = paths.flatMap((path) => flagsForFile(path, before.files.get(path), after.files.get(path)));\n if (flags.length <= MAX_FLAGS) return flags;\n return [...flags.slice(0, MAX_FLAGS), `${flags.length - MAX_FLAGS} more flags not listed`];\n}\n"]}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The completion check: after a turn ends `done`, run the project's configured or discovered checks in the sandbox,
3
+ * flag diff patterns that game them, and record both as a `completion_check` entry. It never changes the stop reason.
4
+ */
5
+ export { ABORTED_EXIT_CODE, type CompletionOutcome, type CompletionSettings, type CompletionStart, DEFAULT_CHECK_TIMEOUT_MS, DENIED_EXIT_CODE, runCompletionCheck, snapshotStart, } from "./check.js";
6
+ export { type CheckConfig, DISCOVERED_SCRIPTS, HARNESS_CONFIG_PATH, type ResolvedChecks, resolveChecks, } from "./checks.js";
7
+ export { flagChanges, isTestFile, MAX_FLAGS, type WorkspaceSnapshot } from "./flags.js";
8
+ export { gitSnapshotter, MAX_SNAPSHOT_FILE_BYTES, MAX_SNAPSHOT_FILES, SNAPSHOT_TIMEOUT_MS, type SnapshotOptions, type Snapshotter, } from "./snapshot.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The completion check: after a turn ends `done`, run the project's configured or discovered checks in the sandbox,
3
+ * flag diff patterns that game them, and record both as a `completion_check` entry. It never changes the stop reason.
4
+ */
5
+ export { ABORTED_EXIT_CODE, DEFAULT_CHECK_TIMEOUT_MS, DENIED_EXIT_CODE, runCompletionCheck, snapshotStart, } from "./check.js";
6
+ export { DISCOVERED_SCRIPTS, HARNESS_CONFIG_PATH, resolveChecks, } from "./checks.js";
7
+ export { flagChanges, isTestFile, MAX_FLAGS } from "./flags.js";
8
+ export { gitSnapshotter, MAX_SNAPSHOT_FILE_BYTES, MAX_SNAPSHOT_FILES, SNAPSHOT_TIMEOUT_MS, } from "./snapshot.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/completion/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACL,iBAAiB,EAIjB,wBAAwB,EACxB,gBAAgB,EAChB,kBAAkB,EAClB,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EAEL,kBAAkB,EAClB,mBAAmB,EAEnB,aAAa,GACd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAA0B,MAAM,YAAY,CAAC;AACxF,OAAO,EACL,cAAc,EACd,uBAAuB,EACvB,kBAAkB,EAClB,mBAAmB,GAGpB,MAAM,eAAe,CAAC","sourcesContent":["/**\n * The completion check: after a turn ends `done`, run the project's configured or discovered checks in the sandbox,\n * flag diff patterns that game them, and record both as a `completion_check` entry. It never changes the stop reason.\n */\nexport {\n ABORTED_EXIT_CODE,\n type CompletionOutcome,\n type CompletionSettings,\n type CompletionStart,\n DEFAULT_CHECK_TIMEOUT_MS,\n DENIED_EXIT_CODE,\n runCompletionCheck,\n snapshotStart,\n} from \"./check.js\";\nexport {\n type CheckConfig,\n DISCOVERED_SCRIPTS,\n HARNESS_CONFIG_PATH,\n type ResolvedChecks,\n resolveChecks,\n} from \"./checks.js\";\nexport { flagChanges, isTestFile, MAX_FLAGS, type WorkspaceSnapshot } from \"./flags.js\";\nexport {\n gitSnapshotter,\n MAX_SNAPSHOT_FILE_BYTES,\n MAX_SNAPSHOT_FILES,\n SNAPSHOT_TIMEOUT_MS,\n type SnapshotOptions,\n type Snapshotter,\n} from \"./snapshot.js\";\n"]}
@@ -0,0 +1,33 @@
1
+ import type { Sandbox } from "../sandbox/types.js";
2
+ import type { WorkspaceSnapshot } from "./flags.js";
3
+ /** Takes a snapshot, or returns `undefined` when the workspace can't be listed, so no diff flags are raised. */
4
+ export type Snapshotter = (sandbox: Sandbox, options: SnapshotOptions) => Promise<WorkspaceSnapshot | undefined>;
5
+ /** What a snapshotter needs to run a command in the sandbox. */
6
+ export interface SnapshotOptions {
7
+ readonly env: Readonly<Record<string, string>>;
8
+ readonly signal: AbortSignal;
9
+ /**
10
+ * The paths an earlier snapshot of the same workspace held. They are read first and always, so a file that a later
11
+ * listing pushes past the cap, or that no longer appears in it, still has its text; new paths fill what is left of
12
+ * `MAX_SNAPSHOT_FILES`.
13
+ */
14
+ readonly known?: ReadonlySet<string>;
15
+ /** Paths an earlier snapshot skipped. They stay skipped and are not read again. */
16
+ readonly skipped?: ReadonlySet<string>;
17
+ /** The longest the listing, and each file read, may take, in milliseconds. Default `SNAPSHOT_TIMEOUT_MS`. */
18
+ readonly timeoutMs?: number;
19
+ }
20
+ /** How long the listing, and each file read, may take before the snapshot gives up on it. */
21
+ export declare const SNAPSHOT_TIMEOUT_MS: number;
22
+ /** The largest file a snapshot keeps, in bytes. A bigger file is left out of both snapshots, so it is never flagged. */
23
+ export declare const MAX_SNAPSHOT_FILE_BYTES: number;
24
+ /** The most files a snapshot keeps. */
25
+ export declare const MAX_SNAPSHOT_FILES = 5000;
26
+ /**
27
+ * The default snapshotter: every file git tracks or would track (so untracked files that `.gitignore` leaves out stay
28
+ * out), read as UTF-8 text up to `MAX_SNAPSHOT_FILE_BYTES` each and `MAX_SNAPSHOT_FILES` files. A file it leaves out
29
+ * for its size, its encoding or the cap, or that it could not read, goes in `skipped`, and the diff ignores it. Only a
30
+ * read that fails with `sandbox_not_found` counts as a deleted file. The listing and each read stop after `timeoutMs`.
31
+ * It returns `undefined` where `git` is missing, the workspace is no repository, or the listing timed out.
32
+ */
33
+ export declare const gitSnapshotter: Snapshotter;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Snapshots of the workspace's text files, taken inside the sandbox with `git ls-files`, so a turn's changes can be
3
+ * diffed against its start state without a second copy of the workspace.
4
+ */
5
+ import { HarnessError } from "../errors.js";
6
+ /** How long the listing, and each file read, may take before the snapshot gives up on it. */
7
+ export const SNAPSHOT_TIMEOUT_MS = 60 * 1000;
8
+ /** The largest file a snapshot keeps, in bytes. A bigger file is left out of both snapshots, so it is never flagged. */
9
+ export const MAX_SNAPSHOT_FILE_BYTES = 256 * 1024;
10
+ /** The most files a snapshot keeps. */
11
+ export const MAX_SNAPSHOT_FILES = 5000;
12
+ const DECODER = new TextDecoder("utf-8", { fatal: true });
13
+ const BATCH = 32;
14
+ /** Settles with `promise`, or with `fallback` once `ms` pass, so one hung read can't hold up the turn. */
15
+ function within(promise, ms, fallback) {
16
+ let timer;
17
+ const late = new Promise((resolve) => {
18
+ timer = setTimeout(() => resolve(fallback), ms);
19
+ });
20
+ return Promise.race([promise, late]).finally(() => clearTimeout(timer));
21
+ }
22
+ /**
23
+ * The text of a file, `"gone"` for one no longer on disk, or `"skipped"` for one that is binary, not UTF-8, too large,
24
+ * or that could not be read for any other reason (a policy refusal, a sandbox error, a read that timed out).
25
+ */
26
+ async function readText(sandbox, path, timeoutMs) {
27
+ let bytes;
28
+ try {
29
+ bytes = await within(sandbox.readFile(path), timeoutMs, "skipped");
30
+ }
31
+ catch (error) {
32
+ // A tracked file the turn deleted is listed by git but no longer on disk. Any other failure says nothing about
33
+ // whether the file is there, so it is skipped, and the diff never reports it as deleted.
34
+ return error instanceof HarnessError && error.code === "sandbox_not_found" ? "gone" : "skipped";
35
+ }
36
+ if (bytes === "skipped" || bytes.length > MAX_SNAPSHOT_FILE_BYTES || bytes.includes(0))
37
+ return "skipped";
38
+ try {
39
+ return DECODER.decode(bytes);
40
+ }
41
+ catch {
42
+ return "skipped";
43
+ }
44
+ }
45
+ /**
46
+ * The default snapshotter: every file git tracks or would track (so untracked files that `.gitignore` leaves out stay
47
+ * out), read as UTF-8 text up to `MAX_SNAPSHOT_FILE_BYTES` each and `MAX_SNAPSHOT_FILES` files. A file it leaves out
48
+ * for its size, its encoding or the cap, or that it could not read, goes in `skipped`, and the diff ignores it. Only a
49
+ * read that fails with `sandbox_not_found` counts as a deleted file. The listing and each read stop after `timeoutMs`.
50
+ * It returns `undefined` where `git` is missing, the workspace is no repository, or the listing timed out.
51
+ */
52
+ export const gitSnapshotter = async (sandbox, options) => {
53
+ const timeoutMs = options.timeoutMs ?? SNAPSHOT_TIMEOUT_MS;
54
+ const listed = await sandbox.exec(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
55
+ env: options.env,
56
+ signal: options.signal,
57
+ timeoutMs,
58
+ });
59
+ if ("denied" in listed || listed.exitCode !== 0)
60
+ return undefined;
61
+ const skipped = new Set(options.skipped);
62
+ const known = [...(options.known ?? [])].filter((path) => !skipped.has(path));
63
+ const seen = new Set([...known, ...skipped]);
64
+ const fresh = [...new Set(listed.stdout.split("\0").filter((path) => path !== ""))].filter((path) => !seen.has(path));
65
+ const room = Math.max(0, MAX_SNAPSHOT_FILES - known.length);
66
+ for (const path of fresh.slice(room))
67
+ skipped.add(path);
68
+ const paths = [...known, ...fresh.slice(0, room)];
69
+ const files = new Map();
70
+ for (let start = 0; start < paths.length; start += BATCH) {
71
+ const batch = paths.slice(start, start + BATCH);
72
+ const texts = await Promise.all(batch.map((path) => readText(sandbox, path, timeoutMs)));
73
+ for (const [index, text] of texts.entries()) {
74
+ const path = batch[index];
75
+ if (text === "skipped")
76
+ skipped.add(path);
77
+ else if (text !== "gone")
78
+ files.set(path, text);
79
+ }
80
+ }
81
+ return { files, skipped };
82
+ };
83
+ //# sourceMappingURL=snapshot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshot.js","sourceRoot":"","sources":["../../src/completion/snapshot.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAuB5C,6FAA6F;AAC7F,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,IAAI,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E,KAAK,EAAE,OAAO,EAAE,CAAC;AAC5B,CAAC,CAAC","sourcesContent":["/**\n * Snapshots of the workspace's text files, taken inside the sandbox with `git ls-files`, so a turn's changes can be\n * diffed against its start state without a second copy of the workspace.\n */\nimport { HarnessError } from \"../errors.js\";\nimport type { Sandbox } from \"../sandbox/types.js\";\nimport type { WorkspaceSnapshot } from \"./flags.js\";\n\n/** Takes a snapshot, or returns `undefined` when the workspace can't be listed, so no diff flags are raised. */\nexport type Snapshotter = (sandbox: Sandbox, options: SnapshotOptions) => Promise<WorkspaceSnapshot | undefined>;\n\n/** What a snapshotter needs to run a command in the sandbox. */\nexport interface SnapshotOptions {\n readonly env: Readonly<Record<string, string>>;\n readonly signal: AbortSignal;\n /**\n * The paths an earlier snapshot of the same workspace held. They are read first and always, so a file that a later\n * listing pushes past the cap, or that no longer appears in it, still has its text; new paths fill what is left of\n * `MAX_SNAPSHOT_FILES`.\n */\n readonly known?: ReadonlySet<string>;\n /** Paths an earlier snapshot skipped. They stay skipped and are not read again. */\n readonly skipped?: ReadonlySet<string>;\n /** The longest the listing, and each file read, may take, in milliseconds. Default `SNAPSHOT_TIMEOUT_MS`. */\n readonly timeoutMs?: number;\n}\n\n/** How long the listing, and each file read, may take before the snapshot gives up on it. */\nexport const SNAPSHOT_TIMEOUT_MS = 60 * 1000;\n\n/** The largest file a snapshot keeps, in bytes. A bigger file is left out of both snapshots, so it is never flagged. */\nexport const MAX_SNAPSHOT_FILE_BYTES = 256 * 1024;\n/** The most files a snapshot keeps. */\nexport const MAX_SNAPSHOT_FILES = 5000;\n\nconst DECODER = new TextDecoder(\"utf-8\", { fatal: true });\nconst BATCH = 32;\n\n/** Settles with `promise`, or with `fallback` once `ms` pass, so one hung read can't hold up the turn. */\nfunction within<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<T>((resolve) => {\n timer = setTimeout(() => resolve(fallback), ms);\n });\n return Promise.race([promise, late]).finally(() => clearTimeout(timer));\n}\n\n/**\n * The text of a file, `\"gone\"` for one no longer on disk, or `\"skipped\"` for one that is binary, not UTF-8, too large,\n * or that could not be read for any other reason (a policy refusal, a sandbox error, a read that timed out).\n */\nasync function readText(sandbox: Sandbox, path: string, timeoutMs: number): Promise<string | \"gone\" | \"skipped\"> {\n let bytes: Uint8Array | \"skipped\";\n try {\n bytes = await within<Uint8Array | \"skipped\">(sandbox.readFile(path), timeoutMs, \"skipped\");\n } catch (error) {\n // A tracked file the turn deleted is listed by git but no longer on disk. Any other failure says nothing about\n // whether the file is there, so it is skipped, and the diff never reports it as deleted.\n return error instanceof HarnessError && error.code === \"sandbox_not_found\" ? \"gone\" : \"skipped\";\n }\n if (bytes === \"skipped\" || bytes.length > MAX_SNAPSHOT_FILE_BYTES || bytes.includes(0)) return \"skipped\";\n try {\n return DECODER.decode(bytes);\n } catch {\n return \"skipped\";\n }\n}\n\n/**\n * The default snapshotter: every file git tracks or would track (so untracked files that `.gitignore` leaves out stay\n * out), read as UTF-8 text up to `MAX_SNAPSHOT_FILE_BYTES` each and `MAX_SNAPSHOT_FILES` files. A file it leaves out\n * for its size, its encoding or the cap, or that it could not read, goes in `skipped`, and the diff ignores it. Only a\n * read that fails with `sandbox_not_found` counts as a deleted file. The listing and each read stop after `timeoutMs`.\n * It returns `undefined` where `git` is missing, the workspace is no repository, or the listing timed out.\n */\nexport const gitSnapshotter: Snapshotter = async (sandbox, options) => {\n const timeoutMs = options.timeoutMs ?? SNAPSHOT_TIMEOUT_MS;\n const listed = await sandbox.exec([\"git\", \"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\"], {\n env: options.env,\n signal: options.signal,\n timeoutMs,\n });\n if (\"denied\" in listed || listed.exitCode !== 0) return undefined;\n const skipped = new Set(options.skipped);\n const known = [...(options.known ?? [])].filter((path) => !skipped.has(path));\n const seen = new Set([...known, ...skipped]);\n const fresh = [...new Set(listed.stdout.split(\"\\0\").filter((path) => path !== \"\"))].filter((path) => !seen.has(path));\n const room = Math.max(0, MAX_SNAPSHOT_FILES - known.length);\n for (const path of fresh.slice(room)) skipped.add(path);\n const paths = [...known, ...fresh.slice(0, room)];\n const files = new Map<string, string>();\n for (let start = 0; start < paths.length; start += BATCH) {\n const batch = paths.slice(start, start + BATCH);\n const texts = await Promise.all(batch.map((path) => readText(sandbox, path, timeoutMs)));\n for (const [index, text] of texts.entries()) {\n const path = batch[index] as string;\n if (text === \"skipped\") skipped.add(path);\n else if (text !== \"gone\") files.set(path, text);\n }\n }\n return { files, skipped };\n};\n"]}
@@ -0,0 +1,32 @@
1
+ /** The write cap's decision for one tool result: what the model reads instead, and where the full text went. */
2
+ import type { ModelContent } from "@buildanagent/gateway";
3
+ /** What `capResult()` needs to know about one result. */
4
+ export interface CapInput {
5
+ readonly content: readonly ModelContent[];
6
+ readonly details: unknown;
7
+ /** The cap in bytes of the log, from the policy's `writeCapBytes`. */
8
+ readonly cap: number;
9
+ /** The name the spill file takes. */
10
+ readonly name: string;
11
+ /** Stores the full text under `name` and returns its path. It may throw; the result is then cut and the rest is lost. */
12
+ readonly write: (name: string, text: string) => Promise<string>;
13
+ }
14
+ /** A result's replacement, and the spill that holds the rest when there is one. */
15
+ export interface Capped {
16
+ readonly patch: {
17
+ readonly content?: ModelContent[];
18
+ readonly details?: unknown;
19
+ };
20
+ readonly spill?: {
21
+ readonly path: string;
22
+ readonly bytes: number;
23
+ };
24
+ }
25
+ /**
26
+ * Caps one result, or returns `undefined` when it already fits. The cap counts the log's bytes, JSON escaping and the
27
+ * result's other blocks and details included, plus room for the entry's own fields, so a capped entry always fits the
28
+ * store. Details that would crowd out the text are replaced by a note; the model never reads them. Image and other
29
+ * non-text blocks that alone take more than half the room are replaced by a note in the text. If the spill store
30
+ * can't write, the text is cut all the same and the notice says the rest was not kept.
31
+ */
32
+ export declare function capResult(input: CapInput): Promise<Capped | undefined>;
@@ -0,0 +1,50 @@
1
+ import { byteLength, capNotice, ENTRY_RESERVE_BYTES, escapedBytes, fitHead, textOf } from "./write-cap.js";
2
+ /** The JSON bytes of what a result stores besides its text: its images, its other blocks and its details. */
3
+ function otherBytes(content, details) {
4
+ const rest = content.filter((block) => block.type !== "text");
5
+ return byteLength(JSON.stringify({ rest, details: details ?? null }));
6
+ }
7
+ const DETAILS_NOTE = { omitted: "the result's details were over the entry bound" };
8
+ /** Whether a spill that holds `text` is needed, or the result already fits once its details are replaced. */
9
+ function textFits(content, room) {
10
+ return escapedBytes(textOf(content)) + otherBytes(content, undefined) <= room;
11
+ }
12
+ /**
13
+ * Caps one result, or returns `undefined` when it already fits. The cap counts the log's bytes, JSON escaping and the
14
+ * result's other blocks and details included, plus room for the entry's own fields, so a capped entry always fits the
15
+ * store. Details that would crowd out the text are replaced by a note; the model never reads them. Image and other
16
+ * non-text blocks that alone take more than half the room are replaced by a note in the text. If the spill store
17
+ * can't write, the text is cut all the same and the notice says the rest was not kept.
18
+ */
19
+ export async function capResult(input) {
20
+ const { content, details, cap } = input;
21
+ const room = cap - Math.min(ENTRY_RESERVE_BYTES, cap >> 2);
22
+ if (escapedBytes(textOf(content)) + otherBytes(content, details) <= room)
23
+ return undefined;
24
+ const bigDetails = details !== undefined && byteLength(JSON.stringify(details)) > room >> 2;
25
+ // Only the details are too big: replace them, and the text goes back whole with nothing to spill.
26
+ if (bigDetails && textFits(content, room))
27
+ return { patch: { details: DETAILS_NOTE } };
28
+ const text = textOf(content);
29
+ const bytes = byteLength(text);
30
+ // A store that throws before it returns a promise is caught the same way as one that rejects.
31
+ const path = await Promise.resolve()
32
+ .then(() => input.write(input.name, text))
33
+ .catch(() => undefined);
34
+ const rest = content.filter((block) => block.type !== "text");
35
+ const dropRest = byteLength(JSON.stringify(rest)) > room >> 1;
36
+ const keptBlocks = dropRest ? [] : rest;
37
+ const kept = otherBytes(keptBlocks, bigDetails ? undefined : details);
38
+ const noticeBytes = escapedBytes(capNotice(room, bytes, path)) + escapedBytes("\n");
39
+ const head = fitHead(text, room - kept - noticeBytes);
40
+ const dropped = dropRest && rest.length > 0 ? `\n[${rest.length} image or other block(s) over the entry bound were left out]` : "";
41
+ const notice = `${capNotice(byteLength(head), bytes, path)}${dropped}`;
42
+ return {
43
+ patch: {
44
+ content: [{ type: "text", text: `${head}\n${notice}` }, ...keptBlocks],
45
+ ...(bigDetails ? { details: DETAILS_NOTE } : {}),
46
+ },
47
+ ...(path === undefined ? {} : { spill: { path, bytes } }),
48
+ };
49
+ }
50
+ //# sourceMappingURL=cap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cap.js","sourceRoot":"","sources":["../../src/context/cap.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,mBAAmB,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE3G,6GAA6G;AAC7G,SAAS,UAAU,CAAC,OAAgC,EAAE,OAAgB;IACpE,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC;IAC9D,OAAO,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;AACxE,CAAC;AAoBD,MAAM,YAAY,GAAG,EAAE,OAAO,EAAE,gDAAgD,EAAE,CAAC;AAEnF,6GAA6G;AAC7G,SAAS,QAAQ,CAAC,OAAgC,EAAE,IAAY;IAC9D,OAAO,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,UAAU,CAAC,OAAO,EAAE,SAAS,CAAC,IAAI,IAAI,CAAC;AAChF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,KAAe;IAC7C,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,KAAK,CAAC;IACxC,MAAM,IAAI,GAAG,GAA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,CAAC,CAAC,OAAO,CAAC,CAAC;IACtE,MAAM,WAAW,GAAG,YAAY,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IACpF,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,WAAW,CAAC,CAAC;IACtD,MAAM,OAAO,GACX,QAAQ,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,MAAM,8DAA8D,CAAC,CAAC,CAAC,EAAE,CAAC;IACrH,MAAM,MAAM,GAAG,GAAG,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,GAAG,OAAO,EAAE,CAAC;IACvE,OAAO;QACL,KAAK,EAAE;YACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,KAAK,MAAM,EAAE,EAAE,EAAE,GAAG,UAAU,CAAC;YACtE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACjD;QACD,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;KAC1D,CAAC;AACJ,CAAC","sourcesContent":["/** The write cap's decision for one tool result: what the model reads instead, and where the full text went. */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport { byteLength, capNotice, ENTRY_RESERVE_BYTES, escapedBytes, fitHead, textOf } from \"./write-cap.js\";\n\n/** The JSON bytes of what a result stores besides its text: its images, its other blocks and its details. */\nfunction otherBytes(content: readonly ModelContent[], details: unknown): number {\n const rest = content.filter((block) => block.type !== \"text\");\n return byteLength(JSON.stringify({ rest, details: details ?? null }));\n}\n\n/** What `capResult()` needs to know about one result. */\nexport interface CapInput {\n readonly content: readonly ModelContent[];\n readonly details: unknown;\n /** The cap in bytes of the log, from the policy's `writeCapBytes`. */\n readonly cap: number;\n /** The name the spill file takes. */\n readonly name: string;\n /** Stores the full text under `name` and returns its path. It may throw; the result is then cut and the rest is lost. */\n readonly write: (name: string, text: string) => Promise<string>;\n}\n\n/** A result's replacement, and the spill that holds the rest when there is one. */\nexport interface Capped {\n readonly patch: { readonly content?: ModelContent[]; readonly details?: unknown };\n readonly spill?: { readonly path: string; readonly bytes: number };\n}\n\nconst DETAILS_NOTE = { omitted: \"the result's details were over the entry bound\" };\n\n/** Whether a spill that holds `text` is needed, or the result already fits once its details are replaced. */\nfunction textFits(content: readonly ModelContent[], room: number): boolean {\n return escapedBytes(textOf(content)) + otherBytes(content, undefined) <= room;\n}\n\n/**\n * Caps one result, or returns `undefined` when it already fits. The cap counts the log's bytes, JSON escaping and the\n * result's other blocks and details included, plus room for the entry's own fields, so a capped entry always fits the\n * store. Details that would crowd out the text are replaced by a note; the model never reads them. Image and other\n * non-text blocks that alone take more than half the room are replaced by a note in the text. If the spill store\n * can't write, the text is cut all the same and the notice says the rest was not kept.\n */\nexport async function capResult(input: CapInput): Promise<Capped | undefined> {\n const { content, details, cap } = input;\n const room = cap - Math.min(ENTRY_RESERVE_BYTES, cap >> 2);\n if (escapedBytes(textOf(content)) + otherBytes(content, details) <= room) return undefined;\n const bigDetails = details !== undefined && byteLength(JSON.stringify(details)) > room >> 2;\n // Only the details are too big: replace them, and the text goes back whole with nothing to spill.\n if (bigDetails && textFits(content, room)) return { patch: { details: DETAILS_NOTE } };\n const text = textOf(content);\n const bytes = byteLength(text);\n // A store that throws before it returns a promise is caught the same way as one that rejects.\n const path = await Promise.resolve()\n .then(() => input.write(input.name, text))\n .catch(() => undefined);\n const rest = content.filter((block) => block.type !== \"text\");\n const dropRest = byteLength(JSON.stringify(rest)) > room >> 1;\n const keptBlocks = dropRest ? [] : rest;\n const kept = otherBytes(keptBlocks, bigDetails ? undefined : details);\n const noticeBytes = escapedBytes(capNotice(room, bytes, path)) + escapedBytes(\"\\n\");\n const head = fitHead(text, room - kept - noticeBytes);\n const dropped =\n dropRest && rest.length > 0 ? `\\n[${rest.length} image or other block(s) over the entry bound were left out]` : \"\";\n const notice = `${capNotice(byteLength(head), bytes, path)}${dropped}`;\n return {\n patch: {\n content: [{ type: \"text\", text: `${head}\\n${notice}` }, ...keptBlocks],\n ...(bigDetails ? { details: DETAILS_NOTE } : {}),\n },\n ...(path === undefined ? {} : { spill: { path, bytes } }),\n };\n}\n"]}
@@ -0,0 +1,18 @@
1
+ /** The token estimates the context layers use: the last response's usage when there is one, characters over four otherwise. */
2
+ import type { ContentBlock, Message, ModelContent } from "@buildanagent/gateway";
3
+ import { totalInput } from "@buildanagent/gateway";
4
+ /** The characters in one message's content, counted as JSON. */
5
+ export declare const charsOf: (message: {
6
+ content: readonly ContentBlock[] | readonly ModelContent[];
7
+ }) => number;
8
+ /** Tokens for `chars` characters, rounded up. */
9
+ export declare const tokensOfChars: (chars: number) => number;
10
+ /** The usage of the last response, which tells how many tokens the context held then. */
11
+ export type LastUsage = Parameters<typeof totalInput>[0] & {
12
+ output: number;
13
+ };
14
+ /**
15
+ * The token estimate for a request view. With the last response's usage it is that call's input and output, plus a
16
+ * character estimate of what the view added since; without it, a character estimate of the whole view.
17
+ */
18
+ export declare function estimate(system: string, messages: readonly Message[], last?: LastUsage): number;
@@ -0,0 +1,20 @@
1
+ /** The token estimates the context layers use: the last response's usage when there is one, characters over four otherwise. */
2
+ import { totalInput } from "@buildanagent/gateway";
3
+ const CHARS_PER_TOKEN = 4;
4
+ /** The characters in one message's content, counted as JSON. */
5
+ export const charsOf = (message) => JSON.stringify(message.content).length;
6
+ /** Tokens for `chars` characters, rounded up. */
7
+ export const tokensOfChars = (chars) => Math.ceil(chars / CHARS_PER_TOKEN);
8
+ /**
9
+ * The token estimate for a request view. With the last response's usage it is that call's input and output, plus a
10
+ * character estimate of what the view added since; without it, a character estimate of the whole view.
11
+ */
12
+ export function estimate(system, messages, last) {
13
+ if (last === undefined) {
14
+ return tokensOfChars(messages.reduce((sum, message) => sum + charsOf(message), system.length));
15
+ }
16
+ const lastAssistant = messages.findLastIndex((message) => message.role === "assistant");
17
+ const added = messages.slice(lastAssistant + 1).reduce((sum, message) => sum + charsOf(message), 0);
18
+ return totalInput(last) + last.output + tokensOfChars(added);
19
+ }
20
+ //# sourceMappingURL=estimate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"estimate.js","sourceRoot":"","sources":["../../src/context/estimate.ts"],"names":[],"mappings":"AAAA,+HAA+H;AAG/H,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAEnD,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,gEAAgE;AAChE,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,OAAuE,EAAU,EAAE,CACzG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC;AAEzC,iDAAiD;AACjD,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,KAAa,EAAU,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,GAAG,eAAe,CAAC,CAAC;AAK3F;;;GAGG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAc,EAAE,QAA4B,EAAE,IAAgB;IACrF,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IACjG,CAAC;IACD,MAAM,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;IACxF,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,aAAa,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;IACpG,OAAO,UAAU,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["/** The token estimates the context layers use: the last response's usage when there is one, characters over four otherwise. */\n\nimport type { ContentBlock, Message, ModelContent } from \"@buildanagent/gateway\";\nimport { totalInput } from \"@buildanagent/gateway\";\n\nconst CHARS_PER_TOKEN = 4;\n\n/** The characters in one message's content, counted as JSON. */\nexport const charsOf = (message: { content: readonly ContentBlock[] | readonly ModelContent[] }): number =>\n JSON.stringify(message.content).length;\n\n/** Tokens for `chars` characters, rounded up. */\nexport const tokensOfChars = (chars: number): number => Math.ceil(chars / CHARS_PER_TOKEN);\n\n/** The usage of the last response, which tells how many tokens the context held then. */\nexport type LastUsage = Parameters<typeof totalInput>[0] & { output: number };\n\n/**\n * The token estimate for a request view. With the last response's usage it is that call's input and output, plus a\n * character estimate of what the view added since; without it, a character estimate of the whole view.\n */\nexport function estimate(system: string, messages: readonly Message[], last?: LastUsage): number {\n if (last === undefined) {\n return tokensOfChars(messages.reduce((sum, message) => sum + charsOf(message), system.length));\n }\n const lastAssistant = messages.findLastIndex((message) => message.role === \"assistant\");\n const added = messages.slice(lastAssistant + 1).reduce((sum, message) => sum + charsOf(message), 0);\n return totalInput(last) + last.output + tokensOfChars(added);\n}\n"]}
@@ -0,0 +1,15 @@
1
+ import { type SessionKey } from "../session/store.js";
2
+ import type { SpillStore } from "./types.js";
3
+ /** A spill store in files, which can also read back the spills of one session. */
4
+ export interface FileSpillStore extends SpillStore {
5
+ /**
6
+ * The text spilled to `path` for the session `key`, or `undefined` when `path` is not a spill file of that session.
7
+ * `path` must be absolute, as `write()` returns it. A relative path, a path outside the session's folder, and one
8
+ * that leads out through a symlink are never read.
9
+ */
10
+ read(key: SessionKey, path: string): Promise<string | undefined>;
11
+ }
12
+ /** A spill store that writes `<dir>/<user>/<session>/<callId>.txt` and returns that path. */
13
+ export declare function fileSpillStore(options: {
14
+ readonly dir: string;
15
+ }): FileSpillStore;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The spill store that keeps each capped tool result in a file, one per call, in a folder per session. It uses Node's
3
+ * file system, loaded with `process.getBuiltinModule()` when a result is written or read, so importing it costs a
4
+ * portable bundle nothing. It has its own entry, `@buildanagent/harness/context/file`.
5
+ */
6
+ import { HarnessError } from "../errors.js";
7
+ import { encodeName } from "../session/store.js";
8
+ function nodeModules() {
9
+ if (typeof process === "undefined" || typeof process.getBuiltinModule !== "function") {
10
+ throw new HarnessError("spill_unavailable", "fileSpillStore needs Node's file system, which this runtime lacks");
11
+ }
12
+ return { fs: process.getBuiltinModule("node:fs/promises"), path: process.getBuiltinModule("node:path") };
13
+ }
14
+ /** A spill store that writes `<dir>/<user>/<session>/<callId>.txt` and returns that path. */
15
+ export function fileSpillStore(options) {
16
+ const folderOf = (key) => nodeModules().path.resolve(options.dir, encodeName(key.userId), encodeName(key.sessionId));
17
+ return {
18
+ async write(key, callId, text) {
19
+ const { fs, path } = nodeModules();
20
+ const folder = folderOf(key);
21
+ await fs.mkdir(folder, { recursive: true });
22
+ const file = path.join(folder, `${encodeName(callId)}.txt`);
23
+ await fs.writeFile(file, text, "utf8");
24
+ return file;
25
+ },
26
+ async read(key, file) {
27
+ const { fs, path } = nodeModules();
28
+ // A relative path would resolve against the spill folder, so a workspace file's name could open a spill.
29
+ if (!path.isAbsolute(file))
30
+ return undefined;
31
+ // Both sides are real paths, so a link inside the folder that points out of it is caught.
32
+ const folder = await fs.realpath(folderOf(key)).catch(() => undefined);
33
+ const real = await fs.realpath(path.resolve(folderOf(key), file)).catch(() => undefined);
34
+ if (folder === undefined || real === undefined || path.dirname(real) !== folder)
35
+ return undefined;
36
+ return fs.readFile(real, "utf8").catch(() => undefined);
37
+ },
38
+ };
39
+ }
40
+ //# sourceMappingURL=file-spill.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-spill.js","sourceRoot":"","sources":["../../src/context/file-spill.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAmB,MAAM,qBAAqB,CAAC;AAalE,SAAS,WAAW;IAClB,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;QACrF,MAAM,IAAI,YAAY,CAAC,mBAAmB,EAAE,mEAAmE,CAAC,CAAC;IACnH,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,gBAAgB,CAAC,kBAAkB,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC,EAAE,CAAC;AAC3G,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,cAAc,CAAC,OAAiC;IAC9D,MAAM,QAAQ,GAAG,CAAC,GAAe,EAAE,EAAE,CACnC,WAAW,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;IAC7F,OAAO;QACL,KAAK,CAAC,KAAK,CAAC,GAAe,EAAE,MAAc,EAAE,IAAY;YACvD,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,WAAW,EAAE,CAAC;YACnC,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC7B,MAAM,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC5D,MAAM,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;YACvC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,GAAe,EAAE,IAAY;YACtC,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,WAAW,EAAE,CAAC;YACnC,yGAAyG;YACzG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;gBAAE,OAAO,SAAS,CAAC;YAC7C,0FAA0F;YAC1F,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YACvE,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YACzF,IAAI,MAAM,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,MAAM;gBAAE,OAAO,SAAS,CAAC;YAClG,OAAO,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC1D,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The spill store that keeps each capped tool result in a file, one per call, in a folder per session. It uses Node's\n * file system, loaded with `process.getBuiltinModule()` when a result is written or read, so importing it costs a\n * portable bundle nothing. It has its own entry, `@buildanagent/harness/context/file`.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { encodeName, type SessionKey } from \"../session/store.js\";\nimport type { SpillStore } from \"./types.js\";\n\n/** A spill store in files, which can also read back the spills of one session. */\nexport interface FileSpillStore extends SpillStore {\n /**\n * The text spilled to `path` for the session `key`, or `undefined` when `path` is not a spill file of that session.\n * `path` must be absolute, as `write()` returns it. A relative path, a path outside the session's folder, and one\n * that leads out through a symlink are never read.\n */\n read(key: SessionKey, path: string): Promise<string | undefined>;\n}\n\nfunction nodeModules() {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new HarnessError(\"spill_unavailable\", \"fileSpillStore needs Node's file system, which this runtime lacks\");\n }\n return { fs: process.getBuiltinModule(\"node:fs/promises\"), path: process.getBuiltinModule(\"node:path\") };\n}\n\n/** A spill store that writes `<dir>/<user>/<session>/<callId>.txt` and returns that path. */\nexport function fileSpillStore(options: { readonly dir: string }): FileSpillStore {\n const folderOf = (key: SessionKey) =>\n nodeModules().path.resolve(options.dir, encodeName(key.userId), encodeName(key.sessionId));\n return {\n async write(key: SessionKey, callId: string, text: string): Promise<string> {\n const { fs, path } = nodeModules();\n const folder = folderOf(key);\n await fs.mkdir(folder, { recursive: true });\n const file = path.join(folder, `${encodeName(callId)}.txt`);\n await fs.writeFile(file, text, \"utf8\");\n return file;\n },\n async read(key: SessionKey, file: string): Promise<string | undefined> {\n const { fs, path } = nodeModules();\n // A relative path would resolve against the spill folder, so a workspace file's name could open a spill.\n if (!path.isAbsolute(file)) return undefined;\n // Both sides are real paths, so a link inside the folder that points out of it is caught.\n const folder = await fs.realpath(folderOf(key)).catch(() => undefined);\n const real = await fs.realpath(path.resolve(folderOf(key), file)).catch(() => undefined);\n if (folder === undefined || real === undefined || path.dirname(real) !== folder) return undefined;\n return fs.readFile(real, \"utf8\").catch(() => undefined);\n },\n };\n}\n"]}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `@buildanagent/harness/context`: the context layers that keep a long run inside its model's window, cheapest
3
+ * first. `createContextPolicy()` builds all five: the write cap with spill, stepped masking, the summary between
4
+ * turns, the mid-turn summary and the retry after an overflow. A harness takes the policy as `context`.
5
+ */
6
+ export { cutoffFor, maskMessages } from "./mask.js";
7
+ export { createContextPolicy } from "./policy.js";
8
+ export { memorySpillStore } from "./spill.js";
9
+ export { SUMMARY_PROMPT_VERSION } from "./summary-template.js";
10
+ export type { CompactEvent, CompactionLog, CompactionRecord, ContextFill, ContextHooks, ContextPolicy, ContextPolicyOptions, LayerName, SpillStore, SummarizeSettings, TurnContext, TurnContextOptions, } from "./types.js";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `@buildanagent/harness/context`: the context layers that keep a long run inside its model's window, cheapest
3
+ * first. `createContextPolicy()` builds all five: the write cap with spill, stepped masking, the summary between
4
+ * turns, the mid-turn summary and the retry after an overflow. A harness takes the policy as `context`.
5
+ */
6
+ export { cutoffFor, maskMessages } from "./mask.js";
7
+ export { createContextPolicy } from "./policy.js";
8
+ export { memorySpillStore } from "./spill.js";
9
+ export { SUMMARY_PROMPT_VERSION } from "./summary-template.js";
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/context/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/context`: the context layers that keep a long run inside its model's window, cheapest\n * first. `createContextPolicy()` builds all five: the write cap with spill, stepped masking, the summary between\n * turns, the mid-turn summary and the retry after an overflow. A harness takes the policy as `context`.\n */\nexport { cutoffFor, maskMessages } from \"./mask.js\";\nexport { createContextPolicy } from \"./policy.js\";\nexport { memorySpillStore } from \"./spill.js\";\nexport { SUMMARY_PROMPT_VERSION } from \"./summary-template.js\";\nexport type {\n CompactEvent,\n CompactionLog,\n CompactionRecord,\n ContextFill,\n ContextHooks,\n ContextPolicy,\n ContextPolicyOptions,\n LayerName,\n SpillStore,\n SummarizeSettings,\n TurnContext,\n TurnContextOptions,\n} from \"./types.js\";\n"]}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Layer 2: mask older tool results in the request view, in steps. Only the view changes; the log keeps every result. The
3
+ * cutoff moves once every `stepMessages` messages, so the view's prefix stays byte-identical in between and a provider's
4
+ * prompt cache keeps hitting it.
5
+ */
6
+ import type { AssistantMessage, Message } from "@buildanagent/gateway";
7
+ /** The settings masking uses. */
8
+ export interface MaskSettings {
9
+ readonly keepChars: number;
10
+ readonly stepMessages: number;
11
+ }
12
+ /** The message index before which tool results are masked: it moves forward in whole steps as the transcript grows. */
13
+ export declare function cutoffFor(length: number, stepMessages: number): number;
14
+ /** An assistant message without its signed reasoning, or `undefined` when nothing remains to send. */
15
+ export declare function withoutSignedReasoning(message: AssistantMessage): AssistantMessage | undefined;
16
+ /**
17
+ * The messages with every tool result before the cutoff masked, and where the cutoff stands. `where` says where the full
18
+ * text of a call is: it gets the call's id and which of the transcript's results with that id this is, because a
19
+ * provider may reuse an id.
20
+ *
21
+ * A model that checks signed thinking against the earlier request rejects a block that follows an edited message, and
22
+ * a model that thinks in a tool loop needs the loop's own thinking blocks back. So the cutoff moves only where that
23
+ * costs nothing: while the tool loop in progress holds signed thinking (it follows the last user message), the cutoff
24
+ * stays where the loop started, so the blocks the loop generated stay valid. Signed reasoning in the messages before the
25
+ * loop, after the first edited result, is dropped from the view.
26
+ */
27
+ export declare function maskMessages(messages: readonly Message[], settings: MaskSettings, where: (callId: string, occurrence: number) => string): readonly Message[];
@@ -0,0 +1,71 @@
1
+ import { textOf } from "./write-cap.js";
2
+ /** The message index before which tool results are masked: it moves forward in whole steps as the transcript grows. */
3
+ export function cutoffFor(length, stepMessages) {
4
+ return Math.max(0, Math.floor((length - stepMessages) / stepMessages) * stepMessages);
5
+ }
6
+ const pointerLine = (chars, where) => `[older tool result masked: ${chars} characters, ${where}]`;
7
+ /** The first `keepChars` UTF-16 units of `text`, backing off one when the cut would leave half of a surrogate pair. */
8
+ function headChars(text, keepChars) {
9
+ const last = text.charCodeAt(keepChars - 1);
10
+ const cut = keepChars > 0 && last >= 0xd800 && last <= 0xdbff ? keepChars - 1 : keepChars;
11
+ return text.slice(0, cut);
12
+ }
13
+ /** One masked tool message, or `undefined` when the result is already short enough to keep. */
14
+ function maskedResult(message, keepChars, where) {
15
+ const text = textOf(message.content);
16
+ const hasImage = message.content.some((block) => block.type === "image");
17
+ if (text.length <= keepChars && !hasImage)
18
+ return undefined;
19
+ const content = [
20
+ { type: "text", text: `${headChars(text, keepChars)}\n${pointerLine(text.length, where)}` },
21
+ ];
22
+ return { ...message, content };
23
+ }
24
+ /** An assistant message without its signed reasoning, or `undefined` when nothing remains to send. */
25
+ export function withoutSignedReasoning(message) {
26
+ const content = message.content.filter((block) => !(block.type === "reasoning" && block.signature !== undefined));
27
+ if (content.length === message.content.length)
28
+ return message;
29
+ return content.length === 0 ? undefined : { ...message, content };
30
+ }
31
+ const isSigned = (message) => message.role === "assistant" &&
32
+ message.content.some((block) => block.type === "reasoning" && block.signature !== undefined);
33
+ /**
34
+ * The messages with every tool result before the cutoff masked, and where the cutoff stands. `where` says where the full
35
+ * text of a call is: it gets the call's id and which of the transcript's results with that id this is, because a
36
+ * provider may reuse an id.
37
+ *
38
+ * A model that checks signed thinking against the earlier request rejects a block that follows an edited message, and
39
+ * a model that thinks in a tool loop needs the loop's own thinking blocks back. So the cutoff moves only where that
40
+ * costs nothing: while the tool loop in progress holds signed thinking (it follows the last user message), the cutoff
41
+ * stays where the loop started, so the blocks the loop generated stay valid. Signed reasoning in the messages before the
42
+ * loop, after the first edited result, is dropped from the view.
43
+ */
44
+ export function maskMessages(messages, settings, where) {
45
+ const loopStart = messages.findLastIndex((message) => message.role === "user");
46
+ const inLoop = messages.slice(loopStart + 1).some(isSigned);
47
+ const cutoff = cutoffFor(inLoop ? loopStart + 1 : messages.length, settings.stepMessages);
48
+ const seen = new Map();
49
+ let firstEdit = -1;
50
+ const masked = messages.map((message, index) => {
51
+ if (message.role !== "tool")
52
+ return message;
53
+ const occurrence = seen.get(message.callId) ?? 0;
54
+ seen.set(message.callId, occurrence + 1);
55
+ if (index >= cutoff)
56
+ return message;
57
+ const edited = maskedResult(message, settings.keepChars, where(message.callId, occurrence));
58
+ if (edited !== undefined && firstEdit < 0)
59
+ firstEdit = index;
60
+ return edited ?? message;
61
+ });
62
+ if (firstEdit < 0)
63
+ return messages;
64
+ return masked.flatMap((message, index) => {
65
+ if (index <= firstEdit || index > loopStart || message.role !== "assistant")
66
+ return [message];
67
+ const trimmed = withoutSignedReasoning(message);
68
+ return trimmed === undefined ? [] : [trimmed];
69
+ });
70
+ }
71
+ //# sourceMappingURL=mask.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mask.js","sourceRoot":"","sources":["../../src/context/mask.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAQxC,uHAAuH;AACvH,MAAM,UAAU,SAAS,CAAC,MAAc,EAAE,YAAoB;IAC5D,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,YAAY,CAAC,GAAG,YAAY,CAAC,GAAG,YAAY,CAAC,CAAC;AACxF,CAAC;AAED,MAAM,WAAW,GAAG,CAAC,KAAa,EAAE,KAAa,EAAU,EAAE,CAC3D,8BAA8B,KAAK,gBAAgB,KAAK,GAAG,CAAC;AAE9D,uHAAuH;AACvH,SAAS,SAAS,CAAC,IAAY,EAAE,SAAiB;IAChD,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;IAC5C,MAAM,GAAG,GAAG,SAAS,GAAG,CAAC,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC,CAAC,CA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Q,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;QAC5F,IAAI,MAAM,KAAK,SAAS,IAAI,SAAS,GAAG,CAAC;YAAE,SAAS,GAAG,KAAK,CAAC;QAC7D,OAAO,MAAM,IAAI,OAAO,CAAC;IAC3B,CAAC,CAAC,CAAC;IACH,IAAI,SAAS,GAAG,CAAC;QAAE,OAAO,QAAQ,CAAC;IACnC,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE;QACvC,IAAI,KAAK,IAAI,SAAS,IAAI,KAAK,GAAG,SAAS,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;YAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QAC9F,MAAM,OAAO,GAAG,sBAAsB,CAAC,OAAO,CAAC,CAAC;QAChD,OAAO,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IAChD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Layer 2: mask older tool results in the request view, in steps. Only the view changes; the log keeps every result. The\n * cutoff moves once every `stepMessages` messages, so the view's prefix stays byte-identical in between and a provider's\n * prompt cache keeps hitting it.\n */\nimport type { AssistantMessage, Message, ModelContent } from \"@buildanagent/gateway\";\nimport { textOf } from \"./write-cap.js\";\n\n/** The settings masking uses. */\nexport interface MaskSettings {\n readonly keepChars: number;\n readonly stepMessages: number;\n}\n\n/** The message index before which tool results are masked: it moves forward in whole steps as the transcript grows. */\nexport function cutoffFor(length: number, stepMessages: number): number {\n return Math.max(0, Math.floor((length - stepMessages) / stepMessages) * stepMessages);\n}\n\nconst pointerLine = (chars: number, where: string): string =>\n `[older tool result masked: ${chars} characters, ${where}]`;\n\n/** The first `keepChars` UTF-16 units of `text`, backing off one when the cut would leave half of a surrogate pair. */\nfunction headChars(text: string, keepChars: number): string {\n const last = text.charCodeAt(keepChars - 1);\n const cut = keepChars > 0 && last >= 0xd800 && last <= 0xdbff ? keepChars - 1 : keepChars;\n return text.slice(0, cut);\n}\n\n/** One masked tool message, or `undefined` when the result is already short enough to keep. */\nfunction maskedResult(\n message: Extract<Message, { role: \"tool\" }>,\n keepChars: number,\n where: string,\n): Extract<Message, { role: \"tool\" }> | undefined {\n const text = textOf(message.content);\n const hasImage = message.content.some((block) => block.type === \"image\");\n if (text.length <= keepChars && !hasImage) return undefined;\n const content: ModelContent[] = [\n { type: \"text\", text: `${headChars(text, keepChars)}\\n${pointerLine(text.length, where)}` },\n ];\n return { ...message, content };\n}\n\n/** An assistant message without its signed reasoning, or `undefined` when nothing remains to send. */\nexport function withoutSignedReasoning(message: AssistantMessage): AssistantMessage | undefined {\n const content = message.content.filter((block) => !(block.type === \"reasoning\" && block.signature !== undefined));\n if (content.length === message.content.length) return message;\n return content.length === 0 ? undefined : { ...message, content };\n}\n\nconst isSigned = (message: Message): boolean =>\n message.role === \"assistant\" &&\n message.content.some((block) => block.type === \"reasoning\" && block.signature !== undefined);\n\n/**\n * The messages with every tool result before the cutoff masked, and where the cutoff stands. `where` says where the full\n * text of a call is: it gets the call's id and which of the transcript's results with that id this is, because a\n * provider may reuse an id.\n *\n * A model that checks signed thinking against the earlier request rejects a block that follows an edited message, and\n * a model that thinks in a tool loop needs the loop's own thinking blocks back. So the cutoff moves only where that\n * costs nothing: while the tool loop in progress holds signed thinking (it follows the last user message), the cutoff\n * stays where the loop started, so the blocks the loop generated stay valid. Signed reasoning in the messages before the\n * loop, after the first edited result, is dropped from the view.\n */\nexport function maskMessages(\n messages: readonly Message[],\n settings: MaskSettings,\n where: (callId: string, occurrence: number) => string,\n): readonly Message[] {\n const loopStart = messages.findLastIndex((message) => message.role === \"user\");\n const inLoop = messages.slice(loopStart + 1).some(isSigned);\n const cutoff = cutoffFor(inLoop ? loopStart + 1 : messages.length, settings.stepMessages);\n const seen = new Map<string, number>();\n let firstEdit = -1;\n const masked = messages.map((message, index) => {\n if (message.role !== \"tool\") return message;\n const occurrence = seen.get(message.callId) ?? 0;\n seen.set(message.callId, occurrence + 1);\n if (index >= cutoff) return message;\n const edited = maskedResult(message, settings.keepChars, where(message.callId, occurrence));\n if (edited !== undefined && firstEdit < 0) firstEdit = index;\n return edited ?? message;\n });\n if (firstEdit < 0) return messages;\n return masked.flatMap((message, index) => {\n if (index <= firstEdit || index > loopStart || message.role !== \"assistant\") return [message];\n const trimmed = withoutSignedReasoning(message);\n return trimmed === undefined ? [] : [trimmed];\n });\n}\n"]}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Layer 4: compact inside a turn. The SDK's loop keeps the run's whole transcript, so a compaction in the middle of a
3
+ * run cannot shorten it; it changes the view every later model call of the run reads. The first call that would push the
4
+ * context past a share of the window summarises the span before a verbatim tail, writes a `compaction` entry, and from
5
+ * then on the view is the summary, the tail and what the run adds. Later turns rebuild the same view from the log.
6
+ */
7
+ import type { Message } from "@buildanagent/gateway";
8
+ import type { ContextEvent } from "@buildanagent/sdk";
9
+ import type { Session } from "../session/session.js";
10
+ import type { Compacted, CompactInput } from "./summarize.js";
11
+ import type { AppendEntry, CompactionLog } from "./types.js";
12
+ /** What a turn lends the layer once its writer exists: a way to write entries and to wait for the ones queued. */
13
+ export interface MidTurnBindings {
14
+ readonly append: AppendEntry;
15
+ /** Resolves once every entry the run has produced so far is in the log. */
16
+ readonly settle: () => Promise<void>;
17
+ }
18
+ /** Runs one compaction with the policy's settings filled in. */
19
+ export type RunCompaction = (input: Pick<CompactInput, "path" | "append" | "signal" | "layer" | "force" | "view">) => Promise<Compacted | undefined>;
20
+ /** One turn's mid-turn compaction. It compacts at most once, and only when `enabled`. */
21
+ export declare class MidTurn {
22
+ #private;
23
+ constructor(options: {
24
+ session: Session;
25
+ enabled: boolean;
26
+ limitTokens: number;
27
+ compact: RunCompaction;
28
+ log: CompactionLog | undefined;
29
+ });
30
+ attach(bindings: MidTurnBindings): void;
31
+ /** Whether this turn has compacted, so the caller drops the last response's usage from its estimates. */
32
+ get applied(): boolean;
33
+ /**
34
+ * The last response's usage when it still describes this view. A compaction in this turn makes the usage of the calls
35
+ * before it describe the old context, so it counts again only from the first response made under the new view.
36
+ */
37
+ usageFor(event: ContextEvent): ContextEvent["lastUsage"];
38
+ /** The messages the next model call starts from: the run's own, or the compacted view of them. */
39
+ view(event: ContextEvent): Promise<readonly Message[]>;
40
+ }