@animalabs/agent-framework 0.26.2 → 0.28.0

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 (371) hide show
  1. package/README.md +99 -8
  2. package/dist/src/agent.d.ts +291 -23
  3. package/dist/src/agent.d.ts.map +1 -1
  4. package/dist/src/agent.js +596 -61
  5. package/dist/src/agent.js.map +1 -1
  6. package/dist/src/api/server.d.ts.map +1 -1
  7. package/dist/src/api/server.js +5 -4
  8. package/dist/src/api/server.js.map +1 -1
  9. package/dist/src/auto-continue.d.ts +34 -0
  10. package/dist/src/auto-continue.d.ts.map +1 -0
  11. package/dist/src/auto-continue.js +36 -0
  12. package/dist/src/auto-continue.js.map +1 -0
  13. package/dist/src/code-execution/isolate/scripts.d.ts +11 -0
  14. package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -1
  15. package/dist/src/code-execution/isolate/scripts.js +5 -1
  16. package/dist/src/code-execution/isolate/scripts.js.map +1 -1
  17. package/dist/src/cut-off-round.d.ts +24 -0
  18. package/dist/src/cut-off-round.d.ts.map +1 -0
  19. package/dist/src/cut-off-round.js +87 -0
  20. package/dist/src/cut-off-round.js.map +1 -0
  21. package/dist/src/framework.d.ts +1038 -193
  22. package/dist/src/framework.d.ts.map +1 -1
  23. package/dist/src/framework.js +5967 -1514
  24. package/dist/src/framework.js.map +1 -1
  25. package/dist/src/gate/event-gate.d.ts +405 -46
  26. package/dist/src/gate/event-gate.d.ts.map +1 -1
  27. package/dist/src/gate/event-gate.js +2646 -399
  28. package/dist/src/gate/event-gate.js.map +1 -1
  29. package/dist/src/gate/index.d.ts +3 -2
  30. package/dist/src/gate/index.d.ts.map +1 -1
  31. package/dist/src/gate/index.js +2 -1
  32. package/dist/src/gate/index.js.map +1 -1
  33. package/dist/src/gate/recipe-reconcile.d.ts +103 -0
  34. package/dist/src/gate/recipe-reconcile.d.ts.map +1 -0
  35. package/dist/src/gate/recipe-reconcile.js +325 -0
  36. package/dist/src/gate/recipe-reconcile.js.map +1 -0
  37. package/dist/src/gate/reply-judge.d.ts +116 -0
  38. package/dist/src/gate/reply-judge.d.ts.map +1 -0
  39. package/dist/src/gate/reply-judge.js +467 -0
  40. package/dist/src/gate/reply-judge.js.map +1 -0
  41. package/dist/src/gate/types.d.ts +229 -8
  42. package/dist/src/gate/types.d.ts.map +1 -1
  43. package/dist/src/heartbeat/heartbeat.d.ts +184 -0
  44. package/dist/src/heartbeat/heartbeat.d.ts.map +1 -0
  45. package/dist/src/heartbeat/heartbeat.js +752 -0
  46. package/dist/src/heartbeat/heartbeat.js.map +1 -0
  47. package/dist/src/heartbeat/reminder-time.d.ts +5 -0
  48. package/dist/src/heartbeat/reminder-time.d.ts.map +1 -0
  49. package/dist/src/heartbeat/reminder-time.js +107 -0
  50. package/dist/src/heartbeat/reminder-time.js.map +1 -0
  51. package/dist/src/index.d.ts +10 -4
  52. package/dist/src/index.d.ts.map +1 -1
  53. package/dist/src/index.js +7 -2
  54. package/dist/src/index.js.map +1 -1
  55. package/dist/src/mcpl/capability-mask.d.ts.map +1 -1
  56. package/dist/src/mcpl/capability-mask.js +3 -2
  57. package/dist/src/mcpl/capability-mask.js.map +1 -1
  58. package/dist/src/mcpl/channel-registry.d.ts +433 -113
  59. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  60. package/dist/src/mcpl/channel-registry.js +1154 -435
  61. package/dist/src/mcpl/channel-registry.js.map +1 -1
  62. package/dist/src/mcpl/conversation-router.d.ts +16 -8
  63. package/dist/src/mcpl/conversation-router.d.ts.map +1 -1
  64. package/dist/src/mcpl/conversation-router.js +29 -15
  65. package/dist/src/mcpl/conversation-router.js.map +1 -1
  66. package/dist/src/mcpl/convert-block.d.ts.map +1 -1
  67. package/dist/src/mcpl/convert-block.js +14 -2
  68. package/dist/src/mcpl/convert-block.js.map +1 -1
  69. package/dist/src/mcpl/hook-orchestrator.d.ts +7 -1
  70. package/dist/src/mcpl/hook-orchestrator.d.ts.map +1 -1
  71. package/dist/src/mcpl/hook-orchestrator.js +32 -7
  72. package/dist/src/mcpl/hook-orchestrator.js.map +1 -1
  73. package/dist/src/mcpl/inbound-source.d.ts +26 -10
  74. package/dist/src/mcpl/inbound-source.d.ts.map +1 -1
  75. package/dist/src/mcpl/inbound-source.js +40 -69
  76. package/dist/src/mcpl/inbound-source.js.map +1 -1
  77. package/dist/src/mcpl/index.d.ts +5 -1
  78. package/dist/src/mcpl/index.d.ts.map +1 -1
  79. package/dist/src/mcpl/index.js +4 -0
  80. package/dist/src/mcpl/index.js.map +1 -1
  81. package/dist/src/mcpl/inference-router.d.ts +14 -2
  82. package/dist/src/mcpl/inference-router.d.ts.map +1 -1
  83. package/dist/src/mcpl/inference-router.js +73 -28
  84. package/dist/src/mcpl/inference-router.js.map +1 -1
  85. package/dist/src/mcpl/prose-grammar.d.ts +4 -0
  86. package/dist/src/mcpl/prose-grammar.d.ts.map +1 -1
  87. package/dist/src/mcpl/prose-grammar.js +6 -0
  88. package/dist/src/mcpl/prose-grammar.js.map +1 -1
  89. package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
  90. package/dist/src/mcpl/protocol-family.js +3 -0
  91. package/dist/src/mcpl/protocol-family.js.map +1 -1
  92. package/dist/src/mcpl/push-coalescer.d.ts +20 -2
  93. package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
  94. package/dist/src/mcpl/push-coalescer.js +33 -11
  95. package/dist/src/mcpl/push-coalescer.js.map +1 -1
  96. package/dist/src/mcpl/reference-fetcher.d.ts +63 -42
  97. package/dist/src/mcpl/reference-fetcher.d.ts.map +1 -1
  98. package/dist/src/mcpl/reference-fetcher.js +177 -145
  99. package/dist/src/mcpl/reference-fetcher.js.map +1 -1
  100. package/dist/src/mcpl/references.d.ts +380 -46
  101. package/dist/src/mcpl/references.d.ts.map +1 -1
  102. package/dist/src/mcpl/references.js +736 -77
  103. package/dist/src/mcpl/references.js.map +1 -1
  104. package/dist/src/mcpl/server-connection.d.ts +93 -4
  105. package/dist/src/mcpl/server-connection.d.ts.map +1 -1
  106. package/dist/src/mcpl/server-connection.js +176 -11
  107. package/dist/src/mcpl/server-connection.js.map +1 -1
  108. package/dist/src/mcpl/tags.d.ts +9 -2
  109. package/dist/src/mcpl/tags.d.ts.map +1 -1
  110. package/dist/src/mcpl/tags.js +12 -2
  111. package/dist/src/mcpl/tags.js.map +1 -1
  112. package/dist/src/mcpl/tool-lifecycle.d.ts +11 -0
  113. package/dist/src/mcpl/tool-lifecycle.d.ts.map +1 -1
  114. package/dist/src/mcpl/tool-lifecycle.js +21 -0
  115. package/dist/src/mcpl/tool-lifecycle.js.map +1 -1
  116. package/dist/src/mcpl/tool-presence.d.ts +311 -0
  117. package/dist/src/mcpl/tool-presence.d.ts.map +1 -0
  118. package/dist/src/mcpl/tool-presence.js +697 -0
  119. package/dist/src/mcpl/tool-presence.js.map +1 -0
  120. package/dist/src/mcpl/tool-result-normalize.d.ts +9 -3
  121. package/dist/src/mcpl/tool-result-normalize.d.ts.map +1 -1
  122. package/dist/src/mcpl/tool-result-normalize.js +14 -6
  123. package/dist/src/mcpl/tool-result-normalize.js.map +1 -1
  124. package/dist/src/mcpl/tool-signature.d.ts +46 -0
  125. package/dist/src/mcpl/tool-signature.d.ts.map +1 -0
  126. package/dist/src/mcpl/tool-signature.js +321 -0
  127. package/dist/src/mcpl/tool-signature.js.map +1 -0
  128. package/dist/src/mcpl/toolset-host.d.ts +251 -0
  129. package/dist/src/mcpl/toolset-host.d.ts.map +1 -0
  130. package/dist/src/mcpl/toolset-host.js +720 -0
  131. package/dist/src/mcpl/toolset-host.js.map +1 -0
  132. package/dist/src/mcpl/toolsets-module.d.ts +83 -0
  133. package/dist/src/mcpl/toolsets-module.d.ts.map +1 -0
  134. package/dist/src/mcpl/toolsets-module.js +523 -0
  135. package/dist/src/mcpl/toolsets-module.js.map +1 -0
  136. package/dist/src/mcpl/transport.d.ts +2 -2
  137. package/dist/src/mcpl/transport.d.ts.map +1 -1
  138. package/dist/src/mcpl/transport.js +3 -2
  139. package/dist/src/mcpl/transport.js.map +1 -1
  140. package/dist/src/mcpl/types.d.ts +24 -2
  141. package/dist/src/mcpl/types.d.ts.map +1 -1
  142. package/dist/src/mcpl/types.js.map +1 -1
  143. package/dist/src/mcpl/visible-content.d.ts +7 -9
  144. package/dist/src/mcpl/visible-content.d.ts.map +1 -1
  145. package/dist/src/mcpl/visible-content.js +21 -9
  146. package/dist/src/mcpl/visible-content.js.map +1 -1
  147. package/dist/src/module-registry.d.ts +27 -9
  148. package/dist/src/module-registry.d.ts.map +1 -1
  149. package/dist/src/module-registry.js +77 -17
  150. package/dist/src/module-registry.js.map +1 -1
  151. package/dist/src/modules/discord/index.js +1 -1
  152. package/dist/src/modules/discord/index.js.map +1 -1
  153. package/dist/src/modules/history/index.d.ts +2 -1
  154. package/dist/src/modules/history/index.d.ts.map +1 -1
  155. package/dist/src/modules/history/index.js +73 -28
  156. package/dist/src/modules/history/index.js.map +1 -1
  157. package/dist/src/modules/history/semantic.d.ts +108 -6
  158. package/dist/src/modules/history/semantic.d.ts.map +1 -1
  159. package/dist/src/modules/history/semantic.js +273 -57
  160. package/dist/src/modules/history/semantic.js.map +1 -1
  161. package/dist/src/modules/workspace/answers.d.ts +22 -0
  162. package/dist/src/modules/workspace/answers.d.ts.map +1 -0
  163. package/dist/src/modules/workspace/answers.js +123 -0
  164. package/dist/src/modules/workspace/answers.js.map +1 -0
  165. package/dist/src/modules/workspace/branch-intent.d.ts +5 -3
  166. package/dist/src/modules/workspace/branch-intent.d.ts.map +1 -1
  167. package/dist/src/modules/workspace/branch-intent.js +6 -2
  168. package/dist/src/modules/workspace/branch-intent.js.map +1 -1
  169. package/dist/src/modules/workspace/direct-write.d.ts +184 -0
  170. package/dist/src/modules/workspace/direct-write.d.ts.map +1 -0
  171. package/dist/src/modules/workspace/direct-write.js +417 -0
  172. package/dist/src/modules/workspace/direct-write.js.map +1 -0
  173. package/dist/src/modules/workspace/disk-agreement.d.ts +33 -11
  174. package/dist/src/modules/workspace/disk-agreement.d.ts.map +1 -1
  175. package/dist/src/modules/workspace/disk-agreement.js +48 -17
  176. package/dist/src/modules/workspace/disk-agreement.js.map +1 -1
  177. package/dist/src/modules/workspace/edit-text.d.ts +27 -12
  178. package/dist/src/modules/workspace/edit-text.d.ts.map +1 -1
  179. package/dist/src/modules/workspace/edit-text.js +61 -29
  180. package/dist/src/modules/workspace/edit-text.js.map +1 -1
  181. package/dist/src/modules/workspace/effects.d.ts +10 -0
  182. package/dist/src/modules/workspace/effects.d.ts.map +1 -1
  183. package/dist/src/modules/workspace/effects.js +21 -14
  184. package/dist/src/modules/workspace/effects.js.map +1 -1
  185. package/dist/src/modules/workspace/index.d.ts +308 -78
  186. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  187. package/dist/src/modules/workspace/index.js +2103 -720
  188. package/dist/src/modules/workspace/index.js.map +1 -1
  189. package/dist/src/modules/workspace/observe.d.ts +75 -63
  190. package/dist/src/modules/workspace/observe.d.ts.map +1 -1
  191. package/dist/src/modules/workspace/observe.js +366 -180
  192. package/dist/src/modules/workspace/observe.js.map +1 -1
  193. package/dist/src/modules/workspace/read-page.d.ts +41 -0
  194. package/dist/src/modules/workspace/read-page.d.ts.map +1 -0
  195. package/dist/src/modules/workspace/read-page.js +219 -0
  196. package/dist/src/modules/workspace/read-page.js.map +1 -0
  197. package/dist/src/modules/workspace/reconcile.d.ts.map +1 -1
  198. package/dist/src/modules/workspace/reconcile.js +26 -16
  199. package/dist/src/modules/workspace/reconcile.js.map +1 -1
  200. package/dist/src/modules/workspace/result-text.d.ts +68 -0
  201. package/dist/src/modules/workspace/result-text.d.ts.map +1 -0
  202. package/dist/src/modules/workspace/result-text.js +94 -0
  203. package/dist/src/modules/workspace/result-text.js.map +1 -0
  204. package/dist/src/modules/workspace/sync.d.ts +9 -0
  205. package/dist/src/modules/workspace/sync.d.ts.map +1 -1
  206. package/dist/src/modules/workspace/sync.js +14 -0
  207. package/dist/src/modules/workspace/sync.js.map +1 -1
  208. package/dist/src/modules/workspace/text.d.ts +29 -12
  209. package/dist/src/modules/workspace/text.d.ts.map +1 -1
  210. package/dist/src/modules/workspace/text.js +35 -33
  211. package/dist/src/modules/workspace/text.js.map +1 -1
  212. package/dist/src/modules/workspace/types.d.ts +137 -60
  213. package/dist/src/modules/workspace/types.d.ts.map +1 -1
  214. package/dist/src/modules/workspace/types.js.map +1 -1
  215. package/dist/src/modules/workspace/watcher.d.ts.map +1 -1
  216. package/dist/src/modules/workspace/watcher.js +8 -3
  217. package/dist/src/modules/workspace/watcher.js.map +1 -1
  218. package/dist/src/prose-drafts.d.ts +4 -3
  219. package/dist/src/prose-drafts.d.ts.map +1 -1
  220. package/dist/src/prose-drafts.js +3 -2
  221. package/dist/src/prose-drafts.js.map +1 -1
  222. package/dist/src/reasoning-loss-notice.d.ts +23 -0
  223. package/dist/src/reasoning-loss-notice.d.ts.map +1 -0
  224. package/dist/src/reasoning-loss-notice.js +50 -0
  225. package/dist/src/reasoning-loss-notice.js.map +1 -0
  226. package/dist/src/reasoning-loss.d.ts +24 -0
  227. package/dist/src/reasoning-loss.d.ts.map +1 -0
  228. package/dist/src/reasoning-loss.js +102 -0
  229. package/dist/src/reasoning-loss.js.map +1 -0
  230. package/dist/src/send-tools.d.ts +3 -2
  231. package/dist/src/send-tools.d.ts.map +1 -1
  232. package/dist/src/send-tools.js +3 -2
  233. package/dist/src/send-tools.js.map +1 -1
  234. package/dist/src/sent-rows.d.ts +59 -0
  235. package/dist/src/sent-rows.d.ts.map +1 -0
  236. package/dist/src/sent-rows.js +145 -0
  237. package/dist/src/sent-rows.js.map +1 -0
  238. package/dist/src/silent-heartbeat.d.ts +17 -10
  239. package/dist/src/silent-heartbeat.d.ts.map +1 -1
  240. package/dist/src/silent-heartbeat.js.map +1 -1
  241. package/dist/src/stable-hash.d.ts +3 -0
  242. package/dist/src/stable-hash.d.ts.map +1 -0
  243. package/dist/src/stable-hash.js +15 -0
  244. package/dist/src/stable-hash.js.map +1 -0
  245. package/dist/src/stored-injections.d.ts +99 -0
  246. package/dist/src/stored-injections.d.ts.map +1 -0
  247. package/dist/src/stored-injections.js +106 -0
  248. package/dist/src/stored-injections.js.map +1 -0
  249. package/dist/src/text-as-stored.d.ts +4 -3
  250. package/dist/src/text-as-stored.d.ts.map +1 -1
  251. package/dist/src/text-as-stored.js +4 -3
  252. package/dist/src/text-as-stored.js.map +1 -1
  253. package/dist/src/thinking-drops.d.ts +74 -0
  254. package/dist/src/thinking-drops.d.ts.map +1 -0
  255. package/dist/src/thinking-drops.js +96 -0
  256. package/dist/src/thinking-drops.js.map +1 -0
  257. package/dist/src/tool-args.d.ts +12 -0
  258. package/dist/src/tool-args.d.ts.map +1 -1
  259. package/dist/src/tool-args.js +35 -1
  260. package/dist/src/tool-args.js.map +1 -1
  261. package/dist/src/tool-image-ledger.d.ts +9 -8
  262. package/dist/src/tool-image-ledger.d.ts.map +1 -1
  263. package/dist/src/tool-image-ledger.js +9 -8
  264. package/dist/src/tool-image-ledger.js.map +1 -1
  265. package/dist/src/tool-presentation.d.ts.map +1 -1
  266. package/dist/src/tool-presentation.js +3 -1
  267. package/dist/src/tool-presentation.js.map +1 -1
  268. package/dist/src/tool-result-guard.d.ts +12 -6
  269. package/dist/src/tool-result-guard.d.ts.map +1 -1
  270. package/dist/src/tool-result-guard.js +44 -17
  271. package/dist/src/tool-result-guard.js.map +1 -1
  272. package/dist/src/tool-result-history.d.ts +176 -24
  273. package/dist/src/tool-result-history.d.ts.map +1 -1
  274. package/dist/src/tool-result-history.js +411 -91
  275. package/dist/src/tool-result-history.js.map +1 -1
  276. package/dist/src/tune-out/coordinator.d.ts +17 -9
  277. package/dist/src/tune-out/coordinator.d.ts.map +1 -1
  278. package/dist/src/tune-out/coordinator.js +84 -37
  279. package/dist/src/tune-out/coordinator.js.map +1 -1
  280. package/dist/src/tune-out/tools.d.ts +4 -1
  281. package/dist/src/tune-out/tools.d.ts.map +1 -1
  282. package/dist/src/types/agent.d.ts +217 -7
  283. package/dist/src/types/agent.d.ts.map +1 -1
  284. package/dist/src/types/events.d.ts +33 -9
  285. package/dist/src/types/events.d.ts.map +1 -1
  286. package/dist/src/types/framework.d.ts +39 -3
  287. package/dist/src/types/framework.d.ts.map +1 -1
  288. package/dist/src/types/module.d.ts +95 -9
  289. package/dist/src/types/module.d.ts.map +1 -1
  290. package/dist/src/types/trace.d.ts +91 -3
  291. package/dist/src/types/trace.d.ts.map +1 -1
  292. package/package.json +5 -4
  293. package/src/agent.ts +661 -67
  294. package/src/api/server.ts +5 -4
  295. package/src/auto-continue.ts +43 -0
  296. package/src/code-execution/isolate/scripts.ts +11 -3
  297. package/src/cut-off-round.ts +98 -0
  298. package/src/framework.ts +6168 -1540
  299. package/src/gate/event-gate.ts +2895 -405
  300. package/src/gate/index.ts +10 -1
  301. package/src/gate/recipe-reconcile.ts +355 -0
  302. package/src/gate/reply-judge.ts +512 -0
  303. package/src/gate/types.ts +234 -9
  304. package/src/heartbeat/heartbeat.ts +804 -0
  305. package/src/heartbeat/reminder-time.ts +107 -0
  306. package/src/index.ts +11 -4
  307. package/src/mcpl/capability-mask.ts +3 -2
  308. package/src/mcpl/channel-registry.ts +1222 -468
  309. package/src/mcpl/conversation-router.ts +34 -16
  310. package/src/mcpl/convert-block.ts +14 -1
  311. package/src/mcpl/hook-orchestrator.ts +33 -6
  312. package/src/mcpl/inbound-source.ts +42 -69
  313. package/src/mcpl/index.ts +6 -1
  314. package/src/mcpl/inference-router.ts +79 -34
  315. package/src/mcpl/prose-grammar.ts +7 -0
  316. package/src/mcpl/protocol-family.ts +2 -0
  317. package/src/mcpl/push-coalescer.ts +51 -13
  318. package/src/mcpl/reference-fetcher.ts +201 -162
  319. package/src/mcpl/references.ts +851 -77
  320. package/src/mcpl/server-connection.ts +189 -11
  321. package/src/mcpl/tags.ts +13 -2
  322. package/src/mcpl/tool-lifecycle.ts +21 -0
  323. package/src/mcpl/tool-presence.ts +716 -0
  324. package/src/mcpl/tool-result-normalize.ts +18 -6
  325. package/src/mcpl/tool-signature.ts +316 -0
  326. package/src/mcpl/toolset-host.ts +727 -0
  327. package/src/mcpl/toolsets-module.ts +545 -0
  328. package/src/mcpl/transport.ts +3 -2
  329. package/src/mcpl/types.ts +25 -2
  330. package/src/mcpl/visible-content.ts +22 -9
  331. package/src/module-registry.ts +85 -26
  332. package/src/modules/discord/index.ts +1 -1
  333. package/src/modules/history/index.ts +70 -30
  334. package/src/modules/history/semantic.ts +308 -54
  335. package/src/modules/workspace/answers.ts +133 -0
  336. package/src/modules/workspace/branch-intent.ts +10 -5
  337. package/src/modules/workspace/direct-write.ts +460 -0
  338. package/src/modules/workspace/disk-agreement.ts +52 -21
  339. package/src/modules/workspace/edit-text.ts +84 -35
  340. package/src/modules/workspace/effects.ts +22 -13
  341. package/src/modules/workspace/index.ts +2142 -723
  342. package/src/modules/workspace/observe.ts +381 -177
  343. package/src/modules/workspace/read-page.ts +228 -0
  344. package/src/modules/workspace/reconcile.ts +27 -15
  345. package/src/modules/workspace/result-text.ts +121 -0
  346. package/src/modules/workspace/sync.ts +16 -0
  347. package/src/modules/workspace/text.ts +58 -32
  348. package/src/modules/workspace/types.ts +137 -60
  349. package/src/modules/workspace/watcher.ts +8 -3
  350. package/src/prose-drafts.ts +4 -3
  351. package/src/reasoning-loss-notice.ts +62 -0
  352. package/src/reasoning-loss.ts +120 -0
  353. package/src/send-tools.ts +3 -2
  354. package/src/sent-rows.ts +162 -0
  355. package/src/silent-heartbeat.ts +17 -10
  356. package/src/stable-hash.ts +14 -0
  357. package/src/stored-injections.ts +131 -0
  358. package/src/text-as-stored.ts +4 -3
  359. package/src/thinking-drops.ts +135 -0
  360. package/src/tool-args.ts +34 -1
  361. package/src/tool-image-ledger.ts +9 -8
  362. package/src/tool-presentation.ts +3 -1
  363. package/src/tool-result-guard.ts +45 -17
  364. package/src/tool-result-history.ts +471 -90
  365. package/src/tune-out/coordinator.ts +80 -37
  366. package/src/tune-out/tools.ts +4 -1
  367. package/src/types/agent.ts +220 -7
  368. package/src/types/events.ts +33 -9
  369. package/src/types/framework.ts +36 -3
  370. package/src/types/module.ts +91 -9
  371. package/src/types/trace.ts +94 -3
@@ -0,0 +1,228 @@
1
+ import type { ToolResult } from '../../types/events.js';
2
+ import { answerText, fieldLine, sectionLead, sectionText, textAnswer } from './result-text.js';
3
+ import { type FileText, MAX_LINE_CHARS, numberedLine, safeCut } from './text.js';
4
+ import { didNothing } from './answers.js';
5
+
6
+ /**
7
+ * One page of a read, held to the result limit as its text measures it: a
8
+ * model reads the page's text (result-text.ts), and what passes the caller's
9
+ * limit doesn't reach it whole. A model's result spills into a file, cut, and
10
+ * a script gets ResultTooLarge in its place. So a page stops before its text
11
+ * would pass the limit, and its note says where to continue. A script's
12
+ * answer carries the page's fields, its content among them, beside its text,
13
+ * and the limit counts the text alone. A script's limit counts each character
14
+ * at the six bytes it takes at most in the answer, and no character but a
15
+ * control character takes more than three, so the text and the fields
16
+ * together pass what the script takes only on a page of more than half that
17
+ * limit (about 3.7 million characters at the default 128 MiB of script
18
+ * memory) holding control characters.
19
+ */
20
+
21
+ /** How many lines a read shows when it isn't given a limit. */
22
+ export const DEFAULT_READ_LINE_LIMIT = 2000;
23
+
24
+ /** What a read says about the text it shows, besides the lines themselves. */
25
+ export function textNotes(file: FileText): string[] {
26
+ const notes: string[] = [];
27
+ if (file.crlfEnds > 0) {
28
+ // A line whose own text ends in a CR shows its line end's CR too (fileText).
29
+ const kept = file.crKept > 0
30
+ ? `, except on ${file.crKept} ${file.crKept === 1 ? 'line whose own text ends in a CR, which shows' : 'lines whose own text ends in a CR, which show'} both CRs`
31
+ : '';
32
+ notes.push(file.lfEnds > 0
33
+ ? `Line ends are mixed, ${file.crlfEnds} CRLF and ${file.lfEnds} LF, and a CRLF end is shown without its CR${kept}. An edit matches text as read shows it, and keeps each line's end.`
34
+ : `Line ends are CRLF, shown without the CR${kept}. An edit matches text as read shows it, and keeps the CRLF ends.`);
35
+ }
36
+ if (file.bom) notes.push('The file starts with a UTF-8 BOM, which isn\'t shown. An edit keeps it.');
37
+ if (!file.utf8) notes.push(NOT_UTF8);
38
+ return notes;
39
+ }
40
+
41
+ const NOT_UTF8 = 'The file isn\'t valid UTF-8: each invalid byte sequence shows as U+FFFD. Edit refuses this file, and write replaces it whole.';
42
+
43
+ const joined = (notes: Array<string | null>): string | undefined => {
44
+ const kept = notes.filter((n): n is string => n !== null);
45
+ return kept.length > 0 ? kept.join(' ') : undefined;
46
+ };
47
+
48
+ /** A page's fields: a line page's or a character page's, and its content, numbered lines or raw text. */
49
+ type Page = { path: string; content: string; note?: string } & Record<string, string | number | null | undefined>;
50
+
51
+ /** A page's text: its fields, one to a line in their order, and then its content under its label. */
52
+ function pageText(page: Page): string {
53
+ const header = Object.entries(page)
54
+ .filter((entry): entry is [string, string | number | null] => entry[0] !== 'content' && entry[1] !== undefined)
55
+ .map(([key, value]) => fieldLine(key, value));
56
+ return answerText(header, [sectionText('content', page.content)]);
57
+ }
58
+
59
+ /** A page as read answers it: its text for the model, and its fields for a script. */
60
+ const pageAnswer = (page: Page): ToolResult => textAnswer(pageText(page), page);
61
+
62
+ /**
63
+ * Lines from `offset` (1-based), at most `limit` of them, each numbered and a
64
+ * long one cut with the offsetChars and limitChars that read the rest. The
65
+ * page is the longest whose text fits within `maxChars`; where none fits
66
+ * with its first line as a page shows it, that line is cut shorter, at the
67
+ * most the page has room for. Where the page's last line is cut, its note
68
+ * names where that line's rest starts and how long it is, since reading on in
69
+ * order starts there: before the next line, or, on the page that ends the
70
+ * file, before the file is read whole. A page whose own fields and least
71
+ * content pass `maxChars` still moves on, and passes it. With no `maxChars`,
72
+ * for a call made in process, which takes the data itself, the page holds to
73
+ * `limit` alone and shows every line whole.
74
+ */
75
+ export function linePage(path: string, file: FileText, offset: number, limit: number, maxChars: number | undefined, extraNotes: string[] = []): ToolResult {
76
+ const { lines, starts } = file;
77
+ const total = lines.length;
78
+ const first = offset - 1;
79
+ const notes = [...textNotes(file), ...extraNotes];
80
+ if (first >= total) {
81
+ // Nothing to show: an empty file, or an offset past the last line. No
82
+ // range is claimed, and the line count says where the file ends.
83
+ const note = joined([
84
+ // Reading an empty file from its start is reading it whole.
85
+ first > 0 ? `Line ${first + 1} is past the end: the file has ${total} line${total === 1 ? '' : 's'}.` : null,
86
+ ...notes,
87
+ ]);
88
+ return pageAnswer({ path, totalLines: total, ...(note !== undefined ? { note } : {}), content: '' });
89
+ }
90
+ const last = Math.min(first + limit, total);
91
+ const shown = (i: number, maxLineChars = MAX_LINE_CHARS) =>
92
+ numberedLine(lines[i], i + 1, maxLineChars,
93
+ (cut) => `read the rest with offsetChars=${starts[i] + cut} and limitChars=${lines[i].length - cut}`);
94
+ // Where the rest of line i starts in the stored text, shown at most
95
+ // maxLineChars long, as its marker says; null for a line shown whole.
96
+ const restOf = (i: number, maxLineChars: number): number | null =>
97
+ lines[i].length > maxLineChars ? starts[i] + safeCut(lines[i], maxLineChars) : null;
98
+ // The rest's length is what's left of the line as a page shows it, so a
99
+ // character read of it ends where the line does.
100
+ const cutLine = (to: number, rest: number) =>
101
+ `Line ${to} is cut: read its rest with offsetChars=${rest} and limitChars=${starts[to - 1]! + lines[to - 1]!.length - rest}`;
102
+ const limitNote = (to: number, rest: number | null) =>
103
+ `Truncated at ${limit} lines (file has ${total}).${rest === null ? '' : ` ${cutLine(to, rest)}.`} Use offset/limit to read more.`;
104
+ const budgetNote = (to: number, rest: number | null) =>
105
+ `Stopped at line ${to} to stay within the ${maxChars}-character result limit (file has ${total}). `
106
+ + (rest === null ? `Continue with offset=${to + 1}.` : `${cutLine(to, rest)}, then continue with offset=${to + 1}.`);
107
+ const page = (to: number, content: string, note: string | undefined): Page => ({
108
+ path, totalLines: total, fromLine: first + 1, toLine: to, ...(note !== undefined ? { note } : {}), content,
109
+ });
110
+ if (maxChars === undefined) {
111
+ const whole = lines.slice(first, last).map((line, k) => numberedLine(line, first + k + 1, Infinity)).join('\n');
112
+ return pageAnswer(page(last, whole, joined([last < total ? limitNote(last, null) : null, ...notes])));
113
+ }
114
+ // The note of the page that ends at line `to`, its last line shown at most
115
+ // lastMax long: the page that ends where it was asked to, at the file's end
116
+ // or the line limit, says so, and any other says it stopped for the limit.
117
+ const noteAt = (to: number, lastMax = MAX_LINE_CHARS) => {
118
+ const rest = restOf(to - 1, lastMax);
119
+ const endNote = to < total ? limitNote(to, rest) : rest === null ? null : `${cutLine(to, rest)}.`;
120
+ return joined([to === last ? endNote : budgetNote(to, rest), ...notes]);
121
+ };
122
+ // A page's text's length: its fields' and note's, measured with no content,
123
+ // and its content's, under the content's label. A page here has a line.
124
+ const lengthAt = (to: number, contentChars: number, note: string | undefined) =>
125
+ pageText(page(to, '', note)).length + sectionLead('content') + contentChars;
126
+ // The page is the longest that fits. Its length isn't monotone in its
127
+ // lines: the page that ends the file carries no stop note, the one at the
128
+ // line limit a shorter one than a stop, and one whose last line is cut a
129
+ // longer one. But every page carries `notes` and a longer page shows more,
130
+ // so once a page passes the limit with those alone, no longer one fits.
131
+ const shownLines: string[] = [];
132
+ let contentChars = 0;
133
+ let best = 0;
134
+ for (let i = first; i < last; i++) {
135
+ const line = shown(i);
136
+ shownLines.push(line);
137
+ // Each line after the first comes after a line feed.
138
+ contentChars += line.length + (i > first ? 1 : 0);
139
+ if (lengthAt(i + 1, contentChars, noteAt(i + 1)) <= maxChars) best = shownLines.length;
140
+ else if (lengthAt(i + 1, contentChars, joined(notes)) > maxChars) break;
141
+ }
142
+ if (best > 0) {
143
+ shownLines.length = best;
144
+ return pageAnswer(page(first + best, shownLines.join('\n'), noteAt(first + best)));
145
+ }
146
+ // No page fits with its first line as a page shows it: the loop tried that
147
+ // page first, since a read's limit is at least 1, and it is pageWith(top).
148
+ // So the line is cut shorter, at the most the page has room for, and ends
149
+ // the page: its note names where the line's rest starts and how long it is,
150
+ // since that comes next. Each cut is measured on the page itself, since its
151
+ // note names the cut. Every cut below `top` shows a marker. A longer cut
152
+ // adds a character of text at least, and the offsets only grow, but the
153
+ // rest's length is in the marker and in the note, so where it loses a digit
154
+ // the page loses two characters: it can be one character shorter than the
155
+ // page a cut before. The search takes the page as growing with the cut.
156
+ // Such a dip is one cut, and the next is many cuts away, so the longest cut
157
+ // that fits is the one the search finds or, past a dip, at most two cuts
158
+ // further, four code units at most, and those are tried too.
159
+ const pageWith = (chars: number) => page(first + 1, shown(first, chars), noteAt(first + 1, chars));
160
+ const fitsAt = (chars: number) => pageText(pageWith(chars)).length <= maxChars;
161
+ const top = Math.min(lines[first].length, MAX_LINE_CHARS);
162
+ let fits = 0;
163
+ let over = top;
164
+ while (over - fits > 1) {
165
+ const mid = Math.floor((fits + over) / 2);
166
+ if (fitsAt(mid)) fits = mid; else over = mid;
167
+ }
168
+ // The search ends with `fits + 1` measured as too long, or as `top`.
169
+ const found = fits;
170
+ for (let chars = found + 2; chars <= found + 4 && chars < top; chars++) if (fitsAt(chars)) fits = chars;
171
+ return pageAnswer(pageWith(fits));
172
+ }
173
+
174
+ const splitsPair = (text: string, at: number): boolean =>
175
+ at > 0 && at < text.length
176
+ && text.charCodeAt(at - 1) >= 0xd800 && text.charCodeAt(at - 1) <= 0xdbff
177
+ && text.charCodeAt(at) >= 0xdc00 && text.charCodeAt(at) <= 0xdfff;
178
+
179
+ /**
180
+ * Raw text from `offsetChars`, at most `limitChars` code units (one more to
181
+ * keep a surrogate pair whole), stopped sooner where its page's text would
182
+ * pass `maxChars`, if there is one.
183
+ */
184
+ export function characterPage(path: string, file: FileText, offsetChars: number, limitChars: number, maxChars: number | undefined, extraNotes: string[] = []): ToolResult {
185
+ const text = file.raw;
186
+ const start = Math.min(offsetChars, text.length);
187
+ if (splitsPair(text, start)) {
188
+ return {
189
+ success: false,
190
+ isError: true,
191
+ error: didNothing('read', `"offsetChars" ${start} falls between the two halves of a surrogate pair, one character in UTF-16. `
192
+ + `Give ${start - 1} or ${start + 1}; a page's nextOffsetChars never splits one.`),
193
+ };
194
+ }
195
+ let end = start + Math.min(limitChars, text.length - start);
196
+ if (splitsPair(text, end)) end++;
197
+ const notes = [...(file.utf8 ? [] : [NOT_UTF8]), ...extraNotes];
198
+ // A page that stops short of what it was asked for gives what's left of
199
+ // that as limitChars, so a reader that follows its notes ends where it
200
+ // asked to: at a cut line's end, for the rest a line page's note names.
201
+ const stoppedNote = (to: number, left: number) =>
202
+ `Stopped at character ${to} to stay within the ${maxChars}-character result limit; read the rest of what you asked for with offsetChars=${to} and limitChars=${left}.`;
203
+ const page = (to: number, note: string | undefined): Page => ({
204
+ path,
205
+ totalChars: text.length,
206
+ offsetChars: start,
207
+ nextOffsetChars: to < text.length ? to : null,
208
+ ...(note !== undefined ? { note } : {}),
209
+ content: text.slice(start, to),
210
+ });
211
+ const whole = page(end, joined(notes));
212
+ if (maxChars === undefined || pageText(whole).length <= maxChars) return pageAnswer(whole);
213
+ // As many characters as fit beside the rest of the page, which takes the
214
+ // most with the largest offset it could stop at and the most left. A page
215
+ // moves by whole characters, a surrogate pair at once, so it never stops
216
+ // inside one.
217
+ const overhead = pageText({ ...page(end, joined([stoppedNote(end, end - start), ...notes])), nextOffsetChars: end, content: '' }).length + sectionLead('content');
218
+ const step = (at: number) => (splitsPair(text, at + 1) ? 2 : 1);
219
+ let to = Math.min(end, start + Math.max(0, maxChars - overhead));
220
+ if (splitsPair(text, to)) to--;
221
+ // A page always moves on, by one character at least, though a limit too
222
+ // small for the page's own fields and its first character then passes it:
223
+ // with room for one code unit, a surrogate pair is still taken whole. Where
224
+ // that reaches the page's own end, it holds all it was asked for, so it
225
+ // names no stop.
226
+ if (to === start) to = Math.min(end, start + step(start));
227
+ return pageAnswer(page(to, joined([to < end ? stoppedNote(to, end - to) : null, ...notes])));
228
+ }
@@ -53,9 +53,11 @@ import {
53
53
  sameRootIdentity,
54
54
  } from './disk-agreement.js';
55
55
  import type { BranchIntent, BranchIntents, ConflictKind, ConflictRecord, DiskCounterpart } from './branch-intent.js';
56
+ import { storedBytes, type StoredBytes } from './sync.js';
56
57
  import {
57
58
  IGNORED,
58
59
  type MountView,
60
+ NOT_A_DIRECTORY,
59
61
  OTHER_MOUNT,
60
62
  ROOT_REPLACED,
61
63
  type Walk,
@@ -75,6 +77,7 @@ import {
75
77
  withinIncludes,
76
78
  } from './observe.js';
77
79
  import { EffectFailed, type Expect, chainOf, chmodContained, narrowedTo, syncDirectories, unlinkContained, writeContained } from './effects.js';
80
+ import { errnoWords } from './answers.js';
78
81
 
79
82
  export type EntryState =
80
83
  | 'synced'
@@ -486,7 +489,7 @@ function inTheWay(reason: string | undefined, deletion: boolean): string | null
486
489
  }
487
490
  // A deletion below a file finds nothing there to unlink, so only a write
488
491
  // meets this one.
489
- if (reason === 'a parent path is not a directory') {
492
+ if (reason === NOT_A_DIRECTORY) {
490
493
  return 'disk has a file or a symlink where this path needs a directory, and no push writes below one, forced or not — ' +
491
494
  'move or remove it on disk and materialize again, or write the file under another path';
492
495
  }
@@ -506,7 +509,7 @@ function inTheWay(reason: string | undefined, deletion: boolean): string | null
506
509
  * to pass.
507
510
  */
508
511
  function forcedWay(note: string | undefined, deletion: boolean, forced: string): string {
509
- if (note === 'cannot open (EACCES)') return `, or, if disk lets the workspace ${deletion ? 'unlink' : 'write'} the file, ${forced}`;
512
+ if (note === `cannot open (${errnoWords('EACCES')})`) return `, or, if disk lets the workspace ${deletion ? 'unlink' : 'write'} the file, ${forced}`;
510
513
  return '';
511
514
  }
512
515
 
@@ -914,8 +917,8 @@ async function gather(store: JsStore, agreement: DiskAgreement, mount: MountRunt
914
917
  byDesign = OTHER_MOUNT;
915
918
  } else if (!opts.named) {
916
919
  const slash = path.lastIndexOf('/');
917
- const above = slash < 0 ? undefined : passedOverAt(path.slice(0, slash), mount.view.ignore, mount.view.others);
918
- const own = above === undefined && !walk ? passedOverAt(path, mount.view.ignore, mount.view.others) : undefined;
920
+ const above = slash < 0 ? undefined : passedOverAt(path.slice(0, slash), mount.view.ignore, mount.view.others, true);
921
+ const own = above === undefined && !walk ? passedOverAt(path, mount.view.ignore, mount.view.others, false) : undefined;
919
922
  byDesign = above ?? own;
920
923
  } else if (scope.kind === 'dir') {
921
924
  byDesign = passedOverBetween(scope.dir, path, ignoreBeneath(scope.dir, mount.view.ignore), mount.view.others);
@@ -1028,9 +1031,13 @@ export async function reconcilePass(
1028
1031
  }
1029
1032
 
1030
1033
  // The evidence about to be recorded describes the root it was gathered
1031
- // under, which is recorded first (once per mount), so no crash can leave
1032
- // evidence without its root.
1033
- if (gathered.rootIdentity && planned.some((x) => x.verdict.adopt !== undefined || x.verdict.p !== undefined)) {
1034
+ // under, which is recorded first, so no crash can leave evidence without
1035
+ // its root. Once a root is recorded, every pass that found it offers it,
1036
+ // evidence or none: the same root on a new device, or with its first
1037
+ // birth time, is recorded again (recordRootIdentity writes nothing
1038
+ // otherwise), and a quiet mount's passes are where an old record learns
1039
+ // its birth time.
1040
+ if (gathered.rootIdentity && (agreement.rootIdentity(mount.name) !== undefined || planned.some((x) => x.verdict.adopt !== undefined || x.verdict.p !== undefined))) {
1034
1041
  agreement.recordRootIdentity(mount.name, gathered.rootIdentity);
1035
1042
  }
1036
1043
 
@@ -1386,12 +1393,12 @@ export async function pushPaths(
1386
1393
  continue;
1387
1394
  }
1388
1395
  const priorP = p && (p.kind === 'absent' || p.kind === 'content') ? p : null;
1389
- const blob = store.getBlob(s.hash);
1396
+ const stored = storedBytes(store, s.hash);
1390
1397
  const forcedMode = mount.modesObserved && s.mode !== undefined && s.mode !== (d.kind === 'file' ? d.mode : undefined) ? s.mode : undefined;
1391
1398
  const agreedMode = priorP?.kind === 'content' ? priorP.mode : undefined;
1392
- if (blob) {
1399
+ if ('bytes' in stored) {
1393
1400
  plans.push({
1394
- path, kind: 'write', blob, hash: s.hash, prior: priorP, before: agreement.get(mount.name, path), expect,
1401
+ path, kind: 'write', blob: stored.bytes, hash: s.hash, prior: priorP, before: agreement.get(mount.name, path), expect,
1395
1402
  ...(forcedMode !== undefined ? { apply: forcedMode } : {}),
1396
1403
  ...(forcedMode !== undefined && d.kind === 'file' && agreedMode !== d.mode ? { overDisk: true as const } : {}),
1397
1404
  ...(s.mode !== undefined ? { storeMode: s.mode } : {}),
@@ -1400,7 +1407,7 @@ export async function pushPaths(
1400
1407
  ...(agreedMode !== undefined ? { priorMode: agreedMode } : {}),
1401
1408
  ...(d.kind === 'file' && d.mode !== undefined ? { seenMode: d.mode } : {}),
1402
1409
  });
1403
- } else result.skipped.push({ path, reason: 'the workspace copy is missing from the store' });
1410
+ } else result.skipped.push({ path, reason: unstoredCopy(stored) });
1404
1411
  continue;
1405
1412
  }
1406
1413
  if (v.mode === 'adopt' && s && d.kind === 'file') {
@@ -1426,7 +1433,7 @@ export async function pushPaths(
1426
1433
  }
1427
1434
  // Whatever the verdict learned about disk (an agreement, a resolved
1428
1435
  // intent) is recorded before anything is pushed over it, and the root it
1429
- // was learned under before that (once per mount), as a pass does.
1436
+ // was learned under before that, as a pass does.
1430
1437
  if (v.p !== undefined) agreement.recordRootIdentity(mount.name, root.identity);
1431
1438
  if (v.p === 'forget') agreement.forget(mount.name, path);
1432
1439
  else if (v.p !== undefined) agreement.set(mount.name, path, v.p, { afterCommittedState: true });
@@ -1551,11 +1558,12 @@ export async function pushPaths(
1551
1558
  plans.push({ path, kind: 'unlink', prior, before: agreement.get(mount.name, path), expect });
1552
1559
  continue;
1553
1560
  }
1554
- const blob = store.getBlob(s.hash);
1555
- if (!blob) {
1556
- result.skipped.push({ path, reason: 'the workspace copy is missing from the store' });
1561
+ const stored = storedBytes(store, s.hash);
1562
+ if (!('bytes' in stored)) {
1563
+ result.skipped.push({ path, reason: unstoredCopy(stored) });
1557
1564
  continue;
1558
1565
  }
1566
+ const blob = stored.bytes;
1559
1567
  // The store's mode goes to disk with its bytes where the file is new,
1560
1568
  // the push is forced, or disk still has the mode they last agreed on. A
1561
1569
  // push that completes our own unconfirmed one, whose bytes landed, is a
@@ -1774,3 +1782,7 @@ export async function pushPaths(
1774
1782
  agreement.maybeCheckpoint();
1775
1783
  return result;
1776
1784
  }
1785
+
1786
+ function unstoredCopy(stored: Exclude<StoredBytes, { bytes: Buffer }>): string {
1787
+ return 'missing' in stored ? 'the workspace copy is missing from the store' : `the workspace copy is unreadable in the store (${stored.unreadable})`;
1788
+ }
@@ -0,0 +1,121 @@
1
+ import type { ToolResult } from '../../types/events.js';
2
+
3
+ /**
4
+ * The text a model reads of read's, grep's, edit's and edit_many's answers:
5
+ * a header of the answer's own fields, one `key: value` to a line in the
6
+ * fields' order, then its sections, each a `--- label ---` line and the lines
7
+ * under it, an empty one left out. The answer's fields themselves reach a
8
+ * script as its structuredContent (ToolResult.structured), and a page or a
9
+ * receipt is held to the call's result limit as this text measures it.
10
+ */
11
+
12
+ /** The characters Unicode says end a line (UAX #14's mandatory breaks): LF, VT, FF, CR, NEL, U+2028 and U+2029. */
13
+ const LINE_BREAK = /[\n\v\f\r\u0085\u2028\u2029]/;
14
+
15
+ /**
16
+ * A value as a header line, a section's label or a listed line writes it: as
17
+ * it is, or, where it holds a line break or starts with a quote, as a JSON
18
+ * string. A path can hold a line break, and so can a note naming it or a line
19
+ * of a file grep matched; written as it is, it would start a line that reads
20
+ * as one of the answer's own. A value written as it is never starts with a
21
+ * quote, so one that does is always the quoted form, which gives back exactly
22
+ * what the value holds: without that, a value that is itself a JSON string,
23
+ * such as a line of a file reading `"a\nb"`, would read as the quoted form of
24
+ * another. JSON leaves NEL, U+2028 and U+2029 as they are, so they're escaped
25
+ * too.
26
+ */
27
+ export function shownValue(value: string | number | boolean | null): string {
28
+ if (typeof value !== 'string') return String(value);
29
+ if (!value.startsWith('"') && !LINE_BREAK.test(value)) return value;
30
+ return JSON.stringify(value).replace(/[\u0085\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
31
+ }
32
+
33
+ export type DiskState = 'done' | 'waits for materialize' | 'waits for materialize with applyDeletions' | 'in conflict with disk';
34
+
35
+ /** A header line: a field's key and its value as shownValue writes it. */
36
+ export const fieldLine = (key: string, value: string | number | boolean | null): string => `${key}: ${shownValue(value)}`;
37
+
38
+ /** A section's text, its label and then its lines; an empty section is no text. */
39
+ export const sectionText = (label: string, body: string): string => (body === '' ? '' : `--- ${label} ---\n${body}`);
40
+
41
+ /** The answer's text: its header lines and then its sections, each on lines of its own. */
42
+ export const answerText = (header: string[], sections: string[] = []): string =>
43
+ [...header, ...sections.filter((section) => section !== '')].join('\n');
44
+
45
+ /** How much a section with any lines adds to its answer's text before them: the line feed before its label, and the label's line. */
46
+ export const sectionLead = (label: string): number => `\n--- ${label} ---\n`.length;
47
+
48
+ /** A success whose text is what the model reads and whose fields reach a script as its structuredContent. */
49
+ export const textAnswer = (text: string, structured: Record<string, unknown>): ToolResult =>
50
+ ({ success: true, data: [{ type: 'text', text }], structured });
51
+
52
+ /** A grep result: the matches of one version of a file. */
53
+ export interface GrepResult {
54
+ file: string;
55
+ state?: string;
56
+ version: string;
57
+ lineEndings?: string;
58
+ matches: Array<{ line: number; text: string; context?: string[] }>;
59
+ }
60
+
61
+ /** What grep found, as its structuredContent holds it. */
62
+ export interface GrepAnswer {
63
+ pattern: string;
64
+ results: GrepResult[];
65
+ totalMatches: number;
66
+ note?: string;
67
+ skipped?: Array<{ file: string; reason: string; size?: number; mimeType?: string }>;
68
+ incomplete?: Array<{ path: string; reason: string }>;
69
+ }
70
+
71
+ /**
72
+ * grep's text: its pattern, match count and note, then a section for each
73
+ * version of a file it matched, labelled with the file, the version, the
74
+ * file's state where grep gives one and its line ends where it has them, then
75
+ * what it skipped and where its search was incomplete. As grep writes them, a
76
+ * match's line reads `N:text`, and where the call asked for context, each
77
+ * line around it reads `N-text`: matches whose context meets or overlaps are
78
+ * one run of lines, each line once, and `--` stands between runs with lines
79
+ * left out between them. Each match's context starts `contextBefore` lines
80
+ * before it, or at the file's first line. A line's text is written through
81
+ * shownValue, since more of the answer follows it.
82
+ */
83
+ export function grepText(answer: GrepAnswer, contextBefore: number): string {
84
+ const header = [fieldLine('pattern', answer.pattern), fieldLine('totalMatches', answer.totalMatches)];
85
+ if (answer.note !== undefined) header.push(fieldLine('note', answer.note));
86
+ const sections = answer.results.map((result) => {
87
+ const label = `${shownValue(result.file)}: ${result.version}`
88
+ + (result.state !== undefined ? ` (${result.state})` : '')
89
+ + (result.lineEndings !== undefined ? `; lineEndings: ${result.lineEndings}` : '');
90
+ const lines: string[] = [];
91
+ const matched = new Set(result.matches.map((match) => match.line));
92
+ // The last line written: matches come in line order, so a window that
93
+ // meets or overlaps the run before it goes on from there.
94
+ let last = 0;
95
+ for (const match of result.matches) {
96
+ if (match.context === undefined) {
97
+ lines.push(`${String(match.line).padStart(6)}:${shownValue(match.text)}`);
98
+ continue;
99
+ }
100
+ const first = Math.max(1, match.line - contextBefore);
101
+ match.context.forEach((text, k) => {
102
+ const n = first + k;
103
+ if (n <= last) return;
104
+ if (last > 0 && n > last + 1) lines.push('--');
105
+ lines.push(`${String(n).padStart(6)}${matched.has(n) ? ':' : '-'}${shownValue(text)}`);
106
+ last = n;
107
+ });
108
+ }
109
+ return sectionText(label, lines.join('\n'));
110
+ });
111
+ if (answer.skipped !== undefined) {
112
+ sections.push(sectionText('skipped', answer.skipped.map((skip) => {
113
+ const facts = [...(skip.size !== undefined ? [`${skip.size} bytes`] : []), ...(skip.mimeType !== undefined ? [skip.mimeType] : [])];
114
+ return `${shownValue(skip.file)}: ${shownValue(skip.reason)}${facts.length ? ` (${facts.join(', ')})` : ''}`;
115
+ }).join('\n')));
116
+ }
117
+ if (answer.incomplete !== undefined) {
118
+ sections.push(sectionText('incomplete', answer.incomplete.map((gap) => `${shownValue(gap.path)}: ${shownValue(gap.reason)}`).join('\n')));
119
+ }
120
+ return answerText(header, sections);
121
+ }
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { createHash } from 'node:crypto';
9
+ import type { JsStore } from '@animalabs/chronicle';
9
10
 
10
11
  export const DEFAULT_MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
11
12
 
@@ -18,3 +19,18 @@ export function hashContent(content: string | Buffer): string {
18
19
  hash.update(content);
19
20
  return hash.digest('hex');
20
21
  }
22
+
23
+ export type StoredBytes = { bytes: Buffer } | { missing: true } | { unreadable: string };
24
+
25
+ export function storedBytes(store: JsStore, hash: string): StoredBytes {
26
+ try {
27
+ const blob = store.getBlob(hash);
28
+ return blob ? { bytes: blob } : { missing: true };
29
+ } catch (error) {
30
+ if (store.isClosed()) throw error;
31
+ // Chronicle's getBlob throws, rather than answering null, for a blob file
32
+ // it can't read whole or whose format, checksum or hash doesn't check out,
33
+ // such as one a write cut short left truncated.
34
+ return { unreadable: error instanceof Error ? error.message : String(error) };
35
+ }
36
+ }
@@ -1,7 +1,9 @@
1
+ import { isUtf8 } from 'node:buffer';
2
+
1
3
  /**
2
- * Lines numbered the way `cat -n` numbers them, with a long one cut, and a
3
- * string's length as JSON, which a budget for a stored result counts. edit's
4
- * answers use them.
4
+ * A stored file's text as read shows it and grep searches it, and lines
5
+ * numbered the way `cat -n` numbers them, with a long one cut. Read, grep and
6
+ * edit's answers use them.
5
7
  */
6
8
 
7
9
  /** Whether the bytes open with a UTF-8 byte order mark. */
@@ -9,6 +11,57 @@ export function hasBom(bytes: Uint8Array): boolean {
9
11
  return bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
10
12
  }
11
13
 
14
+ export interface FileText {
15
+ /** The bytes decoded as UTF-8, as character paging reads them: a BOM and every CR kept. */
16
+ raw: string;
17
+ /**
18
+ * Its lines, as read shows them and grep searches them: without the BOM, a
19
+ * CR before a line feed dropped, and a final line end ending the last line
20
+ * rather than starting an empty one. So "a\r\nb\r\n" is two lines, and an
21
+ * empty text has none. A line whose own text ends in a CR keeps its line
22
+ * end's CR too, as stored: an edit reads a CR before a line feed in its old
23
+ * text as part of the line end, so text copied from "a\r" and the next line
24
+ * would lose the CR that is the line's own.
25
+ */
26
+ lines: string[];
27
+ /** Where each line starts in `raw`. */
28
+ starts: number[];
29
+ bom: boolean;
30
+ /** How many line ends were CRLF, and how many a bare LF. */
31
+ crlfEnds: number;
32
+ lfEnds: number;
33
+ /** How many lines with a CRLF end keep its CR, since their own text ends in a CR. */
34
+ crKept: number;
35
+ /** Whether the bytes are valid UTF-8; where they aren't, `raw` holds U+FFFD. */
36
+ utf8: boolean;
37
+ }
38
+
39
+ export function fileText(bytes: Buffer): FileText {
40
+ const raw = bytes.toString('utf-8');
41
+ const bom = hasBom(bytes);
42
+ const lines: string[] = [];
43
+ const starts: number[] = [];
44
+ let crlfEnds = 0;
45
+ let lfEnds = 0;
46
+ let crKept = 0;
47
+ // A BOM decodes to the single code unit U+FEFF.
48
+ for (let at = bom ? 1 : 0; at < raw.length;) {
49
+ const lf = raw.indexOf('\n', at);
50
+ starts.push(at);
51
+ if (lf === -1) {
52
+ lines.push(raw.slice(at));
53
+ break;
54
+ }
55
+ const crlf = lf > at && raw.charCodeAt(lf - 1) === 13;
56
+ if (crlf) crlfEnds++; else lfEnds++;
57
+ const keepsCr = crlf && lf - 1 > at && raw.charCodeAt(lf - 2) === 13;
58
+ if (keepsCr) crKept++;
59
+ lines.push(raw.slice(at, crlf && !keepsCr ? lf - 1 : lf));
60
+ at = lf + 1;
61
+ }
62
+ return { raw, lines, starts, bom, crlfEnds, lfEnds, crKept, utf8: isUtf8(bytes) };
63
+ }
64
+
12
65
  /** How long a line read shows before it cuts the line. */
13
66
  export const MAX_LINE_CHARS = 2000;
14
67
 
@@ -26,43 +79,16 @@ export function safeCut(value: string, at: number): number {
26
79
  /**
27
80
  * One line numbered the way `cat -n` numbers it: a six-wide number, a tab and
28
81
  * the line. A line longer than `maxChars` is cut, saying how many characters
29
- * it holds past the cut, and `readOn` adds how to read them.
82
+ * it holds past the cut, or, where `readOn` is given, how to read them.
30
83
  */
31
84
  export function numberedLine(line: string, n: number, maxChars = MAX_LINE_CHARS, readOn?: (cut: number) => string): string {
32
85
  const number = String(n).padStart(6);
33
86
  if (line.length <= maxChars) return `${number}\t${line}`;
34
87
  const cut = safeCut(line, maxChars);
35
- return `${number}\t${line.slice(0, cut)} [… ${line.length - cut} more chars${readOn ? `; ${readOn(cut)}` : ''}]`;
88
+ return `${number}\t${line.slice(0, cut)} [… ${readOn ? readOn(cut) : `${line.length - cut} more chars`}]`;
36
89
  }
37
90
 
38
91
  /** Lines numbered from `start`, each as numberedLine shows it. */
39
92
  export function numbered(lines: string[], start: number, maxChars = MAX_LINE_CHARS): string {
40
93
  return lines.map((line, i) => numberedLine(line, start + i, maxChars)).join('\n');
41
94
  }
42
-
43
- /**
44
- * How many characters a string takes inside JSON's quotes, as JSON.stringify
45
- * writes it: a quote, a backslash or a control character is escaped, and so
46
- * is a lone surrogate.
47
- */
48
- export function jsonLength(value: string): number {
49
- let length = 0;
50
- for (let i = 0; i < value.length; i++) length += jsonCharLength(value, i);
51
- return length;
52
- }
53
-
54
- /** The JSON length of the code unit at `i`, as jsonLength counts it. */
55
- export function jsonCharLength(value: string, i: number): number {
56
- const c = value.charCodeAt(i);
57
- if (c === 0x22 || c === 0x5c) return 2;
58
- if (c < 0x20) return c === 0x08 || c === 0x09 || c === 0x0a || c === 0x0c || c === 0x0d ? 2 : 6;
59
- if (c >= 0xd800 && c <= 0xdbff) {
60
- const next = value.charCodeAt(i + 1);
61
- return next >= 0xdc00 && next <= 0xdfff ? 1 : 6;
62
- }
63
- if (c >= 0xdc00 && c <= 0xdfff) {
64
- const before = i > 0 ? value.charCodeAt(i - 1) : 0;
65
- return before >= 0xd800 && before <= 0xdbff ? 1 : 6;
66
- }
67
- return 1;
68
- }