@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,204 @@
1
+ /**
2
+ * Layer 3: summarise the span a long session has outgrown, between turns. The harness keeps a verbatim tail, asks a
3
+ * model for a recall-first summary of everything before it, and writes the result as a `compaction` entry beside a
4
+ * `usage` entry that holds the call's cost. No entry is changed or removed: the log still holds every original, and
5
+ * only the context a later turn rebuilds starts from the summary.
6
+ */
7
+ import { projectCallCost, } from "@buildanagent/gateway";
8
+ import { contextWithStarts, summaryMessage } from "../session/rebuild.js";
9
+ import { charsOf, estimate, tokensOfChars } from "./estimate.js";
10
+ import { SUMMARY_PROMPT_VERSION, SUMMARY_SYSTEM, summaryPrompt } from "./summary-template.js";
11
+ const ZERO_USAGE = {
12
+ uncachedInput: 0,
13
+ cacheRead: 0,
14
+ cacheWrite: { "5m": 0, "1h": 0 },
15
+ output: 0,
16
+ reasoning: 0,
17
+ raw: null,
18
+ };
19
+ /** The usage of the last model call since the latest compaction, or `undefined` when none is a fair size of the context. */
20
+ function lastUsageSince(path) {
21
+ const from = path.findLastIndex((entry) => entry.type === "compaction");
22
+ const last = path.slice(from + 1).findLast((entry) => entry.type === "usage" && entry.source === "model_call");
23
+ return last?.type === "usage" && last.usage.raw !== null ? last.usage : undefined;
24
+ }
25
+ /**
26
+ * The index of the first message of the tail: the newest messages that together reach `tailTokens`, moved earlier until
27
+ * the tail starts with an assistant message, so a call is never split from its result and the summary is never followed
28
+ * by another user message. 0 means nothing can be dropped.
29
+ */
30
+ export function tailStart(messages, tailTokens) {
31
+ let tokens = 0;
32
+ let start = messages.length;
33
+ while (start > 0 && tokens < tailTokens) {
34
+ start--;
35
+ tokens += tokensOfChars(charsOf(messages[start]));
36
+ }
37
+ // The tail starts with an assistant message: after the summary, which is a user message, a tool result would lose its
38
+ // call and a second user message would follow a user message.
39
+ while (start > 0 && messages[start]?.role !== "assistant")
40
+ start--;
41
+ return start;
42
+ }
43
+ /** The reason the summary request cannot fit the summary model's window, or `undefined` when it fits. */
44
+ function tooLongFor(model, request, maxOutputTokens) {
45
+ const chars = request.messages.reduce((sum, message) => sum + charsOf(message), request.system.length);
46
+ const room = model.caps.contextWindow - maxOutputTokens;
47
+ if (tokensOfChars(chars) <= room)
48
+ return undefined;
49
+ return `the span is about ${tokensOfChars(chars)} tokens, more than the summary model's window leaves room for (${room})`;
50
+ }
51
+ /** Money spent on the branch so far, from the `usage` entries from the root to HEAD; `null` when a call's price is unknown. */
52
+ function spentUsd(path) {
53
+ let total = 0;
54
+ for (const entry of path) {
55
+ if (entry.type !== "usage")
56
+ continue;
57
+ if (entry.cost.total === null)
58
+ return null;
59
+ total += entry.cost.total;
60
+ }
61
+ return total;
62
+ }
63
+ /** Why the summary call may not run under the session cap, or `undefined` when it may. */
64
+ function overCap(path, projected, capUsd) {
65
+ if (capUsd === undefined)
66
+ return undefined;
67
+ const spent = spentUsd(path);
68
+ if (spent === null || projected === null)
69
+ return "the session's spend or the summary call's price is unknown";
70
+ if (spent + projected > capUsd)
71
+ return `the summary call's projected cost ($${projected.toFixed(4)}) would take the session past its cap ($${capUsd})`;
72
+ return undefined;
73
+ }
74
+ const summaryOf = (message) => message.content
75
+ .flatMap((block) => (block.type === "text" ? [block.text] : []))
76
+ .join("\n")
77
+ .trim();
78
+ /** Writes the `usage` entry for the summary call and returns its id. */
79
+ async function writeUsage(input, message) {
80
+ const entry = await input.append("harness", {
81
+ type: "usage",
82
+ source: "summary",
83
+ usage: message?.usage ?? ZERO_USAGE,
84
+ ...(message?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: message.lastAttemptUsage }),
85
+ // A summary a hook wrote cost nothing here.
86
+ cost: message?.cost ?? { total: 0, basis: "catalog", currency: "USD" },
87
+ });
88
+ return entry.id;
89
+ }
90
+ /** What to do with the context: nothing (under budget), skip with a reason, or compact this span. */
91
+ function plan(input) {
92
+ const { context, starts } = input.view === undefined ? contextWithStarts(input.path) : { context: input.view, starts: input.view.starts };
93
+ const lastUsage = input.view === undefined ? lastUsageSince(input.path) : input.view.lastUsage;
94
+ const before = estimate(context.system, context.messages, lastUsage);
95
+ if (input.force !== true && before <= input.budgetTokens)
96
+ return undefined;
97
+ const cut = tailStart(context.messages, input.settings.tailTokens);
98
+ const firstKept = starts[cut];
99
+ // Nothing to drop when the tail is the whole context, or the only message before it is an earlier summary.
100
+ if (cut === 0 || firstKept === null || firstKept === undefined || (cut === 1 && starts[0] === null)) {
101
+ return { skip: "there is no span to summarise before the verbatim tail" };
102
+ }
103
+ return {
104
+ before,
105
+ span: context.messages.slice(0, cut),
106
+ kept: context.messages.slice(cut),
107
+ firstKept,
108
+ system: context.system,
109
+ cut,
110
+ };
111
+ }
112
+ /** The summary text and the call that wrote it, or the reason there is none. */
113
+ async function summarise(input, p) {
114
+ const { settings, hooks } = input;
115
+ const model = settings.model ?? input.model;
116
+ const event = {
117
+ span: p.span,
118
+ tokens: p.before,
119
+ ...(settings.focus === undefined ? {} : { focus: settings.focus }),
120
+ };
121
+ const replaced = (await hooks.beforeCompact?.(event))?.summary;
122
+ if (replaced !== undefined && replaced.trim() !== "")
123
+ return { summary: replaced, model };
124
+ const prompt = summaryPrompt(p.span, { toolOutputChars: settings.toolOutputChars, focus: settings.focus });
125
+ const request = {
126
+ system: SUMMARY_SYSTEM,
127
+ messages: [{ role: "user", content: [{ type: "text", text: prompt }] }],
128
+ tools: [],
129
+ };
130
+ const callOptions = { cacheRetention: "none", maxOutputTokens: settings.maxOutputTokens };
131
+ const tooLong = tooLongFor(model, request, settings.maxOutputTokens);
132
+ if (tooLong !== undefined)
133
+ return { skip: tooLong };
134
+ const reason = overCap(input.path, projectCallCost(model, request, callOptions).total, settings.capUsd);
135
+ if (reason !== undefined)
136
+ return { skip: reason };
137
+ const message = await model.complete(request, {
138
+ ...callOptions,
139
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
140
+ });
141
+ return { summary: summaryOf(message), message, model };
142
+ }
143
+ /**
144
+ * Compacts the session when its context is over the budget, or at once when `force` is set. Returns what the new
145
+ * `compaction` entry replaced, or `undefined` when it wrote none. A skipped or failed summary writes nothing but, when
146
+ * the call was made, its `usage` entry, and says why through `log`.
147
+ */
148
+ export async function compact(input) {
149
+ const { log, hooks } = input;
150
+ const p = plan(input);
151
+ if (p === undefined)
152
+ return undefined;
153
+ const skipped = (detail) => log?.({ layer: input.layer, event: "skipped", detail });
154
+ if ("skip" in p) {
155
+ skipped(p.skip);
156
+ return undefined;
157
+ }
158
+ let made;
159
+ try {
160
+ made = await summarise(input, p);
161
+ }
162
+ catch (error) {
163
+ // The layer is optional: a provider error or a throwing hook must not stop the turn. An abort still does.
164
+ if (input.signal?.aborted === true)
165
+ throw error;
166
+ skipped(`the summary call failed: ${error instanceof Error ? error.message : String(error)}`);
167
+ return undefined;
168
+ }
169
+ if ("skip" in made) {
170
+ skipped(made.skip);
171
+ return undefined;
172
+ }
173
+ const usageEntryId = await writeUsage(input, made.message);
174
+ // A reply that stopped for any reason but its own end, such as the output limit, is cut off and would replace the span for good.
175
+ if (made.summary === "" || (made.message !== undefined && made.message.stopReason !== "stop")) {
176
+ skipped(`the summary call returned no usable summary (${made.message?.stopReason ?? "empty"})`);
177
+ return undefined;
178
+ }
179
+ const hooked = made.message === undefined;
180
+ const keptChars = p.kept.reduce((sum, m) => sum + charsOf(m), 0);
181
+ const entry = await input.append("harness", {
182
+ type: "compaction",
183
+ layer: input.layer,
184
+ summary: made.summary,
185
+ firstKeptEntryId: p.firstKept,
186
+ tokensBefore: p.before,
187
+ tokensAfter: tokensOfChars(p.system.length + keptChars + charsOf(summaryMessage(made.summary))),
188
+ model: hooked ? { api: "hook", provider: "hook", id: "beforeCompact" } : made.model.ref,
189
+ promptVersion: hooked ? "hook" : SUMMARY_PROMPT_VERSION,
190
+ usageEntryId,
191
+ ...(input.settings.focus === undefined ? {} : { focus: input.settings.focus }),
192
+ });
193
+ log?.({
194
+ layer: input.layer,
195
+ event: "compacted",
196
+ detail: `${p.before} tokens before, ${tokensOfChars(keptChars)} kept`,
197
+ });
198
+ // The entry is written, so a failing hook is reported and the compaction stands.
199
+ await Promise.resolve()
200
+ .then(() => hooks.afterCompact?.(entry))
201
+ .catch((error) => skipped(`afterCompact failed: ${error instanceof Error ? error.message : String(error)}`));
202
+ return { summary: made.summary, keptFrom: p.cut };
203
+ }
204
+ //# sourceMappingURL=summarize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"summarize.js","sourceRoot":"","sources":["../../src/context/summarize.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAKL,eAAe,GAChB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAkB,aAAa,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAqC9F,MAAM,UAAU,GAAG;IACjB,aAAa,EAAE,CAAC;IAChB,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE;IAChC,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;IACZ,GAAG,EAAE,IAAI;CACV,CAAC;AAEF,4HAA4H;AAC5H,SAAS,cAAc,CAAC,IAA6B;IACnD,MAAM,IAAI,GAAG,IAAI,CAAC,aAAa,CAAC,CAAC,KAAK,EAAE,E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,YAAY;QACZ,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;KAC/E,CAAC,CAAC;IACH,GAAG,EAAE,CAAC;QACJ,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,KAAK,EAAE,WAAW;QAClB,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,mBAAmB,aAAa,CAAC,SAAS,CAAC,OAAO;KACtE,CAAC,CAAC;IACH,iFAAiF;IACjF,MAAM,OAAO,CAAC,OAAO,EAAE;SACpB,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC,KAAwB,CAAC,CAAC;SAC1D,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE,CACxB,OAAO,CAAC,wBAAwB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAC1F,CAAC;IACJ,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC;AACpD,CAAC","sourcesContent":["/**\n * Layer 3: summarise the span a long session has outgrown, between turns. The harness keeps a verbatim tail, asks a\n * model for a recall-first summary of everything before it, and writes the result as a `compaction` entry beside a\n * `usage` entry that holds the call's cost. No entry is changed or removed: the log still holds every original, and\n * only the context a later turn rebuilds starts from the summary.\n */\nimport {\n type AssistantMessage,\n type Message,\n type Model,\n type ModelContext,\n projectCallCost,\n} from \"@buildanagent/gateway\";\nimport type { CompactionEntry, SessionEntry } from \"@buildanagent/protocol\";\nimport { contextWithStarts, summaryMessage } from \"../session/rebuild.js\";\nimport { charsOf, estimate, type LastUsage, tokensOfChars } from \"./estimate.js\";\nimport { SUMMARY_PROMPT_VERSION, SUMMARY_SYSTEM, summaryPrompt } from \"./summary-template.js\";\nimport type { AppendEntry, CompactEvent, CompactionLog, ContextHooks, SummarizeSettings } from \"./types.js\";\n\n/** What `compact()` needs for one turn. */\nexport interface CompactInput {\n readonly path: readonly SessionEntry[];\n readonly append: AppendEntry;\n readonly model: Model;\n readonly settings: Required<Pick<SummarizeSettings, \"tailTokens\" | \"toolOutputChars\" | \"maxOutputTokens\">> &\n Pick<SummarizeSettings, \"model\" | \"focus\" | \"capUsd\">;\n readonly budgetTokens: number;\n readonly hooks: ContextHooks;\n readonly log: CompactionLog | undefined;\n /** Stops the summary call when the turn is aborted. */\n readonly signal?: AbortSignal | undefined;\n /** Which layer is compacting; written on the entry and in each log record. */\n readonly layer: CompactionEntry[\"layer\"];\n /** Compact whatever the size: a provider has already said the context is too big. */\n readonly force?: boolean;\n /**\n * The context to compact, when it is not the one the log rebuilds: a run's own transcript in the middle of a turn.\n * `starts` names the entry each message begins at, and must line up with `messages`.\n */\n readonly view?: {\n readonly system: string;\n readonly messages: readonly Message[];\n readonly starts: readonly (string | null)[];\n readonly lastUsage?: LastUsage | undefined;\n };\n}\n\n/** What a compaction replaced: the summary, and the index of the first message kept. */\nexport interface Compacted {\n readonly summary: string;\n readonly keptFrom: number;\n}\n\nconst ZERO_USAGE = {\n uncachedInput: 0,\n cacheRead: 0,\n cacheWrite: { \"5m\": 0, \"1h\": 0 },\n output: 0,\n reasoning: 0,\n raw: null,\n};\n\n/** The usage of the last model call since the latest compaction, or `undefined` when none is a fair size of the context. */\nfunction lastUsageSince(path: readonly SessionEntry[]): LastUsage | undefined {\n const from = path.findLastIndex((entry) => entry.type === \"compaction\");\n const last = path.slice(from + 1).findLast((entry) => entry.type === \"usage\" && entry.source === \"model_call\");\n return last?.type === \"usage\" && last.usage.raw !== null ? last.usage : undefined;\n}\n\n/**\n * The index of the first message of the tail: the newest messages that together reach `tailTokens`, moved earlier until\n * the tail starts with an assistant message, so a call is never split from its result and the summary is never followed\n * by another user message. 0 means nothing can be dropped.\n */\nexport function tailStart(messages: readonly Message[], tailTokens: number): number {\n let tokens = 0;\n let start = messages.length;\n while (start > 0 && tokens < tailTokens) {\n start--;\n tokens += tokensOfChars(charsOf(messages[start] as Message));\n }\n // The tail starts with an assistant message: after the summary, which is a user message, a tool result would lose its\n // call and a second user message would follow a user message.\n while (start > 0 && messages[start]?.role !== \"assistant\") start--;\n return start;\n}\n\n/** The reason the summary request cannot fit the summary model's window, or `undefined` when it fits. */\nfunction tooLongFor(model: Model, request: ModelContext, maxOutputTokens: number): string | undefined {\n const chars = request.messages.reduce((sum, message) => sum + charsOf(message), request.system.length);\n const room = model.caps.contextWindow - maxOutputTokens;\n if (tokensOfChars(chars) <= room) return undefined;\n return `the span is about ${tokensOfChars(chars)} tokens, more than the summary model's window leaves room for (${room})`;\n}\n\n/** Money spent on the branch so far, from the `usage` entries from the root to HEAD; `null` when a call's price is unknown. */\nfunction spentUsd(path: readonly SessionEntry[]): number | null {\n let total = 0;\n for (const entry of path) {\n if (entry.type !== \"usage\") continue;\n if (entry.cost.total === null) return null;\n total += entry.cost.total;\n }\n return total;\n}\n\n/** Why the summary call may not run under the session cap, or `undefined` when it may. */\nfunction overCap(\n path: readonly SessionEntry[],\n projected: number | null,\n capUsd: number | undefined,\n): string | undefined {\n if (capUsd === undefined) return undefined;\n const spent = spentUsd(path);\n if (spent === null || projected === null) return \"the session's spend or the summary call's price is unknown\";\n if (spent + projected > capUsd)\n return `the summary call's projected cost ($${projected.toFixed(4)}) would take the session past its cap ($${capUsd})`;\n return undefined;\n}\n\nconst summaryOf = (message: AssistantMessage): string =>\n message.content\n .flatMap((block) => (block.type === \"text\" ? [block.text] : []))\n .join(\"\\n\")\n .trim();\n\n/** Writes the `usage` entry for the summary call and returns its id. */\nasync function writeUsage(input: CompactInput, message: AssistantMessage | undefined): Promise<string> {\n const entry = await input.append(\"harness\", {\n type: \"usage\",\n source: \"summary\",\n usage: message?.usage ?? ZERO_USAGE,\n ...(message?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: message.lastAttemptUsage }),\n // A summary a hook wrote cost nothing here.\n cost: message?.cost ?? { total: 0, basis: \"catalog\", currency: \"USD\" },\n });\n return entry.id;\n}\n\n/** The part of the context a compaction replaces, and where the kept tail begins. */\ninterface Plan {\n readonly before: number;\n readonly span: readonly Message[];\n readonly kept: readonly Message[];\n readonly firstKept: string;\n readonly system: string;\n readonly cut: number;\n}\n\n/** What to do with the context: nothing (under budget), skip with a reason, or compact this span. */\nfunction plan(input: CompactInput): Plan | { readonly skip: string } | undefined {\n const { context, starts } =\n input.view === undefined ? contextWithStarts(input.path) : { context: input.view, starts: input.view.starts };\n const lastUsage = input.view === undefined ? lastUsageSince(input.path) : input.view.lastUsage;\n const before = estimate(context.system, context.messages, lastUsage);\n if (input.force !== true && before <= input.budgetTokens) return undefined;\n const cut = tailStart(context.messages, input.settings.tailTokens);\n const firstKept = starts[cut];\n // Nothing to drop when the tail is the whole context, or the only message before it is an earlier summary.\n if (cut === 0 || firstKept === null || firstKept === undefined || (cut === 1 && starts[0] === null)) {\n return { skip: \"there is no span to summarise before the verbatim tail\" };\n }\n return {\n before,\n span: context.messages.slice(0, cut),\n kept: context.messages.slice(cut),\n firstKept,\n system: context.system,\n cut,\n };\n}\n\n/** The summary text and the call that wrote it, or the reason there is none. */\nasync function summarise(\n input: CompactInput,\n p: Plan,\n): Promise<{ summary: string; message?: AssistantMessage; model: Model } | { skip: string }> {\n const { settings, hooks } = input;\n const model = settings.model ?? input.model;\n const event: CompactEvent = {\n span: p.span,\n tokens: p.before,\n ...(settings.focus === undefined ? {} : { focus: settings.focus }),\n };\n const replaced = (await hooks.beforeCompact?.(event))?.summary;\n if (replaced !== undefined && replaced.trim() !== \"\") return { summary: replaced, model };\n const prompt = summaryPrompt(p.span, { toolOutputChars: settings.toolOutputChars, focus: settings.focus });\n const request: ModelContext = {\n system: SUMMARY_SYSTEM,\n messages: [{ role: \"user\", content: [{ type: \"text\", text: prompt }] }],\n tools: [],\n };\n const callOptions = { cacheRetention: \"none\" as const, maxOutputTokens: settings.maxOutputTokens };\n const tooLong = tooLongFor(model, request, settings.maxOutputTokens);\n if (tooLong !== undefined) return { skip: tooLong };\n const reason = overCap(input.path, projectCallCost(model, request, callOptions).total, settings.capUsd);\n if (reason !== undefined) return { skip: reason };\n const message = await model.complete(request, {\n ...callOptions,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n return { summary: summaryOf(message), message, model };\n}\n\n/**\n * Compacts the session when its context is over the budget, or at once when `force` is set. Returns what the new\n * `compaction` entry replaced, or `undefined` when it wrote none. A skipped or failed summary writes nothing but, when\n * the call was made, its `usage` entry, and says why through `log`.\n */\nexport async function compact(input: CompactInput): Promise<Compacted | undefined> {\n const { log, hooks } = input;\n const p = plan(input);\n if (p === undefined) return undefined;\n const skipped = (detail: string) => log?.({ layer: input.layer, event: \"skipped\", detail });\n if (\"skip\" in p) {\n skipped(p.skip);\n return undefined;\n }\n let made: Awaited<ReturnType<typeof summarise>>;\n try {\n made = await summarise(input, p);\n } catch (error) {\n // The layer is optional: a provider error or a throwing hook must not stop the turn. An abort still does.\n if (input.signal?.aborted === true) throw error;\n skipped(`the summary call failed: ${error instanceof Error ? error.message : String(error)}`);\n return undefined;\n }\n if (\"skip\" in made) {\n skipped(made.skip);\n return undefined;\n }\n const usageEntryId = await writeUsage(input, made.message);\n // A reply that stopped for any reason but its own end, such as the output limit, is cut off and would replace the span for good.\n if (made.summary === \"\" || (made.message !== undefined && made.message.stopReason !== \"stop\")) {\n skipped(`the summary call returned no usable summary (${made.message?.stopReason ?? \"empty\"})`);\n return undefined;\n }\n const hooked = made.message === undefined;\n const keptChars = p.kept.reduce((sum, m) => sum + charsOf(m), 0);\n const entry = await input.append(\"harness\", {\n type: \"compaction\",\n layer: input.layer,\n summary: made.summary,\n firstKeptEntryId: p.firstKept,\n tokensBefore: p.before,\n tokensAfter: tokensOfChars(p.system.length + keptChars + charsOf(summaryMessage(made.summary))),\n model: hooked ? { api: \"hook\", provider: \"hook\", id: \"beforeCompact\" } : made.model.ref,\n promptVersion: hooked ? \"hook\" : SUMMARY_PROMPT_VERSION,\n usageEntryId,\n ...(input.settings.focus === undefined ? {} : { focus: input.settings.focus }),\n });\n log?.({\n layer: input.layer,\n event: \"compacted\",\n detail: `${p.before} tokens before, ${tokensOfChars(keptChars)} kept`,\n });\n // The entry is written, so a failing hook is reported and the compaction stands.\n await Promise.resolve()\n .then(() => hooks.afterCompact?.(entry as CompactionEntry))\n .catch((error: unknown) =>\n skipped(`afterCompact failed: ${error instanceof Error ? error.message : String(error)}`),\n );\n return { summary: made.summary, keptFrom: p.cut };\n}\n"]}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The summary request: a recall-first template with fixed sections, and a rule to keep exact identifiers. The system
3
+ * prompt and the sections are Pi's compaction prompt (`@earendil-works/pi-coding-agent` 1.5.2), copied from the text
4
+ * its summary call sends; the version names this wording, so an entry says which template wrote its summary and a change
5
+ * to the wording is a new version.
6
+ *
7
+ * Pi is MIT licensed, and its notice is kept here as the licence asks:
8
+ *
9
+ * MIT License. Copyright (c) 2025 Mario Zechner. Permission is hereby granted, free of charge, to any person obtaining a
10
+ * copy of this software and associated documentation files (the "Software"), to deal in the Software without
11
+ * restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
13
+ * following conditions: The above copyright notice and this permission notice shall be included in all copies or
14
+ * substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
18
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+ */
20
+ import type { Message } from "@buildanagent/gateway";
21
+ /** The version of the template below. Stored on each `compaction` entry as `promptVersion`. */
22
+ export declare const SUMMARY_PROMPT_VERSION = "recall-v1";
23
+ /** The system prompt of the summary call. */
24
+ export declare const SUMMARY_SYSTEM = "You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.";
25
+ /** The summary call's user message: the whole span, then the format, then an optional focus. */
26
+ export declare function summaryPrompt(span: readonly Message[], options: {
27
+ toolOutputChars: number;
28
+ focus?: string | undefined;
29
+ }): string;
@@ -0,0 +1,69 @@
1
+ /** The version of the template below. Stored on each `compaction` entry as `promptVersion`. */
2
+ export const SUMMARY_PROMPT_VERSION = "recall-v1";
3
+ /** The system prompt of the summary call. */
4
+ export const SUMMARY_SYSTEM = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
5
+
6
+ Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;
7
+ const SECTIONS = `## Goal
8
+ [What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
9
+
10
+ ## Constraints & Preferences
11
+ - [Any constraints, preferences, or requirements mentioned by user]
12
+ - [Or "(none)" if none were mentioned]
13
+
14
+ ## Progress
15
+ ### Done
16
+ - [x] [Completed tasks/changes]
17
+
18
+ ### In Progress
19
+ - [ ] [Current work]
20
+
21
+ ### Blocked
22
+ - [Issues preventing progress, if any]
23
+
24
+ ## Key Decisions
25
+ - **[Decision]**: [Brief rationale]
26
+
27
+ ## Next Steps
28
+ 1. [Ordered list of what should happen next]
29
+
30
+ ## Critical Context
31
+ - [Any data, examples, or references needed to continue]
32
+ - [Or "(none)" if not applicable]`;
33
+ const text = (blocks) => blocks.map((block) => (block.type === "text" ? block.text : "[image]")).join("\n");
34
+ const cut = (value, chars) => value.length <= chars ? value : `${value.slice(0, chars)} [... ${value.length - chars} more characters cut]`;
35
+ /** One message as the summary call reads it: a labelled line, with a tool result cut to `toolOutputChars`. */
36
+ function render(message, toolOutputChars) {
37
+ if (message.role === "user")
38
+ return `[User]: ${message.content.map((b) => (b.type === "text" ? b.text : "[image]")).join("\n")}`;
39
+ if (message.role === "tool")
40
+ return `[Tool result${message.isError ? " (error)" : ""}]: ${cut(text(message.content), toolOutputChars)}`;
41
+ const parts = message.content.flatMap((block) => {
42
+ if (block.type === "text")
43
+ return [`[Assistant]: ${block.text}`];
44
+ if (block.type === "tool_call")
45
+ return [`[Assistant tool call]: ${block.name}(${JSON.stringify(block.input)})`];
46
+ return [];
47
+ });
48
+ return parts.join("\n\n");
49
+ }
50
+ /** The summary call's user message: the whole span, then the format, then an optional focus. */
51
+ export function summaryPrompt(span, options) {
52
+ const conversation = span
53
+ .map((message) => render(message, options.toolOutputChars))
54
+ .filter((line) => line !== "")
55
+ .join("\n\n");
56
+ const focus = options.focus === undefined ? "" : `\n\nPay particular attention to: ${options.focus}`;
57
+ return `<conversation>
58
+ ${conversation}
59
+ </conversation>
60
+
61
+ The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
62
+
63
+ Use this EXACT format:
64
+
65
+ ${SECTIONS}
66
+
67
+ Keep each section concise. Preserve exact file paths, function names, and error messages.${focus}`;
68
+ }
69
+ //# sourceMappingURL=summary-template.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"summary-template.js","sourceRoot":"","sources":["../../src/context/summary-template.ts"],"names":[],"mappings":"AAqBA,+FAA+F;AAC/F,MAAM,CAAC,MAAM,sBAAsB,GAAG,WAAW,CAAC;AAElD,6CAA6C;AAC7C,MAAM,CAAC,MAAM,cAAc,GAAG;;2HAE6F,CAAC;AAE5H,MAAM,QAAQ,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;kCAyB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AE,CAAC,CAAC;QACjE,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW;YAAE,OAAO,CAAC,0BAA0B,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAChH,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,CAAC;AAED,gGAAgG;AAChG,MAAM,UAAU,aAAa,CAC3B,IAAwB,EACxB,OAAgE;IAEhE,MAAM,YAAY,GAAG,IAAI;SACtB,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;SAC1D,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC;SAC7B,IAAI,CAAC,MAAM,CAAC,CAAC;IAChB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,oCAAoC,OAAO,CAAC,KAAK,EAAE,CAAC;IACrG,OAAO;EACP,YAAY;;;;;;;EAOZ,QAAQ;;2FAEiF,KAAK,EAAE,CAAC;AACnG,CAAC","sourcesContent":["/**\n * The summary request: a recall-first template with fixed sections, and a rule to keep exact identifiers. The system\n * prompt and the sections are Pi's compaction prompt (`@earendil-works/pi-coding-agent` 1.5.2), copied from the text\n * its summary call sends; the version names this wording, so an entry says which template wrote its summary and a change\n * to the wording is a new version.\n *\n * Pi is MIT licensed, and its notice is kept here as the licence asks:\n *\n * MIT License. Copyright (c) 2025 Mario Zechner. Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the\n * following conditions: The above copyright notice and this permission notice shall be included in all copies or\n * substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport type { Message, ModelContent } from \"@buildanagent/gateway\";\n\n/** The version of the template below. Stored on each `compaction` entry as `promptVersion`. */\nexport const SUMMARY_PROMPT_VERSION = \"recall-v1\";\n\n/** The system prompt of the summary call. */\nexport const SUMMARY_SYSTEM = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n\nconst SECTIONS = `## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]`;\n\nconst text = (blocks: readonly ModelContent[]): string =>\n blocks.map((block) => (block.type === \"text\" ? block.text : \"[image]\")).join(\"\\n\");\n\nconst cut = (value: string, chars: number): string =>\n value.length <= chars ? value : `${value.slice(0, chars)} [... ${value.length - chars} more characters cut]`;\n\n/** One message as the summary call reads it: a labelled line, with a tool result cut to `toolOutputChars`. */\nfunction render(message: Message, toolOutputChars: number): string {\n if (message.role === \"user\")\n return `[User]: ${message.content.map((b) => (b.type === \"text\" ? b.text : \"[image]\")).join(\"\\n\")}`;\n if (message.role === \"tool\")\n return `[Tool result${message.isError ? \" (error)\" : \"\"}]: ${cut(text(message.content), toolOutputChars)}`;\n const parts = message.content.flatMap((block) => {\n if (block.type === \"text\") return [`[Assistant]: ${block.text}`];\n if (block.type === \"tool_call\") return [`[Assistant tool call]: ${block.name}(${JSON.stringify(block.input)})`];\n return [];\n });\n return parts.join(\"\\n\\n\");\n}\n\n/** The summary call's user message: the whole span, then the format, then an optional focus. */\nexport function summaryPrompt(\n span: readonly Message[],\n options: { toolOutputChars: number; focus?: string | undefined },\n): string {\n const conversation = span\n .map((message) => render(message, options.toolOutputChars))\n .filter((line) => line !== \"\")\n .join(\"\\n\\n\");\n const focus = options.focus === undefined ? \"\" : `\\n\\nPay particular attention to: ${options.focus}`;\n return `<conversation>\n${conversation}\n</conversation>\n\nThe messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n${SECTIONS}\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.${focus}`;\n}\n"]}
@@ -0,0 +1,150 @@
1
+ import type { Message, Model } from "@buildanagent/gateway";
2
+ import type { CompactionEntry, Origin, SessionEntry } from "@buildanagent/protocol";
3
+ import type { Interceptors } from "@buildanagent/sdk";
4
+ import type { Session } from "../session/session.js";
5
+ import type { EntryInput, SessionKey } from "../session/store.js";
6
+ /** The five context layers, cheapest first. A layer can be switched off by name in `ContextPolicyOptions.layers`. */
7
+ export type LayerName = "write_cap" | "mask" | "summarize" | "mid_turn" | "overflow_retry";
8
+ /** Where the full text of a capped tool result goes, so the model keeps a pointer and nothing is lost. */
9
+ export interface SpillStore {
10
+ /** Stores `text` for one tool call of one session and returns the path the model and the log name it by. */
11
+ write(key: SessionKey, callId: string, text: string): Promise<string>;
12
+ }
13
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
14
+ /** An entry as the policy hands it to the harness's writer: the writer adds its id, parent, time and origin. */
15
+ export type EntryBody = DistributiveOmit<EntryInput, "id" | "parentId" | "timestamp" | "origin">;
16
+ /** Writes one entry at the log's end and returns it as stored. */
17
+ export type AppendEntry = (origin: Origin, body: EntryBody) => Promise<SessionEntry>;
18
+ /** What `hooks.beforeCompact` receives: the span about to be summarised. */
19
+ export interface CompactEvent {
20
+ /** The messages the summary replaces: the whole discarded span, never its tail only. */
21
+ readonly span: readonly Message[];
22
+ /** The estimated tokens of the context before compaction. */
23
+ readonly tokens: number;
24
+ readonly focus?: string;
25
+ }
26
+ /** Hooks around a compaction. */
27
+ export interface ContextHooks {
28
+ /** Returns `{ summary }` to use that text in place of the model's; the entry then records `promptVersion: "hook"`. */
29
+ readonly beforeCompact?: (event: CompactEvent) => Promise<{
30
+ readonly summary?: string;
31
+ } | undefined>;
32
+ /** Called with the `compaction` entry after it is written. */
33
+ readonly afterCompact?: (entry: CompactionEntry) => Promise<void>;
34
+ }
35
+ /** What a layer reports when it compacts or declines to. */
36
+ export interface CompactionRecord {
37
+ readonly layer: LayerName;
38
+ readonly event: "compacted" | "skipped";
39
+ readonly detail: string;
40
+ }
41
+ /** Called with each record of a compaction or a skipped one. */
42
+ export type CompactionLog = (record: CompactionRecord) => void;
43
+ /** The settings of the summary layer. */
44
+ export interface SummarizeSettings {
45
+ /** The tokens of the newest messages kept verbatim. Default 20,000. */
46
+ readonly tailTokens?: number;
47
+ /** The characters of each tool result the summary call reads. Default 2,000. */
48
+ readonly toolOutputChars?: number;
49
+ /** The output limit of the summary call. Default 4,096. */
50
+ readonly maxOutputTokens?: number;
51
+ /** The model that writes the summary. Default the turn's model. */
52
+ readonly model?: Model;
53
+ /** A hint that steers what the summary keeps; recorded on the entry. */
54
+ readonly focus?: string;
55
+ /**
56
+ * The session's spend cap in US dollars, counted over the entries from the root to HEAD, so a branch left behind by a
57
+ * re-run is not counted. A summary whose projected cost would pass it is skipped. It guards the summary call only: it
58
+ * keeps no room for the turn's own next call, and a summary a hook wrote is not checked. Default none.
59
+ */
60
+ readonly capUsd?: number;
61
+ }
62
+ /** The settings of `createContextPolicy()`. */
63
+ export interface ContextPolicyOptions {
64
+ /** Where the write cap keeps a result's full text. Required unless the `write_cap` layer is off. */
65
+ readonly spill?: SpillStore;
66
+ /**
67
+ * The most bytes a tool result takes in the log, JSON escaping and a 1 KiB reserve for the entry's own fields
68
+ * included, so the model reads a little less than this. Default 65,536, the stores' entry bound.
69
+ */
70
+ readonly writeCapBytes?: number;
71
+ /** How masking shortens an older tool result and how often its cutoff moves. Defaults 500 characters, 8 messages. */
72
+ readonly mask?: {
73
+ readonly keepChars: number;
74
+ readonly stepMessages: number;
75
+ };
76
+ /** The token budget `fill()` reports against. Default the model's window less 16,384, at most 200,000. */
77
+ readonly budgetTokens?: number;
78
+ /** The share of the window at which the mid-turn layer compacts. Default 0.9. */
79
+ readonly midTurnRatio?: number;
80
+ /** The summary layer's settings. */
81
+ readonly summarize?: SummarizeSettings;
82
+ /** Hooks around a compaction. */
83
+ readonly hooks?: ContextHooks;
84
+ /** Told of each compaction and each one skipped. */
85
+ readonly log?: CompactionLog;
86
+ /** A layer set to `false` has no effect. Every layer defaults to on. */
87
+ readonly layers?: Partial<Record<LayerName, boolean>>;
88
+ }
89
+ /** How full the request view is: an estimate, so a display can warn before the window does. */
90
+ export interface ContextFill {
91
+ readonly tokens: number;
92
+ readonly budget: number;
93
+ readonly window: number;
94
+ }
95
+ /** What the policy knows about one turn. */
96
+ export interface TurnContextOptions {
97
+ readonly session: Session;
98
+ readonly model: Model;
99
+ /** Called with the fill after each request view is built. */
100
+ readonly onFill?: (fill: ContextFill) => void;
101
+ /** False when the turn is a retry after an overflow, which compacts at most once more, through the overflow layer. */
102
+ readonly midTurn?: boolean;
103
+ /** True when the caller supplied the turn's history, so the log's entries do not describe the context. */
104
+ readonly ownHistory?: boolean;
105
+ }
106
+ /** The policy's hooks and state for one turn. */
107
+ export interface TurnContext {
108
+ /** The write cap in `afterToolCall` and masking in `transformContext`. */
109
+ readonly interceptors: Pick<Interceptors, "transformContext" | "afterToolCall">;
110
+ /** Where the write cap put a call's full text, or `undefined` when the call was not capped. */
111
+ spillOf(callId: string): {
112
+ readonly path: string;
113
+ readonly bytes: number;
114
+ } | undefined;
115
+ /**
116
+ * Summarises the session when its context is over the budget, before the turn's input is written. Returns whether it
117
+ * wrote a `compaction` entry.
118
+ */
119
+ compact(input: {
120
+ readonly path: readonly SessionEntry[];
121
+ readonly append: AppendEntry;
122
+ /** Stops the summary call when the turn is aborted. */
123
+ readonly signal?: AbortSignal;
124
+ }): Promise<boolean>;
125
+ /**
126
+ * Gives the turn's writer to the layers that write inside a run, once it exists: `append` writes an entry and
127
+ * `settle` waits for every entry the run has produced so far.
128
+ */
129
+ attach(bindings: {
130
+ readonly append: AppendEntry;
131
+ readonly settle: () => Promise<void>;
132
+ }): void;
133
+ /**
134
+ * Called when a model call failed because the request was too large. Compacts once, whatever the size, and returns
135
+ * whether it wrote a `compaction` entry; the caller then tries the call again on the rebuilt context.
136
+ */
137
+ onOverflow(input: {
138
+ readonly path: readonly SessionEntry[];
139
+ readonly append: AppendEntry;
140
+ readonly signal?: AbortSignal;
141
+ }): Promise<boolean>;
142
+ /** The fill after the latest request view. */
143
+ fill(): ContextFill;
144
+ }
145
+ /** A context policy: the layers, built once and applied to every turn of a harness. */
146
+ export interface ContextPolicy {
147
+ /** Starts the layers for one turn of one session. */
148
+ forTurn(options: TurnContextOptions): TurnContext;
149
+ }
150
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/context/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Message, Model } from \"@buildanagent/gateway\";\nimport type { CompactionEntry, Origin, SessionEntry } from \"@buildanagent/protocol\";\nimport type { Interceptors } from \"@buildanagent/sdk\";\nimport type { Session } from \"../session/session.js\";\nimport type { EntryInput, SessionKey } from \"../session/store.js\";\n\n/** The five context layers, cheapest first. A layer can be switched off by name in `ContextPolicyOptions.layers`. */\nexport type LayerName = \"write_cap\" | \"mask\" | \"summarize\" | \"mid_turn\" | \"overflow_retry\";\n\n/** Where the full text of a capped tool result goes, so the model keeps a pointer and nothing is lost. */\nexport interface SpillStore {\n /** Stores `text` for one tool call of one session and returns the path the model and the log name it by. */\n write(key: SessionKey, callId: string, text: string): Promise<string>;\n}\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n/** An entry as the policy hands it to the harness's writer: the writer adds its id, parent, time and origin. */\nexport type EntryBody = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n/** Writes one entry at the log's end and returns it as stored. */\nexport type AppendEntry = (origin: Origin, body: EntryBody) => Promise<SessionEntry>;\n\n/** What `hooks.beforeCompact` receives: the span about to be summarised. */\nexport interface CompactEvent {\n /** The messages the summary replaces: the whole discarded span, never its tail only. */\n readonly span: readonly Message[];\n /** The estimated tokens of the context before compaction. */\n readonly tokens: number;\n readonly focus?: string;\n}\n\n/** Hooks around a compaction. */\nexport interface ContextHooks {\n /** Returns `{ summary }` to use that text in place of the model's; the entry then records `promptVersion: \"hook\"`. */\n readonly beforeCompact?: (event: CompactEvent) => Promise<{ readonly summary?: string } | undefined>;\n /** Called with the `compaction` entry after it is written. */\n readonly afterCompact?: (entry: CompactionEntry) => Promise<void>;\n}\n\n/** What a layer reports when it compacts or declines to. */\nexport interface CompactionRecord {\n readonly layer: LayerName;\n readonly event: \"compacted\" | \"skipped\";\n readonly detail: string;\n}\n\n/** Called with each record of a compaction or a skipped one. */\nexport type CompactionLog = (record: CompactionRecord) => void;\n\n/** The settings of the summary layer. */\nexport interface SummarizeSettings {\n /** The tokens of the newest messages kept verbatim. Default 20,000. */\n readonly tailTokens?: number;\n /** The characters of each tool result the summary call reads. Default 2,000. */\n readonly toolOutputChars?: number;\n /** The output limit of the summary call. Default 4,096. */\n readonly maxOutputTokens?: number;\n /** The model that writes the summary. Default the turn's model. */\n readonly model?: Model;\n /** A hint that steers what the summary keeps; recorded on the entry. */\n readonly focus?: string;\n /**\n * The session's spend cap in US dollars, counted over the entries from the root to HEAD, so a branch left behind by a\n * re-run is not counted. A summary whose projected cost would pass it is skipped. It guards the summary call only: it\n * keeps no room for the turn's own next call, and a summary a hook wrote is not checked. Default none.\n */\n readonly capUsd?: number;\n}\n\n/** The settings of `createContextPolicy()`. */\nexport interface ContextPolicyOptions {\n /** Where the write cap keeps a result's full text. Required unless the `write_cap` layer is off. */\n readonly spill?: SpillStore;\n /**\n * The most bytes a tool result takes in the log, JSON escaping and a 1 KiB reserve for the entry's own fields\n * included, so the model reads a little less than this. Default 65,536, the stores' entry bound.\n */\n readonly writeCapBytes?: number;\n /** How masking shortens an older tool result and how often its cutoff moves. Defaults 500 characters, 8 messages. */\n readonly mask?: { readonly keepChars: number; readonly stepMessages: number };\n /** The token budget `fill()` reports against. Default the model's window less 16,384, at most 200,000. */\n readonly budgetTokens?: number;\n /** The share of the window at which the mid-turn layer compacts. Default 0.9. */\n readonly midTurnRatio?: number;\n /** The summary layer's settings. */\n readonly summarize?: SummarizeSettings;\n /** Hooks around a compaction. */\n readonly hooks?: ContextHooks;\n /** Told of each compaction and each one skipped. */\n readonly log?: CompactionLog;\n /** A layer set to `false` has no effect. Every layer defaults to on. */\n readonly layers?: Partial<Record<LayerName, boolean>>;\n}\n\n/** How full the request view is: an estimate, so a display can warn before the window does. */\nexport interface ContextFill {\n readonly tokens: number;\n readonly budget: number;\n readonly window: number;\n}\n\n/** What the policy knows about one turn. */\nexport interface TurnContextOptions {\n readonly session: Session;\n readonly model: Model;\n /** Called with the fill after each request view is built. */\n readonly onFill?: (fill: ContextFill) => void;\n /** False when the turn is a retry after an overflow, which compacts at most once more, through the overflow layer. */\n readonly midTurn?: boolean;\n /** True when the caller supplied the turn's history, so the log's entries do not describe the context. */\n readonly ownHistory?: boolean;\n}\n\n/** The policy's hooks and state for one turn. */\nexport interface TurnContext {\n /** The write cap in `afterToolCall` and masking in `transformContext`. */\n readonly interceptors: Pick<Interceptors, \"transformContext\" | \"afterToolCall\">;\n /** Where the write cap put a call's full text, or `undefined` when the call was not capped. */\n spillOf(callId: string): { readonly path: string; readonly bytes: number } | undefined;\n /**\n * Summarises the session when its context is over the budget, before the turn's input is written. Returns whether it\n * wrote a `compaction` entry.\n */\n compact(input: {\n readonly path: readonly SessionEntry[];\n readonly append: AppendEntry;\n /** Stops the summary call when the turn is aborted. */\n readonly signal?: AbortSignal;\n }): Promise<boolean>;\n /**\n * Gives the turn's writer to the layers that write inside a run, once it exists: `append` writes an entry and\n * `settle` waits for every entry the run has produced so far.\n */\n attach(bindings: { readonly append: AppendEntry; readonly settle: () => Promise<void> }): void;\n /**\n * Called when a model call failed because the request was too large. Compacts once, whatever the size, and returns\n * whether it wrote a `compaction` entry; the caller then tries the call again on the rebuilt context.\n */\n onOverflow(input: {\n readonly path: readonly SessionEntry[];\n readonly append: AppendEntry;\n readonly signal?: AbortSignal;\n }): Promise<boolean>;\n /** The fill after the latest request view. */\n fill(): ContextFill;\n}\n\n/** A context policy: the layers, built once and applied to every turn of a harness. */\nexport interface ContextPolicy {\n /** Starts the layers for one turn of one session. */\n forTurn(options: TurnContextOptions): TurnContext;\n}\n"]}
@@ -0,0 +1,19 @@
1
+ /** Layer 1: cap what the model reads of one tool result, and keep the full text in a spill file. */
2
+ import type { ModelContent } from "@buildanagent/gateway";
3
+ /** The text blocks of a result, joined, and the other blocks (images) left as they are. */
4
+ export declare function textOf(content: readonly ModelContent[]): string;
5
+ /** The first `bytes` bytes of `text`, cut so no UTF-8 character is split. */
6
+ export declare function headBytes(text: string, bytes: number): string;
7
+ /** The byte length of `text` in UTF-8. */
8
+ export declare const byteLength: (text: string) => number;
9
+ /** The line that tells the model where the rest of a capped result went, or that it was not kept. */
10
+ export declare const capNotice: (kept: number, total: number, path: string | undefined) => string;
11
+ /** The room an entry's own fields (ids, timestamps, the call's name) take beside its content. */
12
+ export declare const ENTRY_RESERVE_BYTES = 1024;
13
+ /** The bytes `text` takes inside a JSON string, quotes left out: what a quote, a newline or a control character costs. */
14
+ export declare const escapedBytes: (text: string) => number;
15
+ /**
16
+ * The longest start of `text` whose JSON-escaped form is at most `limit` bytes, cut so no UTF-8 character is split.
17
+ * A text full of newlines or quotes takes more bytes in the log than it has characters, so the cut counts the log's bytes.
18
+ */
19
+ export declare function fitHead(text: string, limit: number): string;
@@ -0,0 +1,41 @@
1
+ const encoder = new TextEncoder();
2
+ const decoder = new TextDecoder("utf-8", { fatal: false });
3
+ /** The text blocks of a result, joined, and the other blocks (images) left as they are. */
4
+ export function textOf(content) {
5
+ return content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
6
+ }
7
+ /** The first `bytes` bytes of `text`, cut so no UTF-8 character is split. */
8
+ export function headBytes(text, bytes) {
9
+ const encoded = encoder.encode(text);
10
+ if (encoded.length <= bytes)
11
+ return text;
12
+ let end = bytes;
13
+ // A continuation byte starts with 10; back up to the byte that begins the character the cut split.
14
+ while (end > 0 && (encoded[end] & 0b1100_0000) === 0b1000_0000)
15
+ end--;
16
+ return decoder.decode(encoded.subarray(0, end));
17
+ }
18
+ /** The byte length of `text` in UTF-8. */
19
+ export const byteLength = (text) => encoder.encode(text).length;
20
+ /** The line that tells the model where the rest of a capped result went, or that it was not kept. */
21
+ export const capNotice = (kept, total, path) => path === undefined
22
+ ? `[output cut: the first ${kept} of ${total} bytes are shown; the rest could not be saved]`
23
+ : `[output cut: the first ${kept} of ${total} bytes are shown; the full text is in ${path}]`;
24
+ /** The room an entry's own fields (ids, timestamps, the call's name) take beside its content. */
25
+ export const ENTRY_RESERVE_BYTES = 1024;
26
+ /** The bytes `text` takes inside a JSON string, quotes left out: what a quote, a newline or a control character costs. */
27
+ export const escapedBytes = (text) => byteLength(JSON.stringify(text)) - 2;
28
+ /**
29
+ * The longest start of `text` whose JSON-escaped form is at most `limit` bytes, cut so no UTF-8 character is split.
30
+ * A text full of newlines or quotes takes more bytes in the log than it has characters, so the cut counts the log's bytes.
31
+ */
32
+ export function fitHead(text, limit) {
33
+ if (limit <= 0)
34
+ return "";
35
+ let head = headBytes(text, Math.max(0, limit));
36
+ for (let over = escapedBytes(head) - limit; over > 0; over = escapedBytes(head) - limit) {
37
+ head = headBytes(head, Math.max(0, byteLength(head) - over));
38
+ }
39
+ return head;
40
+ }
41
+ //# sourceMappingURL=write-cap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write-cap.js","sourceRoot":"","sources":["../../src/context/write-cap.ts"],"names":[],"mappings":"AAGA,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;AAE3D,2FAA2F;AAC3F,MAAM,UAAU,MAAM,CAAC,OAAgC;IACrD,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC5F,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,SAAS,CAAC,IAAY,EAAE,KAAa;IACnD,MAAM,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACrC,IAAI,OAAO,CAAC,MAAM,IAAI,KAAK;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,GAAG,GAAG,KAAK,CAAC;IAChB,mGAAmG;IACnG,OAAO,GAAG,GAAG,CAAC,IAAI,CAAE,OAAO,CAAC,GAAG,CAAY,GAAG,WAAW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IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/** Layer 1: cap what the model reads of one tool result, and keep the full text in a spill file. */\nimport type { ModelContent } from \"@buildanagent/gateway\";\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: false });\n\n/** The text blocks of a result, joined, and the other blocks (images) left as they are. */\nexport function textOf(content: readonly ModelContent[]): string {\n return content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n}\n\n/** The first `bytes` bytes of `text`, cut so no UTF-8 character is split. */\nexport function headBytes(text: string, bytes: number): string {\n const encoded = encoder.encode(text);\n if (encoded.length <= bytes) return text;\n let end = bytes;\n // A continuation byte starts with 10; back up to the byte that begins the character the cut split.\n while (end > 0 && ((encoded[end] as number) & 0b1100_0000) === 0b1000_0000) end--;\n return decoder.decode(encoded.subarray(0, end));\n}\n\n/** The byte length of `text` in UTF-8. */\nexport const byteLength = (text: string): number => encoder.encode(text).length;\n\n/** The line that tells the model where the rest of a capped result went, or that it was not kept. */\nexport const capNotice = (kept: number, total: number, path: string | undefined): string =>\n path === undefined\n ? `[output cut: the first ${kept} of ${total} bytes are shown; the rest could not be saved]`\n : `[output cut: the first ${kept} of ${total} bytes are shown; the full text is in ${path}]`;\n\n/** The room an entry's own fields (ids, timestamps, the call's name) take beside its content. */\nexport const ENTRY_RESERVE_BYTES = 1024;\n\n/** The bytes `text` takes inside a JSON string, quotes left out: what a quote, a newline or a control character costs. */\nexport const escapedBytes = (text: string): number => byteLength(JSON.stringify(text)) - 2;\n\n/**\n * The longest start of `text` whose JSON-escaped form is at most `limit` bytes, cut so no UTF-8 character is split.\n * A text full of newlines or quotes takes more bytes in the log than it has characters, so the cut counts the log's bytes.\n */\nexport function fitHead(text: string, limit: number): string {\n if (limit <= 0) return \"\";\n let head = headBytes(text, Math.max(0, limit));\n for (let over = escapedBytes(head) - limit; over > 0; over = escapedBytes(head) - limit) {\n head = headBytes(head, Math.max(0, byteLength(head) - over));\n }\n return head;\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `createHarness()`: a harness from its options, with the defaults filled in and `invokeTool()` bound to the code-call
3
+ * runner. It is apart from the harness's types because the runner imports them.
4
+ */
5
+ import type { Harness, HarnessOptions } from "./harness.js";
6
+ /** Creates a harness. `H` types the host context of each turn, so `runTurn()` checks it. */
7
+ export declare function createHarness<H = unknown>(options: HarnessOptions<H>): Harness<H>;