@nhtio/adk 0.1.0-master-d0e68851 → 0.1.0-master-298eb7ff

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 (502) hide show
  1. package/CHANGELOG.md +167 -0
  2. package/batteries/context/compact/contracts.cjs +2 -0
  3. package/batteries/context/compact/contracts.d.ts +120 -0
  4. package/batteries/context/compact/contracts.mjs +0 -0
  5. package/batteries/context/compact/index.d.ts +102 -0
  6. package/batteries/context/compact/summarizer.cjs +201 -0
  7. package/batteries/context/compact/summarizer.cjs.map +1 -0
  8. package/batteries/context/compact/summarizer.d.ts +197 -0
  9. package/batteries/context/compact/summarizer.mjs +194 -0
  10. package/batteries/context/compact/summarizer.mjs.map +1 -0
  11. package/batteries/context/compact.cjs +11 -0
  12. package/batteries/context/compact.mjs +3 -0
  13. package/batteries/context/exceptions.cjs +60 -0
  14. package/batteries/context/exceptions.cjs.map +1 -0
  15. package/batteries/context/exceptions.d.ts +54 -0
  16. package/batteries/context/exceptions.mjs +58 -0
  17. package/batteries/context/exceptions.mjs.map +1 -0
  18. package/batteries/context/index.d.ts +34 -0
  19. package/batteries/context/thrift/contracts.cjs +2 -0
  20. package/batteries/context/thrift/contracts.d.ts +263 -0
  21. package/batteries/context/thrift/contracts.mjs +0 -0
  22. package/batteries/context/thrift/index.d.ts +97 -0
  23. package/batteries/context/thrift/relevance.cjs +227 -0
  24. package/batteries/context/thrift/relevance.cjs.map +1 -0
  25. package/batteries/context/thrift/relevance.d.ts +255 -0
  26. package/batteries/context/thrift/relevance.mjs +216 -0
  27. package/batteries/context/thrift/relevance.mjs.map +1 -0
  28. package/batteries/context/thrift/subtractive_pass.cjs +361 -0
  29. package/batteries/context/thrift/subtractive_pass.cjs.map +1 -0
  30. package/batteries/context/thrift/subtractive_pass.d.ts +335 -0
  31. package/batteries/context/thrift/subtractive_pass.mjs +354 -0
  32. package/batteries/context/thrift/subtractive_pass.mjs.map +1 -0
  33. package/batteries/context/thrift.cjs +22 -0
  34. package/batteries/context/thrift.mjs +4 -0
  35. package/batteries/context.cjs +31 -0
  36. package/batteries/context.mjs +7 -0
  37. package/batteries/embeddings/openai/adapter.cjs +3 -3
  38. package/batteries/embeddings/openai/adapter.cjs.map +1 -1
  39. package/batteries/embeddings/openai/adapter.mjs +1 -1
  40. package/batteries/embeddings/openai/adapter.mjs.map +1 -1
  41. package/batteries/embeddings/transformers_js/adapter.cjs +3 -3
  42. package/batteries/embeddings/transformers_js/adapter.cjs.map +1 -1
  43. package/batteries/embeddings/transformers_js/adapter.mjs +1 -1
  44. package/batteries/embeddings/transformers_js/validation.cjs +2 -2
  45. package/batteries/embeddings/transformers_js/validation.cjs.map +1 -1
  46. package/batteries/embeddings/transformers_js/validation.mjs +1 -1
  47. package/batteries/embeddings/webllm/adapter.cjs +3 -3
  48. package/batteries/embeddings/webllm/adapter.cjs.map +1 -1
  49. package/batteries/embeddings/webllm/adapter.mjs +1 -1
  50. package/batteries/encoding.cjs +10 -11
  51. package/batteries/encoding.cjs.map +1 -1
  52. package/batteries/encoding.mjs +6 -7
  53. package/batteries/encoding.mjs.map +1 -1
  54. package/batteries/index.d.ts +1 -0
  55. package/batteries/llm/chat_common/exceptions.cjs +39 -0
  56. package/batteries/llm/chat_common/exceptions.cjs.map +1 -0
  57. package/batteries/llm/chat_common/exceptions.d.ts +33 -0
  58. package/batteries/llm/chat_common/exceptions.mjs +37 -0
  59. package/batteries/llm/chat_common/exceptions.mjs.map +1 -0
  60. package/batteries/llm/chat_common/gpu_budget.d.ts +138 -0
  61. package/batteries/llm/chat_common/helpers.d.ts +51 -0
  62. package/batteries/llm/chat_common/index.d.ts +2 -0
  63. package/batteries/llm/chat_common/lifecycle.d.ts +10 -2
  64. package/batteries/llm/chat_common/tool_parsers.d.ts +44 -3
  65. package/batteries/llm/chat_common/types.d.ts +174 -5
  66. package/batteries/llm/litert_lm/adapter.cjs +152 -63
  67. package/batteries/llm/litert_lm/adapter.cjs.map +1 -1
  68. package/batteries/llm/litert_lm/adapter.d.ts +25 -0
  69. package/batteries/llm/litert_lm/adapter.mjs +136 -48
  70. package/batteries/llm/litert_lm/adapter.mjs.map +1 -1
  71. package/batteries/llm/litert_lm/helpers.cjs +103 -61
  72. package/batteries/llm/litert_lm/helpers.cjs.map +1 -1
  73. package/batteries/llm/litert_lm/helpers.d.ts +49 -8
  74. package/batteries/llm/litert_lm/helpers.mjs +49 -17
  75. package/batteries/llm/litert_lm/helpers.mjs.map +1 -1
  76. package/batteries/llm/litert_lm/index.d.ts +5 -3
  77. package/batteries/llm/litert_lm/types.d.ts +32 -2
  78. package/batteries/llm/litert_lm/validation.cjs +11 -11
  79. package/batteries/llm/litert_lm/validation.cjs.map +1 -1
  80. package/batteries/llm/litert_lm/validation.mjs +10 -10
  81. package/batteries/llm/litert_lm/validation.mjs.map +1 -1
  82. package/batteries/llm/litert_lm.cjs +39 -30
  83. package/batteries/llm/litert_lm.mjs +6 -4
  84. package/batteries/llm/ollama/adapter.cjs +98 -53
  85. package/batteries/llm/ollama/adapter.cjs.map +1 -1
  86. package/batteries/llm/ollama/adapter.mjs +78 -33
  87. package/batteries/llm/ollama/adapter.mjs.map +1 -1
  88. package/batteries/llm/ollama/helpers.cjs +3 -4
  89. package/batteries/llm/ollama/helpers.cjs.map +1 -1
  90. package/batteries/llm/ollama/helpers.mjs +3 -4
  91. package/batteries/llm/ollama/helpers.mjs.map +1 -1
  92. package/batteries/llm/ollama/types.d.ts +57 -1
  93. package/batteries/llm/ollama/validation.cjs +9 -3
  94. package/batteries/llm/ollama/validation.cjs.map +1 -1
  95. package/batteries/llm/ollama/validation.mjs +9 -3
  96. package/batteries/llm/ollama/validation.mjs.map +1 -1
  97. package/batteries/llm/ollama.cjs +1 -1
  98. package/batteries/llm/ollama.mjs +1 -1
  99. package/batteries/llm/openai_chat_completions/adapter.cjs +115 -54
  100. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
  101. package/batteries/llm/openai_chat_completions/adapter.mjs +95 -34
  102. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
  103. package/batteries/llm/openai_chat_completions/helpers.cjs +3 -4
  104. package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -1
  105. package/batteries/llm/openai_chat_completions/helpers.mjs +3 -4
  106. package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -1
  107. package/batteries/llm/openai_chat_completions/index.d.ts +1 -0
  108. package/batteries/llm/openai_chat_completions/types.d.ts +51 -1
  109. package/batteries/llm/openai_chat_completions/validation.cjs +9 -3
  110. package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -1
  111. package/batteries/llm/openai_chat_completions/validation.mjs +9 -3
  112. package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -1
  113. package/batteries/llm/openai_chat_completions.cjs +1 -1
  114. package/batteries/llm/openai_chat_completions.mjs +1 -1
  115. package/batteries/llm/transformers_js/adapter.cjs +240 -74
  116. package/batteries/llm/transformers_js/adapter.cjs.map +1 -1
  117. package/batteries/llm/transformers_js/adapter.d.ts +22 -0
  118. package/batteries/llm/transformers_js/adapter.mjs +221 -55
  119. package/batteries/llm/transformers_js/adapter.mjs.map +1 -1
  120. package/batteries/llm/transformers_js/helpers.cjs +86 -55
  121. package/batteries/llm/transformers_js/helpers.cjs.map +1 -1
  122. package/batteries/llm/transformers_js/helpers.d.ts +24 -4
  123. package/batteries/llm/transformers_js/helpers.mjs +31 -10
  124. package/batteries/llm/transformers_js/helpers.mjs.map +1 -1
  125. package/batteries/llm/transformers_js/index.d.ts +5 -3
  126. package/batteries/llm/transformers_js/model_source.cjs +2 -2
  127. package/batteries/llm/transformers_js/model_source.cjs.map +1 -1
  128. package/batteries/llm/transformers_js/model_source.mjs +1 -1
  129. package/batteries/llm/transformers_js/types.d.ts +70 -2
  130. package/batteries/llm/transformers_js/validation.cjs +11 -5
  131. package/batteries/llm/transformers_js/validation.cjs.map +1 -1
  132. package/batteries/llm/transformers_js/validation.mjs +10 -4
  133. package/batteries/llm/transformers_js/validation.mjs.map +1 -1
  134. package/batteries/llm/transformers_js.cjs +57 -47
  135. package/batteries/llm/transformers_js.mjs +5 -3
  136. package/batteries/llm/webllm_chat_completions/adapter.cjs +115 -54
  137. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
  138. package/batteries/llm/webllm_chat_completions/adapter.mjs +96 -35
  139. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
  140. package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
  141. package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
  142. package/batteries/llm/webllm_chat_completions/validation.cjs +9 -3
  143. package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -1
  144. package/batteries/llm/webllm_chat_completions/validation.mjs +9 -3
  145. package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -1
  146. package/batteries/llm/webllm_chat_completions.cjs +1 -1
  147. package/batteries/llm/webllm_chat_completions.mjs +1 -1
  148. package/batteries/llm.cjs +1 -1
  149. package/batteries/llm.mjs +1 -1
  150. package/batteries/media/contracts.cjs +3 -3
  151. package/batteries/media/contracts.cjs.map +1 -1
  152. package/batteries/media/contracts.mjs +1 -1
  153. package/batteries/media/engines/audio_decode.cjs +2 -2
  154. package/batteries/media/engines/audio_decode.cjs.map +1 -1
  155. package/batteries/media/engines/audio_decode.mjs +1 -1
  156. package/batteries/media/engines/data.cjs +2 -2
  157. package/batteries/media/engines/data.cjs.map +1 -1
  158. package/batteries/media/engines/data.mjs +1 -1
  159. package/batteries/media/engines/exceljs.cjs +3 -3
  160. package/batteries/media/engines/exceljs.cjs.map +1 -1
  161. package/batteries/media/engines/exceljs.mjs +1 -1
  162. package/batteries/media/engines/execa_executor.cjs +3 -3
  163. package/batteries/media/engines/execa_executor.cjs.map +1 -1
  164. package/batteries/media/engines/execa_executor.mjs +1 -1
  165. package/batteries/media/engines/fs_workspace.cjs +3 -3
  166. package/batteries/media/engines/fs_workspace.cjs.map +1 -1
  167. package/batteries/media/engines/fs_workspace.mjs +1 -1
  168. package/batteries/media/engines/jimp.cjs +2 -2
  169. package/batteries/media/engines/jimp.cjs.map +1 -1
  170. package/batteries/media/engines/jimp.mjs +1 -1
  171. package/batteries/media/engines/sharp.cjs +2 -2
  172. package/batteries/media/engines/sharp.cjs.map +1 -1
  173. package/batteries/media/engines/sharp.mjs +1 -1
  174. package/batteries/media/engines/sheetjs.cjs +3 -3
  175. package/batteries/media/engines/sheetjs.cjs.map +1 -1
  176. package/batteries/media/engines/sheetjs.mjs +1 -1
  177. package/batteries/media/engines/tesseract_js.cjs +2 -2
  178. package/batteries/media/engines/tesseract_js.cjs.map +1 -1
  179. package/batteries/media/engines/tesseract_js.mjs +1 -1
  180. package/batteries/media/engines/transformers_asr.cjs +2 -2
  181. package/batteries/media/engines/transformers_asr.cjs.map +1 -1
  182. package/batteries/media/engines/transformers_asr.mjs +1 -1
  183. package/batteries/media/forge.cjs +10 -10
  184. package/batteries/media/forge.cjs.map +1 -1
  185. package/batteries/media/forge.mjs +6 -6
  186. package/batteries/media/forge.mjs.map +1 -1
  187. package/batteries/media/lint.cjs +1 -1
  188. package/batteries/media/lint.mjs +1 -1
  189. package/batteries/media.cjs +41 -25
  190. package/batteries/media.cjs.map +1 -1
  191. package/batteries/media.mjs +18 -2
  192. package/batteries/media.mjs.map +1 -1
  193. package/batteries/storage/flydrive.cjs +2 -2
  194. package/batteries/storage/flydrive.cjs.map +1 -1
  195. package/batteries/storage/flydrive.mjs +1 -1
  196. package/batteries/storage/in_memory.cjs +2 -2
  197. package/batteries/storage/in_memory.cjs.map +1 -1
  198. package/batteries/storage/in_memory.mjs +1 -1
  199. package/batteries/storage/opfs.cjs +5 -4
  200. package/batteries/storage/opfs.cjs.map +1 -1
  201. package/batteries/storage/opfs.mjs +2 -1
  202. package/batteries/storage/opfs.mjs.map +1 -1
  203. package/batteries/tools/_shared.cjs +7 -7
  204. package/batteries/tools/_shared.cjs.map +1 -1
  205. package/batteries/tools/_shared.mjs +2 -2
  206. package/batteries/tools/color.cjs +5 -5
  207. package/batteries/tools/color.cjs.map +1 -1
  208. package/batteries/tools/color.mjs +2 -2
  209. package/batteries/tools/comparison.cjs +6 -6
  210. package/batteries/tools/comparison.cjs.map +1 -1
  211. package/batteries/tools/comparison.mjs +3 -3
  212. package/batteries/tools/data_structure.cjs +8 -8
  213. package/batteries/tools/data_structure.cjs.map +1 -1
  214. package/batteries/tools/data_structure.mjs +3 -3
  215. package/batteries/tools/datetime_extended.cjs +7 -7
  216. package/batteries/tools/datetime_extended.cjs.map +1 -1
  217. package/batteries/tools/datetime_extended.mjs +2 -2
  218. package/batteries/tools/datetime_math.cjs +5 -5
  219. package/batteries/tools/datetime_math.cjs.map +1 -1
  220. package/batteries/tools/datetime_math.mjs +2 -2
  221. package/batteries/tools/encoding.cjs +9 -9
  222. package/batteries/tools/encoding.cjs.map +1 -1
  223. package/batteries/tools/encoding.mjs +3 -3
  224. package/batteries/tools/formatting.cjs +6 -6
  225. package/batteries/tools/formatting.cjs.map +1 -1
  226. package/batteries/tools/formatting.mjs +3 -3
  227. package/batteries/tools/geo_basics.cjs +5 -5
  228. package/batteries/tools/geo_basics.cjs.map +1 -1
  229. package/batteries/tools/geo_basics.mjs +2 -2
  230. package/batteries/tools/math.cjs +9 -9
  231. package/batteries/tools/math.cjs.map +1 -1
  232. package/batteries/tools/math.mjs +3 -3
  233. package/batteries/tools/memory.cjs +13 -13
  234. package/batteries/tools/memory.cjs.map +1 -1
  235. package/batteries/tools/memory.mjs +5 -5
  236. package/batteries/tools/parsing.cjs +10 -10
  237. package/batteries/tools/parsing.cjs.map +1 -1
  238. package/batteries/tools/parsing.mjs +4 -4
  239. package/batteries/tools/retrievables.cjs +12 -12
  240. package/batteries/tools/retrievables.cjs.map +1 -1
  241. package/batteries/tools/retrievables.mjs +4 -4
  242. package/batteries/tools/scrapper.cjs +1 -1
  243. package/batteries/tools/scrapper.mjs +1 -1
  244. package/batteries/tools/searxng.cjs +1 -1
  245. package/batteries/tools/searxng.mjs +1 -1
  246. package/batteries/tools/standing_instructions.cjs +10 -10
  247. package/batteries/tools/standing_instructions.cjs.map +1 -1
  248. package/batteries/tools/standing_instructions.mjs +4 -4
  249. package/batteries/tools/statistics.cjs +10 -10
  250. package/batteries/tools/statistics.cjs.map +1 -1
  251. package/batteries/tools/statistics.mjs +4 -4
  252. package/batteries/tools/string_processing.cjs +8 -8
  253. package/batteries/tools/string_processing.cjs.map +1 -1
  254. package/batteries/tools/string_processing.mjs +3 -3
  255. package/batteries/tools/structured_data.cjs +9 -9
  256. package/batteries/tools/structured_data.cjs.map +1 -1
  257. package/batteries/tools/structured_data.mjs +3 -3
  258. package/batteries/tools/text_analysis.cjs +5 -5
  259. package/batteries/tools/text_analysis.cjs.map +1 -1
  260. package/batteries/tools/text_analysis.mjs +3 -3
  261. package/batteries/tools/text_comparison.cjs +4 -4
  262. package/batteries/tools/text_comparison.cjs.map +1 -1
  263. package/batteries/tools/text_comparison.mjs +2 -2
  264. package/batteries/tools/time.cjs +4 -4
  265. package/batteries/tools/time.cjs.map +1 -1
  266. package/batteries/tools/time.mjs +2 -2
  267. package/batteries/tools/unit_conversion.cjs +3 -3
  268. package/batteries/tools/unit_conversion.cjs.map +1 -1
  269. package/batteries/tools/unit_conversion.mjs +2 -2
  270. package/batteries/tools/web_retrieval.cjs +2 -2
  271. package/batteries/tools/web_retrieval.cjs.map +1 -1
  272. package/batteries/tools/web_retrieval.mjs +1 -1
  273. package/batteries/tools.cjs +2 -2
  274. package/batteries/tools.mjs +2 -2
  275. package/batteries/vector/arangodb.cjs +2 -2
  276. package/batteries/vector/arangodb.cjs.map +1 -1
  277. package/batteries/vector/arangodb.mjs +1 -1
  278. package/batteries/vector/chroma.cjs +1 -1
  279. package/batteries/vector/chroma.mjs +1 -1
  280. package/batteries/vector/clickhouse.cjs +3 -3
  281. package/batteries/vector/clickhouse.cjs.map +1 -1
  282. package/batteries/vector/clickhouse.mjs +2 -2
  283. package/batteries/vector/cloudflare.cjs +4 -4
  284. package/batteries/vector/cloudflare.cjs.map +1 -1
  285. package/batteries/vector/cloudflare.mjs +3 -3
  286. package/batteries/vector/cloudflare.mjs.map +1 -1
  287. package/batteries/vector/couchbase.cjs +3 -3
  288. package/batteries/vector/couchbase.cjs.map +1 -1
  289. package/batteries/vector/couchbase.mjs +2 -2
  290. package/batteries/vector/duckdb.cjs +3 -3
  291. package/batteries/vector/duckdb.cjs.map +1 -1
  292. package/batteries/vector/duckdb.mjs +2 -2
  293. package/batteries/vector/elasticsearch.cjs +3 -3
  294. package/batteries/vector/elasticsearch.cjs.map +1 -1
  295. package/batteries/vector/elasticsearch.mjs +2 -2
  296. package/batteries/vector/filters.cjs +2 -2
  297. package/batteries/vector/filters.cjs.map +1 -1
  298. package/batteries/vector/filters.mjs +1 -1
  299. package/batteries/vector/helpers.cjs +23 -0
  300. package/batteries/vector/helpers.cjs.map +1 -1
  301. package/batteries/vector/helpers.d.ts +8 -0
  302. package/batteries/vector/helpers.mjs +23 -1
  303. package/batteries/vector/helpers.mjs.map +1 -1
  304. package/batteries/vector/hnswlib.cjs +3 -3
  305. package/batteries/vector/hnswlib.cjs.map +1 -1
  306. package/batteries/vector/hnswlib.mjs +2 -2
  307. package/batteries/vector/in_memory.cjs +1 -1
  308. package/batteries/vector/in_memory.mjs +1 -1
  309. package/batteries/vector/lancedb.cjs +3 -3
  310. package/batteries/vector/lancedb.cjs.map +1 -1
  311. package/batteries/vector/lancedb.mjs +2 -2
  312. package/batteries/vector/mariadb.cjs +3 -3
  313. package/batteries/vector/mariadb.cjs.map +1 -1
  314. package/batteries/vector/mariadb.mjs +2 -2
  315. package/batteries/vector/meilisearch.cjs +2 -2
  316. package/batteries/vector/meilisearch.cjs.map +1 -1
  317. package/batteries/vector/meilisearch.mjs +1 -1
  318. package/batteries/vector/migrate.cjs +3 -3
  319. package/batteries/vector/migrate.cjs.map +1 -1
  320. package/batteries/vector/migrate.mjs +1 -1
  321. package/batteries/vector/milvus.cjs +1 -1
  322. package/batteries/vector/milvus.mjs +1 -1
  323. package/batteries/vector/mongodb.cjs +2 -2
  324. package/batteries/vector/mongodb.cjs.map +1 -1
  325. package/batteries/vector/mongodb.mjs +1 -1
  326. package/batteries/vector/neo4j.cjs +2 -2
  327. package/batteries/vector/neo4j.cjs.map +1 -1
  328. package/batteries/vector/neo4j.mjs +1 -1
  329. package/batteries/vector/opensearch.cjs +3 -3
  330. package/batteries/vector/opensearch.cjs.map +1 -1
  331. package/batteries/vector/opensearch.mjs +2 -2
  332. package/batteries/vector/oracle23ai.cjs +3 -3
  333. package/batteries/vector/oracle23ai.cjs.map +1 -1
  334. package/batteries/vector/oracle23ai.mjs +2 -2
  335. package/batteries/vector/orama.cjs +1 -1
  336. package/batteries/vector/orama.mjs +1 -1
  337. package/batteries/vector/pgvector.cjs +1 -1
  338. package/batteries/vector/pgvector.mjs +1 -1
  339. package/batteries/vector/pinecone.cjs +6 -6
  340. package/batteries/vector/pinecone.cjs.map +1 -1
  341. package/batteries/vector/pinecone.mjs +3 -3
  342. package/batteries/vector/pinecone.mjs.map +1 -1
  343. package/batteries/vector/qdrant.cjs +2 -2
  344. package/batteries/vector/qdrant.cjs.map +1 -1
  345. package/batteries/vector/qdrant.mjs +2 -2
  346. package/batteries/vector/qdrant.mjs.map +1 -1
  347. package/batteries/vector/redis.cjs +4 -4
  348. package/batteries/vector/redis.cjs.map +1 -1
  349. package/batteries/vector/redis.mjs +3 -3
  350. package/batteries/vector/redis.mjs.map +1 -1
  351. package/batteries/vector/retrievable.cjs +1 -1
  352. package/batteries/vector/retrievable.mjs +1 -1
  353. package/batteries/vector/s3vectors.cjs +4 -4
  354. package/batteries/vector/s3vectors.cjs.map +1 -1
  355. package/batteries/vector/s3vectors.mjs +3 -3
  356. package/batteries/vector/s3vectors.mjs.map +1 -1
  357. package/batteries/vector/solr.cjs +2 -2
  358. package/batteries/vector/solr.cjs.map +1 -1
  359. package/batteries/vector/solr.mjs +1 -1
  360. package/batteries/vector/sqlite_vec.cjs +1 -1
  361. package/batteries/vector/sqlite_vec.mjs +1 -1
  362. package/batteries/vector/surrealdb.cjs +2 -2
  363. package/batteries/vector/surrealdb.cjs.map +1 -1
  364. package/batteries/vector/surrealdb.mjs +1 -1
  365. package/batteries/vector/typesense.cjs +3 -3
  366. package/batteries/vector/typesense.cjs.map +1 -1
  367. package/batteries/vector/typesense.mjs +2 -2
  368. package/batteries/vector/vespa.cjs +3 -3
  369. package/batteries/vector/vespa.cjs.map +1 -1
  370. package/batteries/vector/vespa.mjs +2 -2
  371. package/batteries/vector/weaviate.cjs +6 -6
  372. package/batteries/vector/weaviate.cjs.map +1 -1
  373. package/batteries/vector/weaviate.mjs +2 -2
  374. package/batteries/vector.cjs +2 -1
  375. package/batteries/vector.mjs +2 -2
  376. package/batteries.cjs +35 -6
  377. package/batteries.mjs +13 -8
  378. package/{common-0CmrSKNb.mjs → common-B9TJQuci.mjs} +6 -8
  379. package/{common-0CmrSKNb.mjs.map → common-B9TJQuci.mjs.map} +1 -1
  380. package/{common-CpcsEqPY.js → common-De4KA03b.js} +13 -15
  381. package/{common-CpcsEqPY.js.map → common-De4KA03b.js.map} +1 -1
  382. package/common.cjs +11 -12
  383. package/common.mjs +6 -7
  384. package/{dispatch_runner-C2ZpFfw4.mjs → dispatch_runner-C8S_EVTS.mjs} +137 -61
  385. package/dispatch_runner-C8S_EVTS.mjs.map +1 -0
  386. package/{dispatch_runner-DMTkGHQI.js → dispatch_runner-CuqREXs9.js} +168 -92
  387. package/dispatch_runner-CuqREXs9.js.map +1 -0
  388. package/dispatch_runner.cjs +1 -1
  389. package/dispatch_runner.mjs +1 -1
  390. package/eslint/rules.cjs +1 -1
  391. package/eslint/rules.mjs +1 -1
  392. package/eslint.cjs +2 -2
  393. package/eslint.mjs +2 -2
  394. package/exceptions.cjs +40 -32
  395. package/exceptions.d.ts +22 -1
  396. package/exceptions.mjs +4 -2
  397. package/forge.cjs +4 -6
  398. package/forge.mjs +2 -4
  399. package/gpu_budget-BRj7BEHY.mjs +361 -0
  400. package/gpu_budget-BRj7BEHY.mjs.map +1 -0
  401. package/gpu_budget-kTqZqMPe.js +504 -0
  402. package/gpu_budget-kTqZqMPe.js.map +1 -0
  403. package/guards.cjs +14 -15
  404. package/guards.cjs.map +1 -1
  405. package/guards.mjs +7 -8
  406. package/guards.mjs.map +1 -1
  407. package/{helpers-CJcqikes.js → helpers-CGSPsSAA.js} +89 -5
  408. package/helpers-CGSPsSAA.js.map +1 -0
  409. package/{helpers-DlrRbLVn.mjs → helpers-N6Q1uO9p.mjs} +72 -6
  410. package/helpers-N6Q1uO9p.mjs.map +1 -0
  411. package/index.cjs +48 -47
  412. package/index.cjs.map +1 -1
  413. package/index.d.ts +5 -2
  414. package/index.mjs +10 -12
  415. package/index.mjs.map +1 -1
  416. package/lib/classes/tokenizable.d.ts +148 -19
  417. package/lib/classes/tool_call.d.ts +25 -21
  418. package/lib/classes/tool_registry.d.ts +16 -11
  419. package/lib/exceptions/runtime.d.ts +21 -0
  420. package/lib/types/dispatch_runner.d.ts +35 -0
  421. package/lib/types/turn_runner.d.ts +7 -1
  422. package/lib/utils/estimation_context.d.ts +59 -0
  423. package/lifecycle-C4kwYJ-N.mjs.map +1 -1
  424. package/lifecycle-vYQJ2rmf.js.map +1 -1
  425. package/mcp/adk-docs-corpus.json +1 -1
  426. package/package.json +352 -296
  427. package/{scrapper-DqXdDL9n.js → scrapper-BFZHv1ox.js} +6 -6
  428. package/{scrapper-DqXdDL9n.js.map → scrapper-BFZHv1ox.js.map} +1 -1
  429. package/{scrapper-D--WGokd.mjs → scrapper-Op8Ep8TM.mjs} +4 -4
  430. package/{scrapper-D--WGokd.mjs.map → scrapper-Op8Ep8TM.mjs.map} +1 -1
  431. package/{searxng-B_-SsTKT.js → searxng-B8G4kSQ2.js} +6 -6
  432. package/{searxng-B_-SsTKT.js.map → searxng-B8G4kSQ2.js.map} +1 -1
  433. package/{searxng-t0jGAeeH.mjs → searxng-DOl_-dwb.mjs} +4 -4
  434. package/{searxng-t0jGAeeH.mjs.map → searxng-DOl_-dwb.mjs.map} +1 -1
  435. package/server.json +2 -2
  436. package/shims/index.d.ts +340 -0
  437. package/shims.cjs +320 -0
  438. package/shims.cjs.map +1 -0
  439. package/shims.mjs +313 -0
  440. package/shims.mjs.map +1 -0
  441. package/skills/adk-assembly/SKILL.md +2 -2
  442. package/spooled_artifact-BVLjXkVV.js +1569 -0
  443. package/spooled_artifact-BVLjXkVV.js.map +1 -0
  444. package/{spooled_artifact-fgc1lutm.mjs → spooled_artifact-DTvSor18.mjs} +805 -7
  445. package/spooled_artifact-DTvSor18.mjs.map +1 -0
  446. package/spooled_artifact.cjs +2 -2
  447. package/spooled_artifact.mjs +2 -2
  448. package/{spooled_markdown_artifact-3sK6HFRw.mjs → spooled_markdown_artifact-BU_qNXZU.mjs} +3 -3
  449. package/{spooled_markdown_artifact-3sK6HFRw.mjs.map → spooled_markdown_artifact-BU_qNXZU.mjs.map} +1 -1
  450. package/{spooled_markdown_artifact-Gj0ruiLJ.js → spooled_markdown_artifact-D6kAcyoR.js} +15 -15
  451. package/{spooled_markdown_artifact-Gj0ruiLJ.js.map → spooled_markdown_artifact-D6kAcyoR.js.map} +1 -1
  452. package/{thought-CU7PYkB1.js → thought-BCSKj3yC.js} +27 -28
  453. package/{thought-CU7PYkB1.js.map → thought-BCSKj3yC.js.map} +1 -1
  454. package/{thought-DmcfCRAw.mjs → thought-CxgDq_HF.mjs} +3 -4
  455. package/{thought-DmcfCRAw.mjs.map → thought-CxgDq_HF.mjs.map} +1 -1
  456. package/{runtime-UzFb0eCc.js → tokenizable-CL5HgOtO.js} +574 -1
  457. package/tokenizable-CL5HgOtO.js.map +1 -0
  458. package/tokenizable-ORM5BBTC.mjs +897 -0
  459. package/tokenizable-ORM5BBTC.mjs.map +1 -0
  460. package/{tool_call-BixyvnWZ.js → tool_call-BAs4EHeG.js} +18 -19
  461. package/{tool_call-BixyvnWZ.js.map → tool_call-BAs4EHeG.js.map} +1 -1
  462. package/{tool_call-pfvAsgkY.mjs → tool_call-DNh1D2_Y.mjs} +4 -5
  463. package/{tool_call-pfvAsgkY.mjs.map → tool_call-DNh1D2_Y.mjs.map} +1 -1
  464. package/{reasoning_parsers-D8Lc3ZsC.mjs → tool_parsers-DGKVwTR7.mjs} +443 -295
  465. package/tool_parsers-DGKVwTR7.mjs.map +1 -0
  466. package/{reasoning_parsers-R5wZbkqE.js → tool_parsers-DzLv7WJ-.js} +457 -411
  467. package/tool_parsers-DzLv7WJ-.js.map +1 -0
  468. package/{turn_runner-DB-WWls8.js → turn_runner-DHeODuGx.js} +111 -93
  469. package/turn_runner-DHeODuGx.js.map +1 -0
  470. package/{turn_runner-Brz6Sd0F.mjs → turn_runner-x4HHcxzH.mjs} +99 -81
  471. package/turn_runner-x4HHcxzH.mjs.map +1 -0
  472. package/turn_runner.cjs +1 -1
  473. package/turn_runner.mjs +1 -1
  474. package/types.d.ts +2 -2
  475. package/{validate-B4RXgYJC.js → validate-B0Fcza5A.js} +152 -152
  476. package/validate-B0Fcza5A.js.map +1 -0
  477. package/{validate-MBEmBzMl.mjs → validate-BF88bCPi.mjs} +151 -151
  478. package/validate-BF88bCPi.mjs.map +1 -0
  479. package/dispatch_runner-C2ZpFfw4.mjs.map +0 -1
  480. package/dispatch_runner-DMTkGHQI.js.map +0 -1
  481. package/helpers-CJcqikes.js.map +0 -1
  482. package/helpers-DlrRbLVn.mjs.map +0 -1
  483. package/reasoning_parsers-D8Lc3ZsC.mjs.map +0 -1
  484. package/reasoning_parsers-R5wZbkqE.js.map +0 -1
  485. package/runtime-D2VRuySV.mjs +0 -390
  486. package/runtime-D2VRuySV.mjs.map +0 -1
  487. package/runtime-UzFb0eCc.js.map +0 -1
  488. package/spooled_artifact-MbMz6NXX.js +0 -745
  489. package/spooled_artifact-MbMz6NXX.js.map +0 -1
  490. package/spooled_artifact-fgc1lutm.mjs.map +0 -1
  491. package/tool-Bt6tmFXT.js +0 -351
  492. package/tool-Bt6tmFXT.js.map +0 -1
  493. package/tool-C_uxdxjp.mjs +0 -346
  494. package/tool-C_uxdxjp.mjs.map +0 -1
  495. package/tool_registry-CIIfbY_w.js +0 -850
  496. package/tool_registry-CIIfbY_w.js.map +0 -1
  497. package/tool_registry-FeMMz993.mjs +0 -789
  498. package/tool_registry-FeMMz993.mjs.map +0 -1
  499. package/turn_runner-Brz6Sd0F.mjs.map +0 -1
  500. package/turn_runner-DB-WWls8.js.map +0 -1
  501. package/validate-B4RXgYJC.js.map +0 -1
  502. package/validate-MBEmBzMl.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -15,6 +15,169 @@ you *when* you got it, not *what changed*: a `^` range will float across battery
15
15
  breaking changes, so pin an exact version if you need stability and read the entry before
16
16
  upgrading.
17
17
 
18
+ ## 2026-07-07
19
+
20
+ ### Security
21
+
22
+ - **Prototype pollution in the `data.*` media steps (GHSA-xwg2-cvvj-3w4v).** `data.set` and
23
+ `data.delete` walk a caller-supplied dot/bracket path (`a.b[2].c`) with plain bracket access
24
+ (`container[seg]`); a path segment of `__proto__`, `prototype`, or `constructor` resolved
25
+ through the real prototype chain instead of stopping at an own property, so `data.set` with
26
+ `path: "__proto__.polluted"` reached `Object.prototype` and poisoned every plain object in
27
+ the process for the remainder of its lifetime — reachable from LLM tool-call arguments via
28
+ the forged `media_query`/`data_set` tool surface. `parsePath` now rejects any segment in that
29
+ denylist before `walkToParent` ever runs, closing both verbs (they share the same parser).
30
+ `data.merge` used a different code path (`{ ...target }` spread) that is not independently
31
+ exploitable — spreading onto a fresh object literal makes `__proto__` an inert own property,
32
+ not a prototype reassignment — but a new `assertSafeObjectKeys` guard now rejects the same
33
+ three keys anywhere in a merge fragment's tree before either the shallow or deep merge
34
+ strategy runs, so the verb can't be used to smuggle a poisoned key back out through a
35
+ round-tripped document.
36
+ - **Defense-in-depth: reject the same three keys in vector-adapter metadata.** An audit for
37
+ the same vulnerability class found five adapters (`pinecone`, `s3vectors`, `qdrant`, `redis`,
38
+ `cloudflare`) that spread caller-supplied `record.metadata` onto a fresh object literal before
39
+ upsert. None of these were independently exploitable for the reason above — the spread target
40
+ is always a new `{}`, never a walked reference — but a `__proto__`-keyed metadata object would
41
+ otherwise round-trip verbatim through storage and back out to a caller. A new
42
+ `sanitizeMetadata` helper (`src/batteries/vector/helpers.ts`) strips `__proto__`, `prototype`,
43
+ and `constructor` keys before each adapter's upsert path builds its stored record.
44
+ - Audited the rest of the codebase for the same reachable-prototype-chain pattern — the
45
+ `data_structure` and `structured_data` tool batteries, the `apply_patch` media step, the
46
+ data-format `MediaEngine`, and `Registry`'s `dset`-backed path storage — and found no further
47
+ instances; everything else either only reads, or only ever writes to a freshly constructed
48
+ object.
49
+
50
+ ### Added
51
+
52
+ - **`Tokenizable` accepts a dynamic evaluator, resolved at prompt-assembly time.** Alongside a plain
53
+ string, the constructor now takes a {@link TokenizableEvaluator} — a `(ctx?) => string` — so wrapped
54
+ content can compute itself coherent with the live `DispatchContext` it ships in (e.g. an instruction
55
+ that adapts to whether a tool survived the subtractive-context pass). Resolutions are cached
56
+ per-context in a `WeakMap` so repeated measures of the same dispatch (subtractive pass + overflow
57
+ guard) don't re-invoke the evaluator. A `render(ctx)` method is the explicit, context-aware read;
58
+ the standard string-coercion protocol (`toString`/`valueOf`/`toJSON`) resolves with no context, hitting
59
+ the evaluator's own `undefined`-branch fallback. An evaluator that throws or returns a non-string
60
+ raises the new `E_TOKENIZABLE_EVALUATOR_INVALID` — loud, no silent coercion. New `'gemma'` encoding
61
+ identifier for {@link Tokenizable.estimateTokens} (Gemma 2/3/4, backed by the same
62
+ `@lenml/tokenizer-gemini` SentencePiece vocabulary as `'gemini'` — deliberate reuse, distinct name).
63
+ Files: `src/lib/classes/tokenizable.ts`, `src/lib/exceptions/runtime.ts`.
64
+ - **Token-estimation failures degrade instead of silently returning `Infinity`.** A real-tokenizer
65
+ failure (e.g. a special-token literal, an encoder bug) inside a `TurnRunner` run or `DispatchRunner`
66
+ dispatch now emits a `warning` and falls back to a char-based guesstimate, rather than the previous
67
+ silent `Number.POSITIVE_INFINITY` — which, combined with the overflow guards, could spuriously trip
68
+ an `E_*_CONTEXT_OVERFLOW` on ordinary text. Outside any runner execution, the failure still re-throws
69
+ (a genuine bug in non-runner code must surface). The ambient channel a runner publishes for the
70
+ duration of its run is `src/lib/utils/estimation_context.ts` (new) — a LIFO stack of warn-emit sinks
71
+ so a dispatch nested inside a turn routes to its own (richer) emitter.
72
+ - **WebGPU memory observability for the on-device LLM batteries.** `probeGpuBudget()`
73
+ (`src/batteries/llm/chat_common/gpu_budget.ts`, new) reads the WebGPU adapter's buffer-size limits
74
+ and adapter info, non-invasively — observability only, allocates nothing. A new opt-in
75
+ `instrumentGpuBuffers()` wraps `GPUDevice.prototype.createBuffer` to track live/peak GPU buffer bytes
76
+ against that budget, for an application that wants a live "you're at X of Y GiB" gauge. Paired with a
77
+ new typed `E_LLM_GPU_OUT_OF_MEMORY` (`chat_common/exceptions.ts`, new) — `isGpuOutOfMemoryError()`
78
+ matches ORT-web's several GPU-exhaustion and WASM-linear-memory-exhaustion error signatures and both
79
+ the `transformers_js` and `litert_lm` batteries translate a raw provider throw into this one typed,
80
+ catchable error, surfaced via a non-fatal `ctx.nack(...)` rather than a throw. A new `gpuBudget` field
81
+ on the battery lifecycle report carries the probed snapshot. Consistent with the ADK's
82
+ surface-don't-impose stance: the batteries never auto-cap the caller's context window.
83
+ - **Shared tool-call parser layer expanded and hardened.** The `gemma` parser is rewritten as a
84
+ string-aware balanced-brace scanner — correctly handles nested argument objects and the curly smart
85
+ quotes (`“…”`, `‘…’`) small models emit in place of ASCII quotes, instead of the previous lazy-regex
86
+ approach. Two new parser families: `'bare_pythonic'` and `'loose_keyed'` (`toolCallParser` /
87
+ `ToolCallParserName`). New observer seams on every LLM battery's options: `onRawGeneration` (the raw
88
+ model text for a completed generation, after envelope-stripping but before persistence — reasoning /
89
+ tool-call parser bring-up, live abstention debugging, fixture capture) and `onPromptAssembled` (the
90
+ fully-assembled request about to ship, the mirror tap on the way in). Both are purely observational,
91
+ default-absent, and consumed by all five LLM batteries (`chat_common/tool_parsers.ts`,
92
+ `chat_common/lifecycle.ts`, `chat_common/types.ts`).
93
+ - **`litert_lm` battery: engine hosted in a disposable Web Worker.** New standalone worker build
94
+ configs — `litert-lm-worker.vite.config.mts` and `webllm-worker.vite.config.mts` — with matching
95
+ `build:litert-lm-worker` / `build:webllm-worker` package scripts, compiling the LiteRT-LM (IIFE,
96
+ classic-worker-compatible — LiteRT's Emscripten glue calls `importScripts()`, illegal in a module
97
+ worker) and WebLLM (ES module worker) engine handlers as separate bundles co-located with their wasm
98
+ assets, so a long-lived session can recover from a browser-level WebGPU device loss by terminating
99
+ and respawning the worker rather than reusing a dead `GPUAdapter`. The adapter's existing
100
+ `createEngine` injection seam (`LiteRtLmAdapterOptions.createEngine`) is what a host wires a
101
+ worker-backed engine through; the battery itself stays runtime-agnostic.
102
+ - **`DispatchRunner` / `TurnRunner` emit a `WarningEvent`** observability payload — non-fatal
103
+ conditions (starting with the token-estimation degrade above) surfaced through the same observability
104
+ bus as `LogEvent` / `GenerationStatsEvent`, carrying `dispatchId`/`iteration`, a `source`, and a
105
+ `kind`. Executor-thrown and nacked errors also now preserve a meaningful `Error`-shaped `cause` even
106
+ when the thrown/nacked value is not itself a strict `Error` (a raw string or cross-realm error no
107
+ longer collapses to a cause-less generic wrapper) — `toErrorCause` in `src/lib/dispatch_runner.ts`.
108
+ - **Documentation: the "Punching Above Its Weights" showcase family.** The flagship agent showcase
109
+ (`docs/showcase/punching-above-its-weights.md`) demonstrates building a real tool-using agent under
110
+ hostile conditions — Gemma-4 E2B via `LiteRtLmAdapter` in a browser tab, a 4GB GPU ceiling, a
111
+ live-draggable context window — technique by technique (planner book-end, subtractive pass over the
112
+ shipped context battery, gate cascade, artifact handles, GPU survival), each with real code embeds
113
+ and field-note receipts, closing on the blind-judged 5-cell evaluation matrix. Its companion
114
+ **"The Agent, In Full"** (`docs/showcase/punching-above-its-weights-source.md`) exposes the complete
115
+ 31-file agent source in a read-only in-page Monaco viewer, with an LLM-consumable full-source
116
+ mirror emitted through the docs pipeline for coding agents to port from. Method-side pages:
117
+ **Token Thrift** (`docs/the-loop/token-thrift.md`, the context-discipline lever), **Behavioral
118
+ Rails** (`docs/the-loop/behavioral-rails.md`, gates/own-voice nudges/the planner contract), **Read
119
+ the Wire** (`docs/the-loop/read-the-wire.md`, evidence-directed agent debugging), and **Runtime
120
+ Loading** (`docs/assembly/runtime-loading.md`, the `@nhtio/adk/shims` consumption guide). The
121
+ underlying evaluation/research harness (corpus runs, floor calibration, adversarial threads, the
122
+ LiteRT worker Step-0 probe) is committed under `research/`.
123
+
124
+ - **New context battery domain: `thrift` and `compact`, two strategies for what goes into one
125
+ dispatch's window.** `src/batteries/context/thrift` is the subtractive strategy already backing
126
+ the Token Thrift work above — `subtractToFit`, `stripPriorTurnThoughts`, and the calibrated
127
+ `selectRelevantTurns`/`scaledRelevanceFloor` relevance-based turn selection (floor constants
128
+ `RELEVANCE_FLOOR_MIN`/`MAX`/`CURVE` calibrated against a triple-oracle, 94-turn stress corpus) are
129
+ now a standalone, importable battery rather than flagship-agent-only code.
130
+ `src/batteries/context/compact` is new: a faithful extraction of the flagship agent's own
131
+ Claude-Code-style auto-compaction (`assembleCompactedTurns`, `summariseTurns`,
132
+ `COMPACTION_SYSTEM_PROMPT`) — keep the newest turns verbatim, fold everything older into a
133
+ rolling summary once it crosses a token threshold. Both batteries are built entirely on injected
134
+ resolvers rather than bundled capabilities: `EstimateTokensFn` (no default tokenizer) and, for
135
+ `compact`, `SummarizeFn` (no default model transport) — with **zero imports from `@nhtio/adk`
136
+ core** at the structural-contract layer (`WorkingMessage`, `WorkingMemory`, `WorkingRetrievable`,
137
+ and friends are locally-declared, duck-typed shapes a real core object satisfies structurally
138
+ without either side importing the other). This decoupling is practical against real models
139
+ because of the token-estimator registry added above ({@link registerTokenEstimator}) — a caller
140
+ can register a custom encoding's estimator without editing `Tokenizable`'s internal switch, so
141
+ `thrift`/`compact` work against any encoding a project uses, built-in or not. The two batteries
142
+ are composable: `thrift`'s `isSummaryMessage` predicate (default id `'__compact-summary'`,
143
+ matching `compact`'s `DEFAULT_SUMMARY_MESSAGE_ID`) protects `compact`'s rolling summary message
144
+ from being shed like an ordinary old turn when both run in the same pipeline. Evaluated
145
+ head-to-head against a naive-recency baseline across five model/window cells on a shared 94-turn
146
+ corpus: thrift is the lightest arm nearly everywhere and never collapses, while compact tops the
147
+ two cells where real context pressure meets a paid summarizer budget (kimi-k2.5 @ 128k, 1.48 vs.
148
+ 1.13 3-judge; gemma-31b @ 128k, 2-judge pool pending its third judge) — documented in full,
149
+ including the naive baseline's 0.08 collapse on the kimi cell and per-cell dispatch/summarizer-
150
+ overhead tables, in the new `docs/batteries/context/` pages.
151
+
152
+ - **`@nhtio/adk/shims` — an async-resolver seam for binding a runtime-loaded ADK bundle without
153
+ importing core into the consumer's module graph.** {@link createAdkShim} wraps a consumer-supplied
154
+ {@link AdkResolverFn} (all environment knowledge — `fetch` + dynamic `import()`, a Worker handshake,
155
+ a host-injected global — lives in that one function; the shim ships no loading policy of its own)
156
+ and returns `{ resolve, get, resolved, proxy }`: single-flight `resolve()`, a synchronous `get()` for
157
+ already-resolved reads, a live `resolved` boolean, and a `proxy` that replaces the hand-rolled
158
+ `export let Foo: typeof Module.Foo` holder pattern with one destructurable object. Memoization is
159
+ GC-safe — the resolved bundle is held via `WeakRef` (never strongly retained by the shim itself),
160
+ falling back to a plain strong reference only where `WeakRef` is unavailable. A module-scope ambient
161
+ variant (`registerAdkResolver` + `adk`) covers the "many files, one shared binding" case. Three typed
162
+ exceptions cover the failure modes: `E_SHIM_NOT_RESOLVED` (a sync read before anything resolved),
163
+ `E_SHIM_RESOLUTION_FAILED` (the resolver rejected or threw, cause preserved), and
164
+ `E_SHIM_RESOLVER_ALREADY_RESOLVED` (re-registering the ambient resolver after it already resolved
165
+ once — a split-brain guard). `src/shims/index.ts` is a **leaf module** — proven at dist level
166
+ (`shims.mjs`, 17.7KB) to import only the exceptions chunk plus `@nhtio/validation` and `fast-printf`,
167
+ zero core graph — and deliberately not re-exported from the root `@nhtio/adk` barrel, since doing so
168
+ would drag the very module graph this subpath exists to let you avoid back into the import. The docs
169
+ site itself now dogfoods this exact seam: `docs/.vitepress/theme/components/quickstart_demo_runtime.ts`
170
+ replaced its own four-times-hand-rolled memoizing loader (the one that exists because importing ADK
171
+ source into the VitePress module graph overflows the JS call stack on iOS WebKit) with
172
+ `createAdkShim(resolver)`, the resolver supplying only the docs app's URL-resolving policy.
173
+
174
+ ### Changed
175
+
176
+ - **`@sqlite.org/sqlite-wasm` and `kysely` are now docs-site devDependencies** — used by the docs
177
+ site's in-browser SQLite demo tooling, never shipped in the published package. **`katex`** is now a
178
+ runtime `dependency` (previously absent) — it backs the math tools battery
179
+ (`src/batteries/tools/math/index.ts`).
180
+
18
181
  ## 2026-06-26
19
182
 
20
183
  ### Added
@@ -82,6 +245,10 @@ upgrading.
82
245
  (or the existing `--base-url` / `--api-key` flags), replacing internal-specific env-var names. Dev tool only;
83
246
  not part of the published runtime surface.
84
247
 
248
+ ### Fixed
249
+
250
+ - Fixed the documentation release pipeline.
251
+
85
252
  ## 2026-06-25
86
253
 
87
254
  ### Added
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ require("../../../chunk-Cek0wNdY.js");
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Structural contracts for the Compact (summarize-over-threshold) context-management battery — the
3
+ * seams it invokes via injected functions, and the one cost-observability shape it hands back.
4
+ *
5
+ * @module @nhtio/adk/batteries/context/compact/contracts
6
+ *
7
+ * @remarks
8
+ * This module has **zero imports** — not even a type-only import from `@nhtio/adk` core. Same
9
+ * discipline as {@link @nhtio/adk/batteries/context/thrift/contracts}: every capability this battery
10
+ * cannot perform itself is an INJECTED function, and every shape it reads or writes is a local
11
+ * structural declaration.
12
+ *
13
+ * Compact needs exactly TWO capabilities it cannot bundle itself:
14
+ *
15
+ * 1. **Summarization** ({@link SummarizeFn}) — an actual model call. Unlike Token Thrift, which is a
16
+ * zero-model-call algorithm end-to-end, Compact's entire thesis is PAYING for a model call to
17
+ * compress old turns into a running summary — so this seam is unavoidable, and the battery never
18
+ * pretends otherwise.
19
+ * 2. **Token estimation** ({@link EstimateTokensFn}, re-exported from
20
+ * {@link @nhtio/adk/batteries/context/thrift/contracts} — same signature, same rationale: no
21
+ * bundled tokenizer, ever).
22
+ */
23
+ export type { EstimateTokensFn } from "../thrift/contracts";
24
+ /**
25
+ * THE model-call seam this battery cannot perform itself: given a system prompt and a body of text to
26
+ * summarize, return the summary text.
27
+ *
28
+ * @remarks
29
+ * The battery never names `DispatchRunner`, an adapter, or an executor — it has no idea how the
30
+ * caller talks to a model, and it must not. The canonical ADK recipe for building one (the recipe the
31
+ * production flagship agent this battery was extracted from actually uses, and the one the docs page
32
+ * for this battery walks through in full) is:
33
+ *
34
+ * ```ts
35
+ * const summarize: SummarizeFn = async ({ system, text }) => {
36
+ * let out = ''
37
+ * const noop = async (): Promise<void> => undefined
38
+ * const noopArr = async (): Promise<never[]> => []
39
+ * await DispatchRunner.dispatch({
40
+ * raw: {
41
+ * systemPrompt: new Tokenizable(system),
42
+ * standingInstructions: [],
43
+ * messages: [new Message({ id: `__compact-${Date.now()}`, role: 'user', content: text, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() })],
44
+ * // Every other RawTurnContext capability is a noop — this dispatch never reads or writes any
45
+ * // OTHER persisted state, it only wants the model's completion text.
46
+ * fetchMemories: noopArr, fetchRetrievables: noopArr, fetchMessages: noopArr,
47
+ * fetchThoughts: noopArr, fetchToolCalls: noopArr, fetchTools: noopArr,
48
+ * refreshStandingInstructions: noopArr,
49
+ * storeStandingInstruction: noop, mutateStandingInstruction: noop, deleteStandingInstruction: noop,
50
+ * storeMemory: noop, mutateMemory: noop, deleteMemory: noop,
51
+ * storeRetrievable: noop, mutateRetrievable: noop, deleteRetrievable: noop,
52
+ * storeMessage: async (_c, v) => { out += v.content?.toString?.() ?? '' },
53
+ * mutateMessage: noop, deleteMessage: noop,
54
+ * storeThought: noop, mutateThought: noop, deleteThought: noop,
55
+ * storeToolCall: noop, mutateToolCall: noop, deleteToolCall: noop,
56
+ * storeMediaBytes: noop, storeRetrievableBytes: noop,
57
+ * } as never,
58
+ * executor: await adapter.executor({ maxTokens: 1200, toolCallParser: 'none', stream: false, autoAck: true, enableThinking: false }),
59
+ * })
60
+ * return out.trim()
61
+ * }
62
+ * ```
63
+ *
64
+ * A caller with a different transport (a direct HTTP call to an LLM API, a queue-backed worker, a
65
+ * mocked test double) supplies whatever function satisfies this signature — the battery only ever
66
+ * awaits the returned string.
67
+ *
68
+ * @param req - `system`: the compaction instructions (see {@link @nhtio/adk/batteries/context/compact/summarizer!COMPACTION_SYSTEM_PROMPT}
69
+ * for the shipped default); `text`: the body of older conversation (and, on a rolling re-summarize,
70
+ * the prior summary folded in — see {@link @nhtio/adk/batteries/context/compact/summarizer!summariseTurns}) to compress.
71
+ * @returns The summary text, awaited. A rejected promise propagates to the caller of
72
+ * `summariseTurns`/`assembleCompactedTurns` uncaught — this battery does not swallow summarizer
73
+ * failures; a caller wanting graceful degradation (e.g. "fall back to the prior summary") implements
74
+ * that inside their own `SummarizeFn`, exactly as the production flagship agent's own summarizer did.
75
+ */
76
+ export type SummarizeFn = (req: {
77
+ system: string;
78
+ text: string;
79
+ }) => Promise<string>;
80
+ /**
81
+ * One summarization call's estimated token cost — reported via {@link OnCostFn} so a caller can total
82
+ * up the real overhead this battery pays (the cost profile a `thrift`-only pipeline never incurs).
83
+ *
84
+ * @remarks
85
+ * `inTok`/`outTok` are ESTIMATES, not metered usage: when the injected {@link SummarizeFn}'s transport
86
+ * doesn't report real token usage back (many don't — a bare `Promise<string>` return carries no usage
87
+ * envelope), the battery has no other way to know what the call cost. It measures what it CAN measure
88
+ * — the exact text it sent (`system + text`) and the exact text it got back (the summary) — via the
89
+ * same injected {@link EstimateTokensFn} the caller already supplies for its own token accounting, so
90
+ * these numbers are at least self-consistent with whatever budget arithmetic the caller runs
91
+ * elsewhere. A caller whose `SummarizeFn` DOES have access to real usage counts can ignore this
92
+ * estimate and total its own numbers from inside the function instead.
93
+ */
94
+ export interface CompactionCostEvent {
95
+ /** How many summarization calls this event represents — always `1` per {@link OnCostFn} firing (one
96
+ * call, one event); a caller totals `calls` across events to get the run's summarizer call count. */
97
+ calls: number;
98
+ /** Estimated input token cost: `estimateTokens(system + text, encoding)` for the exact request sent
99
+ * to {@link SummarizeFn} this call (system prompt plus the history/prior-summary text). */
100
+ inTok: number;
101
+ /** Estimated output token cost: `estimateTokens(summary, encoding)` for the text {@link SummarizeFn}
102
+ * returned. */
103
+ outTok: number;
104
+ }
105
+ /**
106
+ * Optional per-summarization cost callback — fired once per {@link SummarizeFn} call that actually
107
+ * runs, replacing the production flagship agent's `globalThis.__agentCompactionCost` ring buffer with
108
+ * an injectable, testable seam that leaves no global state behind.
109
+ *
110
+ * @remarks
111
+ * Never invoked when the threshold hasn't been crossed (no summarization call made — see
112
+ * {@link @nhtio/adk/batteries/context/compact/summarizer!assembleCompactedTurns}'s below-threshold
113
+ * pass-through path). A caller who wants a running total across a whole session's worth of dispatches
114
+ * accumulates across `onCost` firings themselves; this battery holds no cross-call state of its own
115
+ * beyond what a single `assembleCompactedTurns` invocation's caller threads through (the rolling prior
116
+ * summary is passed in and returned explicitly, never stashed on `globalThis`).
117
+ *
118
+ * @param event - See {@link CompactionCostEvent}.
119
+ */
120
+ export type OnCostFn = (event: CompactionCostEvent) => void;
File without changes
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Compact — summarize-over-threshold context management. Instead of shedding old turns outright, pay
3
+ * for a model call to fold them into a running summary, trading a real API cost for retaining
4
+ * compressed signal from everything folded away.
5
+ *
6
+ * @module @nhtio/adk/batteries/context/compact
7
+ *
8
+ * @remarks
9
+ * ## The thesis
10
+ *
11
+ * Where {@link @nhtio/adk/batteries/context/thrift} is a zero-model-call subtractive algorithm — shed
12
+ * the lowest-signal content until the dispatch fits, never pay for compression — Compact takes the
13
+ * opposite bet: keep the most recent `keepVerbatim` turns in full, and once everything OLDER than that
14
+ * grows past a token threshold, pay for ONE summarization call to compress it into a running summary
15
+ * message that stands in for all of it. On the next threshold crossing, the prior summary is folded
16
+ * BACK into the next summarization request (a rolling summary), so detail degrades gracefully across
17
+ * many compactions rather than being recomputed from scratch or lost outright.
18
+ *
19
+ * This is a direct extraction of the flagship reference agent's production "compact" baseline — the
20
+ * faithful Claude Code auto-compaction schema, lifted verbatim (see
21
+ * {@link @nhtio/adk/batteries/context/compact/summarizer!COMPACTION_SYSTEM_PROMPT}) — evaluated
22
+ * HEAD-TO-HEAD against Token Thrift and a naive-recency baseline on a shared 94-turn stress corpus
23
+ * across five models.
24
+ *
25
+ * ## The evaluation (honest, both ways)
26
+ *
27
+ * - **The one win**: on a SINGLE reasoning-model cell, Compact beat Thrift 1.48 vs. 1.13 (3-judge
28
+ * committee scoring) — a reasoning model made better use of a paid compression step than of
29
+ * subtraction alone. Compact also led at the 128k-window control condition, 1.40 vs. Thrift's 1.27.
30
+ * - **The price**: ~80-89 summarizer calls and roughly 380k-550k EXTRA tokens over a 94-turn run,
31
+ * compared to Thrift's zero. This is the fundamental trade-off, not an implementation detail —
32
+ * Compact is a paid strategy by construction.
33
+ * - **Where it degenerates**: on a 1M-token window, the older-region threshold never triggered across
34
+ * the whole run (0 summarizer calls) — with that much headroom, Compact never fires and behaves
35
+ * identically to naive unbounded accumulation. It only earns its cost at real context pressure.
36
+ * - **Under a TIGHT budget, an honest caveat**: this extraction's message-shedding (whatever a caller
37
+ * layers on top to fit the FINAL dispatch, e.g. Thrift's own subtractive pass running downstream)
38
+ * is UNFAITHFUL to what real compaction products do under pressure — it drops verbatim recent turns
39
+ * outright rather than triggering an earlier/tighter re-summarization. Real Claude-Code-style
40
+ * compaction re-summarizes more aggressively as the wall approaches; a caller who needs that
41
+ * fidelity under tight budgets should tune `summariseAtTokens` down rather than rely on a downstream
42
+ * shed to save them.
43
+ *
44
+ * See {@link @nhtio/adk/batteries/context/thrift} for the full Thrift-side account of this same
45
+ * evaluation, including where Thrift wins (cost, everywhere; quality, almost everywhere).
46
+ *
47
+ * ## Choosing between the two
48
+ *
49
+ * Reach for `compact` when: the target model is a reasoning model, the pipeline can afford a
50
+ * summarizer budget (extra latency + tokens per compaction), and the window is small enough that the
51
+ * threshold will actually fire. Reach for `thrift` (the always-safe default) when: cost matters, the
52
+ * window is large enough that compaction would degenerate anyway, or the model doesn't specifically
53
+ * benefit from compressed-prose continuity over raw subtraction. The two are COMPOSABLE, not
54
+ * mutually exclusive — Thrift ships an `isSummaryMessage` predicate (default `id === '__compact-summary'`)
55
+ * that recognizes and protects Compact's synthetic summary message from being shed like an ordinary
56
+ * old turn, so a pipeline can run `compact` upstream (turn-level assembly) and `thrift` downstream
57
+ * (final budget fit) together. See
58
+ * {@link @nhtio/adk/batteries/context/compact/summarizer!DEFAULT_SUMMARY_MESSAGE_ID} for that
59
+ * contract's exact terms.
60
+ *
61
+ * ## Zero-coupling, one unavoidable seam
62
+ *
63
+ * Every structural type here is a local, duck-typed declaration (zero core imports — see
64
+ * {@link @nhtio/adk/batteries/context/compact/contracts}) except for the turn/message shapes, which
65
+ * are reused directly from {@link @nhtio/adk/batteries/context/thrift/relevance} via a relative,
66
+ * battery-internal import (compact operates on the SAME upstream turn shape thrift's relevance
67
+ * selection produces — no need to redeclare it). The one capability this battery truly cannot bundle
68
+ * is the model call itself: {@link @nhtio/adk/batteries/context/compact/contracts!SummarizeFn} is an
69
+ * injected function, never a bundled transport — see its TSDoc for the canonical ADK recipe (a
70
+ * `DispatchRunner.dispatch` call with an all-noop `RawTurnContext`).
71
+ *
72
+ * ## Usage sketch
73
+ *
74
+ * ```ts
75
+ * import { assembleCompactedTurns, type SummarizeFn } from '@nhtio/adk/batteries/context/compact'
76
+ * import { groupHistoryIntoTurns } from '@nhtio/adk/batteries/context/thrift'
77
+ * import { Tokenizable } from '@nhtio/adk'
78
+ *
79
+ * // A stub SummarizeFn — see the contract's TSDoc for the real DispatchRunner recipe.
80
+ * const summarize: SummarizeFn = async ({ system, text }) => {
81
+ * const completion = await myLlmCall({ system, prompt: text })
82
+ * return completion.trim()
83
+ * }
84
+ *
85
+ * const turns = groupHistoryIntoTurns(myMessages, myToolCalls)
86
+ * let priorState: { summary: string | null; coveredOlder: number } | undefined
87
+ *
88
+ * const result = await assembleCompactedTurns(turns, {
89
+ * summarize,
90
+ * estimateTokens: (value, encoding, ctx) => Tokenizable.estimateTokens(value, encoding, ctx),
91
+ * priorState,
92
+ * onCost: (event) => trackCompactionCost(event), // replaces globalThis.__agentCompactionCost
93
+ * })
94
+ *
95
+ * priorState = { summary: result.summary, coveredOlder: result.coveredOlder } // persist for next turn
96
+ * // result.turns: [syntheticSummaryTurn?, ...recentVerbatimTurns] — feed downstream (e.g. into
97
+ * // thrift's subtractToFit) exactly like any other grouped-turn history.
98
+ * ```
99
+ */
100
+ export * from "./contracts";
101
+ export * from "./summarizer";
102
+ export { E_CONTEXT_RESOLVER_MISSING } from "../exceptions";
@@ -0,0 +1,201 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ require("../../../chunk-Cek0wNdY.js");
3
+ const require_batteries_context_exceptions = require("../exceptions.cjs");
4
+ //#region src/batteries/context/compact/summarizer.ts
5
+ /**
6
+ * The Compact summarizer and history assembler — the whole Compact thesis, in code.
7
+ *
8
+ * @module @nhtio/adk/batteries/context/compact/summarizer
9
+ *
10
+ * @remarks
11
+ * This is a direct extraction of the flagship reference agent's `#summariseTurns` /
12
+ * `#assembleCompactedTurns` head-to-head baseline (the "compact" arm evaluated against Token Thrift —
13
+ * see the battery barrel's TSDoc for the honest, both-ways evaluation results), retargeted at the
14
+ * local structural contracts in {@link @nhtio/adk/batteries/context/compact/contracts} and the shared
15
+ * {@link @nhtio/adk/batteries/context/thrift/relevance!HistoryTurn} shape so it couples to nothing in
16
+ * `@nhtio/adk` core — the one true dependency this battery cannot avoid (an actual model call to
17
+ * summarize) is an injected {@link SummarizeFn}, never a bundled transport.
18
+ */
19
+ /**
20
+ * How many of the MOST RECENT turns stay verbatim, never folded into the running summary —
21
+ * coreference ("it", "that file") needs the immediately preceding turns present no matter what.
22
+ *
23
+ * @remarks
24
+ * The flagship reference agent's own calibrated value (`COMPACT_KEEP_VERBATIM`), lifted unchanged.
25
+ */
26
+ var DEFAULT_KEEP_VERBATIM = 2;
27
+ /**
28
+ * The token threshold, measured over the OLDER (non-verbatim) region's combined text, past which a
29
+ * (re)summarization call fires.
30
+ *
31
+ * @remarks
32
+ * The flagship reference agent's own calibrated value (`COMPACT_SUMMARISE_AT_TOKENS`), lifted
33
+ * unchanged — modeled on Claude Code auto-compacting as it approaches the context limit (there, a
34
+ * fraction of an 8k window).
35
+ */
36
+ var DEFAULT_SUMMARISE_AT_TOKENS = 2500;
37
+ /**
38
+ * The default id assigned to the synthetic summary message {@link assembleCompactedTurns} emits.
39
+ *
40
+ * @remarks
41
+ * This exact string is the cross-battery contract with Token Thrift: `thrift`'s
42
+ * {@link @nhtio/adk/batteries/context/thrift/contracts!IsSummaryMessageFn} default predicate is
43
+ * `id === '__compact-summary'` — a caller running `compact` upstream of `thrift` in the same pipeline
44
+ * gets, for free, thrift's protection of this message from being shed like an ordinary old turn. If a
45
+ * caller overrides `summaryMessageId` here, they must also override thrift's `isSummaryMessage` option
46
+ * to match, or thrift will treat the running summary as just another shed-able message.
47
+ */
48
+ var DEFAULT_SUMMARY_MESSAGE_ID = "__compact-summary";
49
+ /**
50
+ * The FAITHFUL Claude Code compaction schema — the 9 sections extracted VERBATIM from the flagship
51
+ * reference agent's own real auto-compactions (~4700-token structured summaries observed across 28
52
+ * compactions in that agent's development session). Using the real prompt (not an invented one) is
53
+ * what makes this battery's evaluation honest: the compact strategy loses exactly the detail Claude
54
+ * Code's own compaction loses, no more and no less.
55
+ *
56
+ * @remarks
57
+ * The 9 sections: (1) Primary Request and Intent, (2) Key Technical Concepts, (3) Files and Code
58
+ * Sections, (4) Errors and Fixes, (5) Problem Solving, (6) All User Messages, (7) Pending Tasks,
59
+ * (8) Current Work, (9) Next Step. Callers may supply their own prompt via the `systemPrompt` option
60
+ * on {@link assembleCompactedTurns} (and {@link summariseTurns} directly) — this default is a
61
+ * calibrated starting point, not a hard requirement.
62
+ */
63
+ var COMPACTION_SYSTEM_PROMPT = "Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions. This summary will REPLACE the older conversation history, so it must capture every fact a later turn might need. Structure it under these sections:\n1. Primary Request and Intent — what the user is trying to accomplish, verbatim where possible.\n2. Key Technical Concepts — technologies, APIs, and terms discussed.\n3. Files and Code Sections — specific files/functions/values examined or referenced.\n4. Errors and Fixes — problems hit and how they were resolved.\n5. Problem Solving — decisions made and why.\n6. All User Messages — a list of every non-tool user message, to preserve intent.\n7. Pending Tasks — what remains to do.\n8. Current Work — what was happening most recently.\n9. Next Step — the immediate next action.\nBe precise and factual. Preserve exact names, paths, and values. Do not summarise away specifics.";
64
+ /** The token encoding this battery measures cost under, by default (matches Token Thrift's own
65
+ * default — see {@link @nhtio/adk/batteries/context/thrift/subtractive_pass!DEFAULT_ENCODING}). */
66
+ var DEFAULT_ENCODING = "cl100k_base";
67
+ /** The character-length cap the flagship reference agent applied to the summarizer's input text
68
+ * (prior summary + older-turn text combined), to keep the summarizer dispatch itself bounded. Lifted
69
+ * unchanged from `#summariseTurns`'s `.slice(0, 12000)`. */
70
+ var HISTORY_TEXT_CHAR_CAP = 12e3;
71
+ /**
72
+ * Run ONE summarization call: fold `priorSummary` (if any) and `historyText` into the request text
73
+ * exactly as the flagship reference agent's `#summariseTurns` did, dispatch it through the injected
74
+ * {@link SummarizeFn}, and report the estimated token cost via `options.onCost`.
75
+ *
76
+ * @remarks
77
+ * **Faithfulness to the original**: this is a line-for-line port of `#summariseTurns`'s request
78
+ * assembly and prompt shape, with exactly one deliberate behavioral change: the original SWALLOWED a
79
+ * failed summarizer call and degraded to `priorSummary ?? ''` (never letting a summarizer error
80
+ * propagate, since it ran inline in a chat turn that had to keep going); this battery instead lets a
81
+ * rejected {@link SummarizeFn} promise propagate UNCAUGHT (see {@link SummarizeFn}'s own TSDoc) — a
82
+ * battery has no chat-turn context to know whether "degrade silently" is the right failure mode for
83
+ * a given caller, so it surfaces the error and lets the caller decide (their own `SummarizeFn` can
84
+ * implement the original's degrade-on-failure behavior internally if desired, by catching there
85
+ * instead). The original's GPU-OOM special-case rethrow is likewise the caller's concern now — it
86
+ * lived inside the original's own adapter-specific `SummarizeFn` equivalent, not in the algorithm.
87
+ *
88
+ * @param historyText - The older-turn text to summarize (already assembled by the caller, e.g. from
89
+ * {@link assembleCompactedTurns}'s older-turns join).
90
+ * @param priorSummary - The prior rolling summary, if one exists, folded into the request text ahead
91
+ * of `historyText` under a `PREVIOUS SUMMARY (extend/merge, do not lose facts)` header — `null` on
92
+ * the first summarization of a run.
93
+ * @param options - See {@link SummariseTurnsOptions}.
94
+ * @returns The new summary text, trimmed. Falls back to `priorSummary ?? ''` only when
95
+ * {@link SummarizeFn} resolves to an empty/whitespace-only string (never on rejection — see above).
96
+ * @throws {@link @nhtio/adk/batteries/context/exceptions!E_CONTEXT_RESOLVER_MISSING} When
97
+ * `options.summarize` or `options.estimateTokens` is not a function.
98
+ */
99
+ async function summariseTurns(historyText, priorSummary, options) {
100
+ if (typeof options?.summarize !== "function") throw new require_batteries_context_exceptions.E_CONTEXT_RESOLVER_MISSING(["summariseTurns", "summarize"]);
101
+ if (typeof options?.estimateTokens !== "function") throw new require_batteries_context_exceptions.E_CONTEXT_RESOLVER_MISSING(["summariseTurns", "estimateTokens"]);
102
+ const encoding = options.encoding ?? DEFAULT_ENCODING;
103
+ const system = options.systemPrompt ?? "Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions. This summary will REPLACE the older conversation history, so it must capture every fact a later turn might need. Structure it under these sections:\n1. Primary Request and Intent — what the user is trying to accomplish, verbatim where possible.\n2. Key Technical Concepts — technologies, APIs, and terms discussed.\n3. Files and Code Sections — specific files/functions/values examined or referenced.\n4. Errors and Fixes — problems hit and how they were resolved.\n5. Problem Solving — decisions made and why.\n6. All User Messages — a list of every non-tool user message, to preserve intent.\n7. Pending Tasks — what remains to do.\n8. Current Work — what was happening most recently.\n9. Next Step — the immediate next action.\nBe precise and factual. Preserve exact names, paths, and values. Do not summarise away specifics.";
104
+ const text = ((priorSummary ? `PREVIOUS SUMMARY (extend/merge, do not lose facts):\n${priorSummary}\n\n---\n\n` : "") + `CONVERSATION TO SUMMARISE:\n${historyText}`).slice(0, HISTORY_TEXT_CHAR_CAP);
105
+ const summary = (await options.summarize({
106
+ system,
107
+ text
108
+ })).trim();
109
+ options.onCost?.({
110
+ calls: 1,
111
+ inTok: options.estimateTokens(`${system}\n\n${text}`, encoding),
112
+ outTok: options.estimateTokens(summary, encoding)
113
+ });
114
+ return summary || (priorSummary ?? "");
115
+ }
116
+ /**
117
+ * The Compact assembly step: keep the newest `keepVerbatim` turns in full; fold everything OLDER into
118
+ * a running structured summary, (re)generated via {@link summariseTurns} when the older region grows
119
+ * past `summariseAtTokens` AND new turns have aged into it since the last summarization. Returns
120
+ * `[syntheticSummaryTurn, ...recentVerbatimTurns]`.
121
+ *
122
+ * @remarks
123
+ * **Faithfulness to the original** (`#assembleCompactedTurns`): the threshold/keep-verbatim/rolling
124
+ * logic is a line-for-line port — same re-summarize condition (`older.length > coveredOlder &&
125
+ * (summary === null || olderTokens > summariseAtTokens)`), same synthetic turn shape (`qa` = the
126
+ * summary text, `createdAt` = the epoch-zero sentinel that sorts before every real turn, one message
127
+ * with `id: summaryMessageId`, content prefixed `[Earlier conversation, compacted summary]`, no tool
128
+ * calls), same "nothing to compact yet" early return when there's no older region at all. The ONE
129
+ * deviation: state that lived on private class fields (`#compactSummary`, `#compactCoveredOlder`) in
130
+ * the original is now explicit input/output (`options.priorState` in, `{ summary, coveredOlder }` out)
131
+ * — a pure battery function cannot own mutable instance state, so the caller threads it through. This
132
+ * is a mechanical decoupling change, not a behavioral one: a caller who persists and re-supplies
133
+ * `priorState` exactly as returned reproduces the original's stateful behavior turn-for-turn.
134
+ *
135
+ * Unlike Token Thrift, this function CANNOT resurface the exact older detail a later turn needs — it
136
+ * only has the summary's blurred prose. See the module barrel for the honest, both-ways evaluation of
137
+ * that fidelity trade-off against thrift's subtractive approach.
138
+ *
139
+ * @param turns - The full grouped history, chronological (e.g. from
140
+ * {@link @nhtio/adk/batteries/context/thrift/relevance!groupHistoryIntoTurns}).
141
+ * @param options - See {@link AssembleCompactedTurnsOptions}.
142
+ * @returns See {@link AssembleCompactedTurnsResult}.
143
+ * @throws {@link @nhtio/adk/batteries/context/exceptions!E_CONTEXT_RESOLVER_MISSING} When
144
+ * `options.summarize` or `options.estimateTokens` is not a function.
145
+ */
146
+ async function assembleCompactedTurns(turns, options) {
147
+ if (typeof options?.summarize !== "function") throw new require_batteries_context_exceptions.E_CONTEXT_RESOLVER_MISSING(["assembleCompactedTurns", "summarize"]);
148
+ if (typeof options?.estimateTokens !== "function") throw new require_batteries_context_exceptions.E_CONTEXT_RESOLVER_MISSING(["assembleCompactedTurns", "estimateTokens"]);
149
+ const encoding = options.encoding ?? DEFAULT_ENCODING;
150
+ const keepVerbatim = options.keepVerbatim ?? 2;
151
+ const summariseAtTokens = options.summariseAtTokens ?? 2500;
152
+ const summaryMessageId = options.summaryMessageId ?? "__compact-summary";
153
+ let summary = options.priorState?.summary ?? null;
154
+ let coveredOlder = options.priorState?.coveredOlder ?? 0;
155
+ const recentStart = Math.max(0, turns.length - keepVerbatim);
156
+ const older = turns.slice(0, recentStart);
157
+ const recent = turns.slice(recentStart);
158
+ if (older.length === 0) return {
159
+ turns: [...recent],
160
+ summary,
161
+ coveredOlder
162
+ };
163
+ const olderText = older.map((t) => t.qa).join("\n\n");
164
+ const olderTokens = options.estimateTokens(olderText, encoding);
165
+ if (older.length > coveredOlder && (summary === null || olderTokens > summariseAtTokens)) {
166
+ summary = await summariseTurns(olderText, summary, {
167
+ summarize: options.summarize,
168
+ estimateTokens: options.estimateTokens,
169
+ encoding,
170
+ systemPrompt: options.systemPrompt,
171
+ onCost: options.onCost
172
+ });
173
+ coveredOlder = older.length;
174
+ }
175
+ const summaryText = summary ?? olderText;
176
+ const sentinelCreatedAt = (/* @__PURE__ */ new Date(0)).toISOString();
177
+ return {
178
+ turns: [{
179
+ qa: summaryText,
180
+ createdAt: sentinelCreatedAt,
181
+ messages: [{
182
+ id: summaryMessageId,
183
+ role: "user",
184
+ content: `[Earlier conversation, compacted summary]\n${summaryText}`,
185
+ createdAt: sentinelCreatedAt
186
+ }],
187
+ toolCalls: []
188
+ }, ...recent],
189
+ summary,
190
+ coveredOlder
191
+ };
192
+ }
193
+ //#endregion
194
+ exports.COMPACTION_SYSTEM_PROMPT = COMPACTION_SYSTEM_PROMPT;
195
+ exports.DEFAULT_KEEP_VERBATIM = DEFAULT_KEEP_VERBATIM;
196
+ exports.DEFAULT_SUMMARISE_AT_TOKENS = DEFAULT_SUMMARISE_AT_TOKENS;
197
+ exports.DEFAULT_SUMMARY_MESSAGE_ID = DEFAULT_SUMMARY_MESSAGE_ID;
198
+ exports.assembleCompactedTurns = assembleCompactedTurns;
199
+ exports.summariseTurns = summariseTurns;
200
+
201
+ //# sourceMappingURL=summarizer.cjs.map