@namzu/sdk 72.0.0 → 74.0.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 (394) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +34 -34
  3. package/dist/agents/examples/SupervisorAgent.d.ts.map +1 -1
  4. package/dist/agents/examples/SupervisorAgent.js +5 -0
  5. package/dist/agents/examples/SupervisorAgent.js.map +1 -1
  6. package/dist/authorization/protected-paths.d.ts +7 -0
  7. package/dist/authorization/protected-paths.d.ts.map +1 -1
  8. package/dist/authorization/protected-paths.js +11 -0
  9. package/dist/authorization/protected-paths.js.map +1 -1
  10. package/dist/authorization/readonly-commands.d.ts +23 -0
  11. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  12. package/dist/authorization/readonly-commands.js +89 -3
  13. package/dist/authorization/readonly-commands.js.map +1 -1
  14. package/dist/authorization/shell-paths.d.ts +8 -0
  15. package/dist/authorization/shell-paths.d.ts.map +1 -1
  16. package/dist/authorization/shell-paths.js +125 -2
  17. package/dist/authorization/shell-paths.js.map +1 -1
  18. package/dist/bridge/acp/permission.d.ts +6 -0
  19. package/dist/bridge/acp/permission.d.ts.map +1 -1
  20. package/dist/bridge/acp/permission.js.map +1 -1
  21. package/dist/bridge/acp/server.d.ts.map +1 -1
  22. package/dist/bridge/acp/server.js +21 -3
  23. package/dist/bridge/acp/server.js.map +1 -1
  24. package/dist/compaction/context-window.d.ts.map +1 -1
  25. package/dist/compaction/context-window.js +11 -0
  26. package/dist/compaction/context-window.js.map +1 -1
  27. package/dist/compaction/manual.d.ts +16 -1
  28. package/dist/compaction/manual.d.ts.map +1 -1
  29. package/dist/compaction/manual.js +75 -13
  30. package/dist/compaction/manual.js.map +1 -1
  31. package/dist/compaction/plan.d.ts +2 -1
  32. package/dist/compaction/plan.d.ts.map +1 -1
  33. package/dist/compaction/plan.js +6 -5
  34. package/dist/compaction/plan.js.map +1 -1
  35. package/dist/compaction/precompute.d.ts +179 -0
  36. package/dist/compaction/precompute.d.ts.map +1 -0
  37. package/dist/compaction/precompute.js +274 -0
  38. package/dist/compaction/precompute.js.map +1 -0
  39. package/dist/compaction/retained-images.d.ts +16 -0
  40. package/dist/compaction/retained-images.d.ts.map +1 -0
  41. package/dist/compaction/retained-images.js +113 -0
  42. package/dist/compaction/retained-images.js.map +1 -0
  43. package/dist/compaction/token-estimate.d.ts +8 -3
  44. package/dist/compaction/token-estimate.d.ts.map +1 -1
  45. package/dist/compaction/token-estimate.js +76 -8
  46. package/dist/compaction/token-estimate.js.map +1 -1
  47. package/dist/compaction/tool-result-editing.d.ts.map +1 -1
  48. package/dist/compaction/tool-result-editing.js +15 -8
  49. package/dist/compaction/tool-result-editing.js.map +1 -1
  50. package/dist/config/runtime.d.ts +4 -0
  51. package/dist/config/runtime.d.ts.map +1 -1
  52. package/dist/config/runtime.js +17 -0
  53. package/dist/config/runtime.js.map +1 -1
  54. package/dist/constants/acp/index.d.ts +2 -0
  55. package/dist/constants/acp/index.d.ts.map +1 -1
  56. package/dist/constants/acp/index.js +2 -0
  57. package/dist/constants/acp/index.js.map +1 -1
  58. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  59. package/dist/manager/agent/lifecycle.js +8 -0
  60. package/dist/manager/agent/lifecycle.js.map +1 -1
  61. package/dist/manager/session/turn-recorder.d.ts +26 -0
  62. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  63. package/dist/manager/session/turn-recorder.js +72 -5
  64. package/dist/manager/session/turn-recorder.js.map +1 -1
  65. package/dist/peers/protocol.d.ts +9 -0
  66. package/dist/peers/protocol.d.ts.map +1 -1
  67. package/dist/peers/protocol.js +4 -0
  68. package/dist/peers/protocol.js.map +1 -1
  69. package/dist/peers/record.d.ts +6 -0
  70. package/dist/peers/record.d.ts.map +1 -1
  71. package/dist/peers/record.js +4 -0
  72. package/dist/peers/record.js.map +1 -1
  73. package/dist/plugin/index.d.ts +2 -2
  74. package/dist/plugin/index.d.ts.map +1 -1
  75. package/dist/plugin/index.js +1 -1
  76. package/dist/plugin/index.js.map +1 -1
  77. package/dist/plugin/shell-hook.d.ts +30 -0
  78. package/dist/plugin/shell-hook.d.ts.map +1 -1
  79. package/dist/plugin/shell-hook.js +35 -0
  80. package/dist/plugin/shell-hook.js.map +1 -1
  81. package/dist/pricing/catalogue.generated.d.ts.map +1 -1
  82. package/dist/pricing/catalogue.generated.js +178 -1
  83. package/dist/pricing/catalogue.generated.js.map +1 -1
  84. package/dist/provider/attribution.js +1 -1
  85. package/dist/provider/attribution.js.map +1 -1
  86. package/dist/public-runtime.d.ts +9 -5
  87. package/dist/public-runtime.d.ts.map +1 -1
  88. package/dist/public-runtime.js +12 -4
  89. package/dist/public-runtime.js.map +1 -1
  90. package/dist/public-tools.d.ts +1 -1
  91. package/dist/public-tools.d.ts.map +1 -1
  92. package/dist/public-tools.js +1 -1
  93. package/dist/public-tools.js.map +1 -1
  94. package/dist/public-types.d.ts +3 -2
  95. package/dist/public-types.d.ts.map +1 -1
  96. package/dist/rag/embedding.d.ts +5 -1
  97. package/dist/rag/embedding.d.ts.map +1 -1
  98. package/dist/rag/embedding.js +22 -7
  99. package/dist/rag/embedding.js.map +1 -1
  100. package/dist/registry/command/kernel-commands.d.ts +7 -1
  101. package/dist/registry/command/kernel-commands.d.ts.map +1 -1
  102. package/dist/registry/command/kernel-commands.js +40 -2
  103. package/dist/registry/command/kernel-commands.js.map +1 -1
  104. package/dist/registry/tool/execute.d.ts +8 -0
  105. package/dist/registry/tool/execute.d.ts.map +1 -1
  106. package/dist/registry/tool/execute.js +12 -0
  107. package/dist/registry/tool/execute.js.map +1 -1
  108. package/dist/runtime/query/abandon-turn.d.ts.map +1 -1
  109. package/dist/runtime/query/abandon-turn.js +9 -0
  110. package/dist/runtime/query/abandon-turn.js.map +1 -1
  111. package/dist/runtime/query/budget-nudge.d.ts +27 -0
  112. package/dist/runtime/query/budget-nudge.d.ts.map +1 -0
  113. package/dist/runtime/query/budget-nudge.js +66 -0
  114. package/dist/runtime/query/budget-nudge.js.map +1 -0
  115. package/dist/runtime/query/compact-session.d.ts +19 -3
  116. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  117. package/dist/runtime/query/compact-session.js +180 -93
  118. package/dist/runtime/query/compact-session.js.map +1 -1
  119. package/dist/runtime/query/guard.d.ts +8 -0
  120. package/dist/runtime/query/guard.d.ts.map +1 -1
  121. package/dist/runtime/query/guard.js +20 -0
  122. package/dist/runtime/query/guard.js.map +1 -1
  123. package/dist/runtime/query/index.d.ts.map +1 -1
  124. package/dist/runtime/query/index.js +1 -0
  125. package/dist/runtime/query/index.js.map +1 -1
  126. package/dist/runtime/query/iteration/index.d.ts +2 -0
  127. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  128. package/dist/runtime/query/iteration/index.js +41 -1
  129. package/dist/runtime/query/iteration/index.js.map +1 -1
  130. package/dist/runtime/query/iteration/phases/compaction.d.ts +1 -0
  131. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  132. package/dist/runtime/query/iteration/phases/compaction.js +203 -45
  133. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  134. package/dist/runtime/query/iteration/phases/context.d.ts +2 -0
  135. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  136. package/dist/runtime/query/iteration/phases/context.js +1 -0
  137. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  138. package/dist/runtime/query/iteration/phases/precompute.d.ts +60 -0
  139. package/dist/runtime/query/iteration/phases/precompute.d.ts.map +1 -0
  140. package/dist/runtime/query/iteration/phases/precompute.js +240 -0
  141. package/dist/runtime/query/iteration/phases/precompute.js.map +1 -0
  142. package/dist/runtime/query/iteration/request-prefix.d.ts +21 -0
  143. package/dist/runtime/query/iteration/request-prefix.d.ts.map +1 -0
  144. package/dist/runtime/query/iteration/request-prefix.js +111 -0
  145. package/dist/runtime/query/iteration/request-prefix.js.map +1 -0
  146. package/dist/runtime/query/review-policy.d.ts +11 -3
  147. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  148. package/dist/runtime/query/review-policy.js +54 -3
  149. package/dist/runtime/query/review-policy.js.map +1 -1
  150. package/dist/runtime/query/turn/outcome-ledger.d.ts +14 -0
  151. package/dist/runtime/query/turn/outcome-ledger.d.ts.map +1 -1
  152. package/dist/runtime/query/turn/outcome-ledger.js +28 -0
  153. package/dist/runtime/query/turn/outcome-ledger.js.map +1 -1
  154. package/dist/sandbox/exec-stdin.d.ts +21 -0
  155. package/dist/sandbox/exec-stdin.d.ts.map +1 -0
  156. package/dist/sandbox/exec-stdin.js +40 -0
  157. package/dist/sandbox/exec-stdin.js.map +1 -0
  158. package/dist/sandbox/file-walk.d.ts +12 -7
  159. package/dist/sandbox/file-walk.d.ts.map +1 -1
  160. package/dist/sandbox/file-walk.js +13 -4
  161. package/dist/sandbox/file-walk.js.map +1 -1
  162. package/dist/sandbox/ignore-matcher.d.ts +1 -0
  163. package/dist/sandbox/ignore-matcher.d.ts.map +1 -1
  164. package/dist/sandbox/ignore-matcher.js.map +1 -1
  165. package/dist/sandbox/ignore-source.js +1 -1
  166. package/dist/sandbox/index.d.ts +3 -2
  167. package/dist/sandbox/index.d.ts.map +1 -1
  168. package/dist/sandbox/index.js +2 -1
  169. package/dist/sandbox/index.js.map +1 -1
  170. package/dist/sandbox/provider/local.d.ts.map +1 -1
  171. package/dist/sandbox/provider/local.js +2 -0
  172. package/dist/sandbox/provider/local.js.map +1 -1
  173. package/dist/session/paths.d.ts +6 -0
  174. package/dist/session/paths.d.ts.map +1 -1
  175. package/dist/session/paths.js +7 -0
  176. package/dist/session/paths.js.map +1 -1
  177. package/dist/session-query/index.d.ts +1 -0
  178. package/dist/session-query/index.d.ts.map +1 -1
  179. package/dist/session-query/index.js +26 -15
  180. package/dist/session-query/index.js.map +1 -1
  181. package/dist/store/evidence/disk.js +3 -1
  182. package/dist/store/evidence/disk.js.map +1 -1
  183. package/dist/store/evidence/index-page.d.ts +1 -0
  184. package/dist/store/evidence/index-page.d.ts.map +1 -1
  185. package/dist/store/evidence/index-page.js +8 -0
  186. package/dist/store/evidence/index-page.js.map +1 -1
  187. package/dist/store/goal/gates.d.ts +53 -0
  188. package/dist/store/goal/gates.d.ts.map +1 -0
  189. package/dist/store/goal/gates.js +664 -0
  190. package/dist/store/goal/gates.js.map +1 -0
  191. package/dist/store/goal/index.d.ts +16 -1
  192. package/dist/store/goal/index.d.ts.map +1 -1
  193. package/dist/store/goal/index.js +74 -0
  194. package/dist/store/goal/index.js.map +1 -1
  195. package/dist/store/memory/operation-lock.d.ts.map +1 -1
  196. package/dist/store/memory/operation-lock.js +15 -1
  197. package/dist/store/memory/operation-lock.js.map +1 -1
  198. package/dist/store/session-log/core.d.ts.map +1 -1
  199. package/dist/store/session-log/core.js +23 -0
  200. package/dist/store/session-log/core.js.map +1 -1
  201. package/dist/tools/builtins/bash.js +1 -1
  202. package/dist/tools/builtins/bash.js.map +1 -1
  203. package/dist/tools/builtins/browser.d.ts.map +1 -1
  204. package/dist/tools/builtins/browser.js +2 -0
  205. package/dist/tools/builtins/browser.js.map +1 -1
  206. package/dist/tools/builtins/computer-use-image.d.ts +9 -0
  207. package/dist/tools/builtins/computer-use-image.d.ts.map +1 -1
  208. package/dist/tools/builtins/computer-use-image.js +21 -0
  209. package/dist/tools/builtins/computer-use-image.js.map +1 -1
  210. package/dist/tools/builtins/computer-use.d.ts +1 -9
  211. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  212. package/dist/tools/builtins/computer-use.js +2 -22
  213. package/dist/tools/builtins/computer-use.js.map +1 -1
  214. package/dist/tools/builtins/monitor.d.ts.map +1 -1
  215. package/dist/tools/builtins/monitor.js +1 -0
  216. package/dist/tools/builtins/monitor.js.map +1 -1
  217. package/dist/tools/builtins/search-tools.js +2 -2
  218. package/dist/tools/builtins/search-tools.js.map +1 -1
  219. package/dist/tools/builtins/sleep-guard.js +1 -1
  220. package/dist/tools/builtins/sleep-guard.js.map +1 -1
  221. package/dist/tools/builtins/wait-for-job.js +1 -1
  222. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  223. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  224. package/dist/tools/coordinator/ask-user-question.js +25 -0
  225. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  226. package/dist/tools/coordinator/index.d.ts.map +1 -1
  227. package/dist/tools/coordinator/index.js +3 -0
  228. package/dist/tools/coordinator/index.js.map +1 -1
  229. package/dist/tools/defineTool.d.ts +2 -0
  230. package/dist/tools/defineTool.d.ts.map +1 -1
  231. package/dist/tools/defineTool.js +3 -0
  232. package/dist/tools/defineTool.js.map +1 -1
  233. package/dist/tools/goal/confirmation.d.ts +40 -2
  234. package/dist/tools/goal/confirmation.d.ts.map +1 -1
  235. package/dist/tools/goal/confirmation.js +117 -0
  236. package/dist/tools/goal/confirmation.js.map +1 -1
  237. package/dist/tools/goal/index.d.ts.map +1 -1
  238. package/dist/tools/goal/index.js +14 -2
  239. package/dist/tools/goal/index.js.map +1 -1
  240. package/dist/tools/memory/save.d.ts.map +1 -1
  241. package/dist/tools/memory/save.js +1 -0
  242. package/dist/tools/memory/save.js.map +1 -1
  243. package/dist/tools/schedules/index.d.ts +1 -0
  244. package/dist/tools/schedules/index.d.ts.map +1 -1
  245. package/dist/tools/schedules/index.js +1 -0
  246. package/dist/tools/schedules/index.js.map +1 -1
  247. package/dist/tools/schedules/loop-tool.d.ts.map +1 -1
  248. package/dist/tools/schedules/loop-tool.js +1 -0
  249. package/dist/tools/schedules/loop-tool.js.map +1 -1
  250. package/dist/tools/schedules/present.d.ts.map +1 -1
  251. package/dist/tools/schedules/present.js +2 -0
  252. package/dist/tools/schedules/present.js.map +1 -1
  253. package/dist/tools/schedules/schedule-tool.d.ts.map +1 -1
  254. package/dist/tools/schedules/schedule-tool.js +79 -9
  255. package/dist/tools/schedules/schedule-tool.js.map +1 -1
  256. package/dist/tools/schedules/self-tool.d.ts +16 -0
  257. package/dist/tools/schedules/self-tool.d.ts.map +1 -0
  258. package/dist/tools/schedules/self-tool.js +140 -0
  259. package/dist/tools/schedules/self-tool.js.map +1 -0
  260. package/dist/tools/schedules/timer-tools.d.ts.map +1 -1
  261. package/dist/tools/schedules/timer-tools.js +1 -0
  262. package/dist/tools/schedules/timer-tools.js.map +1 -1
  263. package/dist/tools/schedules/types.d.ts +63 -0
  264. package/dist/tools/schedules/types.d.ts.map +1 -1
  265. package/dist/toolsets/manager.d.ts +14 -0
  266. package/dist/toolsets/manager.d.ts.map +1 -1
  267. package/dist/toolsets/manager.js +60 -7
  268. package/dist/toolsets/manager.js.map +1 -1
  269. package/dist/types/agent/supervisor.d.ts +10 -0
  270. package/dist/types/agent/supervisor.d.ts.map +1 -1
  271. package/dist/types/agent/task.d.ts +6 -0
  272. package/dist/types/agent/task.d.ts.map +1 -1
  273. package/dist/types/common/index.d.ts +20 -0
  274. package/dist/types/common/index.d.ts.map +1 -1
  275. package/dist/types/common/index.js +4 -1
  276. package/dist/types/common/index.js.map +1 -1
  277. package/dist/types/goal/index.d.ts +66 -0
  278. package/dist/types/goal/index.d.ts.map +1 -1
  279. package/dist/types/hitl/index.d.ts +11 -0
  280. package/dist/types/hitl/index.d.ts.map +1 -1
  281. package/dist/types/hitl/index.js.map +1 -1
  282. package/dist/types/rag/embedding.d.ts +4 -0
  283. package/dist/types/rag/embedding.d.ts.map +1 -1
  284. package/dist/types/sandbox/index.d.ts +19 -0
  285. package/dist/types/sandbox/index.d.ts.map +1 -1
  286. package/dist/types/sandbox/index.js.map +1 -1
  287. package/dist/types/session/events.d.ts +55 -0
  288. package/dist/types/session/events.d.ts.map +1 -1
  289. package/dist/types/session/events.js.map +1 -1
  290. package/dist/types/session/outcome.d.ts +12 -0
  291. package/dist/types/session/outcome.d.ts.map +1 -1
  292. package/dist/types/session/outcome.js.map +1 -1
  293. package/dist/types/session/records.d.ts +81 -1
  294. package/dist/types/session/records.d.ts.map +1 -1
  295. package/dist/types/session/records.js +33 -0
  296. package/dist/types/session/records.js.map +1 -1
  297. package/dist/types/tool/index.d.ts +7 -0
  298. package/dist/types/tool/index.d.ts.map +1 -1
  299. package/dist/types/tool/index.js.map +1 -1
  300. package/dist/utils/cost.d.ts +15 -0
  301. package/dist/utils/cost.d.ts.map +1 -1
  302. package/dist/utils/cost.js +24 -1
  303. package/dist/utils/cost.js.map +1 -1
  304. package/package.json +2 -2
  305. package/src/agents/examples/SupervisorAgent.ts +5 -0
  306. package/src/authorization/protected-paths.ts +11 -0
  307. package/src/authorization/readonly-commands.ts +85 -3
  308. package/src/authorization/shell-paths.ts +141 -3
  309. package/src/bridge/acp/permission.ts +6 -0
  310. package/src/bridge/acp/server.ts +20 -1
  311. package/src/compaction/context-window.ts +11 -0
  312. package/src/compaction/manual.ts +103 -17
  313. package/src/compaction/plan.ts +11 -5
  314. package/src/compaction/precompute.ts +390 -0
  315. package/src/compaction/retained-images.ts +130 -0
  316. package/src/compaction/token-estimate.ts +86 -8
  317. package/src/compaction/tool-result-editing.ts +20 -8
  318. package/src/config/runtime.ts +17 -0
  319. package/src/constants/acp/index.ts +2 -0
  320. package/src/manager/agent/lifecycle.ts +9 -0
  321. package/src/manager/session/turn-recorder.ts +92 -5
  322. package/src/peers/protocol.ts +4 -0
  323. package/src/peers/record.ts +4 -0
  324. package/src/plugin/index.ts +2 -0
  325. package/src/plugin/shell-hook.ts +60 -0
  326. package/src/pricing/catalogue.generated.ts +178 -1
  327. package/src/pricing/rates.source.json +155 -2
  328. package/src/provider/attribution.ts +1 -1
  329. package/src/public-runtime.ts +48 -0
  330. package/src/public-tools.ts +2 -0
  331. package/src/public-types.ts +8 -0
  332. package/src/rag/embedding.ts +23 -7
  333. package/src/registry/command/kernel-commands.ts +62 -3
  334. package/src/registry/tool/execute.ts +14 -0
  335. package/src/runtime/query/abandon-turn.ts +9 -0
  336. package/src/runtime/query/budget-nudge.ts +92 -0
  337. package/src/runtime/query/compact-session.ts +242 -87
  338. package/src/runtime/query/guard.ts +22 -0
  339. package/src/runtime/query/index.ts +1 -0
  340. package/src/runtime/query/iteration/index.ts +40 -1
  341. package/src/runtime/query/iteration/phases/compaction.ts +224 -46
  342. package/src/runtime/query/iteration/phases/context.ts +3 -0
  343. package/src/runtime/query/iteration/phases/precompute.ts +277 -0
  344. package/src/runtime/query/iteration/request-prefix.ts +161 -0
  345. package/src/runtime/query/review-policy.ts +79 -11
  346. package/src/runtime/query/turn/outcome-ledger.ts +34 -0
  347. package/src/sandbox/exec-stdin.ts +54 -0
  348. package/src/sandbox/file-walk.ts +25 -18
  349. package/src/sandbox/ignore-matcher.ts +1 -0
  350. package/src/sandbox/ignore-source.ts +1 -1
  351. package/src/sandbox/index.ts +8 -2
  352. package/src/sandbox/provider/local.ts +2 -0
  353. package/src/session/paths.ts +9 -0
  354. package/src/session-query/index.ts +23 -14
  355. package/src/store/evidence/disk.ts +3 -1
  356. package/src/store/evidence/index-page.ts +11 -0
  357. package/src/store/goal/gates.ts +738 -0
  358. package/src/store/goal/index.ts +109 -0
  359. package/src/store/memory/operation-lock.ts +19 -1
  360. package/src/store/session-log/core.ts +26 -0
  361. package/src/tools/builtins/bash.ts +1 -1
  362. package/src/tools/builtins/browser.ts +4 -0
  363. package/src/tools/builtins/computer-use-image.ts +20 -0
  364. package/src/tools/builtins/computer-use.ts +1 -20
  365. package/src/tools/builtins/monitor.ts +2 -0
  366. package/src/tools/builtins/search-tools.ts +2 -2
  367. package/src/tools/builtins/sleep-guard.ts +1 -1
  368. package/src/tools/builtins/wait-for-job.ts +1 -1
  369. package/src/tools/coordinator/ask-user-question.ts +37 -10
  370. package/src/tools/coordinator/index.ts +3 -0
  371. package/src/tools/defineTool.ts +5 -0
  372. package/src/tools/goal/confirmation.ts +171 -3
  373. package/src/tools/goal/index.ts +15 -3
  374. package/src/tools/memory/save.ts +2 -0
  375. package/src/tools/schedules/index.ts +1 -0
  376. package/src/tools/schedules/loop-tool.ts +2 -0
  377. package/src/tools/schedules/present.ts +2 -0
  378. package/src/tools/schedules/schedule-tool.ts +84 -9
  379. package/src/tools/schedules/self-tool.ts +152 -0
  380. package/src/tools/schedules/timer-tools.ts +2 -0
  381. package/src/tools/schedules/types.ts +62 -0
  382. package/src/toolsets/manager.ts +59 -8
  383. package/src/types/agent/supervisor.ts +11 -0
  384. package/src/types/agent/task.ts +7 -0
  385. package/src/types/common/index.ts +26 -1
  386. package/src/types/goal/index.ts +72 -0
  387. package/src/types/hitl/index.ts +11 -0
  388. package/src/types/rag/embedding.ts +7 -0
  389. package/src/types/sandbox/index.ts +19 -0
  390. package/src/types/session/events.ts +56 -0
  391. package/src/types/session/outcome.ts +16 -1
  392. package/src/types/session/records.ts +41 -0
  393. package/src/types/tool/index.ts +7 -0
  394. package/src/utils/cost.ts +44 -1
@@ -0,0 +1,390 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ import { RECALLED_MEMORY_ENTRY_KEY } from '../turn/memory-recall.js'
4
+ import type { TokenUsage } from '../types/common/index.js'
5
+ import { type Message, turnContextKey } from '../types/message/index.js'
6
+
7
+ /**
8
+ * A compaction summary written before it is needed.
9
+ *
10
+ * When the context nears the trigger, one summary request starts in the
11
+ * background for the span the pass would summarise. At the trigger the pass
12
+ * installs it at once when it is still valid for the conversation as it
13
+ * stands, and writes a fresh one when it is not. Two rules hold everywhere:
14
+ *
15
+ * - A prepared summary only ever replaces the messages it was written from.
16
+ * Anything said after it was armed stays verbatim after the summary, so no
17
+ * message the summary did not see is dropped.
18
+ * - One conversation has at most one summary in flight. A pass that finds one
19
+ * waits for it instead of starting another, and a pass a person asked for
20
+ * stops it first.
21
+ *
22
+ * The store lives in the process, per session. It holds no secrets beyond the
23
+ * summary text the session would have written anyway, and is never written to
24
+ * disk.
25
+ */
26
+
27
+ /** Consecutive prepared summaries that failed or were refused before the session stops preparing them. */
28
+ export const PRECOMPUTE_MAX_FAILURES = 3
29
+
30
+ /** How much of the way to the trigger a summary starts when the host names nothing else: see `armUsage`. */
31
+ export const PRECOMPUTE_DEFAULT_ARM_FRACTION = 0.2
32
+
33
+ /** Why a prepared summary was not used. */
34
+ export type PrecomputeRefusal =
35
+ | 'boundary_missing'
36
+ | 'covered_changed'
37
+ /** An assistant reply sits among the covered messages that the summary never saw. */
38
+ | 'unseen_reply'
39
+ /** The model now serving the conversation has another context window than the one the summary was sized for. */
40
+ | 'window_changed'
41
+ /** A recalled-memory entry the summary was written from is gone or different. */
42
+ | 'memory_withdrawn'
43
+ /** A tool result the summary was written from is gone or different (cleared, replaced). */
44
+ | 'tool_results_withdrawn'
45
+ | 'hook_rewrite'
46
+ | 'would_not_fit'
47
+ | 'summary_failed'
48
+
49
+ /** Where the arm came from, for the log: a loop entry, a reply, an idle host. */
50
+ export type PrecomputeArmSource = 'estimate' | 'after_turn' | 'idle'
51
+
52
+ /** What a prepared summary cost, kept until a pass takes it so the spend lands on the turn that used it. */
53
+ export interface PreparedSpend {
54
+ readonly usage: TokenUsage
55
+ readonly route: { readonly providerId: string; readonly model: string }
56
+ }
57
+
58
+ export interface PrecomputeEntry {
59
+ status: 'pending' | 'ready' | 'failed'
60
+ readonly source: PrecomputeArmSource
61
+ /** The messages the summary was written from, as they were when it was armed. */
62
+ readonly covered: readonly Message[]
63
+ /**
64
+ * What each covered message said when the summary was armed, by
65
+ * {@link messageDigest}. A message edited or replaced in place under the same
66
+ * id, or the same object changed after the summary read it, no longer matches.
67
+ */
68
+ readonly coveredDigests: readonly string[]
69
+ /** The context window the summary was sized for; a model with another window refuses it. */
70
+ readonly windowTokens?: number
71
+ /** The user message the conversation was on when it was armed. */
72
+ readonly prompt: Message | undefined
73
+ readonly controller: AbortController
74
+ /** Settles when the summary is ready, failed or stopped. Never rejects. */
75
+ done: Promise<void>
76
+ summary?: string
77
+ hookInstructions?: string
78
+ /**
79
+ * What the request spent and no turn has booked yet. Spend that arrives while
80
+ * the arming turn is open goes onto that turn at once and never lands here.
81
+ */
82
+ readonly spend: PreparedSpend[]
83
+ }
84
+
85
+ export class PrecomputeStore {
86
+ #entry: PrecomputeEntry | undefined
87
+ /** Spend of prepared summaries that were dropped or outlived their turn, waiting for a pass to book it. */
88
+ readonly #unbooked: PreparedSpend[] = []
89
+ #failures = 0
90
+ #vetoed: Message | undefined
91
+
92
+ get entry(): PrecomputeEntry | undefined {
93
+ return this.#entry
94
+ }
95
+
96
+ get failures(): number {
97
+ return this.#failures
98
+ }
99
+
100
+ /** True when a prepared summary may be started for the conversation as it stands. */
101
+ canArm(prompt: Message | undefined): boolean {
102
+ if (this.#entry) return false
103
+ if (this.#failures >= PRECOMPUTE_MAX_FAILURES) return false
104
+ return !(prompt !== undefined && this.#vetoed === prompt)
105
+ }
106
+
107
+ set(entry: PrecomputeEntry): void {
108
+ this.#entry = entry
109
+ }
110
+
111
+ /** Forget the entry (it was used, refused, or the context it described is gone). */
112
+ clear(entry?: PrecomputeEntry): void {
113
+ if (entry === undefined || this.#entry === entry) this.#entry = undefined
114
+ }
115
+
116
+ /** A prepared summary failed or was refused: count it, and do not retry for the same prompt. */
117
+ countFailure(prompt: Message | undefined): void {
118
+ this.#failures++
119
+ this.#vetoed = prompt
120
+ }
121
+
122
+ /** A prepared summary was used: the failure run ends. */
123
+ countSuccess(): void {
124
+ this.#failures = 0
125
+ this.#vetoed = undefined
126
+ }
127
+
128
+ /**
129
+ * Stop the summary in flight and wait until it has stopped. Returns what it
130
+ * spent that no turn had booked, which the caller owes a ledger: a stopped
131
+ * summary still cost the tokens it used.
132
+ */
133
+ async cancel(): Promise<readonly PreparedSpend[]> {
134
+ const entry = this.#entry
135
+ if (!entry) return []
136
+ this.#entry = undefined
137
+ entry.controller.abort()
138
+ await entry.done
139
+ const spend = [...entry.spend]
140
+ entry.spend.length = 0
141
+ return spend
142
+ }
143
+
144
+ /** Keep spend nobody could book yet for the next pass that can. */
145
+ addUnbooked(spend: readonly PreparedSpend[]): void {
146
+ this.#unbooked.push(...spend)
147
+ }
148
+
149
+ /** Take what is waiting to be booked: spend kept by {@link addUnbooked}. Empties it. */
150
+ drainUnbooked(): PreparedSpend[] {
151
+ return this.#unbooked.splice(0)
152
+ }
153
+
154
+ /**
155
+ * Take every unbooked cost this session holds: the ones kept by
156
+ * {@link addUnbooked} and what the prepared summary in the store spent but no
157
+ * turn booked. The summary is left in place, so a ready one can still be used;
158
+ * its spend is moved out and counted once.
159
+ */
160
+ takeSpend(): PreparedSpend[] {
161
+ const taken = this.drainUnbooked()
162
+ const entry = this.#entry
163
+ if (entry && entry.status !== 'pending') taken.push(...entry.spend.splice(0))
164
+ return taken
165
+ }
166
+
167
+ /** True when the store holds spend nobody has booked. */
168
+ holdsSpend(): boolean {
169
+ return this.#unbooked.length > 0 || (this.#entry?.spend.length ?? 0) > 0
170
+ }
171
+ }
172
+
173
+ const stores = new Map<string, PrecomputeStore>()
174
+ const MAX_STORES = 32
175
+
176
+ /** The store of one session, made on first use. The oldest idle stores are dropped past a bound. */
177
+ export function precomputeStoreFor(sessionId: string): PrecomputeStore {
178
+ let store = stores.get(sessionId)
179
+ if (store) {
180
+ stores.delete(sessionId)
181
+ stores.set(sessionId, store)
182
+ return store
183
+ }
184
+ store = new PrecomputeStore()
185
+ stores.set(sessionId, store)
186
+ for (const [id, old] of stores) {
187
+ if (stores.size <= MAX_STORES) break
188
+ if (id !== sessionId && old.entry?.status !== 'pending' && !old.holdsSpend()) stores.delete(id)
189
+ }
190
+ return store
191
+ }
192
+
193
+ /**
194
+ * End a conversation's prepared summary: stop the one in flight or waiting and
195
+ * return what it and any earlier one cost that no turn or pass booked. A host
196
+ * calls it when the conversation closes, so a summary the conversation never
197
+ * used is still on its ledger once. The session's store is forgotten.
198
+ */
199
+ export async function releasePreparedSummary(sessionId: string): Promise<readonly PreparedSpend[]> {
200
+ const store = stores.get(sessionId)
201
+ if (!store) return []
202
+ const stopped = await store.cancel()
203
+ const spend = [...store.drainUnbooked(), ...stopped]
204
+ stores.delete(sessionId)
205
+ return spend
206
+ }
207
+
208
+ /** For tests: forget every store. */
209
+ export function resetPrecomputeStores(): void {
210
+ stores.clear()
211
+ }
212
+
213
+ /**
214
+ * The context size, as a share of the window, at which a summary starts:
215
+ * `1 - armFraction` of the window, or the trigger when that is lower.
216
+ */
217
+ export function armUsage(trigger: number, armFraction: number): number {
218
+ return Math.min(1 - armFraction, trigger)
219
+ }
220
+
221
+ /** The same message: the same object, or the same recorded id (an edit copies the object and keeps the id). */
222
+ export function sameMessage(a: Message | undefined, b: Message | undefined): boolean {
223
+ if (a === undefined || b === undefined) return false
224
+ if (a === b) return true
225
+ return a.id !== undefined && a.id === b.id && a.role === b.role
226
+ }
227
+
228
+ /** `value` as JSON with object keys in a fixed order, so two equal messages digest alike whatever order they were built in. */
229
+ function canonicalJson(value: unknown): string {
230
+ return JSON.stringify(value, (_key, nested: unknown) => {
231
+ if (typeof nested !== 'object' || nested === null || Array.isArray(nested)) return nested
232
+ const sorted: Record<string, unknown> = {}
233
+ for (const key of Object.keys(nested).sort())
234
+ sorted[key] = (nested as Record<string, unknown>)[key]
235
+ return sorted
236
+ })
237
+ }
238
+
239
+ /** A stable digest of a message as it reads now: role, content, tool calls, source, id, everything it carries. */
240
+ export function messageDigest(message: Message): string {
241
+ return createHash('sha256')
242
+ .update(canonicalJson(message) ?? 'null')
243
+ .digest('hex')
244
+ }
245
+
246
+ export type PreparedAssessment =
247
+ | { readonly ok: true; readonly keepStart: number }
248
+ | { readonly ok: false; readonly reason: PrecomputeRefusal }
249
+
250
+ /** Why the covered message at `index` is no longer what the summary read. */
251
+ function changedReason(
252
+ entry: PrecomputeEntry,
253
+ live: readonly Message[],
254
+ floorLength: number,
255
+ index: number,
256
+ ): PrecomputeRefusal {
257
+ const covered = entry.covered
258
+ const wanted = covered[index] as Message
259
+ const here = live[floorLength + index]
260
+ // An assistant reply the summary never saw, in the middle of what it covers.
261
+ if (
262
+ here?.role === 'assistant' &&
263
+ !covered.some((message) => sameMessage(message, here)) &&
264
+ live.some((message, at) => at > floorLength + index && sameMessage(message, wanted))
265
+ ) {
266
+ return 'unseen_reply'
267
+ }
268
+ return withdrawnReason(wanted) ?? 'covered_changed'
269
+ }
270
+
271
+ /** The reason that names what a covered message was, when what it carried is the kind a host withdraws. */
272
+ function withdrawnReason(message: Message | undefined): PrecomputeRefusal | undefined {
273
+ if (message === undefined) return undefined
274
+ if (turnContextKey(message) === RECALLED_MEMORY_ENTRY_KEY) return 'memory_withdrawn'
275
+ if (message.role === 'tool') return 'tool_results_withdrawn'
276
+ return undefined
277
+ }
278
+
279
+ /**
280
+ * Whether a ready summary still describes the start of the conversation.
281
+ *
282
+ * `floorLength` is the count of leading system messages. The summary stands
283
+ * for the run of messages right after them: every message it covered must
284
+ * still be there, in order, and say what it said (compared by digest, not by
285
+ * identity or id). What came after stays as it is, so the new cut is just past
286
+ * the covered run.
287
+ */
288
+ export function assessPrepared(
289
+ entry: PrecomputeEntry,
290
+ live: readonly Message[],
291
+ input: {
292
+ readonly floorLength: number
293
+ readonly hookInstructions: string | undefined
294
+ /** Size of the context after the swap, and the size it must stay under. */
295
+ readonly tokensAfterSwap: (keepStart: number, summary: string) => number
296
+ readonly limitTokens: number
297
+ /** The window the conversation is sized for now. */
298
+ readonly windowTokens?: number
299
+ },
300
+ ): PreparedAssessment {
301
+ if (entry.status !== 'ready' || entry.summary === undefined) {
302
+ return { ok: false, reason: 'summary_failed' }
303
+ }
304
+ const covered = entry.covered
305
+ if (covered.length === 0 || !live.some((message) => sameMessage(message, covered[0]))) {
306
+ return { ok: false, reason: withdrawnReason(covered[0]) ?? 'boundary_missing' }
307
+ }
308
+ if (
309
+ entry.windowTokens !== undefined &&
310
+ input.windowTokens !== undefined &&
311
+ entry.windowTokens !== input.windowTokens
312
+ ) {
313
+ return { ok: false, reason: 'window_changed' }
314
+ }
315
+ for (let i = 0; i < covered.length; i++) {
316
+ const here = live[input.floorLength + i]
317
+ if (
318
+ here === undefined ||
319
+ !sameMessage(here, covered[i]) ||
320
+ messageDigest(here) !== entry.coveredDigests[i]
321
+ ) {
322
+ return { ok: false, reason: changedReason(entry, live, input.floorLength, i) }
323
+ }
324
+ }
325
+ if (entry.hookInstructions !== input.hookInstructions) {
326
+ return { ok: false, reason: 'hook_rewrite' }
327
+ }
328
+ const keepStart = input.floorLength + covered.length
329
+ if (input.tokensAfterSwap(keepStart, entry.summary) >= input.limitTokens) {
330
+ return { ok: false, reason: 'would_not_fit' }
331
+ }
332
+ return { ok: true, keepStart }
333
+ }
334
+
335
+ export type ClaimedSummary =
336
+ | {
337
+ readonly ok: true
338
+ readonly summary: string
339
+ readonly keepStart: number
340
+ readonly spend: readonly PreparedSpend[]
341
+ }
342
+ | {
343
+ readonly ok: false
344
+ /** `none`: nothing was prepared. */
345
+ readonly reason: PrecomputeRefusal | 'none'
346
+ readonly spend: readonly PreparedSpend[]
347
+ }
348
+
349
+ /**
350
+ * Take the session's prepared summary for a pass about to write one.
351
+ *
352
+ * A summary still in flight is waited for when `awaitPending` is set (it is
353
+ * the one this pass would have written) and left alone otherwise. The entry is
354
+ * consumed either way; a refusal counts toward the failure cap, a use ends it.
355
+ * What the prepared request spent comes back for the caller to put on its
356
+ * ledger.
357
+ */
358
+ export async function claimPrepared(
359
+ store: PrecomputeStore,
360
+ live: readonly Message[],
361
+ input: {
362
+ readonly floorLength: number
363
+ readonly hookInstructions: string | undefined
364
+ readonly tokensAfterSwap: (keepStart: number, summary: string) => number
365
+ readonly limitTokens: number
366
+ readonly windowTokens?: number
367
+ readonly awaitPending: boolean
368
+ readonly waitFor?: (promise: Promise<void>) => Promise<void>
369
+ },
370
+ ): Promise<ClaimedSummary> {
371
+ const entry = store.entry
372
+ if (!entry) return { ok: false, reason: 'none', spend: [] }
373
+ if (entry.status === 'pending') {
374
+ if (!input.awaitPending) return { ok: false, reason: 'none', spend: [] }
375
+ await (input.waitFor ? input.waitFor(entry.done) : entry.done)
376
+ }
377
+ // Another pass may have taken it while this one waited.
378
+ if (store.entry !== entry) return { ok: false, reason: 'none', spend: [] }
379
+ store.clear(entry)
380
+ const spend = [...entry.spend]
381
+ entry.spend.length = 0
382
+ if (entry.status !== 'ready') return { ok: false, reason: 'summary_failed', spend }
383
+ const assessment = assessPrepared(entry, live, input)
384
+ if (!assessment.ok) {
385
+ store.countFailure(entry.prompt)
386
+ return { ok: false, reason: assessment.reason, spend }
387
+ }
388
+ store.countSuccess()
389
+ return { ok: true, summary: entry.summary as string, keepStart: assessment.keepStart, spend }
390
+ }
@@ -0,0 +1,130 @@
1
+ import type { Message, MessageAttachment, ToolResultBlock } from '../types/message/index.js'
2
+ import { findRetainedIndices } from './retention.js'
3
+ import {
4
+ estimateMessagesTokensForModel,
5
+ estimateRichContentTokens,
6
+ estimateTextTokens,
7
+ } from './token-estimate.js'
8
+
9
+ const MAX_RETAINED_IMAGES = 16
10
+ const MAX_RETAINED_IMAGE_BYTES = 8 * 1024 * 1024
11
+
12
+ type RichBlock = MessageAttachment | Exclude<ToolResultBlock, { type: 'text' }>
13
+
14
+ function isImage(block: RichBlock): boolean {
15
+ return block.type === 'stored' ? block.kind === 'image' : block.type !== 'document'
16
+ }
17
+
18
+ function label(text: string): string {
19
+ return text.replace(/\s+/g, ' ').trim().slice(0, 100)
20
+ }
21
+
22
+ export function compactedImageMarker(block: RichBlock, source: string): string {
23
+ const name = 'name' in block && block.name ? ` "${label(block.name)}"` : ''
24
+ return `[image omitted by compaction: ${label(source)}${name} (${label(block.mediaType)})]`
25
+ }
26
+
27
+ /**
28
+ * Fit images around the retained text and the summary. Keep a small recent
29
+ * set, including when a single tool call returned a batch of images.
30
+ * Replacements leave the producing call, caption and result ID in place.
31
+ */
32
+ export function fitRetainedImages(
33
+ messages: Message[],
34
+ tokenLimit: number,
35
+ model?: string,
36
+ tail?: { readonly start: number; readonly tokens: number },
37
+ ): Message[] {
38
+ const items: {
39
+ index: number
40
+ itemIndex: number
41
+ block: RichBlock
42
+ tokens: number
43
+ marker: string
44
+ tool: boolean
45
+ }[] = []
46
+ const tools = new Map<string, string>()
47
+ let newestUser = -1
48
+ for (const [index, message] of messages.entries()) {
49
+ if (message.role === 'user') newestUser = index
50
+ if (message.role === 'assistant') {
51
+ for (const call of message.toolCalls ?? []) tools.set(call.id, call.function.name)
52
+ }
53
+ const tool = message.role === 'tool'
54
+ const blocks =
55
+ message.role === 'user' ? message.attachments : tool ? message.content : undefined
56
+ if (!Array.isArray(blocks)) continue
57
+ for (const [itemIndex, block] of (
58
+ blocks as readonly (RichBlock | { type: 'text' })[]
59
+ ).entries()) {
60
+ if (block.type === 'text' || !isImage(block)) continue
61
+ if ('modelOmission' in block && block.modelOmission) continue
62
+ const source = tool ? (tools.get(message.toolCallId) ?? 'tool result') : 'user attachment'
63
+ items.push({
64
+ index,
65
+ itemIndex,
66
+ block,
67
+ tokens: estimateRichContentTokens(block, model, tool),
68
+ marker: compactedImageMarker(block, source),
69
+ tool,
70
+ })
71
+ }
72
+ }
73
+ if (items.length === 0) return messages
74
+
75
+ let promptTokens = estimateMessagesTokensForModel(messages, model)
76
+ let tailTokens = tail ? estimateMessagesTokensForModel(messages.slice(tail.start), model) : 0
77
+ let count = items.length
78
+ let bytes = items.reduce((sum, { block }) => sum + ('data' in block ? block.data.length : 0), 0)
79
+ const retained = findRetainedIndices(messages)
80
+ const omitted = new Map<number, Map<number, string>>()
81
+ // Old tool observations go first. Within the latest user turn, keep the
82
+ // newest observations regardless of which role supplied them.
83
+ const priority = (item: (typeof items)[number]) =>
84
+ item.index >= newestUser ? 2 : item.tool ? 0 : 1
85
+ for (const item of [...items].sort((a, b) => priority(a) - priority(b))) {
86
+ if (retained.has(item.index)) continue
87
+ const overTail = tail && tailTokens > tail.tokens
88
+ const overPrompt =
89
+ promptTokens > tokenLimit || count > MAX_RETAINED_IMAGES || bytes > MAX_RETAINED_IMAGE_BYTES
90
+ if (!overPrompt && !overTail) break
91
+ if (overTail && !overPrompt && item.index < tail.start) continue
92
+ let blocks = omitted.get(item.index)
93
+ if (!blocks) {
94
+ blocks = new Map()
95
+ omitted.set(item.index, blocks)
96
+ }
97
+ blocks.set(item.itemIndex, item.marker)
98
+ const saved = item.tokens - estimateTextTokens(`\n${item.marker}`)
99
+ promptTokens -= saved
100
+ if (tail && item.index >= tail.start) tailTokens -= saved
101
+ if ('data' in item.block) bytes -= item.block.data.length
102
+ count--
103
+ }
104
+ if (omitted.size === 0) return messages
105
+
106
+ return messages.map((message, index) => {
107
+ const blocks = omitted.get(index)
108
+ if (!blocks) return message
109
+ if (message.role === 'tool' && typeof message.content !== 'string') {
110
+ return {
111
+ ...message,
112
+ content: message.content.map((block, itemIndex): ToolResultBlock => {
113
+ const marker = blocks.get(itemIndex)
114
+ return marker ? { type: 'text', text: marker } : block
115
+ }),
116
+ }
117
+ }
118
+ if (message.role === 'user') {
119
+ const { attachments, ...rest } = message
120
+ const kept = attachments?.filter((_, itemIndex) => !blocks.has(itemIndex)) ?? []
121
+ const markers = attachments?.flatMap((_, itemIndex) => blocks.get(itemIndex) ?? []) ?? []
122
+ return {
123
+ ...rest,
124
+ content: [message.content, ...markers].filter(Boolean).join('\n'),
125
+ ...(kept.length > 0 ? { attachments: kept } : {}),
126
+ }
127
+ }
128
+ return message
129
+ })
130
+ }
@@ -1,4 +1,10 @@
1
+ import { Buffer } from 'node:buffer'
1
2
  import { CHARS_PER_TOKEN } from '../constants/limits.js'
3
+ import {
4
+ pngSize,
5
+ screenshotLimitsForModel,
6
+ screenshotTargetSize,
7
+ } from '../tools/builtins/computer-use-image.js'
2
8
  import type { Message, MessageAttachment, ToolResultBlock } from '../types/message/index.js'
3
9
 
4
10
  // Heuristic allowances, not provider billing formulas or upper bounds. Encoded
@@ -8,10 +14,68 @@ const IMAGE_TOKENS = 1_024
8
14
  const DOCUMENT_TOKENS = 4_096
9
15
  const OMITTED_IMAGE_TOKENS = 64
10
16
 
11
- function richTokens(block: Exclude<ToolResultBlock, { type: 'text' }> | MessageAttachment): number {
12
- if (block.type === 'stored') return block.kind === 'image' ? IMAGE_TOKENS : DOCUMENT_TOKENS
17
+ export function estimateRichContentTokens(
18
+ block: Exclude<ToolResultBlock, { type: 'text' }> | MessageAttachment,
19
+ model = '',
20
+ toolResult = false,
21
+ ): number {
22
+ const id = model.toLowerCase().split('/').at(-1) ?? ''
23
+ const limits = screenshotLimitsForModel(model)
24
+ const gemini = /^gemini-[34](?:[.-]|$)/.test(id)
25
+ const modernPatches = /^(?:gpt-6-astra|gpt-5\.[456])(?:[.-]|$)/.test(id)
26
+ const widePatches = /^gpt-5\.2(?:-|$)/.test(id)
27
+ let tileCost = 0
28
+ if (/^gpt-5(?:\.1)?(?:-20|$)/.test(id)) tileCost = 140
29
+ if (/^gpt-4o-mini(?:-|$)/.test(id)) tileCost = 5667
30
+ if (/^gpt-4(?:o|\.1)(?:-20|$)/.test(id)) tileCost = 170
31
+
32
+ let visualLimit = IMAGE_TOKENS
33
+ if (id.startsWith('claude-')) visualLimit = limits.maxTiles
34
+ if (gemini) visualLimit = 1120
35
+ if (modernPatches) visualLimit = 3000
36
+ if (widePatches) visualLimit = 7373
37
+ if (tileCost) visualLimit = Math.ceil(4.5 * tileCost)
38
+ if (block.type === 'stored') return block.kind === 'image' ? visualLimit : DOCUMENT_TOKENS
13
39
  if (block.type === 'document') return DOCUMENT_TOKENS
14
- return block.modelOmission ? OMITTED_IMAGE_TOKENS : IMAGE_TOKENS
40
+ if (block.modelOmission) return OMITTED_IMAGE_TOKENS
41
+ // Read just the PNG header. Other raster formats use the model allowance.
42
+ if (
43
+ gemini ||
44
+ block.mediaType !== 'image/png' ||
45
+ block.data.length < 32 ||
46
+ !block.data.startsWith('iVBORw0KGgo')
47
+ )
48
+ return visualLimit
49
+ const header = Buffer.from(block.data.slice(0, 32), 'base64')
50
+ if (header.length < 24 || header.toString('ascii', 12, 16) !== 'IHDR') return visualLimit
51
+ const { width, height } = pngSize(header)
52
+ if (!width || !height) return visualLimit
53
+ if (modernPatches || widePatches) {
54
+ let edge = 2048
55
+ let patchLimit = widePatches ? 6144 : 2500
56
+ // Tool observations use high detail. Recent families can use original
57
+ // resolution by default for pasted images.
58
+ if (!toolResult && /^gpt-5\.5(?:-|$)/.test(id)) {
59
+ edge = 6000
60
+ patchLimit = 10_000
61
+ }
62
+ if (!toolResult && /^(?:gpt-6-astra|gpt-5\.6)(?:-|$)/.test(id)) {
63
+ edge = 65_535
64
+ patchLimit = 30_000
65
+ }
66
+ const scale = Math.min(1, edge / Math.max(width, height))
67
+ const patches = Math.ceil((width * scale) / 32) * Math.ceil((height * scale) / 32)
68
+ return Math.ceil(1.2 * Math.min(patchLimit, patches))
69
+ }
70
+ if (tileCost) {
71
+ const scale = Math.min(1, 2048 / Math.max(width, height), 768 / Math.min(width, height))
72
+ return (
73
+ Math.floor(tileCost / 2) +
74
+ tileCost * Math.ceil((width * scale) / 512) * Math.ceil((height * scale) / 512)
75
+ )
76
+ }
77
+ const sized = screenshotTargetSize(width, height, limits)
78
+ return Math.ceil(sized.width / 28) * Math.ceil(sized.height / 28)
15
79
  }
16
80
 
17
81
  /**
@@ -19,11 +83,15 @@ function richTokens(block: Exclude<ToolResultBlock, { type: 'text' }> | MessageA
19
83
  *
20
84
  * Text and tool inputs use the existing characters-per-token approximation.
21
85
  * Images and documents have an explicit allowance independent of compression
22
- * and of whether the bytes are inline or stored externally. Without dimensions,
23
- * page counts and a provider tokenizer their exact cost is unknown. In
86
+ * and fall back to an allowance for legacy stored images and formats without
87
+ * cheaply available dimensions. Exact costs depend on the serving model. In
24
88
  * particular, serialized base64 is never treated as model-visible prose.
25
89
  */
26
90
  export function estimateMessageTokens(message: Message): number {
91
+ return estimateMessageTokensForModel(message)
92
+ }
93
+
94
+ export function estimateMessageTokensForModel(message: Message, model?: string): number {
27
95
  let chars = 0
28
96
  let rich = 0
29
97
  if (typeof message.content === 'string') chars += message.content.length
@@ -31,7 +99,7 @@ export function estimateMessageTokens(message: Message): number {
31
99
  for (const block of message.content) {
32
100
  if (block.type === 'text') chars += block.text.length
33
101
  else {
34
- rich += richTokens(block)
102
+ rich += estimateRichContentTokens(block, model, message.role === 'tool')
35
103
  if (block.type === 'document') chars += block.name?.length ?? 0
36
104
  }
37
105
  }
@@ -43,7 +111,7 @@ export function estimateMessageTokens(message: Message): number {
43
111
  }
44
112
  if (message.role === 'user') {
45
113
  for (const attachment of message.attachments ?? []) {
46
- rich += richTokens(attachment)
114
+ rich += estimateRichContentTokens(attachment, model)
47
115
  if (attachment.type === 'document' || attachment.type === 'stored') {
48
116
  chars += attachment.name?.length ?? 0
49
117
  }
@@ -58,5 +126,15 @@ export function estimateTextTokens(text: string): number {
58
126
  }
59
127
 
60
128
  export function estimateMessagesTokens(messages: readonly Message[]): number {
61
- return messages.reduce((total, message) => total + estimateMessageTokens(message), 0)
129
+ return estimateMessagesTokensForModel(messages)
130
+ }
131
+
132
+ export function estimateMessagesTokensForModel(
133
+ messages: readonly Message[],
134
+ model?: string,
135
+ ): number {
136
+ return messages.reduce(
137
+ (total, message) => total + estimateMessageTokensForModel(message, model),
138
+ 0,
139
+ )
62
140
  }