@nhtio/adk 1.20260607.2 → 1.20260609.1

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 (521) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/batteries/embeddings/openai/adapter.cjs +1 -1
  3. package/batteries/embeddings/openai/adapter.mjs +1 -1
  4. package/batteries/embeddings/openai/exceptions.cjs +1 -1
  5. package/batteries/embeddings/openai/exceptions.mjs +1 -1
  6. package/batteries/embeddings/openai/types.d.ts +7 -0
  7. package/batteries/embeddings/webllm/adapter.cjs +1 -1
  8. package/batteries/embeddings/webllm/adapter.mjs +1 -1
  9. package/batteries/embeddings/webllm/exceptions.cjs +1 -1
  10. package/batteries/embeddings/webllm/exceptions.mjs +1 -1
  11. package/batteries/llm/chat_common/helpers.d.ts +165 -0
  12. package/batteries/llm/chat_common/types.d.ts +309 -0
  13. package/batteries/llm/index.d.ts +5 -0
  14. package/batteries/llm/ollama/adapter.cjs +736 -0
  15. package/batteries/llm/ollama/adapter.cjs.map +1 -0
  16. package/batteries/llm/ollama/adapter.d.ts +64 -0
  17. package/batteries/llm/ollama/adapter.mjs +734 -0
  18. package/batteries/llm/ollama/adapter.mjs.map +1 -0
  19. package/batteries/llm/ollama/exceptions.cjs +105 -0
  20. package/batteries/llm/ollama/exceptions.cjs.map +1 -0
  21. package/batteries/llm/ollama/exceptions.d.ts +112 -0
  22. package/batteries/llm/ollama/exceptions.mjs +96 -0
  23. package/batteries/llm/ollama/exceptions.mjs.map +1 -0
  24. package/batteries/llm/ollama/helpers.cjs +487 -0
  25. package/batteries/llm/ollama/helpers.cjs.map +1 -0
  26. package/batteries/llm/ollama/helpers.d.ts +158 -0
  27. package/batteries/llm/ollama/helpers.mjs +450 -0
  28. package/batteries/llm/ollama/helpers.mjs.map +1 -0
  29. package/batteries/llm/ollama/index.d.ts +29 -0
  30. package/batteries/llm/ollama/types.cjs +2 -0
  31. package/batteries/llm/ollama/types.d.ts +334 -0
  32. package/batteries/llm/ollama/types.mjs +0 -0
  33. package/batteries/llm/ollama/validation.cjs +130 -0
  34. package/batteries/llm/ollama/validation.cjs.map +1 -0
  35. package/batteries/llm/ollama/validation.d.ts +31 -0
  36. package/batteries/llm/ollama/validation.mjs +127 -0
  37. package/batteries/llm/ollama/validation.mjs.map +1 -0
  38. package/batteries/llm/ollama.cjs +54 -0
  39. package/batteries/llm/ollama.mjs +6 -0
  40. package/batteries/llm/openai_chat_completions/adapter.cjs +36 -19
  41. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
  42. package/batteries/llm/openai_chat_completions/adapter.mjs +23 -6
  43. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
  44. package/batteries/llm/openai_chat_completions/exceptions.cjs +1 -1
  45. package/batteries/llm/openai_chat_completions/exceptions.mjs +1 -1
  46. package/batteries/llm/openai_chat_completions/helpers.cjs +80 -320
  47. package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -1
  48. package/batteries/llm/openai_chat_completions/helpers.d.ts +68 -144
  49. package/batteries/llm/openai_chat_completions/helpers.mjs +40 -280
  50. package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -1
  51. package/batteries/llm/openai_chat_completions/types.d.ts +273 -181
  52. package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
  53. package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -1
  54. package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
  55. package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -1
  56. package/batteries/llm/openai_chat_completions.cjs +29 -28
  57. package/batteries/llm/openai_chat_completions.mjs +2 -1
  58. package/batteries/llm/webllm_chat_completions/adapter.cjs +38 -19
  59. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
  60. package/batteries/llm/webllm_chat_completions/adapter.d.ts +18 -0
  61. package/batteries/llm/webllm_chat_completions/adapter.mjs +25 -6
  62. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
  63. package/batteries/llm/webllm_chat_completions/exceptions.cjs +1 -1
  64. package/batteries/llm/webllm_chat_completions/exceptions.mjs +1 -1
  65. package/batteries/llm/webllm_chat_completions/helpers.cjs +29 -28
  66. package/batteries/llm/webllm_chat_completions/helpers.mjs +2 -1
  67. package/batteries/llm/webllm_chat_completions/types.d.ts +21 -0
  68. package/batteries/llm/webllm_chat_completions/validation.cjs +13 -1
  69. package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -1
  70. package/batteries/llm/webllm_chat_completions/validation.d.ts +12 -0
  71. package/batteries/llm/webllm_chat_completions/validation.mjs +13 -1
  72. package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -1
  73. package/batteries/llm/webllm_chat_completions.cjs +29 -28
  74. package/batteries/llm/webllm_chat_completions.mjs +2 -1
  75. package/batteries/llm.cjs +44 -28
  76. package/batteries/llm.mjs +9 -4
  77. package/batteries/storage/flydrive.cjs +1 -1
  78. package/batteries/storage/flydrive.mjs +1 -1
  79. package/batteries/storage/in_memory/index.d.ts +1 -1
  80. package/batteries/storage/in_memory.cjs +2 -2
  81. package/batteries/storage/in_memory.cjs.map +1 -1
  82. package/batteries/storage/in_memory.mjs +2 -2
  83. package/batteries/storage/in_memory.mjs.map +1 -1
  84. package/batteries/storage/opfs/index.d.ts +19 -0
  85. package/batteries/storage/opfs.cjs +1 -1
  86. package/batteries/storage/opfs.cjs.map +1 -1
  87. package/batteries/storage/opfs.mjs +1 -1
  88. package/batteries/storage/opfs.mjs.map +1 -1
  89. package/batteries/tools/_shared/index.d.ts +121 -0
  90. package/batteries/tools/_shared.cjs +157 -0
  91. package/batteries/tools/_shared.cjs.map +1 -0
  92. package/batteries/tools/_shared.mjs +149 -0
  93. package/batteries/tools/_shared.mjs.map +1 -0
  94. package/batteries/tools/color.cjs +3 -2
  95. package/batteries/tools/color.cjs.map +1 -1
  96. package/batteries/tools/color.mjs +3 -2
  97. package/batteries/tools/color.mjs.map +1 -1
  98. package/batteries/tools/comparison.cjs +4 -3
  99. package/batteries/tools/comparison.cjs.map +1 -1
  100. package/batteries/tools/comparison.mjs +4 -3
  101. package/batteries/tools/comparison.mjs.map +1 -1
  102. package/batteries/tools/data_structure.cjs +30 -10
  103. package/batteries/tools/data_structure.cjs.map +1 -1
  104. package/batteries/tools/data_structure.mjs +30 -10
  105. package/batteries/tools/data_structure.mjs.map +1 -1
  106. package/batteries/tools/datetime_extended.cjs +5 -10
  107. package/batteries/tools/datetime_extended.cjs.map +1 -1
  108. package/batteries/tools/datetime_extended.mjs +5 -10
  109. package/batteries/tools/datetime_extended.mjs.map +1 -1
  110. package/batteries/tools/datetime_math.cjs +2 -2
  111. package/batteries/tools/datetime_math.mjs +2 -2
  112. package/batteries/tools/encoding.cjs +13 -4
  113. package/batteries/tools/encoding.cjs.map +1 -1
  114. package/batteries/tools/encoding.mjs +13 -4
  115. package/batteries/tools/encoding.mjs.map +1 -1
  116. package/batteries/tools/formatting.cjs +4 -4
  117. package/batteries/tools/formatting.cjs.map +1 -1
  118. package/batteries/tools/formatting.mjs +4 -4
  119. package/batteries/tools/formatting.mjs.map +1 -1
  120. package/batteries/tools/geo_basics.cjs +2 -2
  121. package/batteries/tools/geo_basics.mjs +2 -2
  122. package/batteries/tools/index.d.ts +3 -0
  123. package/batteries/tools/math.cjs +10 -8
  124. package/batteries/tools/math.cjs.map +1 -1
  125. package/batteries/tools/math.mjs +10 -8
  126. package/batteries/tools/math.mjs.map +1 -1
  127. package/batteries/tools/memory.cjs +5 -5
  128. package/batteries/tools/memory.mjs +5 -5
  129. package/batteries/tools/parsing.cjs +9 -5
  130. package/batteries/tools/parsing.cjs.map +1 -1
  131. package/batteries/tools/parsing.mjs +9 -5
  132. package/batteries/tools/parsing.mjs.map +1 -1
  133. package/batteries/tools/retrievables.cjs +4 -4
  134. package/batteries/tools/retrievables.mjs +4 -4
  135. package/batteries/tools/scrapper/exceptions.d.ts +21 -0
  136. package/batteries/tools/scrapper/index.d.ts +172 -0
  137. package/batteries/tools/scrapper/shared.d.ts +139 -0
  138. package/batteries/tools/scrapper.cjs +8 -0
  139. package/batteries/tools/scrapper.mjs +2 -0
  140. package/batteries/tools/searxng/exceptions.d.ts +21 -0
  141. package/batteries/tools/searxng/index.d.ts +177 -0
  142. package/batteries/tools/searxng.cjs +6 -0
  143. package/batteries/tools/searxng.mjs +2 -0
  144. package/batteries/tools/standing_instructions.cjs +4 -4
  145. package/batteries/tools/standing_instructions.mjs +4 -4
  146. package/batteries/tools/statistics.cjs +54 -43
  147. package/batteries/tools/statistics.cjs.map +1 -1
  148. package/batteries/tools/statistics.mjs +54 -43
  149. package/batteries/tools/statistics.mjs.map +1 -1
  150. package/batteries/tools/string_processing.cjs +5 -5
  151. package/batteries/tools/string_processing.cjs.map +1 -1
  152. package/batteries/tools/string_processing.mjs +5 -5
  153. package/batteries/tools/string_processing.mjs.map +1 -1
  154. package/batteries/tools/structured_data.cjs +8 -13
  155. package/batteries/tools/structured_data.cjs.map +1 -1
  156. package/batteries/tools/structured_data.mjs +8 -13
  157. package/batteries/tools/structured_data.mjs.map +1 -1
  158. package/batteries/tools/text_analysis.cjs +3 -3
  159. package/batteries/tools/text_analysis.mjs +3 -3
  160. package/batteries/tools/text_comparison.cjs +2 -2
  161. package/batteries/tools/text_comparison.mjs +2 -2
  162. package/batteries/tools/time.cjs +2 -2
  163. package/batteries/tools/time.mjs +2 -2
  164. package/batteries/tools/unit_conversion.cjs +10 -8
  165. package/batteries/tools/unit_conversion.cjs.map +1 -1
  166. package/batteries/tools/unit_conversion.mjs +10 -8
  167. package/batteries/tools/unit_conversion.mjs.map +1 -1
  168. package/batteries/tools/web_retrieval/index.d.ts +186 -0
  169. package/batteries/tools/web_retrieval.cjs +206 -0
  170. package/batteries/tools/web_retrieval.cjs.map +1 -0
  171. package/batteries/tools/web_retrieval.mjs +201 -0
  172. package/batteries/tools/web_retrieval.mjs.map +1 -0
  173. package/batteries/tools.cjs +15 -0
  174. package/batteries/tools.mjs +4 -1
  175. package/batteries/vector/arangodb/index.d.ts +2 -0
  176. package/batteries/vector/arangodb.cjs +2 -1
  177. package/batteries/vector/arangodb.cjs.map +1 -1
  178. package/batteries/vector/arangodb.mjs +2 -1
  179. package/batteries/vector/arangodb.mjs.map +1 -1
  180. package/batteries/vector/builder.cjs +31 -0
  181. package/batteries/vector/builder.cjs.map +1 -1
  182. package/batteries/vector/builder.d.ts +58 -0
  183. package/batteries/vector/builder.mjs +31 -0
  184. package/batteries/vector/builder.mjs.map +1 -1
  185. package/batteries/vector/chroma/index.d.ts +4 -0
  186. package/batteries/vector/chroma.cjs +3 -0
  187. package/batteries/vector/chroma.cjs.map +1 -1
  188. package/batteries/vector/chroma.mjs +3 -0
  189. package/batteries/vector/chroma.mjs.map +1 -1
  190. package/batteries/vector/clickhouse/index.d.ts +2 -0
  191. package/batteries/vector/clickhouse.cjs +2 -1
  192. package/batteries/vector/clickhouse.cjs.map +1 -1
  193. package/batteries/vector/clickhouse.mjs +2 -1
  194. package/batteries/vector/clickhouse.mjs.map +1 -1
  195. package/batteries/vector/cloudflare/index.d.ts +2 -0
  196. package/batteries/vector/cloudflare.cjs +2 -1
  197. package/batteries/vector/cloudflare.cjs.map +1 -1
  198. package/batteries/vector/cloudflare.mjs +2 -1
  199. package/batteries/vector/cloudflare.mjs.map +1 -1
  200. package/batteries/vector/conformance/index.d.ts +22 -0
  201. package/batteries/vector/conformance.cjs +22 -0
  202. package/batteries/vector/conformance.cjs.map +1 -1
  203. package/batteries/vector/conformance.mjs +22 -0
  204. package/batteries/vector/conformance.mjs.map +1 -1
  205. package/batteries/vector/contract.cjs +22 -0
  206. package/batteries/vector/contract.cjs.map +1 -1
  207. package/batteries/vector/contract.d.ts +51 -0
  208. package/batteries/vector/contract.mjs +22 -0
  209. package/batteries/vector/contract.mjs.map +1 -1
  210. package/batteries/vector/couchbase/index.d.ts +2 -0
  211. package/batteries/vector/couchbase.cjs +2 -1
  212. package/batteries/vector/couchbase.cjs.map +1 -1
  213. package/batteries/vector/couchbase.mjs +2 -1
  214. package/batteries/vector/couchbase.mjs.map +1 -1
  215. package/batteries/vector/duckdb/index.d.ts +2 -0
  216. package/batteries/vector/duckdb.cjs +2 -1
  217. package/batteries/vector/duckdb.cjs.map +1 -1
  218. package/batteries/vector/duckdb.mjs +2 -1
  219. package/batteries/vector/duckdb.mjs.map +1 -1
  220. package/batteries/vector/elasticsearch/index.d.ts +2 -0
  221. package/batteries/vector/elasticsearch.cjs +2 -1
  222. package/batteries/vector/elasticsearch.cjs.map +1 -1
  223. package/batteries/vector/elasticsearch.mjs +2 -1
  224. package/batteries/vector/elasticsearch.mjs.map +1 -1
  225. package/batteries/vector/exceptions.cjs +1 -1
  226. package/batteries/vector/exceptions.mjs +1 -1
  227. package/batteries/vector/factory.cjs +6 -0
  228. package/batteries/vector/factory.cjs.map +1 -1
  229. package/batteries/vector/factory.d.ts +14 -0
  230. package/batteries/vector/factory.mjs +6 -0
  231. package/batteries/vector/factory.mjs.map +1 -1
  232. package/batteries/vector/filters.cjs +22 -1
  233. package/batteries/vector/filters.cjs.map +1 -1
  234. package/batteries/vector/filters.d.ts +38 -0
  235. package/batteries/vector/filters.mjs +22 -1
  236. package/batteries/vector/filters.mjs.map +1 -1
  237. package/batteries/vector/helpers.cjs +13 -0
  238. package/batteries/vector/helpers.cjs.map +1 -1
  239. package/batteries/vector/helpers.d.ts +14 -0
  240. package/batteries/vector/helpers.mjs +13 -0
  241. package/batteries/vector/helpers.mjs.map +1 -1
  242. package/batteries/vector/hnswlib/index.d.ts +2 -0
  243. package/batteries/vector/hnswlib.cjs +2 -1
  244. package/batteries/vector/hnswlib.cjs.map +1 -1
  245. package/batteries/vector/hnswlib.mjs +2 -1
  246. package/batteries/vector/hnswlib.mjs.map +1 -1
  247. package/batteries/vector/in_memory/index.d.ts +1 -0
  248. package/batteries/vector/in_memory.cjs +1 -0
  249. package/batteries/vector/in_memory.cjs.map +1 -1
  250. package/batteries/vector/in_memory.mjs +1 -0
  251. package/batteries/vector/in_memory.mjs.map +1 -1
  252. package/batteries/vector/lancedb/index.d.ts +2 -0
  253. package/batteries/vector/lancedb.cjs +2 -1
  254. package/batteries/vector/lancedb.cjs.map +1 -1
  255. package/batteries/vector/lancedb.mjs +2 -1
  256. package/batteries/vector/lancedb.mjs.map +1 -1
  257. package/batteries/vector/mariadb/index.d.ts +2 -0
  258. package/batteries/vector/mariadb.cjs +2 -1
  259. package/batteries/vector/mariadb.cjs.map +1 -1
  260. package/batteries/vector/mariadb.mjs +2 -1
  261. package/batteries/vector/mariadb.mjs.map +1 -1
  262. package/batteries/vector/meilisearch/index.d.ts +2 -0
  263. package/batteries/vector/meilisearch.cjs +2 -1
  264. package/batteries/vector/meilisearch.cjs.map +1 -1
  265. package/batteries/vector/meilisearch.mjs +2 -1
  266. package/batteries/vector/meilisearch.mjs.map +1 -1
  267. package/batteries/vector/migrate.cjs +18 -1
  268. package/batteries/vector/migrate.cjs.map +1 -1
  269. package/batteries/vector/migrate.d.ts +31 -0
  270. package/batteries/vector/migrate.mjs +18 -1
  271. package/batteries/vector/migrate.mjs.map +1 -1
  272. package/batteries/vector/milvus/index.d.ts +5 -0
  273. package/batteries/vector/milvus.cjs +4 -0
  274. package/batteries/vector/milvus.cjs.map +1 -1
  275. package/batteries/vector/milvus.mjs +4 -0
  276. package/batteries/vector/milvus.mjs.map +1 -1
  277. package/batteries/vector/mongodb/index.d.ts +2 -0
  278. package/batteries/vector/mongodb.cjs +2 -1
  279. package/batteries/vector/mongodb.cjs.map +1 -1
  280. package/batteries/vector/mongodb.mjs +2 -1
  281. package/batteries/vector/mongodb.mjs.map +1 -1
  282. package/batteries/vector/neo4j/index.d.ts +2 -0
  283. package/batteries/vector/neo4j.cjs +2 -1
  284. package/batteries/vector/neo4j.cjs.map +1 -1
  285. package/batteries/vector/neo4j.mjs +2 -1
  286. package/batteries/vector/neo4j.mjs.map +1 -1
  287. package/batteries/vector/opensearch/index.d.ts +2 -0
  288. package/batteries/vector/opensearch.cjs +2 -1
  289. package/batteries/vector/opensearch.cjs.map +1 -1
  290. package/batteries/vector/opensearch.mjs +2 -1
  291. package/batteries/vector/opensearch.mjs.map +1 -1
  292. package/batteries/vector/oracle23ai/index.d.ts +2 -0
  293. package/batteries/vector/oracle23ai.cjs +2 -1
  294. package/batteries/vector/oracle23ai.cjs.map +1 -1
  295. package/batteries/vector/oracle23ai.mjs +2 -1
  296. package/batteries/vector/oracle23ai.mjs.map +1 -1
  297. package/batteries/vector/orama/index.d.ts +1 -0
  298. package/batteries/vector/orama.cjs +1 -0
  299. package/batteries/vector/orama.cjs.map +1 -1
  300. package/batteries/vector/orama.mjs +1 -0
  301. package/batteries/vector/orama.mjs.map +1 -1
  302. package/batteries/vector/pgvector/index.d.ts +9 -2
  303. package/batteries/vector/pgvector.cjs +4 -0
  304. package/batteries/vector/pgvector.cjs.map +1 -1
  305. package/batteries/vector/pgvector.mjs +4 -0
  306. package/batteries/vector/pgvector.mjs.map +1 -1
  307. package/batteries/vector/pinecone/index.d.ts +5 -0
  308. package/batteries/vector/pinecone.cjs +3 -1
  309. package/batteries/vector/pinecone.cjs.map +1 -1
  310. package/batteries/vector/pinecone.mjs +3 -1
  311. package/batteries/vector/pinecone.mjs.map +1 -1
  312. package/batteries/vector/plan.d.ts +27 -0
  313. package/batteries/vector/qdrant/index.d.ts +5 -0
  314. package/batteries/vector/qdrant.cjs +4 -0
  315. package/batteries/vector/qdrant.cjs.map +1 -1
  316. package/batteries/vector/qdrant.mjs +4 -0
  317. package/batteries/vector/qdrant.mjs.map +1 -1
  318. package/batteries/vector/redis/index.d.ts +2 -0
  319. package/batteries/vector/redis.cjs +2 -1
  320. package/batteries/vector/redis.cjs.map +1 -1
  321. package/batteries/vector/redis.mjs +2 -1
  322. package/batteries/vector/redis.mjs.map +1 -1
  323. package/batteries/vector/retrievable.cjs +9 -1
  324. package/batteries/vector/retrievable.cjs.map +1 -1
  325. package/batteries/vector/retrievable.mjs +9 -1
  326. package/batteries/vector/retrievable.mjs.map +1 -1
  327. package/batteries/vector/retrievable_glue.d.ts +21 -0
  328. package/batteries/vector/s3vectors/index.d.ts +2 -0
  329. package/batteries/vector/s3vectors.cjs +2 -1
  330. package/batteries/vector/s3vectors.cjs.map +1 -1
  331. package/batteries/vector/s3vectors.mjs +2 -1
  332. package/batteries/vector/s3vectors.mjs.map +1 -1
  333. package/batteries/vector/schema.cjs +28 -0
  334. package/batteries/vector/schema.cjs.map +1 -1
  335. package/batteries/vector/schema.d.ts +39 -0
  336. package/batteries/vector/schema.mjs +28 -0
  337. package/batteries/vector/schema.mjs.map +1 -1
  338. package/batteries/vector/solr/index.d.ts +2 -0
  339. package/batteries/vector/solr.cjs +2 -1
  340. package/batteries/vector/solr.cjs.map +1 -1
  341. package/batteries/vector/solr.mjs +2 -1
  342. package/batteries/vector/solr.mjs.map +1 -1
  343. package/batteries/vector/sqlite_vec/index.d.ts +6 -3
  344. package/batteries/vector/sqlite_vec.cjs +2 -0
  345. package/batteries/vector/sqlite_vec.cjs.map +1 -1
  346. package/batteries/vector/sqlite_vec.mjs +2 -0
  347. package/batteries/vector/sqlite_vec.mjs.map +1 -1
  348. package/batteries/vector/surrealdb/index.d.ts +2 -0
  349. package/batteries/vector/surrealdb.cjs +2 -1
  350. package/batteries/vector/surrealdb.cjs.map +1 -1
  351. package/batteries/vector/surrealdb.mjs +2 -1
  352. package/batteries/vector/surrealdb.mjs.map +1 -1
  353. package/batteries/vector/types.d.ts +27 -0
  354. package/batteries/vector/typesense/index.d.ts +2 -0
  355. package/batteries/vector/typesense.cjs +2 -1
  356. package/batteries/vector/typesense.cjs.map +1 -1
  357. package/batteries/vector/typesense.mjs +2 -1
  358. package/batteries/vector/typesense.mjs.map +1 -1
  359. package/batteries/vector/validation.cjs +14 -0
  360. package/batteries/vector/validation.cjs.map +1 -1
  361. package/batteries/vector/validation.d.ts +14 -0
  362. package/batteries/vector/validation.mjs +14 -0
  363. package/batteries/vector/validation.mjs.map +1 -1
  364. package/batteries/vector/vector_store_constructor.cjs +1 -1
  365. package/batteries/vector/vector_store_constructor.cjs.map +1 -1
  366. package/batteries/vector/vector_store_constructor.d.ts +1 -1
  367. package/batteries/vector/vector_store_constructor.mjs +1 -1
  368. package/batteries/vector/vector_store_constructor.mjs.map +1 -1
  369. package/batteries/vector/vespa/index.d.ts +2 -0
  370. package/batteries/vector/vespa.cjs +2 -1
  371. package/batteries/vector/vespa.cjs.map +1 -1
  372. package/batteries/vector/vespa.mjs +2 -1
  373. package/batteries/vector/vespa.mjs.map +1 -1
  374. package/batteries/vector/weaviate/index.d.ts +2 -0
  375. package/batteries/vector/weaviate.cjs +2 -1
  376. package/batteries/vector/weaviate.cjs.map +1 -1
  377. package/batteries/vector/weaviate.mjs +2 -1
  378. package/batteries/vector/weaviate.mjs.map +1 -1
  379. package/batteries.cjs +58 -28
  380. package/batteries.mjs +12 -5
  381. package/{common-BT0nfCi9.mjs → common-DYDUi99O.mjs} +9 -9
  382. package/common-DYDUi99O.mjs.map +1 -0
  383. package/{common-Cj8TaQ9U.js → common-DZl3ADJs.js} +9 -9
  384. package/common-DZl3ADJs.js.map +1 -0
  385. package/common.cjs +7 -7
  386. package/common.mjs +7 -7
  387. package/{dispatch_runner-DPcS7Y_M.mjs → dispatch_runner--ZhdDWRZ.mjs} +27 -5
  388. package/{dispatch_runner-DPcS7Y_M.mjs.map → dispatch_runner--ZhdDWRZ.mjs.map} +1 -1
  389. package/{dispatch_runner-BHBNupqp.js → dispatch_runner-nHDKkxye.js} +27 -5
  390. package/{dispatch_runner-BHBNupqp.js.map → dispatch_runner-nHDKkxye.js.map} +1 -1
  391. package/dispatch_runner.cjs +1 -1
  392. package/dispatch_runner.d.ts +1 -1
  393. package/dispatch_runner.mjs +1 -1
  394. package/eslint/rules/artifact_tool_forbids_artifact_constructor.cjs +1 -0
  395. package/eslint/rules/artifact_tool_forbids_artifact_constructor.cjs.map +1 -1
  396. package/eslint/rules/artifact_tool_forbids_artifact_constructor.d.ts +1 -0
  397. package/eslint/rules/artifact_tool_forbids_artifact_constructor.mjs +1 -0
  398. package/eslint/rules/artifact_tool_forbids_artifact_constructor.mjs.map +1 -1
  399. package/eslint/rules/no_model_in_tool_handler.cjs +1 -0
  400. package/eslint/rules/no_model_in_tool_handler.cjs.map +1 -1
  401. package/eslint/rules/no_model_in_tool_handler.d.ts +1 -0
  402. package/eslint/rules/no_model_in_tool_handler.mjs +1 -0
  403. package/eslint/rules/no_model_in_tool_handler.mjs.map +1 -1
  404. package/eslint/rules/require_validator_any_required.cjs +1 -0
  405. package/eslint/rules/require_validator_any_required.cjs.map +1 -1
  406. package/eslint/rules/require_validator_any_required.d.ts +1 -0
  407. package/eslint/rules/require_validator_any_required.mjs +1 -0
  408. package/eslint/rules/require_validator_any_required.mjs.map +1 -1
  409. package/eslint/rules/thought_payload_requires_replay_tag.cjs +1 -0
  410. package/eslint/rules/thought_payload_requires_replay_tag.cjs.map +1 -1
  411. package/eslint/rules/thought_payload_requires_replay_tag.d.ts +1 -0
  412. package/eslint/rules/thought_payload_requires_replay_tag.mjs +1 -0
  413. package/eslint/rules/thought_payload_requires_replay_tag.mjs.map +1 -1
  414. package/eslint/rules/token_encoding_requires_context_window.cjs +1 -0
  415. package/eslint/rules/token_encoding_requires_context_window.cjs.map +1 -1
  416. package/eslint/rules/token_encoding_requires_context_window.d.ts +1 -0
  417. package/eslint/rules/token_encoding_requires_context_window.mjs +1 -0
  418. package/eslint/rules/token_encoding_requires_context_window.mjs.map +1 -1
  419. package/eslint/rules.cjs +1 -1
  420. package/eslint/rules.mjs +1 -1
  421. package/eslint.cjs +2 -2
  422. package/eslint.mjs +2 -2
  423. package/{exceptions-BeWH2FwP.mjs → exceptions-BDhN0Xzr.mjs} +3 -2
  424. package/exceptions-BDhN0Xzr.mjs.map +1 -0
  425. package/{exceptions-CitH5wZI.js → exceptions-BRXrUKiW.js} +3 -2
  426. package/exceptions-BRXrUKiW.js.map +1 -0
  427. package/exceptions.cjs +2 -2
  428. package/exceptions.mjs +2 -2
  429. package/factories.cjs +1 -1
  430. package/factories.mjs +1 -1
  431. package/forge.cjs +4 -4
  432. package/forge.d.ts +1 -1
  433. package/forge.mjs +4 -4
  434. package/guards.cjs +9 -9
  435. package/guards.mjs +9 -9
  436. package/helpers-DSTFxTiC.js +497 -0
  437. package/helpers-DSTFxTiC.js.map +1 -0
  438. package/helpers-xhrQbMAG.mjs +306 -0
  439. package/helpers-xhrQbMAG.mjs.map +1 -0
  440. package/index.cjs +12 -12
  441. package/index.mjs +12 -12
  442. package/lib/classes/base_exception.d.ts +1 -0
  443. package/lib/classes/media.d.ts +10 -0
  444. package/lib/classes/retrievable.d.ts +1 -1
  445. package/lib/classes/spooled_json_artifact.d.ts +1 -1
  446. package/lib/classes/spooled_markdown_artifact.d.ts +1 -0
  447. package/lib/classes/tokenizable.d.ts +3 -0
  448. package/lib/classes/tool.d.ts +8 -0
  449. package/lib/classes/turn_gate.d.ts +6 -0
  450. package/lib/dispatch_runner.d.ts +4 -32
  451. package/lib/helpers/bignum.cjs +82 -0
  452. package/lib/helpers/bignum.cjs.map +1 -0
  453. package/lib/helpers/bignum.d.ts +52 -0
  454. package/lib/helpers/bignum.mjs +74 -0
  455. package/lib/helpers/bignum.mjs.map +1 -0
  456. package/lib/turn_runner.d.ts +1 -1
  457. package/lib/types/dispatch_runner.d.ts +83 -0
  458. package/lib/utils/exceptions.d.ts +1 -1
  459. package/lib/utils/retry.cjs.map +1 -1
  460. package/lib/utils/retry.d.ts +2 -0
  461. package/lib/utils/retry.mjs.map +1 -1
  462. package/mcp/adk-docs-corpus.json +1 -1
  463. package/package.json +259 -204
  464. package/{runtime-j92CNi5z.mjs → runtime-Bz5zA8wc.mjs} +2 -2
  465. package/{runtime-j92CNi5z.mjs.map → runtime-Bz5zA8wc.mjs.map} +1 -1
  466. package/{runtime-MFFcJrRv.js → runtime-DslE1aBw.js} +2 -2
  467. package/{runtime-MFFcJrRv.js.map → runtime-DslE1aBw.js.map} +1 -1
  468. package/scrapper-BHM1mCde.mjs +432 -0
  469. package/scrapper-BHM1mCde.mjs.map +1 -0
  470. package/scrapper-BeweWurk.js +462 -0
  471. package/scrapper-BeweWurk.js.map +1 -0
  472. package/searxng-BJFulNcK.mjs +247 -0
  473. package/searxng-BJFulNcK.mjs.map +1 -0
  474. package/searxng-B_D--V5q.js +265 -0
  475. package/searxng-B_D--V5q.js.map +1 -0
  476. package/skills/adk-assembly/SKILL.md +2 -2
  477. package/{spooled_artifact-CHoZgWwI.mjs → spooled_artifact-7eePq7JA.mjs} +5 -5
  478. package/{spooled_artifact-CHoZgWwI.mjs.map → spooled_artifact-7eePq7JA.mjs.map} +1 -1
  479. package/{spooled_artifact-BTq6Nzfy.js → spooled_artifact-DX8LLyUX.js} +5 -5
  480. package/{spooled_artifact-BTq6Nzfy.js.map → spooled_artifact-DX8LLyUX.js.map} +1 -1
  481. package/spooled_artifact.cjs +2 -2
  482. package/spooled_artifact.mjs +2 -2
  483. package/{spooled_markdown_artifact-CALSDxIx.js → spooled_markdown_artifact-ClX72lek.js} +4 -4
  484. package/spooled_markdown_artifact-ClX72lek.js.map +1 -0
  485. package/{spooled_markdown_artifact-Ci5UL7l4.mjs → spooled_markdown_artifact-wkrBF3oX.mjs} +4 -4
  486. package/spooled_markdown_artifact-wkrBF3oX.mjs.map +1 -0
  487. package/{thought-D34QQZZ9.mjs → thought-B_vxAiKU.mjs} +5 -5
  488. package/{thought-D34QQZZ9.mjs.map → thought-B_vxAiKU.mjs.map} +1 -1
  489. package/{thought-BbwhJ1wb.js → thought-DLwpF7MI.js} +5 -5
  490. package/{thought-BbwhJ1wb.js.map → thought-DLwpF7MI.js.map} +1 -1
  491. package/{tool-CVyZkFC7.js → tool-D5WGVIcI.js} +4 -4
  492. package/{tool-CVyZkFC7.js.map → tool-D5WGVIcI.js.map} +1 -1
  493. package/{tool-CMhaDRNd.mjs → tool-wMYMVl60.mjs} +4 -4
  494. package/{tool-CMhaDRNd.mjs.map → tool-wMYMVl60.mjs.map} +1 -1
  495. package/{tool_call-CV5qVNlb.mjs → tool_call-B4-_-vjG.mjs} +5 -5
  496. package/tool_call-B4-_-vjG.mjs.map +1 -0
  497. package/{tool_call-Db68hB7y.js → tool_call-DixVlW40.js} +5 -5
  498. package/tool_call-DixVlW40.js.map +1 -0
  499. package/{tool_registry-D1pSSlsd.mjs → tool_registry-791Vrjtf.mjs} +4 -3
  500. package/tool_registry-791Vrjtf.mjs.map +1 -0
  501. package/{tool_registry-DYUYqXvo.js → tool_registry-CKJPze3j.js} +4 -3
  502. package/tool_registry-CKJPze3j.js.map +1 -0
  503. package/{turn_runner-DqWHNP80.js → turn_runner-HXImLGIn.js} +7 -7
  504. package/turn_runner-HXImLGIn.js.map +1 -0
  505. package/{turn_runner-fg1Wc3dK.mjs → turn_runner-ZyYO-Kti.mjs} +7 -7
  506. package/turn_runner-ZyYO-Kti.mjs.map +1 -0
  507. package/turn_runner.cjs +1 -1
  508. package/turn_runner.mjs +1 -1
  509. package/types.d.ts +1 -1
  510. package/common-BT0nfCi9.mjs.map +0 -1
  511. package/common-Cj8TaQ9U.js.map +0 -1
  512. package/exceptions-BeWH2FwP.mjs.map +0 -1
  513. package/exceptions-CitH5wZI.js.map +0 -1
  514. package/spooled_markdown_artifact-CALSDxIx.js.map +0 -1
  515. package/spooled_markdown_artifact-Ci5UL7l4.mjs.map +0 -1
  516. package/tool_call-CV5qVNlb.mjs.map +0 -1
  517. package/tool_call-Db68hB7y.js.map +0 -1
  518. package/tool_registry-D1pSSlsd.mjs.map +0 -1
  519. package/tool_registry-DYUYqXvo.js.map +0 -1
  520. package/turn_runner-DqWHNP80.js.map +0 -1
  521. package/turn_runner-fg1Wc3dK.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"opfs.cjs","names":["#handle","#threshold","#load","#readRange","#ready","#init","#buildStreamingIndex","#resolveRoot","#prefix","#defaultThreshold","#keyFor","#getRoot","#writeStreamViaSyncHandle","#writeStreamViaWritable","#writeViaSyncHandle","#writeViaWritable","#isNotFoundError","#root"],"sources":["../../../src/batteries/storage/opfs/index.ts"],"sourcesContent":["/**\n * Browser-only Origin Private File System storage for spooled artifacts.\n *\n * @module @nhtio/adk/batteries/storage/opfs\n *\n * @remarks\n * Opt-in **browser-only** storage battery backed by the\n * [Origin Private File System](https://developer.mozilla.org/docs/Web/API/File_System_API/Origin_private_file_system)\n * (OPFS). Provides {@link OpfsSpoolReader} (a {@link @nhtio/adk!SpoolReader} over a `OpfsFileHandle`)\n * and {@link OpfsSpoolStore} (a `write(callId, bytes) → reader` persistence layer that wraps an\n * OPFS directory).\n *\n * The reader has two modes selected lazily on first method invocation based on the size of the\n * underlying file:\n *\n * - **Eager mode** — when `file.size` is below `streamThresholdBytes` (default 10 MiB), the\n * reader calls `file.text()` once, splits the content on `\\n`, and caches lines + byte count.\n * All subsequent calls resolve from memory.\n * - **Streaming mode** — when `file.size` meets or exceeds the threshold, the reader streams the\n * file once via `file.stream().getReader()` to build a line-offset index (`number[]` of byte\n * offsets per line), then serves each `line(i)` request by slicing the underlying `Blob` —\n * `Blob.slice(start, end).text()` decodes only the requested range, no head-of-file scan.\n * Caps RAM at one index + one line buffer regardless of file size.\n *\n * The store auto-selects its write API by execution scope:\n *\n * - In **worker scopes** (`self instanceof WorkerGlobalScope`), it acquires a\n * `FileSystemSyncAccessHandle` and writes synchronously. Sync handles are the only API\n * available in workers and the fastest path for the spool-write hot path.\n * - On the **main thread**, it uses `OpfsFileHandle.createWritable()` and the async\n * stream API. Sync access handles are not exposed on the main thread.\n *\n * This module assumes a browser-equivalent runtime — `navigator.storage`,\n * `OpfsFileHandle`, `TextEncoder`/`TextDecoder`, and `Blob` must all exist. It must not\n * be imported from Node code; do so and you will fail at resolve time when `navigator` is\n * referenced.\n *\n * @example\n * ```ts\n * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'\n *\n * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })\n * const reader = await store.write(callId, bytes)\n * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact\n * const artifact = new Ctor(reader)\n * ```\n */\n\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport type { SpoolReader, SpoolStore } from '@nhtio/adk/common'\n\n// The project's tsconfig limits `lib` to `ESNext`, so the DOM and File System Access types\n// referenced below are not in scope by default — neither `tsc --noEmit` nor the downstream dts\n// pipeline (api-extractor) can see them. Re-declare here the **minimum** surface this module\n// touches via a local handle-shape interface. Public API uses `OpfsFileHandle` /\n// `OpfsDirectoryHandle` instead of the DOM globals so the published `.d.ts` is self-contained\n// and consumers do not have to chase the lib graph.\n\n/**\n * Minimal subset of the\n * [File System Access](https://developer.mozilla.org/docs/Web/API/File_System_API)\n * `OpfsFileHandle` interface that this module touches at runtime. Structurally compatible\n * with the DOM-lib `OpfsFileHandle` — at call sites you pass real OPFS handles directly.\n */\nexport interface OpfsFileHandle {\n readonly kind: 'file'\n readonly name: string\n getFile(): Promise<OpfsFile>\n createWritable(): Promise<OpfsWritableFileStream>\n}\n\n/**\n * Minimal subset of the\n * [File System Access](https://developer.mozilla.org/docs/Web/API/File_System_API)\n * `OpfsDirectoryHandle` interface that this module touches at runtime. Structurally\n * compatible with the DOM-lib `OpfsDirectoryHandle` — at call sites you pass real OPFS\n * handles directly.\n */\nexport interface OpfsDirectoryHandle {\n readonly kind: 'directory'\n readonly name: string\n getFileHandle(name: string, options?: { create?: boolean }): Promise<OpfsFileHandle>\n getDirectoryHandle(name: string, options?: { create?: boolean }): Promise<OpfsDirectoryHandle>\n removeEntry(name: string, options?: { recursive?: boolean }): Promise<void>\n}\n\n/**\n * Minimal subset of the DOM `FileSystemWritableFileStream` interface used by the OPFS battery's\n * main-thread write path.\n */\nexport interface OpfsWritableFileStream {\n write(data: Uint8Array | ArrayBufferView | ArrayBuffer | string): Promise<void>\n close(): Promise<void>\n}\n\n/**\n * Minimal subset of the DOM `Blob` interface used by {@link OpfsSpoolReader} streaming-mode\n * random-access reads. Real OPFS handles return a `File` here; we narrow to the methods we\n * actually call.\n */\nexport interface OpfsBlob {\n readonly size: number\n slice(start?: number, end?: number, contentType?: string): OpfsBlob\n text(): Promise<string>\n stream(): OpfsReadableStream\n}\n\n/**\n * Minimal subset of the DOM `File` interface used by {@link OpfsSpoolReader}.\n */\nexport interface OpfsFile extends OpfsBlob {\n readonly name: string\n}\n\n/**\n * Minimal subset of the DOM `ReadableStream<Uint8Array>` interface used by streaming-mode\n * index construction.\n */\nexport interface OpfsReadableStream {\n getReader(): OpfsReadableStreamReader\n}\n\n/**\n * Minimal subset of the DOM `ReadableStreamDefaultReader<Uint8Array>` interface used by\n * streaming-mode index construction.\n */\nexport interface OpfsReadableStreamReader {\n read(): Promise<{ done: false; value: Uint8Array } | { done: true; value: undefined }>\n releaseLock(): void\n}\n\ndeclare const navigator: {\n storage: { getDirectory(): Promise<OpfsDirectoryHandle> }\n}\ndeclare class TextEncoder {\n encode(input?: string): Uint8Array\n}\ndeclare const self: unknown\ndeclare const WorkerGlobalScope: { new (): unknown } | undefined\n\ninterface FileSystemSyncAccessHandle {\n truncate(newSize: number): void\n write(buffer: Uint8Array | ArrayBuffer | ArrayBufferView, options?: { at?: number }): number\n flush(): void\n close(): void\n}\ninterface OpfsFileHandleWithSyncAccess extends OpfsFileHandle {\n createSyncAccessHandle(): Promise<FileSystemSyncAccessHandle>\n}\n\nconst DEFAULT_STREAM_THRESHOLD_BYTES = 10 * 1024 * 1024 // 10 MiB\n\nconst LF = 0x0a // '\\n'\n\nconst isNonNegativeFiniteNumber = (n: unknown): n is number =>\n typeof n === 'number' && Number.isFinite(n) && n >= 0\n\n/**\n * Constructor options for {@link OpfsSpoolReader}.\n */\nexport interface OpfsSpoolReaderOptions {\n /**\n * Byte-length threshold that switches between eager and streaming modes.\n *\n * @remarks\n * - Below the threshold → eager (whole-file in memory).\n * - At or above the threshold → streaming (line-offset index + per-line slice reads).\n *\n * Set to `0` to force streaming mode; set to `Number.POSITIVE_INFINITY` to force eager mode.\n *\n * @defaultValue `10 * 1024 * 1024` (10 MiB)\n */\n streamThresholdBytes?: number\n}\n\ninterface EagerState {\n mode: 'eager'\n lines: string[]\n bytes: number\n content: string\n}\n\ninterface StreamingState {\n mode: 'streaming'\n file: OpfsFile\n /**\n * Byte offsets where each line *starts*. Length equals lineCount + 1; the final entry equals\n * the total byte length. So `offsets[i + 1] - offsets[i]` is the byte length of line `i`\n * including any trailing `\\n`.\n */\n offsets: number[]\n bytes: number\n}\n\ntype ReaderState = EagerState | StreamingState\n\n/**\n * Returns `true` when the current global scope is a Web Worker (`DedicatedWorkerGlobalScope`,\n * `SharedWorkerGlobalScope`, or `ServiceWorkerGlobalScope` all inherit from `WorkerGlobalScope`).\n *\n * @remarks\n * The check is needed at runtime because `FileSystemSyncAccessHandle` is only exposed in worker\n * scopes — calling it from the main thread throws. We pick the write strategy based on the\n * answer here.\n *\n * @internal\n */\nconst isWorkerScope = (): boolean => {\n if (typeof WorkerGlobalScope === 'undefined') return false\n // eslint-disable-next-line adk/use-is-instance-of -- native built-in narrowing on `self`; no cross-realm risk\n return self instanceof WorkerGlobalScope\n}\n\n/**\n * Reads an OPFS-backed file as a {@link @nhtio/adk!SpoolReader}.\n *\n * @remarks\n * Constructor is **not** async — but the first method call awaits a private readiness promise\n * that fetches the underlying `File` (and in eager mode, its contents). Subsequent calls reuse\n * the cached state. This keeps construction call sites synchronous while still doing real I/O\n * lazily.\n *\n * All four `SpoolReader` methods on this reader return promises. The `SpoolReader` contract\n * supports both sync and async return; consumers of `SpooledArtifact` handle either.\n */\nexport class OpfsSpoolReader implements SpoolReader {\n readonly #handle: OpfsFileHandle\n readonly #threshold: number\n #ready: Promise<ReaderState> | undefined\n\n constructor(handle: OpfsFileHandle, opts: OpfsSpoolReaderOptions = {}) {\n this.#handle = handle\n const raw = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES\n // Allow `Infinity` (forces eager) but reject anything non-finite-negative.\n if (typeof raw !== 'number' || Number.isNaN(raw) || raw < 0) {\n throw new TypeError(\n `OpfsSpoolReader: streamThresholdBytes must be a non-negative number or Infinity, got ${String(raw)}`\n )\n }\n this.#threshold = raw\n }\n\n /**\n * Returns `true` if `value` is an {@link OpfsSpoolReader} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is an {@link OpfsSpoolReader} instance.\n */\n public static isOpfsSpoolReader(value: unknown): value is OpfsSpoolReader {\n return isInstanceOf(value, 'OpfsSpoolReader', OpfsSpoolReader)\n }\n\n async line(index: number): Promise<string | undefined> {\n const state = await this.#load()\n if (state.mode === 'eager') return state.lines[index]\n if (index < 0 || index >= state.offsets.length - 1) return undefined\n return this.#readRange(state.file, state.offsets[index], state.offsets[index + 1])\n }\n\n async byteLength(): Promise<number> {\n const state = await this.#load()\n return state.bytes\n }\n\n async lineCount(): Promise<number> {\n const state = await this.#load()\n return state.mode === 'eager' ? state.lines.length : state.offsets.length - 1\n }\n\n /**\n * Returns the full underlying content as a single decoded string, byte-faithful to the source.\n *\n * @remarks\n * In **eager mode** the content is already cached at first-call load and this method is\n * effectively a property access. In **streaming mode** there is no cache: the file is re-read\n * (as a single `File.text()` call) on every invocation. Use `SpooledArtifact.asString()`\n * judiciously on large streaming-mode artifacts.\n */\n async readAll(): Promise<string> {\n const state = await this.#load()\n if (state.mode === 'eager') return state.content\n return state.file.text()\n }\n\n /**\n * Lazily initialise the reader's mode-specific state. Called by every public method; the\n * promise is cached so the work runs at most once.\n */\n #load(): Promise<ReaderState> {\n if (!this.#ready) this.#ready = this.#init()\n return this.#ready\n }\n\n async #init(): Promise<ReaderState> {\n const file = await this.#handle.getFile()\n const bytes = file.size\n if (!isNonNegativeFiniteNumber(bytes)) {\n throw new Error(`OpfsSpoolReader: file handle returned a non-finite size (${String(bytes)})`)\n }\n if (bytes < this.#threshold) {\n // Eager — pull the whole thing into memory.\n const content = await file.text()\n const lines = content === '' ? [] : content.split('\\n')\n return { mode: 'eager', lines, bytes, content }\n }\n // Streaming — build a line-offset index by scanning bytes once.\n return this.#buildStreamingIndex(file, bytes)\n }\n\n async #buildStreamingIndex(file: OpfsFile, bytes: number): Promise<StreamingState> {\n // Edge case first — an empty file is one offset (the EOF), zero lines.\n if (bytes === 0) return { mode: 'streaming', file, offsets: [0], bytes }\n\n // offsets[i] is the byte position where line `i` starts. offsets[lineCount] is one-past-end.\n // For \"a\\nb\\nc\" → offsets=[0, 2, 4, 5] (3 lines).\n // For \"a\\nb\\n\" → offsets=[0, 2, 4, 4] (3 lines, last is the trailing empty line). This\n // mirrors `String.prototype.split('\\n')` semantics so streaming and eager agree.\n const offsets: number[] = [0]\n let position = 0\n let lastByte = -1\n const reader = file.stream().getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n for (const byte of value) {\n position++\n if (byte === LF) offsets.push(position)\n lastByte = byte\n }\n }\n } finally {\n reader.releaseLock()\n }\n // If the file ends on a newline, the byte after the LF is the start of an empty trailing\n // line — record it. If it doesn't, the final line's end is the EOF and we need to push\n // it so line(N-1) can read up to bytes.\n if (lastByte === LF) offsets.push(position)\n else if (offsets[offsets.length - 1] !== position) offsets.push(position)\n return { mode: 'streaming', file, offsets, bytes }\n }\n\n /**\n * Slices the byte range `[start, end)` from the backing file and returns it as a UTF-8\n * string, stripping a trailing `\\n` if present.\n *\n * @remarks\n * `Blob.slice` is O(1) metadata; `Blob.text()` only decodes the slice. The line-offset index\n * brackets each line *with* its trailing LF (so `offsets[i+1]` points at the start of the\n * next line) and the `SpoolReader` contract returns lines *without* their trailing newline,\n * so we strip a single trailing LF if present.\n */\n async #readRange(file: OpfsFile, start: number, end: number): Promise<string> {\n if (start === end) return ''\n const slice = file.slice(start, end)\n const text = await slice.text()\n if (text.length > 0 && text.charCodeAt(text.length - 1) === LF) {\n return text.slice(0, -1)\n }\n return text\n }\n}\n\n/**\n * Constructor options for {@link OpfsSpoolStore}.\n */\nexport interface OpfsSpoolStoreOptions {\n /**\n * Optional thunk that resolves the {@link OpfsDirectoryHandle} used as the store root.\n *\n * @remarks\n * When omitted, the store resolves the root via `navigator.storage.getDirectory()` on its\n * first filesystem call. Override for tests (to point at a per-suite subdirectory) or to\n * scope the store to a nested directory inside OPFS.\n *\n * The thunk is invoked at most once per store; the returned handle is memoised.\n */\n directory?: () => Promise<OpfsDirectoryHandle>\n\n /**\n * Optional filename prefix prepended to every `callId`.\n *\n * @remarks\n * Prefix is a **filename prefix**, not a subdirectory — `keyPrefix: 'agent-runs/'` produces\n * a file literally named `agent-runs/<callId>` at the root, not a nested directory. (OPFS\n * filenames may not contain `/`, so use a non-`/` separator like `-` if you want a flat\n * namespace.) This mirrors the `keyPrefix` semantics in the flydrive and in-memory batteries.\n *\n * @defaultValue `\"\"`\n */\n keyPrefix?: string\n\n /**\n * Default `streamThresholdBytes` for readers produced by `write()` and `read()`. Individual\n * calls may override via their own `opts` argument.\n *\n * @defaultValue `10 * 1024 * 1024` (10 MiB)\n */\n streamThresholdBytes?: number\n}\n\n/**\n * \"Give bytes, get a reader\" persistence layer over an OPFS directory.\n *\n * @remarks\n * `write(callId, bytes)` resolves the root directory (lazily, on first call), opens or creates\n * the file named `keyPrefix + callId`, then writes via the API matching the current scope:\n * a `FileSystemSyncAccessHandle` in worker scopes, `OpfsFileHandle.createWritable()` on\n * the main thread. A fresh {@link OpfsSpoolReader} pointed at the same file is returned.\n *\n * `read(callId)` returns a reader without re-writing; `delete(callId)` removes the entry.\n *\n * The store is otherwise stateless — it owns no in-memory cache of writes. Multiple\n * `OpfsSpoolStore` instances sharing the same root directory and key prefix see the same data.\n *\n * @example\n * ```ts\n * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'\n *\n * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })\n *\n * const bytes = await tool.executor(ctx)(args)\n * const reader = await store.write(callId, bytes)\n * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact\n * const artifact = new Ctor(reader)\n * ```\n */\nexport class OpfsSpoolStore implements SpoolStore {\n readonly #resolveRoot: () => Promise<OpfsDirectoryHandle>\n readonly #prefix: string\n readonly #defaultThreshold: number\n #root: OpfsDirectoryHandle | undefined\n\n constructor(opts: OpfsSpoolStoreOptions = {}) {\n this.#resolveRoot = opts.directory ?? (() => navigator.storage.getDirectory())\n this.#prefix = opts.keyPrefix ?? ''\n this.#defaultThreshold = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES\n }\n\n /**\n * Returns `true` if `value` is an {@link OpfsSpoolStore} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is an {@link OpfsSpoolStore} instance.\n */\n public static isOpfsSpoolStore(value: unknown): value is OpfsSpoolStore {\n return isInstanceOf(value, 'OpfsSpoolStore', OpfsSpoolStore)\n }\n\n /**\n * Persists `bytes` under `callId` and returns a reader bound to the stored key.\n *\n * @remarks\n * `string` input is encoded as UTF-8; `Uint8Array` is stored byte-faithfully;\n * `ReadableStream<Uint8Array>` is written incrementally — the stream is consumed chunk-by-chunk\n * straight to OPFS without first materializing the whole payload in memory, which is the point\n * of accepting a stream for a durable store.\n *\n * @param callId - Identifier used to retrieve the bytes via {@link OpfsSpoolStore.read}.\n * @param bytes - The bytes to store, as a `string`, `Uint8Array`, or `ReadableStream<Uint8Array>`.\n * @param opts - Per-call override for `streamThresholdBytes`.\n * @returns An {@link OpfsSpoolReader} over the stored bytes.\n */\n async write(\n callId: string,\n bytes: string | Uint8Array | ReadableStream<Uint8Array>,\n opts?: OpfsSpoolReaderOptions\n ): Promise<OpfsSpoolReader> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n const handle = await root.getFileHandle(name, { create: true })\n if (isInstanceOf(bytes, 'ReadableStream', ReadableStream)) {\n if (isWorkerScope()) {\n await this.#writeStreamViaSyncHandle(handle, bytes)\n } else {\n await this.#writeStreamViaWritable(handle, bytes)\n }\n } else {\n const payload = typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes\n if (isWorkerScope()) {\n await this.#writeViaSyncHandle(handle, payload)\n } else {\n await this.#writeViaWritable(handle, payload)\n }\n }\n return new OpfsSpoolReader(handle, {\n streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold,\n })\n }\n\n /**\n * Returns a reader over the bytes previously written under `callId`.\n *\n * @remarks\n * Returns `undefined` if the file does not exist.\n *\n * @param callId - Identifier supplied to a prior {@link OpfsSpoolStore.write} call.\n * @param opts - Per-call override for `streamThresholdBytes`.\n * @returns An {@link OpfsSpoolReader}, or `undefined` if the key is missing.\n */\n async read(callId: string, opts?: OpfsSpoolReaderOptions): Promise<OpfsSpoolReader | undefined> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n let handle: OpfsFileHandle\n try {\n handle = await root.getFileHandle(name)\n } catch (err) {\n if (this.#isNotFoundError(err)) return undefined\n throw err\n }\n return new OpfsSpoolReader(handle, {\n streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold,\n })\n }\n\n /**\n * Removes the entry under `callId`.\n *\n * @param callId - Identifier whose entry should be removed.\n * @returns `true` if the entry existed and was removed; `false` if it didn't exist.\n */\n async delete(callId: string): Promise<boolean> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n try {\n await root.removeEntry(name)\n return true\n } catch (err) {\n if (this.#isNotFoundError(err)) return false\n throw err\n }\n }\n\n /**\n * Returns `true` if a file is present under `callId`.\n *\n * @param callId - Identifier to test.\n * @returns `true` when the file exists, `false` otherwise.\n */\n async has(callId: string): Promise<boolean> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n try {\n await root.getFileHandle(name)\n return true\n } catch (err) {\n if (this.#isNotFoundError(err)) return false\n throw err\n }\n }\n\n /**\n * Returns the full filename for a given `callId` (i.e. `keyPrefix + callId`).\n *\n * @remarks\n * Useful for tests or for callers that want to interact with the underlying OPFS directory\n * directly.\n */\n keyFor(callId: string): string {\n return this.#keyFor(callId)\n }\n\n #keyFor(callId: string): string {\n return this.#prefix + callId\n }\n\n async #getRoot(): Promise<OpfsDirectoryHandle> {\n if (!this.#root) this.#root = await this.#resolveRoot()\n return this.#root\n }\n\n async #writeViaSyncHandle(handle: OpfsFileHandle, payload: Uint8Array): Promise<void> {\n const sync = await (handle as OpfsFileHandleWithSyncAccess).createSyncAccessHandle()\n try {\n sync.truncate(0)\n sync.write(payload, { at: 0 })\n sync.flush()\n } finally {\n sync.close()\n }\n }\n\n async #writeViaWritable(handle: OpfsFileHandle, payload: Uint8Array): Promise<void> {\n const writable = await handle.createWritable()\n try {\n await writable.write(payload)\n } finally {\n await writable.close()\n }\n }\n\n async #writeStreamViaWritable(\n handle: OpfsFileHandle,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const writable = await handle.createWritable()\n try {\n const reader = stream.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value) await writable.write(value)\n }\n } finally {\n reader.releaseLock()\n }\n } finally {\n await writable.close()\n }\n }\n\n async #writeStreamViaSyncHandle(\n handle: OpfsFileHandle,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const sync = await (handle as OpfsFileHandleWithSyncAccess).createSyncAccessHandle()\n try {\n sync.truncate(0)\n let at = 0\n const reader = stream.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value && value.byteLength > 0) {\n sync.write(value, { at })\n at += value.byteLength\n }\n }\n } finally {\n reader.releaseLock()\n }\n sync.flush()\n } finally {\n sync.close()\n }\n }\n\n #isNotFoundError(err: unknown): boolean {\n if (err === null || typeof err !== 'object') return false\n const name = (err as { name?: unknown }).name\n return name === 'NotFoundError'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsJA,IAAM,iCAAiC,KAAK,OAAO;AAEnD,IAAM,KAAK;AAEX,IAAM,6BAA6B,MACjC,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,KAAK;;;;;;;;;;;;AAoDtD,IAAM,sB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C,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI;IACF,SAAS;KACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,OAAO,MAAM,SAAS,MAAM,KAAK;IACvC;GACF,UAAU;IACR,OAAO,YAAY;GACrB;EACF,UAAU;GACR,MAAM,SAAS,MAAM;EACvB;CACF;CAEA,MAAMD,0BACJ,QACA,QACe;EACf,MAAM,OAAO,MAAO,OAAwC,uBAAuB;EACnF,IAAI;GACF,KAAK,SAAS,CAAC;GACf,IAAI,KAAK;GACT,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI;IACF,SAAS;KACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,SAAS,MAAM,aAAa,GAAG;MACjC,KAAK,MAAM,OAAO,EAAE,GAAG,CAAC;MACxB,MAAM,MAAM;KACd;IACF;GACF,UAAU;IACR,OAAO,YAAY;GACrB;GACA,KAAK,MAAM;EACb,UAAU;GACR,KAAK,MAAM;EACb;CACF;CAEA,iBAAiB,KAAuB;EACtC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU,OAAO;EAEpD,OADc,IAA2B,SACzB;CAClB;AACF"}
1
+ {"version":3,"file":"opfs.cjs","names":["#handle","#threshold","#load","#readRange","#ready","#init","#buildStreamingIndex","#resolveRoot","#prefix","#defaultThreshold","#keyFor","#getRoot","#writeStreamViaSyncHandle","#writeStreamViaWritable","#writeViaSyncHandle","#writeViaWritable","#isNotFoundError","#root"],"sources":["../../../src/batteries/storage/opfs/index.ts"],"sourcesContent":["/**\n * Browser-only Origin Private File System storage for spooled artifacts.\n *\n * @module @nhtio/adk/batteries/storage/opfs\n *\n * @remarks\n * Opt-in **browser-only** storage battery backed by the\n * [Origin Private File System](https://developer.mozilla.org/docs/Web/API/File_System_API/Origin_private_file_system)\n * (OPFS). Provides {@link OpfsSpoolReader} (a {@link @nhtio/adk!SpoolReader} over a `OpfsFileHandle`)\n * and {@link OpfsSpoolStore} (a `write(callId, bytes) → reader` persistence layer that wraps an\n * OPFS directory).\n *\n * The reader has two modes selected lazily on first method invocation based on the size of the\n * underlying file:\n *\n * - **Eager mode** — when `file.size` is below `streamThresholdBytes` (default 10 MiB), the\n * reader calls `file.text()` once, splits the content on `\\n`, and caches lines + byte count.\n * All subsequent calls resolve from memory.\n * - **Streaming mode** — when `file.size` meets or exceeds the threshold, the reader streams the\n * file once via `file.stream().getReader()` to build a line-offset index (`number[]` of byte\n * offsets per line), then serves each `line(i)` request by slicing the underlying `Blob` —\n * `Blob.slice(start, end).text()` decodes only the requested range, no head-of-file scan.\n * Caps RAM at one index + one line buffer regardless of file size.\n *\n * The store auto-selects its write API by execution scope:\n *\n * - In **worker scopes** (`self instanceof WorkerGlobalScope`), it acquires a\n * `FileSystemSyncAccessHandle` and writes synchronously. Sync handles are the only API\n * available in workers and the fastest path for the spool-write hot path.\n * - On the **main thread**, it uses `OpfsFileHandle.createWritable()` and the async\n * stream API. Sync access handles are not exposed on the main thread.\n *\n * This module assumes a browser-equivalent runtime — `navigator.storage`,\n * `OpfsFileHandle`, `TextEncoder`/`TextDecoder`, and `Blob` must all exist. It must not\n * be imported from Node code; do so and you will fail at resolve time when `navigator` is\n * referenced.\n *\n * @example\n * ```ts\n * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'\n *\n * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })\n * const reader = await store.write(callId, bytes)\n * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact\n * const artifact = new Ctor(reader)\n * ```\n */\n\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport type { SpoolReader, SpoolStore } from '@nhtio/adk/common'\n\n// The project's tsconfig limits `lib` to `ESNext`, so the DOM and File System Access types\n// referenced below are not in scope by default — neither `tsc --noEmit` nor the downstream dts\n// pipeline (api-extractor) can see them. Re-declare here the **minimum** surface this module\n// touches via a local handle-shape interface. Public API uses `OpfsFileHandle` /\n// `OpfsDirectoryHandle` instead of the DOM globals so the published `.d.ts` is self-contained\n// and consumers do not have to chase the lib graph.\n\n/**\n * Minimal subset of the\n * [File System Access](https://developer.mozilla.org/docs/Web/API/File_System_API)\n * `OpfsFileHandle` interface that this module touches at runtime. Structurally compatible\n * with the DOM-lib `OpfsFileHandle` — at call sites you pass real OPFS handles directly.\n */\nexport interface OpfsFileHandle {\n /** Discriminant: always `'file'`. */\n readonly kind: 'file'\n /** The entry's name. */\n readonly name: string\n /** Resolve a readable {@link OpfsFile} snapshot of the handle's contents. */\n getFile(): Promise<OpfsFile>\n /** Open a writable stream that replaces the file's contents. */\n createWritable(): Promise<OpfsWritableFileStream>\n}\n\n/**\n * Minimal subset of the\n * [File System Access](https://developer.mozilla.org/docs/Web/API/File_System_API)\n * `OpfsDirectoryHandle` interface that this module touches at runtime. Structurally\n * compatible with the DOM-lib `OpfsDirectoryHandle` — at call sites you pass real OPFS\n * handles directly.\n */\nexport interface OpfsDirectoryHandle {\n /** Discriminant: always `'directory'`. */\n readonly kind: 'directory'\n /** The directory's name. */\n readonly name: string\n /** Resolve a child file handle, optionally creating it. */\n getFileHandle(name: string, options?: { create?: boolean }): Promise<OpfsFileHandle>\n /** Resolve a child directory handle, optionally creating it. */\n getDirectoryHandle(name: string, options?: { create?: boolean }): Promise<OpfsDirectoryHandle>\n /** Remove a child entry, optionally recursively. */\n removeEntry(name: string, options?: { recursive?: boolean }): Promise<void>\n}\n\n/**\n * Minimal subset of the DOM `FileSystemWritableFileStream` interface used by the OPFS battery's\n * main-thread write path.\n */\nexport interface OpfsWritableFileStream {\n /** Append/write a chunk to the stream. */\n write(data: Uint8Array | ArrayBufferView | ArrayBuffer | string): Promise<void>\n /** Flush and close the stream, committing the written contents. */\n close(): Promise<void>\n}\n\n/**\n * Minimal subset of the DOM `Blob` interface used by {@link OpfsSpoolReader} streaming-mode\n * random-access reads. Real OPFS handles return a `File` here; we narrow to the methods we\n * actually call.\n */\nexport interface OpfsBlob {\n /** Byte length of the blob. */\n readonly size: number\n /** Return a sub-range of the blob as a new blob. */\n slice(start?: number, end?: number, contentType?: string): OpfsBlob\n /** Read the blob's contents as text. */\n text(): Promise<string>\n /** Open a readable byte stream over the blob. */\n stream(): OpfsReadableStream\n}\n\n/**\n * Minimal subset of the DOM `File` interface used by {@link OpfsSpoolReader}.\n */\nexport interface OpfsFile extends OpfsBlob {\n /** The file's name. */\n readonly name: string\n}\n\n/**\n * Minimal subset of the DOM `ReadableStream<Uint8Array>` interface used by streaming-mode\n * index construction.\n */\nexport interface OpfsReadableStream {\n /** Acquire a reader over the stream. */\n getReader(): OpfsReadableStreamReader\n}\n\n/**\n * Minimal subset of the DOM `ReadableStreamDefaultReader<Uint8Array>` interface used by\n * streaming-mode index construction.\n */\nexport interface OpfsReadableStreamReader {\n /** Read the next chunk, or signal end-of-stream with `done: true`. */\n read(): Promise<{ done: false; value: Uint8Array } | { done: true; value: undefined }>\n /** Release the reader's lock on the stream. */\n releaseLock(): void\n}\n\ndeclare const navigator: {\n storage: { getDirectory(): Promise<OpfsDirectoryHandle> }\n}\ndeclare class TextEncoder {\n encode(input?: string): Uint8Array\n}\ndeclare const self: unknown\ndeclare const WorkerGlobalScope: { new (): unknown } | undefined\n\ninterface FileSystemSyncAccessHandle {\n truncate(newSize: number): void\n write(buffer: Uint8Array | ArrayBuffer | ArrayBufferView, options?: { at?: number }): number\n flush(): void\n close(): void\n}\ninterface OpfsFileHandleWithSyncAccess extends OpfsFileHandle {\n createSyncAccessHandle(): Promise<FileSystemSyncAccessHandle>\n}\n\nconst DEFAULT_STREAM_THRESHOLD_BYTES = 10 * 1024 * 1024 // 10 MiB\n\nconst LF = 0x0a // '\\n'\n\nconst isNonNegativeFiniteNumber = (n: unknown): n is number =>\n typeof n === 'number' && Number.isFinite(n) && n >= 0\n\n/**\n * Constructor options for {@link OpfsSpoolReader}.\n */\nexport interface OpfsSpoolReaderOptions {\n /**\n * Byte-length threshold that switches between eager and streaming modes.\n *\n * @remarks\n * - Below the threshold → eager (whole-file in memory).\n * - At or above the threshold → streaming (line-offset index + per-line slice reads).\n *\n * Set to `0` to force streaming mode; set to `Number.POSITIVE_INFINITY` to force eager mode.\n *\n * @defaultValue `10 * 1024 * 1024` (10 MiB)\n */\n streamThresholdBytes?: number\n}\n\ninterface EagerState {\n mode: 'eager'\n lines: string[]\n bytes: number\n content: string\n}\n\ninterface StreamingState {\n mode: 'streaming'\n file: OpfsFile\n /**\n * Byte offsets where each line *starts*. Length equals lineCount + 1; the final entry equals\n * the total byte length. So `offsets[i + 1] - offsets[i]` is the byte length of line `i`\n * including any trailing `\\n`.\n */\n offsets: number[]\n bytes: number\n}\n\ntype ReaderState = EagerState | StreamingState\n\n/**\n * Returns `true` when the current global scope is a Web Worker (`DedicatedWorkerGlobalScope`,\n * `SharedWorkerGlobalScope`, or `ServiceWorkerGlobalScope` all inherit from `WorkerGlobalScope`).\n *\n * @remarks\n * The check is needed at runtime because `FileSystemSyncAccessHandle` is only exposed in worker\n * scopes — calling it from the main thread throws. We pick the write strategy based on the\n * answer here.\n *\n * @internal\n */\nconst isWorkerScope = (): boolean => {\n if (typeof WorkerGlobalScope === 'undefined') return false\n // eslint-disable-next-line adk/use-is-instance-of -- native built-in narrowing on `self`; no cross-realm risk\n return self instanceof WorkerGlobalScope\n}\n\n/**\n * Reads an OPFS-backed file as a {@link @nhtio/adk!SpoolReader}.\n *\n * @remarks\n * Constructor is **not** async — but the first method call awaits a private readiness promise\n * that fetches the underlying `File` (and in eager mode, its contents). Subsequent calls reuse\n * the cached state. This keeps construction call sites synchronous while still doing real I/O\n * lazily.\n *\n * All four `SpoolReader` methods on this reader return promises. The `SpoolReader` contract\n * supports both sync and async return; consumers of `SpooledArtifact` handle either.\n */\nexport class OpfsSpoolReader implements SpoolReader {\n readonly #handle: OpfsFileHandle\n readonly #threshold: number\n #ready: Promise<ReaderState> | undefined\n\n constructor(handle: OpfsFileHandle, opts: OpfsSpoolReaderOptions = {}) {\n this.#handle = handle\n const raw = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES\n // Allow `Infinity` (forces eager) but reject anything non-finite-negative.\n if (typeof raw !== 'number' || Number.isNaN(raw) || raw < 0) {\n throw new TypeError(\n `OpfsSpoolReader: streamThresholdBytes must be a non-negative number or Infinity, got ${String(raw)}`\n )\n }\n this.#threshold = raw\n }\n\n /**\n * Returns `true` if `value` is an {@link OpfsSpoolReader} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is an {@link OpfsSpoolReader} instance.\n */\n public static isOpfsSpoolReader(value: unknown): value is OpfsSpoolReader {\n return isInstanceOf(value, 'OpfsSpoolReader', OpfsSpoolReader)\n }\n\n async line(index: number): Promise<string | undefined> {\n const state = await this.#load()\n if (state.mode === 'eager') return state.lines[index]\n if (index < 0 || index >= state.offsets.length - 1) return undefined\n return this.#readRange(state.file, state.offsets[index], state.offsets[index + 1])\n }\n\n async byteLength(): Promise<number> {\n const state = await this.#load()\n return state.bytes\n }\n\n async lineCount(): Promise<number> {\n const state = await this.#load()\n return state.mode === 'eager' ? state.lines.length : state.offsets.length - 1\n }\n\n /**\n * Returns the full underlying content as a single decoded string, byte-faithful to the source.\n *\n * @remarks\n * In **eager mode** the content is already cached at first-call load and this method is\n * effectively a property access. In **streaming mode** there is no cache: the file is re-read\n * (as a single `File.text()` call) on every invocation. Use `SpooledArtifact.asString()`\n * judiciously on large streaming-mode artifacts.\n */\n async readAll(): Promise<string> {\n const state = await this.#load()\n if (state.mode === 'eager') return state.content\n return state.file.text()\n }\n\n /**\n * Lazily initialise the reader's mode-specific state. Called by every public method; the\n * promise is cached so the work runs at most once.\n */\n #load(): Promise<ReaderState> {\n if (!this.#ready) this.#ready = this.#init()\n return this.#ready\n }\n\n async #init(): Promise<ReaderState> {\n const file = await this.#handle.getFile()\n const bytes = file.size\n if (!isNonNegativeFiniteNumber(bytes)) {\n throw new Error(`OpfsSpoolReader: file handle returned a non-finite size (${String(bytes)})`)\n }\n if (bytes < this.#threshold) {\n // Eager — pull the whole thing into memory.\n const content = await file.text()\n const lines = content === '' ? [] : content.split('\\n')\n return { mode: 'eager', lines, bytes, content }\n }\n // Streaming — build a line-offset index by scanning bytes once.\n return this.#buildStreamingIndex(file, bytes)\n }\n\n async #buildStreamingIndex(file: OpfsFile, bytes: number): Promise<StreamingState> {\n // Edge case first — an empty file is one offset (the EOF), zero lines.\n if (bytes === 0) return { mode: 'streaming', file, offsets: [0], bytes }\n\n // offsets[i] is the byte position where line `i` starts. offsets[lineCount] is one-past-end.\n // For \"a\\nb\\nc\" → offsets=[0, 2, 4, 5] (3 lines).\n // For \"a\\nb\\n\" → offsets=[0, 2, 4, 4] (3 lines, last is the trailing empty line). This\n // mirrors `String.prototype.split('\\n')` semantics so streaming and eager agree.\n const offsets: number[] = [0]\n let position = 0\n let lastByte = -1\n const reader = file.stream().getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n for (const byte of value) {\n position++\n if (byte === LF) offsets.push(position)\n lastByte = byte\n }\n }\n } finally {\n reader.releaseLock()\n }\n // If the file ends on a newline, the byte after the LF is the start of an empty trailing\n // line — record it. If it doesn't, the final line's end is the EOF and we need to push\n // it so line(N-1) can read up to bytes.\n if (lastByte === LF) offsets.push(position)\n else if (offsets[offsets.length - 1] !== position) offsets.push(position)\n return { mode: 'streaming', file, offsets, bytes }\n }\n\n /**\n * Slices the byte range `[start, end)` from the backing file and returns it as a UTF-8\n * string, stripping a trailing `\\n` if present.\n *\n * @remarks\n * `Blob.slice` is O(1) metadata; `Blob.text()` only decodes the slice. The line-offset index\n * brackets each line *with* its trailing LF (so `offsets[i+1]` points at the start of the\n * next line) and the `SpoolReader` contract returns lines *without* their trailing newline,\n * so we strip a single trailing LF if present.\n */\n async #readRange(file: OpfsFile, start: number, end: number): Promise<string> {\n if (start === end) return ''\n const slice = file.slice(start, end)\n const text = await slice.text()\n if (text.length > 0 && text.charCodeAt(text.length - 1) === LF) {\n return text.slice(0, -1)\n }\n return text\n }\n}\n\n/**\n * Constructor options for {@link OpfsSpoolStore}.\n */\nexport interface OpfsSpoolStoreOptions {\n /**\n * Optional thunk that resolves the {@link OpfsDirectoryHandle} used as the store root.\n *\n * @remarks\n * When omitted, the store resolves the root via `navigator.storage.getDirectory()` on its\n * first filesystem call. Override for tests (to point at a per-suite subdirectory) or to\n * scope the store to a nested directory inside OPFS.\n *\n * The thunk is invoked at most once per store; the returned handle is memoised.\n */\n directory?: () => Promise<OpfsDirectoryHandle>\n\n /**\n * Optional filename prefix prepended to every `callId`.\n *\n * @remarks\n * Prefix is a **filename prefix**, not a subdirectory — `keyPrefix: 'agent-runs/'` produces\n * a file literally named `agent-runs/<callId>` at the root, not a nested directory. (OPFS\n * filenames may not contain `/`, so use a non-`/` separator like `-` if you want a flat\n * namespace.) This mirrors the `keyPrefix` semantics in the flydrive and in-memory batteries.\n *\n * @defaultValue `\"\"`\n */\n keyPrefix?: string\n\n /**\n * Default `streamThresholdBytes` for readers produced by `write()` and `read()`. Individual\n * calls may override via their own `opts` argument.\n *\n * @defaultValue `10 * 1024 * 1024` (10 MiB)\n */\n streamThresholdBytes?: number\n}\n\n/**\n * \"Give bytes, get a reader\" persistence layer over an OPFS directory.\n *\n * @remarks\n * `write(callId, bytes)` resolves the root directory (lazily, on first call), opens or creates\n * the file named `keyPrefix + callId`, then writes via the API matching the current scope:\n * a `FileSystemSyncAccessHandle` in worker scopes, `OpfsFileHandle.createWritable()` on\n * the main thread. A fresh {@link OpfsSpoolReader} pointed at the same file is returned.\n *\n * `read(callId)` returns a reader without re-writing; `delete(callId)` removes the entry.\n *\n * The store is otherwise stateless — it owns no in-memory cache of writes. Multiple\n * `OpfsSpoolStore` instances sharing the same root directory and key prefix see the same data.\n *\n * @example\n * ```ts\n * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'\n *\n * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })\n *\n * const bytes = await tool.executor(ctx)(args)\n * const reader = await store.write(callId, bytes)\n * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact\n * const artifact = new Ctor(reader)\n * ```\n */\nexport class OpfsSpoolStore implements SpoolStore {\n readonly #resolveRoot: () => Promise<OpfsDirectoryHandle>\n readonly #prefix: string\n readonly #defaultThreshold: number\n #root: OpfsDirectoryHandle | undefined\n\n constructor(opts: OpfsSpoolStoreOptions = {}) {\n this.#resolveRoot = opts.directory ?? (() => navigator.storage.getDirectory())\n this.#prefix = opts.keyPrefix ?? ''\n this.#defaultThreshold = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES\n }\n\n /**\n * Returns `true` if `value` is an {@link OpfsSpoolStore} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is an {@link OpfsSpoolStore} instance.\n */\n public static isOpfsSpoolStore(value: unknown): value is OpfsSpoolStore {\n return isInstanceOf(value, 'OpfsSpoolStore', OpfsSpoolStore)\n }\n\n /**\n * Persists `bytes` under `callId` and returns a reader bound to the stored key.\n *\n * @remarks\n * `string` input is encoded as UTF-8; `Uint8Array` is stored byte-faithfully;\n * `ReadableStream<Uint8Array>` is written incrementally — the stream is consumed chunk-by-chunk\n * straight to OPFS without first materializing the whole payload in memory, which is the point\n * of accepting a stream for a durable store.\n *\n * @param callId - Identifier used to retrieve the bytes via {@link OpfsSpoolStore.read}.\n * @param bytes - The bytes to store, as a `string`, `Uint8Array`, or `ReadableStream<Uint8Array>`.\n * @param opts - Per-call override for `streamThresholdBytes`.\n * @returns An {@link OpfsSpoolReader} over the stored bytes.\n */\n async write(\n callId: string,\n bytes: string | Uint8Array | ReadableStream<Uint8Array>,\n opts?: OpfsSpoolReaderOptions\n ): Promise<OpfsSpoolReader> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n const handle = await root.getFileHandle(name, { create: true })\n if (isInstanceOf(bytes, 'ReadableStream', ReadableStream)) {\n if (isWorkerScope()) {\n await this.#writeStreamViaSyncHandle(handle, bytes)\n } else {\n await this.#writeStreamViaWritable(handle, bytes)\n }\n } else {\n const payload = typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes\n if (isWorkerScope()) {\n await this.#writeViaSyncHandle(handle, payload)\n } else {\n await this.#writeViaWritable(handle, payload)\n }\n }\n return new OpfsSpoolReader(handle, {\n streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold,\n })\n }\n\n /**\n * Returns a reader over the bytes previously written under `callId`.\n *\n * @remarks\n * Returns `undefined` if the file does not exist.\n *\n * @param callId - Identifier supplied to a prior {@link OpfsSpoolStore.write} call.\n * @param opts - Per-call override for `streamThresholdBytes`.\n * @returns An {@link OpfsSpoolReader}, or `undefined` if the key is missing.\n */\n async read(callId: string, opts?: OpfsSpoolReaderOptions): Promise<OpfsSpoolReader | undefined> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n let handle: OpfsFileHandle\n try {\n handle = await root.getFileHandle(name)\n } catch (err) {\n if (this.#isNotFoundError(err)) return undefined\n throw err\n }\n return new OpfsSpoolReader(handle, {\n streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold,\n })\n }\n\n /**\n * Removes the entry under `callId`.\n *\n * @param callId - Identifier whose entry should be removed.\n * @returns `true` if the entry existed and was removed; `false` if it didn't exist.\n */\n async delete(callId: string): Promise<boolean> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n try {\n await root.removeEntry(name)\n return true\n } catch (err) {\n if (this.#isNotFoundError(err)) return false\n throw err\n }\n }\n\n /**\n * Returns `true` if a file is present under `callId`.\n *\n * @param callId - Identifier to test.\n * @returns `true` when the file exists, `false` otherwise.\n */\n async has(callId: string): Promise<boolean> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n try {\n await root.getFileHandle(name)\n return true\n } catch (err) {\n if (this.#isNotFoundError(err)) return false\n throw err\n }\n }\n\n /**\n * Returns the full filename for a given `callId` (i.e. `keyPrefix + callId`).\n *\n * @remarks\n * Useful for tests or for callers that want to interact with the underlying OPFS directory\n * directly.\n */\n keyFor(callId: string): string {\n return this.#keyFor(callId)\n }\n\n #keyFor(callId: string): string {\n return this.#prefix + callId\n }\n\n async #getRoot(): Promise<OpfsDirectoryHandle> {\n if (!this.#root) this.#root = await this.#resolveRoot()\n return this.#root\n }\n\n async #writeViaSyncHandle(handle: OpfsFileHandle, payload: Uint8Array): Promise<void> {\n const sync = await (handle as OpfsFileHandleWithSyncAccess).createSyncAccessHandle()\n try {\n sync.truncate(0)\n sync.write(payload, { at: 0 })\n sync.flush()\n } finally {\n sync.close()\n }\n }\n\n async #writeViaWritable(handle: OpfsFileHandle, payload: Uint8Array): Promise<void> {\n const writable = await handle.createWritable()\n try {\n await writable.write(payload)\n } finally {\n await writable.close()\n }\n }\n\n async #writeStreamViaWritable(\n handle: OpfsFileHandle,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const writable = await handle.createWritable()\n try {\n const reader = stream.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value) await writable.write(value)\n }\n } finally {\n reader.releaseLock()\n }\n } finally {\n await writable.close()\n }\n }\n\n async #writeStreamViaSyncHandle(\n handle: OpfsFileHandle,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const sync = await (handle as OpfsFileHandleWithSyncAccess).createSyncAccessHandle()\n try {\n sync.truncate(0)\n let at = 0\n const reader = stream.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value && value.byteLength > 0) {\n sync.write(value, { at })\n at += value.byteLength\n }\n }\n } finally {\n reader.releaseLock()\n }\n sync.flush()\n } finally {\n sync.close()\n }\n }\n\n #isNotFoundError(err: unknown): boolean {\n if (err === null || typeof err !== 'object') return false\n const name = (err as { name?: unknown }).name\n return name === 'NotFoundError'\n }\n}\n"],"mappings":";;;;;;;;;;;;;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B,SAAoC;EAClF,MAAM,WAAW,MAAM,OAAO,eAAe;EAC7C,IAAI;GACF,MAAM,SAAS,MAAM,OAAO;EAC9B,UAAU;GACR,MAAM,SAAS,MAAM;EACvB;CACF;CAEA,MAAMF,wBACJ,QACA,QACe;EACf,MAAM,WAAW,MAAM,OAAO,eAAe;EAC7C,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI;IACF,SAAS;KACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,OAAO,MAAM,SAAS,MAAM,KAAK;IACvC;GACF,UAAU;IACR,OAAO,YAAY;GACrB;EACF,UAAU;GACR,MAAM,SAAS,MAAM;EACvB;CACF;CAEA,MAAMD,0BACJ,QACA,QACe;EACf,MAAM,OAAO,MAAO,OAAwC,uBAAuB;EACnF,IAAI;GACF,KAAK,SAAS,CAAC;GACf,IAAI,KAAK;GACT,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI;IACF,SAAS;KACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,SAAS,MAAM,aAAa,GAAG;MACjC,KAAK,MAAM,OAAO,EAAE,GAAG,CAAC;MACxB,MAAM,MAAM;KACd;IACF;GACF,UAAU;IACR,OAAO,YAAY;GACrB;GACA,KAAK,MAAM;EACb,UAAU;GACR,KAAK,MAAM;EACb;CACF;CAEA,iBAAiB,KAAuB;EACtC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU,OAAO;EAEpD,OADc,IAA2B,SACzB;CAClB;AACF"}
@@ -1,4 +1,4 @@
1
- import { s as isInstanceOf } from "../../tool_registry-D1pSSlsd.mjs";
1
+ import { s as isInstanceOf } from "../../tool_registry-791Vrjtf.mjs";
2
2
  import "../../guards.mjs";
3
3
  //#region src/batteries/storage/opfs/index.ts
4
4
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"opfs.mjs","names":["#handle","#threshold","#load","#readRange","#ready","#init","#buildStreamingIndex","#resolveRoot","#prefix","#defaultThreshold","#keyFor","#getRoot","#writeStreamViaSyncHandle","#writeStreamViaWritable","#writeViaSyncHandle","#writeViaWritable","#isNotFoundError","#root"],"sources":["../../../src/batteries/storage/opfs/index.ts"],"sourcesContent":["/**\n * Browser-only Origin Private File System storage for spooled artifacts.\n *\n * @module @nhtio/adk/batteries/storage/opfs\n *\n * @remarks\n * Opt-in **browser-only** storage battery backed by the\n * [Origin Private File System](https://developer.mozilla.org/docs/Web/API/File_System_API/Origin_private_file_system)\n * (OPFS). Provides {@link OpfsSpoolReader} (a {@link @nhtio/adk!SpoolReader} over a `OpfsFileHandle`)\n * and {@link OpfsSpoolStore} (a `write(callId, bytes) → reader` persistence layer that wraps an\n * OPFS directory).\n *\n * The reader has two modes selected lazily on first method invocation based on the size of the\n * underlying file:\n *\n * - **Eager mode** — when `file.size` is below `streamThresholdBytes` (default 10 MiB), the\n * reader calls `file.text()` once, splits the content on `\\n`, and caches lines + byte count.\n * All subsequent calls resolve from memory.\n * - **Streaming mode** — when `file.size` meets or exceeds the threshold, the reader streams the\n * file once via `file.stream().getReader()` to build a line-offset index (`number[]` of byte\n * offsets per line), then serves each `line(i)` request by slicing the underlying `Blob` —\n * `Blob.slice(start, end).text()` decodes only the requested range, no head-of-file scan.\n * Caps RAM at one index + one line buffer regardless of file size.\n *\n * The store auto-selects its write API by execution scope:\n *\n * - In **worker scopes** (`self instanceof WorkerGlobalScope`), it acquires a\n * `FileSystemSyncAccessHandle` and writes synchronously. Sync handles are the only API\n * available in workers and the fastest path for the spool-write hot path.\n * - On the **main thread**, it uses `OpfsFileHandle.createWritable()` and the async\n * stream API. Sync access handles are not exposed on the main thread.\n *\n * This module assumes a browser-equivalent runtime — `navigator.storage`,\n * `OpfsFileHandle`, `TextEncoder`/`TextDecoder`, and `Blob` must all exist. It must not\n * be imported from Node code; do so and you will fail at resolve time when `navigator` is\n * referenced.\n *\n * @example\n * ```ts\n * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'\n *\n * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })\n * const reader = await store.write(callId, bytes)\n * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact\n * const artifact = new Ctor(reader)\n * ```\n */\n\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport type { SpoolReader, SpoolStore } from '@nhtio/adk/common'\n\n// The project's tsconfig limits `lib` to `ESNext`, so the DOM and File System Access types\n// referenced below are not in scope by default — neither `tsc --noEmit` nor the downstream dts\n// pipeline (api-extractor) can see them. Re-declare here the **minimum** surface this module\n// touches via a local handle-shape interface. Public API uses `OpfsFileHandle` /\n// `OpfsDirectoryHandle` instead of the DOM globals so the published `.d.ts` is self-contained\n// and consumers do not have to chase the lib graph.\n\n/**\n * Minimal subset of the\n * [File System Access](https://developer.mozilla.org/docs/Web/API/File_System_API)\n * `OpfsFileHandle` interface that this module touches at runtime. Structurally compatible\n * with the DOM-lib `OpfsFileHandle` — at call sites you pass real OPFS handles directly.\n */\nexport interface OpfsFileHandle {\n readonly kind: 'file'\n readonly name: string\n getFile(): Promise<OpfsFile>\n createWritable(): Promise<OpfsWritableFileStream>\n}\n\n/**\n * Minimal subset of the\n * [File System Access](https://developer.mozilla.org/docs/Web/API/File_System_API)\n * `OpfsDirectoryHandle` interface that this module touches at runtime. Structurally\n * compatible with the DOM-lib `OpfsDirectoryHandle` — at call sites you pass real OPFS\n * handles directly.\n */\nexport interface OpfsDirectoryHandle {\n readonly kind: 'directory'\n readonly name: string\n getFileHandle(name: string, options?: { create?: boolean }): Promise<OpfsFileHandle>\n getDirectoryHandle(name: string, options?: { create?: boolean }): Promise<OpfsDirectoryHandle>\n removeEntry(name: string, options?: { recursive?: boolean }): Promise<void>\n}\n\n/**\n * Minimal subset of the DOM `FileSystemWritableFileStream` interface used by the OPFS battery's\n * main-thread write path.\n */\nexport interface OpfsWritableFileStream {\n write(data: Uint8Array | ArrayBufferView | ArrayBuffer | string): Promise<void>\n close(): Promise<void>\n}\n\n/**\n * Minimal subset of the DOM `Blob` interface used by {@link OpfsSpoolReader} streaming-mode\n * random-access reads. Real OPFS handles return a `File` here; we narrow to the methods we\n * actually call.\n */\nexport interface OpfsBlob {\n readonly size: number\n slice(start?: number, end?: number, contentType?: string): OpfsBlob\n text(): Promise<string>\n stream(): OpfsReadableStream\n}\n\n/**\n * Minimal subset of the DOM `File` interface used by {@link OpfsSpoolReader}.\n */\nexport interface OpfsFile extends OpfsBlob {\n readonly name: string\n}\n\n/**\n * Minimal subset of the DOM `ReadableStream<Uint8Array>` interface used by streaming-mode\n * index construction.\n */\nexport interface OpfsReadableStream {\n getReader(): OpfsReadableStreamReader\n}\n\n/**\n * Minimal subset of the DOM `ReadableStreamDefaultReader<Uint8Array>` interface used by\n * streaming-mode index construction.\n */\nexport interface OpfsReadableStreamReader {\n read(): Promise<{ done: false; value: Uint8Array } | { done: true; value: undefined }>\n releaseLock(): void\n}\n\ndeclare const navigator: {\n storage: { getDirectory(): Promise<OpfsDirectoryHandle> }\n}\ndeclare class TextEncoder {\n encode(input?: string): Uint8Array\n}\ndeclare const self: unknown\ndeclare const WorkerGlobalScope: { new (): unknown } | undefined\n\ninterface FileSystemSyncAccessHandle {\n truncate(newSize: number): void\n write(buffer: Uint8Array | ArrayBuffer | ArrayBufferView, options?: { at?: number }): number\n flush(): void\n close(): void\n}\ninterface OpfsFileHandleWithSyncAccess extends OpfsFileHandle {\n createSyncAccessHandle(): Promise<FileSystemSyncAccessHandle>\n}\n\nconst DEFAULT_STREAM_THRESHOLD_BYTES = 10 * 1024 * 1024 // 10 MiB\n\nconst LF = 0x0a // '\\n'\n\nconst isNonNegativeFiniteNumber = (n: unknown): n is number =>\n typeof n === 'number' && Number.isFinite(n) && n >= 0\n\n/**\n * Constructor options for {@link OpfsSpoolReader}.\n */\nexport interface OpfsSpoolReaderOptions {\n /**\n * Byte-length threshold that switches between eager and streaming modes.\n *\n * @remarks\n * - Below the threshold → eager (whole-file in memory).\n * - At or above the threshold → streaming (line-offset index + per-line slice reads).\n *\n * Set to `0` to force streaming mode; set to `Number.POSITIVE_INFINITY` to force eager mode.\n *\n * @defaultValue `10 * 1024 * 1024` (10 MiB)\n */\n streamThresholdBytes?: number\n}\n\ninterface EagerState {\n mode: 'eager'\n lines: string[]\n bytes: number\n content: string\n}\n\ninterface StreamingState {\n mode: 'streaming'\n file: OpfsFile\n /**\n * Byte offsets where each line *starts*. Length equals lineCount + 1; the final entry equals\n * the total byte length. So `offsets[i + 1] - offsets[i]` is the byte length of line `i`\n * including any trailing `\\n`.\n */\n offsets: number[]\n bytes: number\n}\n\ntype ReaderState = EagerState | StreamingState\n\n/**\n * Returns `true` when the current global scope is a Web Worker (`DedicatedWorkerGlobalScope`,\n * `SharedWorkerGlobalScope`, or `ServiceWorkerGlobalScope` all inherit from `WorkerGlobalScope`).\n *\n * @remarks\n * The check is needed at runtime because `FileSystemSyncAccessHandle` is only exposed in worker\n * scopes — calling it from the main thread throws. We pick the write strategy based on the\n * answer here.\n *\n * @internal\n */\nconst isWorkerScope = (): boolean => {\n if (typeof WorkerGlobalScope === 'undefined') return false\n // eslint-disable-next-line adk/use-is-instance-of -- native built-in narrowing on `self`; no cross-realm risk\n return self instanceof WorkerGlobalScope\n}\n\n/**\n * Reads an OPFS-backed file as a {@link @nhtio/adk!SpoolReader}.\n *\n * @remarks\n * Constructor is **not** async — but the first method call awaits a private readiness promise\n * that fetches the underlying `File` (and in eager mode, its contents). Subsequent calls reuse\n * the cached state. This keeps construction call sites synchronous while still doing real I/O\n * lazily.\n *\n * All four `SpoolReader` methods on this reader return promises. The `SpoolReader` contract\n * supports both sync and async return; consumers of `SpooledArtifact` handle either.\n */\nexport class OpfsSpoolReader implements SpoolReader {\n readonly #handle: OpfsFileHandle\n readonly #threshold: number\n #ready: Promise<ReaderState> | undefined\n\n constructor(handle: OpfsFileHandle, opts: OpfsSpoolReaderOptions = {}) {\n this.#handle = handle\n const raw = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES\n // Allow `Infinity` (forces eager) but reject anything non-finite-negative.\n if (typeof raw !== 'number' || Number.isNaN(raw) || raw < 0) {\n throw new TypeError(\n `OpfsSpoolReader: streamThresholdBytes must be a non-negative number or Infinity, got ${String(raw)}`\n )\n }\n this.#threshold = raw\n }\n\n /**\n * Returns `true` if `value` is an {@link OpfsSpoolReader} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is an {@link OpfsSpoolReader} instance.\n */\n public static isOpfsSpoolReader(value: unknown): value is OpfsSpoolReader {\n return isInstanceOf(value, 'OpfsSpoolReader', OpfsSpoolReader)\n }\n\n async line(index: number): Promise<string | undefined> {\n const state = await this.#load()\n if (state.mode === 'eager') return state.lines[index]\n if (index < 0 || index >= state.offsets.length - 1) return undefined\n return this.#readRange(state.file, state.offsets[index], state.offsets[index + 1])\n }\n\n async byteLength(): Promise<number> {\n const state = await this.#load()\n return state.bytes\n }\n\n async lineCount(): Promise<number> {\n const state = await this.#load()\n return state.mode === 'eager' ? state.lines.length : state.offsets.length - 1\n }\n\n /**\n * Returns the full underlying content as a single decoded string, byte-faithful to the source.\n *\n * @remarks\n * In **eager mode** the content is already cached at first-call load and this method is\n * effectively a property access. In **streaming mode** there is no cache: the file is re-read\n * (as a single `File.text()` call) on every invocation. Use `SpooledArtifact.asString()`\n * judiciously on large streaming-mode artifacts.\n */\n async readAll(): Promise<string> {\n const state = await this.#load()\n if (state.mode === 'eager') return state.content\n return state.file.text()\n }\n\n /**\n * Lazily initialise the reader's mode-specific state. Called by every public method; the\n * promise is cached so the work runs at most once.\n */\n #load(): Promise<ReaderState> {\n if (!this.#ready) this.#ready = this.#init()\n return this.#ready\n }\n\n async #init(): Promise<ReaderState> {\n const file = await this.#handle.getFile()\n const bytes = file.size\n if (!isNonNegativeFiniteNumber(bytes)) {\n throw new Error(`OpfsSpoolReader: file handle returned a non-finite size (${String(bytes)})`)\n }\n if (bytes < this.#threshold) {\n // Eager — pull the whole thing into memory.\n const content = await file.text()\n const lines = content === '' ? [] : content.split('\\n')\n return { mode: 'eager', lines, bytes, content }\n }\n // Streaming — build a line-offset index by scanning bytes once.\n return this.#buildStreamingIndex(file, bytes)\n }\n\n async #buildStreamingIndex(file: OpfsFile, bytes: number): Promise<StreamingState> {\n // Edge case first — an empty file is one offset (the EOF), zero lines.\n if (bytes === 0) return { mode: 'streaming', file, offsets: [0], bytes }\n\n // offsets[i] is the byte position where line `i` starts. offsets[lineCount] is one-past-end.\n // For \"a\\nb\\nc\" → offsets=[0, 2, 4, 5] (3 lines).\n // For \"a\\nb\\n\" → offsets=[0, 2, 4, 4] (3 lines, last is the trailing empty line). This\n // mirrors `String.prototype.split('\\n')` semantics so streaming and eager agree.\n const offsets: number[] = [0]\n let position = 0\n let lastByte = -1\n const reader = file.stream().getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n for (const byte of value) {\n position++\n if (byte === LF) offsets.push(position)\n lastByte = byte\n }\n }\n } finally {\n reader.releaseLock()\n }\n // If the file ends on a newline, the byte after the LF is the start of an empty trailing\n // line — record it. If it doesn't, the final line's end is the EOF and we need to push\n // it so line(N-1) can read up to bytes.\n if (lastByte === LF) offsets.push(position)\n else if (offsets[offsets.length - 1] !== position) offsets.push(position)\n return { mode: 'streaming', file, offsets, bytes }\n }\n\n /**\n * Slices the byte range `[start, end)` from the backing file and returns it as a UTF-8\n * string, stripping a trailing `\\n` if present.\n *\n * @remarks\n * `Blob.slice` is O(1) metadata; `Blob.text()` only decodes the slice. The line-offset index\n * brackets each line *with* its trailing LF (so `offsets[i+1]` points at the start of the\n * next line) and the `SpoolReader` contract returns lines *without* their trailing newline,\n * so we strip a single trailing LF if present.\n */\n async #readRange(file: OpfsFile, start: number, end: number): Promise<string> {\n if (start === end) return ''\n const slice = file.slice(start, end)\n const text = await slice.text()\n if (text.length > 0 && text.charCodeAt(text.length - 1) === LF) {\n return text.slice(0, -1)\n }\n return text\n }\n}\n\n/**\n * Constructor options for {@link OpfsSpoolStore}.\n */\nexport interface OpfsSpoolStoreOptions {\n /**\n * Optional thunk that resolves the {@link OpfsDirectoryHandle} used as the store root.\n *\n * @remarks\n * When omitted, the store resolves the root via `navigator.storage.getDirectory()` on its\n * first filesystem call. Override for tests (to point at a per-suite subdirectory) or to\n * scope the store to a nested directory inside OPFS.\n *\n * The thunk is invoked at most once per store; the returned handle is memoised.\n */\n directory?: () => Promise<OpfsDirectoryHandle>\n\n /**\n * Optional filename prefix prepended to every `callId`.\n *\n * @remarks\n * Prefix is a **filename prefix**, not a subdirectory — `keyPrefix: 'agent-runs/'` produces\n * a file literally named `agent-runs/<callId>` at the root, not a nested directory. (OPFS\n * filenames may not contain `/`, so use a non-`/` separator like `-` if you want a flat\n * namespace.) This mirrors the `keyPrefix` semantics in the flydrive and in-memory batteries.\n *\n * @defaultValue `\"\"`\n */\n keyPrefix?: string\n\n /**\n * Default `streamThresholdBytes` for readers produced by `write()` and `read()`. Individual\n * calls may override via their own `opts` argument.\n *\n * @defaultValue `10 * 1024 * 1024` (10 MiB)\n */\n streamThresholdBytes?: number\n}\n\n/**\n * \"Give bytes, get a reader\" persistence layer over an OPFS directory.\n *\n * @remarks\n * `write(callId, bytes)` resolves the root directory (lazily, on first call), opens or creates\n * the file named `keyPrefix + callId`, then writes via the API matching the current scope:\n * a `FileSystemSyncAccessHandle` in worker scopes, `OpfsFileHandle.createWritable()` on\n * the main thread. A fresh {@link OpfsSpoolReader} pointed at the same file is returned.\n *\n * `read(callId)` returns a reader without re-writing; `delete(callId)` removes the entry.\n *\n * The store is otherwise stateless — it owns no in-memory cache of writes. Multiple\n * `OpfsSpoolStore` instances sharing the same root directory and key prefix see the same data.\n *\n * @example\n * ```ts\n * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'\n *\n * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })\n *\n * const bytes = await tool.executor(ctx)(args)\n * const reader = await store.write(callId, bytes)\n * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact\n * const artifact = new Ctor(reader)\n * ```\n */\nexport class OpfsSpoolStore implements SpoolStore {\n readonly #resolveRoot: () => Promise<OpfsDirectoryHandle>\n readonly #prefix: string\n readonly #defaultThreshold: number\n #root: OpfsDirectoryHandle | undefined\n\n constructor(opts: OpfsSpoolStoreOptions = {}) {\n this.#resolveRoot = opts.directory ?? (() => navigator.storage.getDirectory())\n this.#prefix = opts.keyPrefix ?? ''\n this.#defaultThreshold = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES\n }\n\n /**\n * Returns `true` if `value` is an {@link OpfsSpoolStore} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is an {@link OpfsSpoolStore} instance.\n */\n public static isOpfsSpoolStore(value: unknown): value is OpfsSpoolStore {\n return isInstanceOf(value, 'OpfsSpoolStore', OpfsSpoolStore)\n }\n\n /**\n * Persists `bytes` under `callId` and returns a reader bound to the stored key.\n *\n * @remarks\n * `string` input is encoded as UTF-8; `Uint8Array` is stored byte-faithfully;\n * `ReadableStream<Uint8Array>` is written incrementally — the stream is consumed chunk-by-chunk\n * straight to OPFS without first materializing the whole payload in memory, which is the point\n * of accepting a stream for a durable store.\n *\n * @param callId - Identifier used to retrieve the bytes via {@link OpfsSpoolStore.read}.\n * @param bytes - The bytes to store, as a `string`, `Uint8Array`, or `ReadableStream<Uint8Array>`.\n * @param opts - Per-call override for `streamThresholdBytes`.\n * @returns An {@link OpfsSpoolReader} over the stored bytes.\n */\n async write(\n callId: string,\n bytes: string | Uint8Array | ReadableStream<Uint8Array>,\n opts?: OpfsSpoolReaderOptions\n ): Promise<OpfsSpoolReader> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n const handle = await root.getFileHandle(name, { create: true })\n if (isInstanceOf(bytes, 'ReadableStream', ReadableStream)) {\n if (isWorkerScope()) {\n await this.#writeStreamViaSyncHandle(handle, bytes)\n } else {\n await this.#writeStreamViaWritable(handle, bytes)\n }\n } else {\n const payload = typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes\n if (isWorkerScope()) {\n await this.#writeViaSyncHandle(handle, payload)\n } else {\n await this.#writeViaWritable(handle, payload)\n }\n }\n return new OpfsSpoolReader(handle, {\n streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold,\n })\n }\n\n /**\n * Returns a reader over the bytes previously written under `callId`.\n *\n * @remarks\n * Returns `undefined` if the file does not exist.\n *\n * @param callId - Identifier supplied to a prior {@link OpfsSpoolStore.write} call.\n * @param opts - Per-call override for `streamThresholdBytes`.\n * @returns An {@link OpfsSpoolReader}, or `undefined` if the key is missing.\n */\n async read(callId: string, opts?: OpfsSpoolReaderOptions): Promise<OpfsSpoolReader | undefined> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n let handle: OpfsFileHandle\n try {\n handle = await root.getFileHandle(name)\n } catch (err) {\n if (this.#isNotFoundError(err)) return undefined\n throw err\n }\n return new OpfsSpoolReader(handle, {\n streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold,\n })\n }\n\n /**\n * Removes the entry under `callId`.\n *\n * @param callId - Identifier whose entry should be removed.\n * @returns `true` if the entry existed and was removed; `false` if it didn't exist.\n */\n async delete(callId: string): Promise<boolean> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n try {\n await root.removeEntry(name)\n return true\n } catch (err) {\n if (this.#isNotFoundError(err)) return false\n throw err\n }\n }\n\n /**\n * Returns `true` if a file is present under `callId`.\n *\n * @param callId - Identifier to test.\n * @returns `true` when the file exists, `false` otherwise.\n */\n async has(callId: string): Promise<boolean> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n try {\n await root.getFileHandle(name)\n return true\n } catch (err) {\n if (this.#isNotFoundError(err)) return false\n throw err\n }\n }\n\n /**\n * Returns the full filename for a given `callId` (i.e. `keyPrefix + callId`).\n *\n * @remarks\n * Useful for tests or for callers that want to interact with the underlying OPFS directory\n * directly.\n */\n keyFor(callId: string): string {\n return this.#keyFor(callId)\n }\n\n #keyFor(callId: string): string {\n return this.#prefix + callId\n }\n\n async #getRoot(): Promise<OpfsDirectoryHandle> {\n if (!this.#root) this.#root = await this.#resolveRoot()\n return this.#root\n }\n\n async #writeViaSyncHandle(handle: OpfsFileHandle, payload: Uint8Array): Promise<void> {\n const sync = await (handle as OpfsFileHandleWithSyncAccess).createSyncAccessHandle()\n try {\n sync.truncate(0)\n sync.write(payload, { at: 0 })\n sync.flush()\n } finally {\n sync.close()\n }\n }\n\n async #writeViaWritable(handle: OpfsFileHandle, payload: Uint8Array): Promise<void> {\n const writable = await handle.createWritable()\n try {\n await writable.write(payload)\n } finally {\n await writable.close()\n }\n }\n\n async #writeStreamViaWritable(\n handle: OpfsFileHandle,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const writable = await handle.createWritable()\n try {\n const reader = stream.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value) await writable.write(value)\n }\n } finally {\n reader.releaseLock()\n }\n } finally {\n await writable.close()\n }\n }\n\n async #writeStreamViaSyncHandle(\n handle: OpfsFileHandle,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const sync = await (handle as OpfsFileHandleWithSyncAccess).createSyncAccessHandle()\n try {\n sync.truncate(0)\n let at = 0\n const reader = stream.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value && value.byteLength > 0) {\n sync.write(value, { at })\n at += value.byteLength\n }\n }\n } finally {\n reader.releaseLock()\n }\n sync.flush()\n } finally {\n sync.close()\n }\n }\n\n #isNotFoundError(err: unknown): boolean {\n if (err === null || typeof err !== 'object') return false\n const name = (err as { name?: unknown }).name\n return name === 'NotFoundError'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A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SAAS,MAAM,OAAO;EAC9B,UAAU;GACR,MAAM,SAAS,MAAM;EACvB;CACF;CAEA,MAAMF,wBACJ,QACA,QACe;EACf,MAAM,WAAW,MAAM,OAAO,eAAe;EAC7C,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI;IACF,SAAS;KACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,OAAO,MAAM,SAAS,MAAM,KAAK;IACvC;GACF,UAAU;IACR,OAAO,YAAY;GACrB;EACF,UAAU;GACR,MAAM,SAAS,MAAM;EACvB;CACF;CAEA,MAAMD,0BACJ,QACA,QACe;EACf,MAAM,OAAO,MAAO,OAAwC,uBAAuB;EACnF,IAAI;GACF,KAAK,SAAS,CAAC;GACf,IAAI,KAAK;GACT,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI;IACF,SAAS;KACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,SAAS,MAAM,aAAa,GAAG;MACjC,KAAK,MAAM,OAAO,EAAE,GAAG,CAAC;MACxB,MAAM,MAAM;KACd;IACF;GACF,UAAU;IACR,OAAO,YAAY;GACrB;GACA,KAAK,MAAM;EACb,UAAU;GACR,KAAK,MAAM;EACb;CACF;CAEA,iBAAiB,KAAuB;EACtC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU,OAAO;EAEpD,OADc,IAA2B,SACzB;CAClB;AACF"}
1
+ {"version":3,"file":"opfs.mjs","names":["#handle","#threshold","#load","#readRange","#ready","#init","#buildStreamingIndex","#resolveRoot","#prefix","#defaultThreshold","#keyFor","#getRoot","#writeStreamViaSyncHandle","#writeStreamViaWritable","#writeViaSyncHandle","#writeViaWritable","#isNotFoundError","#root"],"sources":["../../../src/batteries/storage/opfs/index.ts"],"sourcesContent":["/**\n * Browser-only Origin Private File System storage for spooled artifacts.\n *\n * @module @nhtio/adk/batteries/storage/opfs\n *\n * @remarks\n * Opt-in **browser-only** storage battery backed by the\n * [Origin Private File System](https://developer.mozilla.org/docs/Web/API/File_System_API/Origin_private_file_system)\n * (OPFS). Provides {@link OpfsSpoolReader} (a {@link @nhtio/adk!SpoolReader} over a `OpfsFileHandle`)\n * and {@link OpfsSpoolStore} (a `write(callId, bytes) → reader` persistence layer that wraps an\n * OPFS directory).\n *\n * The reader has two modes selected lazily on first method invocation based on the size of the\n * underlying file:\n *\n * - **Eager mode** — when `file.size` is below `streamThresholdBytes` (default 10 MiB), the\n * reader calls `file.text()` once, splits the content on `\\n`, and caches lines + byte count.\n * All subsequent calls resolve from memory.\n * - **Streaming mode** — when `file.size` meets or exceeds the threshold, the reader streams the\n * file once via `file.stream().getReader()` to build a line-offset index (`number[]` of byte\n * offsets per line), then serves each `line(i)` request by slicing the underlying `Blob` —\n * `Blob.slice(start, end).text()` decodes only the requested range, no head-of-file scan.\n * Caps RAM at one index + one line buffer regardless of file size.\n *\n * The store auto-selects its write API by execution scope:\n *\n * - In **worker scopes** (`self instanceof WorkerGlobalScope`), it acquires a\n * `FileSystemSyncAccessHandle` and writes synchronously. Sync handles are the only API\n * available in workers and the fastest path for the spool-write hot path.\n * - On the **main thread**, it uses `OpfsFileHandle.createWritable()` and the async\n * stream API. Sync access handles are not exposed on the main thread.\n *\n * This module assumes a browser-equivalent runtime — `navigator.storage`,\n * `OpfsFileHandle`, `TextEncoder`/`TextDecoder`, and `Blob` must all exist. It must not\n * be imported from Node code; do so and you will fail at resolve time when `navigator` is\n * referenced.\n *\n * @example\n * ```ts\n * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'\n *\n * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })\n * const reader = await store.write(callId, bytes)\n * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact\n * const artifact = new Ctor(reader)\n * ```\n */\n\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport type { SpoolReader, SpoolStore } from '@nhtio/adk/common'\n\n// The project's tsconfig limits `lib` to `ESNext`, so the DOM and File System Access types\n// referenced below are not in scope by default — neither `tsc --noEmit` nor the downstream dts\n// pipeline (api-extractor) can see them. Re-declare here the **minimum** surface this module\n// touches via a local handle-shape interface. Public API uses `OpfsFileHandle` /\n// `OpfsDirectoryHandle` instead of the DOM globals so the published `.d.ts` is self-contained\n// and consumers do not have to chase the lib graph.\n\n/**\n * Minimal subset of the\n * [File System Access](https://developer.mozilla.org/docs/Web/API/File_System_API)\n * `OpfsFileHandle` interface that this module touches at runtime. Structurally compatible\n * with the DOM-lib `OpfsFileHandle` — at call sites you pass real OPFS handles directly.\n */\nexport interface OpfsFileHandle {\n /** Discriminant: always `'file'`. */\n readonly kind: 'file'\n /** The entry's name. */\n readonly name: string\n /** Resolve a readable {@link OpfsFile} snapshot of the handle's contents. */\n getFile(): Promise<OpfsFile>\n /** Open a writable stream that replaces the file's contents. */\n createWritable(): Promise<OpfsWritableFileStream>\n}\n\n/**\n * Minimal subset of the\n * [File System Access](https://developer.mozilla.org/docs/Web/API/File_System_API)\n * `OpfsDirectoryHandle` interface that this module touches at runtime. Structurally\n * compatible with the DOM-lib `OpfsDirectoryHandle` — at call sites you pass real OPFS\n * handles directly.\n */\nexport interface OpfsDirectoryHandle {\n /** Discriminant: always `'directory'`. */\n readonly kind: 'directory'\n /** The directory's name. */\n readonly name: string\n /** Resolve a child file handle, optionally creating it. */\n getFileHandle(name: string, options?: { create?: boolean }): Promise<OpfsFileHandle>\n /** Resolve a child directory handle, optionally creating it. */\n getDirectoryHandle(name: string, options?: { create?: boolean }): Promise<OpfsDirectoryHandle>\n /** Remove a child entry, optionally recursively. */\n removeEntry(name: string, options?: { recursive?: boolean }): Promise<void>\n}\n\n/**\n * Minimal subset of the DOM `FileSystemWritableFileStream` interface used by the OPFS battery's\n * main-thread write path.\n */\nexport interface OpfsWritableFileStream {\n /** Append/write a chunk to the stream. */\n write(data: Uint8Array | ArrayBufferView | ArrayBuffer | string): Promise<void>\n /** Flush and close the stream, committing the written contents. */\n close(): Promise<void>\n}\n\n/**\n * Minimal subset of the DOM `Blob` interface used by {@link OpfsSpoolReader} streaming-mode\n * random-access reads. Real OPFS handles return a `File` here; we narrow to the methods we\n * actually call.\n */\nexport interface OpfsBlob {\n /** Byte length of the blob. */\n readonly size: number\n /** Return a sub-range of the blob as a new blob. */\n slice(start?: number, end?: number, contentType?: string): OpfsBlob\n /** Read the blob's contents as text. */\n text(): Promise<string>\n /** Open a readable byte stream over the blob. */\n stream(): OpfsReadableStream\n}\n\n/**\n * Minimal subset of the DOM `File` interface used by {@link OpfsSpoolReader}.\n */\nexport interface OpfsFile extends OpfsBlob {\n /** The file's name. */\n readonly name: string\n}\n\n/**\n * Minimal subset of the DOM `ReadableStream<Uint8Array>` interface used by streaming-mode\n * index construction.\n */\nexport interface OpfsReadableStream {\n /** Acquire a reader over the stream. */\n getReader(): OpfsReadableStreamReader\n}\n\n/**\n * Minimal subset of the DOM `ReadableStreamDefaultReader<Uint8Array>` interface used by\n * streaming-mode index construction.\n */\nexport interface OpfsReadableStreamReader {\n /** Read the next chunk, or signal end-of-stream with `done: true`. */\n read(): Promise<{ done: false; value: Uint8Array } | { done: true; value: undefined }>\n /** Release the reader's lock on the stream. */\n releaseLock(): void\n}\n\ndeclare const navigator: {\n storage: { getDirectory(): Promise<OpfsDirectoryHandle> }\n}\ndeclare class TextEncoder {\n encode(input?: string): Uint8Array\n}\ndeclare const self: unknown\ndeclare const WorkerGlobalScope: { new (): unknown } | undefined\n\ninterface FileSystemSyncAccessHandle {\n truncate(newSize: number): void\n write(buffer: Uint8Array | ArrayBuffer | ArrayBufferView, options?: { at?: number }): number\n flush(): void\n close(): void\n}\ninterface OpfsFileHandleWithSyncAccess extends OpfsFileHandle {\n createSyncAccessHandle(): Promise<FileSystemSyncAccessHandle>\n}\n\nconst DEFAULT_STREAM_THRESHOLD_BYTES = 10 * 1024 * 1024 // 10 MiB\n\nconst LF = 0x0a // '\\n'\n\nconst isNonNegativeFiniteNumber = (n: unknown): n is number =>\n typeof n === 'number' && Number.isFinite(n) && n >= 0\n\n/**\n * Constructor options for {@link OpfsSpoolReader}.\n */\nexport interface OpfsSpoolReaderOptions {\n /**\n * Byte-length threshold that switches between eager and streaming modes.\n *\n * @remarks\n * - Below the threshold → eager (whole-file in memory).\n * - At or above the threshold → streaming (line-offset index + per-line slice reads).\n *\n * Set to `0` to force streaming mode; set to `Number.POSITIVE_INFINITY` to force eager mode.\n *\n * @defaultValue `10 * 1024 * 1024` (10 MiB)\n */\n streamThresholdBytes?: number\n}\n\ninterface EagerState {\n mode: 'eager'\n lines: string[]\n bytes: number\n content: string\n}\n\ninterface StreamingState {\n mode: 'streaming'\n file: OpfsFile\n /**\n * Byte offsets where each line *starts*. Length equals lineCount + 1; the final entry equals\n * the total byte length. So `offsets[i + 1] - offsets[i]` is the byte length of line `i`\n * including any trailing `\\n`.\n */\n offsets: number[]\n bytes: number\n}\n\ntype ReaderState = EagerState | StreamingState\n\n/**\n * Returns `true` when the current global scope is a Web Worker (`DedicatedWorkerGlobalScope`,\n * `SharedWorkerGlobalScope`, or `ServiceWorkerGlobalScope` all inherit from `WorkerGlobalScope`).\n *\n * @remarks\n * The check is needed at runtime because `FileSystemSyncAccessHandle` is only exposed in worker\n * scopes — calling it from the main thread throws. We pick the write strategy based on the\n * answer here.\n *\n * @internal\n */\nconst isWorkerScope = (): boolean => {\n if (typeof WorkerGlobalScope === 'undefined') return false\n // eslint-disable-next-line adk/use-is-instance-of -- native built-in narrowing on `self`; no cross-realm risk\n return self instanceof WorkerGlobalScope\n}\n\n/**\n * Reads an OPFS-backed file as a {@link @nhtio/adk!SpoolReader}.\n *\n * @remarks\n * Constructor is **not** async — but the first method call awaits a private readiness promise\n * that fetches the underlying `File` (and in eager mode, its contents). Subsequent calls reuse\n * the cached state. This keeps construction call sites synchronous while still doing real I/O\n * lazily.\n *\n * All four `SpoolReader` methods on this reader return promises. The `SpoolReader` contract\n * supports both sync and async return; consumers of `SpooledArtifact` handle either.\n */\nexport class OpfsSpoolReader implements SpoolReader {\n readonly #handle: OpfsFileHandle\n readonly #threshold: number\n #ready: Promise<ReaderState> | undefined\n\n constructor(handle: OpfsFileHandle, opts: OpfsSpoolReaderOptions = {}) {\n this.#handle = handle\n const raw = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES\n // Allow `Infinity` (forces eager) but reject anything non-finite-negative.\n if (typeof raw !== 'number' || Number.isNaN(raw) || raw < 0) {\n throw new TypeError(\n `OpfsSpoolReader: streamThresholdBytes must be a non-negative number or Infinity, got ${String(raw)}`\n )\n }\n this.#threshold = raw\n }\n\n /**\n * Returns `true` if `value` is an {@link OpfsSpoolReader} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is an {@link OpfsSpoolReader} instance.\n */\n public static isOpfsSpoolReader(value: unknown): value is OpfsSpoolReader {\n return isInstanceOf(value, 'OpfsSpoolReader', OpfsSpoolReader)\n }\n\n async line(index: number): Promise<string | undefined> {\n const state = await this.#load()\n if (state.mode === 'eager') return state.lines[index]\n if (index < 0 || index >= state.offsets.length - 1) return undefined\n return this.#readRange(state.file, state.offsets[index], state.offsets[index + 1])\n }\n\n async byteLength(): Promise<number> {\n const state = await this.#load()\n return state.bytes\n }\n\n async lineCount(): Promise<number> {\n const state = await this.#load()\n return state.mode === 'eager' ? state.lines.length : state.offsets.length - 1\n }\n\n /**\n * Returns the full underlying content as a single decoded string, byte-faithful to the source.\n *\n * @remarks\n * In **eager mode** the content is already cached at first-call load and this method is\n * effectively a property access. In **streaming mode** there is no cache: the file is re-read\n * (as a single `File.text()` call) on every invocation. Use `SpooledArtifact.asString()`\n * judiciously on large streaming-mode artifacts.\n */\n async readAll(): Promise<string> {\n const state = await this.#load()\n if (state.mode === 'eager') return state.content\n return state.file.text()\n }\n\n /**\n * Lazily initialise the reader's mode-specific state. Called by every public method; the\n * promise is cached so the work runs at most once.\n */\n #load(): Promise<ReaderState> {\n if (!this.#ready) this.#ready = this.#init()\n return this.#ready\n }\n\n async #init(): Promise<ReaderState> {\n const file = await this.#handle.getFile()\n const bytes = file.size\n if (!isNonNegativeFiniteNumber(bytes)) {\n throw new Error(`OpfsSpoolReader: file handle returned a non-finite size (${String(bytes)})`)\n }\n if (bytes < this.#threshold) {\n // Eager — pull the whole thing into memory.\n const content = await file.text()\n const lines = content === '' ? [] : content.split('\\n')\n return { mode: 'eager', lines, bytes, content }\n }\n // Streaming — build a line-offset index by scanning bytes once.\n return this.#buildStreamingIndex(file, bytes)\n }\n\n async #buildStreamingIndex(file: OpfsFile, bytes: number): Promise<StreamingState> {\n // Edge case first — an empty file is one offset (the EOF), zero lines.\n if (bytes === 0) return { mode: 'streaming', file, offsets: [0], bytes }\n\n // offsets[i] is the byte position where line `i` starts. offsets[lineCount] is one-past-end.\n // For \"a\\nb\\nc\" → offsets=[0, 2, 4, 5] (3 lines).\n // For \"a\\nb\\n\" → offsets=[0, 2, 4, 4] (3 lines, last is the trailing empty line). This\n // mirrors `String.prototype.split('\\n')` semantics so streaming and eager agree.\n const offsets: number[] = [0]\n let position = 0\n let lastByte = -1\n const reader = file.stream().getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n for (const byte of value) {\n position++\n if (byte === LF) offsets.push(position)\n lastByte = byte\n }\n }\n } finally {\n reader.releaseLock()\n }\n // If the file ends on a newline, the byte after the LF is the start of an empty trailing\n // line — record it. If it doesn't, the final line's end is the EOF and we need to push\n // it so line(N-1) can read up to bytes.\n if (lastByte === LF) offsets.push(position)\n else if (offsets[offsets.length - 1] !== position) offsets.push(position)\n return { mode: 'streaming', file, offsets, bytes }\n }\n\n /**\n * Slices the byte range `[start, end)` from the backing file and returns it as a UTF-8\n * string, stripping a trailing `\\n` if present.\n *\n * @remarks\n * `Blob.slice` is O(1) metadata; `Blob.text()` only decodes the slice. The line-offset index\n * brackets each line *with* its trailing LF (so `offsets[i+1]` points at the start of the\n * next line) and the `SpoolReader` contract returns lines *without* their trailing newline,\n * so we strip a single trailing LF if present.\n */\n async #readRange(file: OpfsFile, start: number, end: number): Promise<string> {\n if (start === end) return ''\n const slice = file.slice(start, end)\n const text = await slice.text()\n if (text.length > 0 && text.charCodeAt(text.length - 1) === LF) {\n return text.slice(0, -1)\n }\n return text\n }\n}\n\n/**\n * Constructor options for {@link OpfsSpoolStore}.\n */\nexport interface OpfsSpoolStoreOptions {\n /**\n * Optional thunk that resolves the {@link OpfsDirectoryHandle} used as the store root.\n *\n * @remarks\n * When omitted, the store resolves the root via `navigator.storage.getDirectory()` on its\n * first filesystem call. Override for tests (to point at a per-suite subdirectory) or to\n * scope the store to a nested directory inside OPFS.\n *\n * The thunk is invoked at most once per store; the returned handle is memoised.\n */\n directory?: () => Promise<OpfsDirectoryHandle>\n\n /**\n * Optional filename prefix prepended to every `callId`.\n *\n * @remarks\n * Prefix is a **filename prefix**, not a subdirectory — `keyPrefix: 'agent-runs/'` produces\n * a file literally named `agent-runs/<callId>` at the root, not a nested directory. (OPFS\n * filenames may not contain `/`, so use a non-`/` separator like `-` if you want a flat\n * namespace.) This mirrors the `keyPrefix` semantics in the flydrive and in-memory batteries.\n *\n * @defaultValue `\"\"`\n */\n keyPrefix?: string\n\n /**\n * Default `streamThresholdBytes` for readers produced by `write()` and `read()`. Individual\n * calls may override via their own `opts` argument.\n *\n * @defaultValue `10 * 1024 * 1024` (10 MiB)\n */\n streamThresholdBytes?: number\n}\n\n/**\n * \"Give bytes, get a reader\" persistence layer over an OPFS directory.\n *\n * @remarks\n * `write(callId, bytes)` resolves the root directory (lazily, on first call), opens or creates\n * the file named `keyPrefix + callId`, then writes via the API matching the current scope:\n * a `FileSystemSyncAccessHandle` in worker scopes, `OpfsFileHandle.createWritable()` on\n * the main thread. A fresh {@link OpfsSpoolReader} pointed at the same file is returned.\n *\n * `read(callId)` returns a reader without re-writing; `delete(callId)` removes the entry.\n *\n * The store is otherwise stateless — it owns no in-memory cache of writes. Multiple\n * `OpfsSpoolStore` instances sharing the same root directory and key prefix see the same data.\n *\n * @example\n * ```ts\n * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'\n *\n * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })\n *\n * const bytes = await tool.executor(ctx)(args)\n * const reader = await store.write(callId, bytes)\n * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact\n * const artifact = new Ctor(reader)\n * ```\n */\nexport class OpfsSpoolStore implements SpoolStore {\n readonly #resolveRoot: () => Promise<OpfsDirectoryHandle>\n readonly #prefix: string\n readonly #defaultThreshold: number\n #root: OpfsDirectoryHandle | undefined\n\n constructor(opts: OpfsSpoolStoreOptions = {}) {\n this.#resolveRoot = opts.directory ?? (() => navigator.storage.getDirectory())\n this.#prefix = opts.keyPrefix ?? ''\n this.#defaultThreshold = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES\n }\n\n /**\n * Returns `true` if `value` is an {@link OpfsSpoolStore} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is an {@link OpfsSpoolStore} instance.\n */\n public static isOpfsSpoolStore(value: unknown): value is OpfsSpoolStore {\n return isInstanceOf(value, 'OpfsSpoolStore', OpfsSpoolStore)\n }\n\n /**\n * Persists `bytes` under `callId` and returns a reader bound to the stored key.\n *\n * @remarks\n * `string` input is encoded as UTF-8; `Uint8Array` is stored byte-faithfully;\n * `ReadableStream<Uint8Array>` is written incrementally — the stream is consumed chunk-by-chunk\n * straight to OPFS without first materializing the whole payload in memory, which is the point\n * of accepting a stream for a durable store.\n *\n * @param callId - Identifier used to retrieve the bytes via {@link OpfsSpoolStore.read}.\n * @param bytes - The bytes to store, as a `string`, `Uint8Array`, or `ReadableStream<Uint8Array>`.\n * @param opts - Per-call override for `streamThresholdBytes`.\n * @returns An {@link OpfsSpoolReader} over the stored bytes.\n */\n async write(\n callId: string,\n bytes: string | Uint8Array | ReadableStream<Uint8Array>,\n opts?: OpfsSpoolReaderOptions\n ): Promise<OpfsSpoolReader> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n const handle = await root.getFileHandle(name, { create: true })\n if (isInstanceOf(bytes, 'ReadableStream', ReadableStream)) {\n if (isWorkerScope()) {\n await this.#writeStreamViaSyncHandle(handle, bytes)\n } else {\n await this.#writeStreamViaWritable(handle, bytes)\n }\n } else {\n const payload = typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes\n if (isWorkerScope()) {\n await this.#writeViaSyncHandle(handle, payload)\n } else {\n await this.#writeViaWritable(handle, payload)\n }\n }\n return new OpfsSpoolReader(handle, {\n streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold,\n })\n }\n\n /**\n * Returns a reader over the bytes previously written under `callId`.\n *\n * @remarks\n * Returns `undefined` if the file does not exist.\n *\n * @param callId - Identifier supplied to a prior {@link OpfsSpoolStore.write} call.\n * @param opts - Per-call override for `streamThresholdBytes`.\n * @returns An {@link OpfsSpoolReader}, or `undefined` if the key is missing.\n */\n async read(callId: string, opts?: OpfsSpoolReaderOptions): Promise<OpfsSpoolReader | undefined> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n let handle: OpfsFileHandle\n try {\n handle = await root.getFileHandle(name)\n } catch (err) {\n if (this.#isNotFoundError(err)) return undefined\n throw err\n }\n return new OpfsSpoolReader(handle, {\n streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold,\n })\n }\n\n /**\n * Removes the entry under `callId`.\n *\n * @param callId - Identifier whose entry should be removed.\n * @returns `true` if the entry existed and was removed; `false` if it didn't exist.\n */\n async delete(callId: string): Promise<boolean> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n try {\n await root.removeEntry(name)\n return true\n } catch (err) {\n if (this.#isNotFoundError(err)) return false\n throw err\n }\n }\n\n /**\n * Returns `true` if a file is present under `callId`.\n *\n * @param callId - Identifier to test.\n * @returns `true` when the file exists, `false` otherwise.\n */\n async has(callId: string): Promise<boolean> {\n const name = this.#keyFor(callId)\n const root = await this.#getRoot()\n try {\n await root.getFileHandle(name)\n return true\n } catch (err) {\n if (this.#isNotFoundError(err)) return false\n throw err\n }\n }\n\n /**\n * Returns the full filename for a given `callId` (i.e. `keyPrefix + callId`).\n *\n * @remarks\n * Useful for tests or for callers that want to interact with the underlying OPFS directory\n * directly.\n */\n keyFor(callId: string): string {\n return this.#keyFor(callId)\n }\n\n #keyFor(callId: string): string {\n return this.#prefix + callId\n }\n\n async #getRoot(): Promise<OpfsDirectoryHandle> {\n if (!this.#root) this.#root = await this.#resolveRoot()\n return this.#root\n }\n\n async #writeViaSyncHandle(handle: OpfsFileHandle, payload: Uint8Array): Promise<void> {\n const sync = await (handle as OpfsFileHandleWithSyncAccess).createSyncAccessHandle()\n try {\n sync.truncate(0)\n sync.write(payload, { at: 0 })\n sync.flush()\n } finally {\n sync.close()\n }\n }\n\n async #writeViaWritable(handle: OpfsFileHandle, payload: Uint8Array): Promise<void> {\n const writable = await handle.createWritable()\n try {\n await writable.write(payload)\n } finally {\n await writable.close()\n }\n }\n\n async #writeStreamViaWritable(\n handle: OpfsFileHandle,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const writable = await handle.createWritable()\n try {\n const reader = stream.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value) await writable.write(value)\n }\n } finally {\n reader.releaseLock()\n }\n } finally {\n await writable.close()\n }\n }\n\n async #writeStreamViaSyncHandle(\n handle: OpfsFileHandle,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const sync = await (handle as OpfsFileHandleWithSyncAccess).createSyncAccessHandle()\n try {\n sync.truncate(0)\n let at = 0\n const reader = stream.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value && value.byteLength > 0) {\n sync.write(value, { at })\n at += value.byteLength\n }\n }\n } finally {\n reader.releaseLock()\n }\n sync.flush()\n } finally {\n sync.close()\n }\n }\n\n #isNotFoundError(err: unknown): boolean {\n if (err === null || typeof err !== 'object') return false\n const name = (err as { name?: unknown }).name\n return name === 'NotFoundError'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyKA,IAAM,iCAAiC,KAAK,OAAO;AAEnD,IAAM,KAAK;AAEX,IAAM,6BAA6B,MACjC,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,KAAK;;;;;;;;;;;;AAoDtD,IAAM,sBAA+B;CACnC,IAAI,OAAO,sBAAsB,aAAa,OAAO;CAErD,OAAO,gBAAgB;AACzB;;;;;;;;;;;;;AAcA,IAAa,kBAAb,MAAa,gBAAuC;CAClD;CACA;CACA;CAEA,YAAY,QAAwB,OAA+B,CAAC,GAAG;EACrE,KAAKA,UAAU;EACf,MAAM,MAAM,KAAK,wBAAwB;EAEzC,IAAI,OAAO,QAAQ,YAAY,OAAO,MAAM,GAAG,KAAK,MAAM,GACxD,MAAM,IAAI,UACR,wFAAwF,OAAO,GAAG,GACpG;EAEF,KAAKC,aAAa;CACpB;;;;;;;;;;CAWA,OAAc,kBAAkB,OAA0C;EACxE,OAAO,aAAa,OAAO,mBAAmB,eAAe;CAC/D;CAEA,MAAM,KAAK,OAA4C;EACrD,MAAM,QAAQ,MAAM,KAAKC,MAAM;EAC/B,IAAI,MAAM,SAAS,SAAS,OAAO,MAAM,MAAM;EAC/C,IAAI,QAAQ,KAAK,SAAS,MAAM,QAAQ,SAAS,GAAG,OAAO,KAAA;EAC3D,OAAO,KAAKC,WAAW,MAAM,MAAM,MAAM,QAAQ,QAAQ,MAAM,QAAQ,QAAQ,EAAE;CACnF;CAEA,MAAM,aAA8B;EAElC,QAAO,MADa,KAAKD,MAAM,GAClB;CACf;CAEA,MAAM,YAA6B;EACjC,MAAM,QAAQ,MAAM,KAAKA,MAAM;EAC/B,OAAO,MAAM,SAAS,UAAU,MAAM,MAAM,SAAS,MAAM,QA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AS,EAAE,IAAI,EAAE,CAAC;GAC7B,KAAK,MAAM;EACb,UAAU;GACR,KAAK,MAAM;EACb;CACF;CAEA,MAAMC,kBAAkB,QAAwB,SAAoC;EAClF,MAAM,WAAW,MAAM,OAAO,eAAe;EAC7C,IAAI;GACF,MAAM,SAAS,MAAM,OAAO;EAC9B,UAAU;GACR,MAAM,SAAS,MAAM;EACvB;CACF;CAEA,MAAMF,wBACJ,QACA,QACe;EACf,MAAM,WAAW,MAAM,OAAO,eAAe;EAC7C,IAAI;GACF,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI;IACF,SAAS;KACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,OAAO,MAAM,SAAS,MAAM,KAAK;IACvC;GACF,UAAU;IACR,OAAO,YAAY;GACrB;EACF,UAAU;GACR,MAAM,SAAS,MAAM;EACvB;CACF;CAEA,MAAMD,0BACJ,QACA,QACe;EACf,MAAM,OAAO,MAAO,OAAwC,uBAAuB;EACnF,IAAI;GACF,KAAK,SAAS,CAAC;GACf,IAAI,KAAK;GACT,MAAM,SAAS,OAAO,UAAU;GAChC,IAAI;IACF,SAAS;KACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,SAAS,MAAM,aAAa,GAAG;MACjC,KAAK,MAAM,OAAO,EAAE,GAAG,CAAC;MACxB,MAAM,MAAM;KACd;IACF;GACF,UAAU;IACR,OAAO,YAAY;GACrB;GACA,KAAK,MAAM;EACb,UAAU;GACR,KAAK,MAAM;EACb;CACF;CAEA,iBAAiB,KAAuB;EACtC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU,OAAO;EAEpD,OADc,IAA2B,SACzB;CAClB;AACF"}
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Cross-battery helpers shared by the configured HTTP tool batteries (SearXNG, Scrapper, …).
3
+ *
4
+ * @module @nhtio/adk/batteries/tools/_shared
5
+ *
6
+ * @remarks
7
+ * These are internal building blocks for the *factory-style* tool batteries — the ones that talk
8
+ * to a configured HTTP instance behind custom auth and expose input/output middleware pipelines.
9
+ * Rather than each battery carry its own copy, the common machinery lives here:
10
+ *
11
+ * - {@link resolveArtifact} / {@link resolveArtifactSync} — turn an {@link ArtifactResolver}
12
+ * (a constructor, a sync resolver, or an async / dynamic-import resolver) into the **sync**
13
+ * `() => SpooledArtifactConstructor` that `Tool.artifactConstructor` requires. Mirrors the vector
14
+ * battery's `resolveClientCtor`.
15
+ * - {@link resolveHeaders} — collapse a static header object or a (sync/async) resolver into a
16
+ * plain header record for one request (refreshable-auth friendly).
17
+ * - {@link runInputPipeline} / {@link runOutputPipeline} — the onion middleware runners (fresh
18
+ * runner per call, short-circuit + non-terminal detection), generic over the context type.
19
+ *
20
+ * This module imports harness primitives only through their specific subpath barrels
21
+ * (`@nhtio/adk/spooled_artifact`, `@nhtio/adk/forge`, `@nhtio/adk/guards`) per the batteries
22
+ * barrel-only rule.
23
+ */
24
+ import { Middleware } from '@nhtio/middleware';
25
+ import type { NextFn } from '@nhtio/middleware';
26
+ import type { SpooledArtifactConstructor } from "../../../forge";
27
+ /** A static set of request headers (used for custom instance authentication). */
28
+ export type ToolHeaders = Record<string, string>;
29
+ /**
30
+ * A resolver returning request headers, sync or async. Use this form when the auth token is
31
+ * refreshable — the resolver runs on every request, so a fresh token can be minted per call.
32
+ */
33
+ export type ToolHeadersResolver = () => ToolHeaders | Promise<ToolHeaders>;
34
+ /**
35
+ * Resolve the configured headers (a static object or a sync/async resolver) for a single request.
36
+ *
37
+ * @param headers - The static header record, the resolver, or `undefined`.
38
+ * @returns A fresh, owned copy of the resolved headers (`{}` when none supplied).
39
+ */
40
+ export declare const resolveHeaders: (headers: ToolHeaders | ToolHeadersResolver | undefined) => Promise<ToolHeaders>;
41
+ /** Convenience alias for the spooled-artifact constructor a tool wraps its output in. */
42
+ export type SpooledArtifactCtor = SpooledArtifactConstructor;
43
+ /**
44
+ * The artifact configuration accepted by a factory: a constructor, a sync resolver, or an async /
45
+ * dynamic-import resolver (which may yield a module namespace whose `default` is the constructor).
46
+ *
47
+ * @remarks
48
+ * Mirrors the vector battery's `client` resolver and `Tool.artifactConstructor`'s indirection. The
49
+ * async form lets a consumer `() => import('@nhtio/adk/spooled_artifact').then(m => m.SpooledMarkdownArtifact)`
50
+ * so the artifact class never enters their static module graph.
51
+ */
52
+ export type ArtifactResolver = SpooledArtifactCtor | (() => SpooledArtifactCtor | {
53
+ default: SpooledArtifactCtor;
54
+ }) | (() => Promise<SpooledArtifactCtor | {
55
+ default: SpooledArtifactCtor;
56
+ }>);
57
+ /** The sync subset of {@link ArtifactResolver} — a constructor or a sync resolver (no Promise). */
58
+ export type SyncArtifactResolver = SpooledArtifactCtor | (() => SpooledArtifactCtor | {
59
+ default: SpooledArtifactCtor;
60
+ });
61
+ /**
62
+ * Resolve an {@link ArtifactResolver} to the **sync** `() => SpooledArtifactCtor` that
63
+ * `Tool.artifactConstructor` requires (the wrap-site and the construction-time validator both
64
+ * invoke it synchronously, so an async resolver cannot be passed straight through).
65
+ *
66
+ * @remarks
67
+ * A bare constructor is itself a function, so it is distinguished from a resolver via
68
+ * `SpooledArtifact.isSpooledArtifactConstructor` (the same duck-typed guard the core validator
69
+ * uses) rather than by arity. Async because a dynamic-import resolver must be awaited here.
70
+ *
71
+ * @param resolver - The artifact configuration. When `undefined`, callers should fall back to
72
+ * their own default (this function rejects `undefined` so the default lives with the caller).
73
+ * @param onInvalid - Throws a battery-scoped error; receives a human-readable reason.
74
+ * @returns A sync `() => SpooledArtifactCtor` suitable for `Tool.artifactConstructor`.
75
+ */
76
+ export declare const resolveArtifact: (resolver: ArtifactResolver, onInvalid: (reason: string) => never) => Promise<() => SpooledArtifactCtor>;
77
+ /**
78
+ * Synchronous {@link resolveArtifact}: accepts only the {@link SyncArtifactResolver} subset and
79
+ * throws (via `onInvalid`) on an async resolver — a runtime guard for JS callers who bypass the
80
+ * compile-time narrowing.
81
+ *
82
+ * @param resolver - A constructor or a sync resolver.
83
+ * @param onInvalid - Throws a battery-scoped error; receives a human-readable reason.
84
+ * @returns A sync `() => SpooledArtifactCtor` suitable for `Tool.artifactConstructor`.
85
+ */
86
+ export declare const resolveArtifactSync: (resolver: SyncArtifactResolver, onInvalid: (reason: string) => never) => (() => SpooledArtifactCtor);
87
+ /** `true` when `value` is the short-circuit sentinel produced by {@link makeShortCircuit}. */
88
+ export declare const isShortCircuit: (value: unknown) => value is {
89
+ result: string;
90
+ };
91
+ /**
92
+ * Build a `shortCircuit(result)` function for an input-pipeline context. Calling it throws the
93
+ * internal sentinel, which {@link runInputPipeline} catches and converts into the verbatim result
94
+ * (skipping the HTTP request entirely — e.g. a cache hit).
95
+ *
96
+ * @returns A function that, when called with a result string, throws the short-circuit sentinel.
97
+ */
98
+ export declare const makeShortCircuit: () => ((result: string) => never);
99
+ /** A generic onion middleware stage over a mutable context `C`. */
100
+ export type MiddlewareFn<C> = (ctx: C, next: NextFn) => void | Promise<void>;
101
+ /**
102
+ * Run an input pipeline over `ctx`. Returns the short-circuit string when a stage short-circuited,
103
+ * or `undefined` when the pipeline reached its terminal handler. A non-terminal pipeline (a stage
104
+ * that neither called `next()` nor short-circuited) throws — the caller converts it to an
105
+ * `Error:` string.
106
+ *
107
+ * @param mw - The `Middleware` instance holding the stages (a fresh `.runner()` is minted here).
108
+ * @param ctx - The mutable input context handed to each stage.
109
+ * @param label - Battery name, used in the non-terminal error message.
110
+ * @returns The short-circuit result string, or `undefined` if the pipeline ran to completion.
111
+ */
112
+ export declare const runInputPipeline: <C>(mw: Middleware<MiddlewareFn<C>>, ctx: C, label: string) => Promise<string | undefined>;
113
+ /**
114
+ * Run an output pipeline over `ctx`; rethrow any stage error to the caller's try/catch. A
115
+ * non-terminal pipeline (no `next()`) throws.
116
+ *
117
+ * @param mw - The `Middleware` instance holding the stages (a fresh `.runner()` is minted here).
118
+ * @param ctx - The mutable output context handed to each stage.
119
+ * @param label - Battery name, used in the non-terminal error message.
120
+ */
121
+ export declare const runOutputPipeline: <C>(mw: Middleware<MiddlewareFn<C>>, ctx: C, label: string) => Promise<void>;
@@ -0,0 +1,157 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ require("../../chunk-Ble4zEEl.js");
3
+ const require_tool_registry = require("../../tool_registry-CKJPze3j.js");
4
+ const require_spooled_artifact = require("../../spooled_artifact-DX8LLyUX.js");
5
+ require("../../guards.cjs");
6
+ require("../../spooled_artifact.cjs");
7
+ //#region src/batteries/tools/_shared/index.ts
8
+ /**
9
+ * Resolve the configured headers (a static object or a sync/async resolver) for a single request.
10
+ *
11
+ * @param headers - The static header record, the resolver, or `undefined`.
12
+ * @returns A fresh, owned copy of the resolved headers (`{}` when none supplied).
13
+ */
14
+ var resolveHeaders = async (headers) => {
15
+ if (typeof headers === "function") return { ...await headers() };
16
+ return { ...headers ?? {} };
17
+ };
18
+ /** Unwrap a resolved value that may be a module namespace whose `default` is the constructor. */
19
+ var unwrapDefault = (value) => {
20
+ if (require_tool_registry.isObject(value) && "default" in value) {
21
+ const def = value.default;
22
+ if (require_spooled_artifact.SpooledArtifact.isSpooledArtifactConstructor(def)) return def;
23
+ }
24
+ return value;
25
+ };
26
+ /**
27
+ * Resolve an {@link ArtifactResolver} to the **sync** `() => SpooledArtifactCtor` that
28
+ * `Tool.artifactConstructor` requires (the wrap-site and the construction-time validator both
29
+ * invoke it synchronously, so an async resolver cannot be passed straight through).
30
+ *
31
+ * @remarks
32
+ * A bare constructor is itself a function, so it is distinguished from a resolver via
33
+ * `SpooledArtifact.isSpooledArtifactConstructor` (the same duck-typed guard the core validator
34
+ * uses) rather than by arity. Async because a dynamic-import resolver must be awaited here.
35
+ *
36
+ * @param resolver - The artifact configuration. When `undefined`, callers should fall back to
37
+ * their own default (this function rejects `undefined` so the default lives with the caller).
38
+ * @param onInvalid - Throws a battery-scoped error; receives a human-readable reason.
39
+ * @returns A sync `() => SpooledArtifactCtor` suitable for `Tool.artifactConstructor`.
40
+ */
41
+ var resolveArtifact = async (resolver, onInvalid) => {
42
+ if (require_spooled_artifact.SpooledArtifact.isSpooledArtifactConstructor(resolver)) {
43
+ const ctor = resolver;
44
+ return () => ctor;
45
+ }
46
+ if (typeof resolver !== "function") onInvalid("artifact must be a SpooledArtifact constructor or a resolver returning one");
47
+ let resolved;
48
+ try {
49
+ resolved = await resolver();
50
+ } catch (err) {
51
+ onInvalid(`artifact resolver threw: ${require_tool_registry.isError(err) ? err.message : String(err)}`);
52
+ }
53
+ resolved = unwrapDefault(resolved);
54
+ if (!require_spooled_artifact.SpooledArtifact.isSpooledArtifactConstructor(resolved)) onInvalid("artifact resolver did not resolve to a SpooledArtifact constructor");
55
+ const ctor = resolved;
56
+ return () => ctor;
57
+ };
58
+ /**
59
+ * Synchronous {@link resolveArtifact}: accepts only the {@link SyncArtifactResolver} subset and
60
+ * throws (via `onInvalid`) on an async resolver — a runtime guard for JS callers who bypass the
61
+ * compile-time narrowing.
62
+ *
63
+ * @param resolver - A constructor or a sync resolver.
64
+ * @param onInvalid - Throws a battery-scoped error; receives a human-readable reason.
65
+ * @returns A sync `() => SpooledArtifactCtor` suitable for `Tool.artifactConstructor`.
66
+ */
67
+ var resolveArtifactSync = (resolver, onInvalid) => {
68
+ if (require_spooled_artifact.SpooledArtifact.isSpooledArtifactConstructor(resolver)) {
69
+ const ctor = resolver;
70
+ return () => ctor;
71
+ }
72
+ if (typeof resolver !== "function") onInvalid("artifact must be a SpooledArtifact constructor or a resolver returning one");
73
+ let resolved;
74
+ try {
75
+ resolved = resolver();
76
+ } catch (err) {
77
+ onInvalid(`artifact resolver threw: ${require_tool_registry.isError(err) ? err.message : String(err)}`);
78
+ }
79
+ if (require_tool_registry.isInstanceOf(resolved, "Promise", Promise)) onInvalid("artifact resolver is async; use the async factory variant for dynamic-import resolvers");
80
+ resolved = unwrapDefault(resolved);
81
+ if (!require_spooled_artifact.SpooledArtifact.isSpooledArtifactConstructor(resolved)) onInvalid("artifact resolver did not resolve to a SpooledArtifact constructor");
82
+ const ctor = resolved;
83
+ return () => ctor;
84
+ };
85
+ /** Internal sentinel a short-circuiting input stage throws to unwind the pipeline immediately. */
86
+ var SHORT_CIRCUIT = Symbol("adk.tools.shortCircuit");
87
+ /** `true` when `value` is the short-circuit sentinel produced by {@link makeShortCircuit}. */
88
+ var isShortCircuit = (value) => require_tool_registry.isObject(value) && value[SHORT_CIRCUIT] === true;
89
+ /**
90
+ * Build a `shortCircuit(result)` function for an input-pipeline context. Calling it throws the
91
+ * internal sentinel, which {@link runInputPipeline} catches and converts into the verbatim result
92
+ * (skipping the HTTP request entirely — e.g. a cache hit).
93
+ *
94
+ * @returns A function that, when called with a result string, throws the short-circuit sentinel.
95
+ */
96
+ var makeShortCircuit = () => {
97
+ return (result) => {
98
+ throw {
99
+ [SHORT_CIRCUIT]: true,
100
+ result
101
+ };
102
+ };
103
+ };
104
+ /**
105
+ * Run an input pipeline over `ctx`. Returns the short-circuit string when a stage short-circuited,
106
+ * or `undefined` when the pipeline reached its terminal handler. A non-terminal pipeline (a stage
107
+ * that neither called `next()` nor short-circuited) throws — the caller converts it to an
108
+ * `Error:` string.
109
+ *
110
+ * @param mw - The `Middleware` instance holding the stages (a fresh `.runner()` is minted here).
111
+ * @param ctx - The mutable input context handed to each stage.
112
+ * @param label - Battery name, used in the non-terminal error message.
113
+ * @returns The short-circuit result string, or `undefined` if the pipeline ran to completion.
114
+ */
115
+ var runInputPipeline = async (mw, ctx, label) => {
116
+ let reached = false;
117
+ let caught;
118
+ await mw.runner().errorHandler(async (error) => {
119
+ caught = error;
120
+ }).finalHandler(async () => {
121
+ reached = true;
122
+ }).run((fn, next) => Promise.resolve(fn(ctx, next)));
123
+ if (caught !== void 0) {
124
+ if (isShortCircuit(caught)) return caught.result;
125
+ throw caught;
126
+ }
127
+ if (!reached) throw new Error(`${label} input pipeline did not call next() and did not short-circuit.`);
128
+ };
129
+ /**
130
+ * Run an output pipeline over `ctx`; rethrow any stage error to the caller's try/catch. A
131
+ * non-terminal pipeline (no `next()`) throws.
132
+ *
133
+ * @param mw - The `Middleware` instance holding the stages (a fresh `.runner()` is minted here).
134
+ * @param ctx - The mutable output context handed to each stage.
135
+ * @param label - Battery name, used in the non-terminal error message.
136
+ */
137
+ var runOutputPipeline = async (mw, ctx, label) => {
138
+ let reached = false;
139
+ let caught;
140
+ await mw.runner().errorHandler(async (error) => {
141
+ caught = error;
142
+ }).finalHandler(async () => {
143
+ reached = true;
144
+ }).run((fn, next) => Promise.resolve(fn(ctx, next)));
145
+ if (caught !== void 0) throw caught;
146
+ if (!reached) throw new Error(`${label} output pipeline did not call next().`);
147
+ };
148
+ //#endregion
149
+ exports.isShortCircuit = isShortCircuit;
150
+ exports.makeShortCircuit = makeShortCircuit;
151
+ exports.resolveArtifact = resolveArtifact;
152
+ exports.resolveArtifactSync = resolveArtifactSync;
153
+ exports.resolveHeaders = resolveHeaders;
154
+ exports.runInputPipeline = runInputPipeline;
155
+ exports.runOutputPipeline = runOutputPipeline;
156
+
157
+ //# sourceMappingURL=_shared.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_shared.cjs","names":[],"sources":["../../../src/batteries/tools/_shared/index.ts"],"sourcesContent":["/**\n * Cross-battery helpers shared by the configured HTTP tool batteries (SearXNG, Scrapper, …).\n *\n * @module @nhtio/adk/batteries/tools/_shared\n *\n * @remarks\n * These are internal building blocks for the *factory-style* tool batteries — the ones that talk\n * to a configured HTTP instance behind custom auth and expose input/output middleware pipelines.\n * Rather than each battery carry its own copy, the common machinery lives here:\n *\n * - {@link resolveArtifact} / {@link resolveArtifactSync} — turn an {@link ArtifactResolver}\n * (a constructor, a sync resolver, or an async / dynamic-import resolver) into the **sync**\n * `() => SpooledArtifactConstructor` that `Tool.artifactConstructor` requires. Mirrors the vector\n * battery's `resolveClientCtor`.\n * - {@link resolveHeaders} — collapse a static header object or a (sync/async) resolver into a\n * plain header record for one request (refreshable-auth friendly).\n * - {@link runInputPipeline} / {@link runOutputPipeline} — the onion middleware runners (fresh\n * runner per call, short-circuit + non-terminal detection), generic over the context type.\n *\n * This module imports harness primitives only through their specific subpath barrels\n * (`@nhtio/adk/spooled_artifact`, `@nhtio/adk/forge`, `@nhtio/adk/guards`) per the batteries\n * barrel-only rule.\n */\n\nimport { Middleware } from '@nhtio/middleware'\nimport { SpooledArtifact } from '@nhtio/adk/spooled_artifact'\nimport { isError, isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport type { NextFn } from '@nhtio/middleware'\nimport type { SpooledArtifactConstructor } from '@nhtio/adk/forge'\n\n// ── Header resolution ────────────────────────────────────────────────────────\n\n/** A static set of request headers (used for custom instance authentication). */\nexport type ToolHeaders = Record<string, string>\n\n/**\n * A resolver returning request headers, sync or async. Use this form when the auth token is\n * refreshable — the resolver runs on every request, so a fresh token can be minted per call.\n */\nexport type ToolHeadersResolver = () => ToolHeaders | Promise<ToolHeaders>\n\n/**\n * Resolve the configured headers (a static object or a sync/async resolver) for a single request.\n *\n * @param headers - The static header record, the resolver, or `undefined`.\n * @returns A fresh, owned copy of the resolved headers (`{}` when none supplied).\n */\nexport const resolveHeaders = async (\n headers: ToolHeaders | ToolHeadersResolver | undefined\n): Promise<ToolHeaders> => {\n if (typeof headers === 'function') return { ...(await headers()) }\n return { ...(headers ?? {}) }\n}\n\n// ── Artifact resolver ────────────────────────────────────────────────────────\n\n/** Convenience alias for the spooled-artifact constructor a tool wraps its output in. */\nexport type SpooledArtifactCtor = SpooledArtifactConstructor\n\n/**\n * The artifact configuration accepted by a factory: a constructor, a sync resolver, or an async /\n * dynamic-import resolver (which may yield a module namespace whose `default` is the constructor).\n *\n * @remarks\n * Mirrors the vector battery's `client` resolver and `Tool.artifactConstructor`'s indirection. The\n * async form lets a consumer `() => import('@nhtio/adk/spooled_artifact').then(m => m.SpooledMarkdownArtifact)`\n * so the artifact class never enters their static module graph.\n */\nexport type ArtifactResolver =\n | SpooledArtifactCtor\n | (() => SpooledArtifactCtor | { default: SpooledArtifactCtor })\n | (() => Promise<SpooledArtifactCtor | { default: SpooledArtifactCtor }>)\n\n/** The sync subset of {@link ArtifactResolver} — a constructor or a sync resolver (no Promise). */\nexport type SyncArtifactResolver =\n | SpooledArtifactCtor\n | (() => SpooledArtifactCtor | { default: SpooledArtifactCtor })\n\n/** Unwrap a resolved value that may be a module namespace whose `default` is the constructor. */\nconst unwrapDefault = (value: unknown): unknown => {\n if (isObject(value) && 'default' in value) {\n const def = (value as { default?: unknown }).default\n if (SpooledArtifact.isSpooledArtifactConstructor(def)) return def\n }\n return value\n}\n\n/**\n * Resolve an {@link ArtifactResolver} to the **sync** `() => SpooledArtifactCtor` that\n * `Tool.artifactConstructor` requires (the wrap-site and the construction-time validator both\n * invoke it synchronously, so an async resolver cannot be passed straight through).\n *\n * @remarks\n * A bare constructor is itself a function, so it is distinguished from a resolver via\n * `SpooledArtifact.isSpooledArtifactConstructor` (the same duck-typed guard the core validator\n * uses) rather than by arity. Async because a dynamic-import resolver must be awaited here.\n *\n * @param resolver - The artifact configuration. When `undefined`, callers should fall back to\n * their own default (this function rejects `undefined` so the default lives with the caller).\n * @param onInvalid - Throws a battery-scoped error; receives a human-readable reason.\n * @returns A sync `() => SpooledArtifactCtor` suitable for `Tool.artifactConstructor`.\n */\nexport const resolveArtifact = async (\n resolver: ArtifactResolver,\n onInvalid: (reason: string) => never\n): Promise<() => SpooledArtifactCtor> => {\n // A constructor: hand back a thunk that returns it.\n if (SpooledArtifact.isSpooledArtifactConstructor(resolver)) {\n const ctor = resolver\n return () => ctor\n }\n // Otherwise it must be a resolver function.\n if (typeof resolver !== 'function') {\n onInvalid('artifact must be a SpooledArtifact constructor or a resolver returning one')\n }\n let resolved: unknown\n try {\n resolved = await (resolver as () => unknown)()\n } catch (err) {\n onInvalid(`artifact resolver threw: ${isError(err) ? err.message : String(err)}`)\n }\n resolved = unwrapDefault(resolved)\n if (!SpooledArtifact.isSpooledArtifactConstructor(resolved)) {\n onInvalid('artifact resolver did not resolve to a SpooledArtifact constructor')\n }\n const ctor = resolved as SpooledArtifactCtor\n return () => ctor\n}\n\n/**\n * Synchronous {@link resolveArtifact}: accepts only the {@link SyncArtifactResolver} subset and\n * throws (via `onInvalid`) on an async resolver — a runtime guard for JS callers who bypass the\n * compile-time narrowing.\n *\n * @param resolver - A constructor or a sync resolver.\n * @param onInvalid - Throws a battery-scoped error; receives a human-readable reason.\n * @returns A sync `() => SpooledArtifactCtor` suitable for `Tool.artifactConstructor`.\n */\nexport const resolveArtifactSync = (\n resolver: SyncArtifactResolver,\n onInvalid: (reason: string) => never\n): (() => SpooledArtifactCtor) => {\n if (SpooledArtifact.isSpooledArtifactConstructor(resolver)) {\n const ctor = resolver\n return () => ctor\n }\n if (typeof resolver !== 'function') {\n onInvalid('artifact must be a SpooledArtifact constructor or a resolver returning one')\n }\n let resolved: unknown\n try {\n resolved = (resolver as () => unknown)()\n } catch (err) {\n onInvalid(`artifact resolver threw: ${isError(err) ? err.message : String(err)}`)\n }\n if (isInstanceOf(resolved, 'Promise', Promise)) {\n onInvalid(\n 'artifact resolver is async; use the async factory variant for dynamic-import resolvers'\n )\n }\n resolved = unwrapDefault(resolved)\n if (!SpooledArtifact.isSpooledArtifactConstructor(resolved)) {\n onInvalid('artifact resolver did not resolve to a SpooledArtifact constructor')\n }\n const ctor = resolved as SpooledArtifactCtor\n return () => ctor\n}\n\n// ── Middleware pipeline runners ──────────────────────────────────────────────\n\n/** Internal sentinel a short-circuiting input stage throws to unwind the pipeline immediately. */\nconst SHORT_CIRCUIT = Symbol('adk.tools.shortCircuit')\n\ninterface ShortCircuitSignal {\n [SHORT_CIRCUIT]: true\n result: string\n}\n\n/** `true` when `value` is the short-circuit sentinel produced by {@link makeShortCircuit}. */\nexport const isShortCircuit = (value: unknown): value is { result: string } =>\n isObject(value) && (value as Record<symbol, unknown>)[SHORT_CIRCUIT] === true\n\n/**\n * Build a `shortCircuit(result)` function for an input-pipeline context. Calling it throws the\n * internal sentinel, which {@link runInputPipeline} catches and converts into the verbatim result\n * (skipping the HTTP request entirely — e.g. a cache hit).\n *\n * @returns A function that, when called with a result string, throws the short-circuit sentinel.\n */\nexport const makeShortCircuit = (): ((result: string) => never) => {\n return (result: string): never => {\n const signal: ShortCircuitSignal = { [SHORT_CIRCUIT]: true, result }\n throw signal\n }\n}\n\n/** A generic onion middleware stage over a mutable context `C`. */\nexport type MiddlewareFn<C> = (ctx: C, next: NextFn) => void | Promise<void>\n\n/**\n * Run an input pipeline over `ctx`. Returns the short-circuit string when a stage short-circuited,\n * or `undefined` when the pipeline reached its terminal handler. A non-terminal pipeline (a stage\n * that neither called `next()` nor short-circuited) throws — the caller converts it to an\n * `Error:` string.\n *\n * @param mw - The `Middleware` instance holding the stages (a fresh `.runner()` is minted here).\n * @param ctx - The mutable input context handed to each stage.\n * @param label - Battery name, used in the non-terminal error message.\n * @returns The short-circuit result string, or `undefined` if the pipeline ran to completion.\n */\nexport const runInputPipeline = async <C>(\n mw: Middleware<MiddlewareFn<C>>,\n ctx: C,\n label: string\n): Promise<string | undefined> => {\n let reached = false\n let caught: unknown\n await mw\n .runner()\n .errorHandler(async (error: unknown) => {\n caught = error\n })\n .finalHandler(async () => {\n reached = true\n })\n .run((fn, next) => Promise.resolve(fn(ctx, next)))\n\n if (caught !== undefined) {\n if (isShortCircuit(caught)) return caught.result\n throw caught\n }\n if (!reached) {\n throw new Error(`${label} input pipeline did not call next() and did not short-circuit.`)\n }\n return undefined\n}\n\n/**\n * Run an output pipeline over `ctx`; rethrow any stage error to the caller's try/catch. A\n * non-terminal pipeline (no `next()`) throws.\n *\n * @param mw - The `Middleware` instance holding the stages (a fresh `.runner()` is minted here).\n * @param ctx - The mutable output context handed to each stage.\n * @param label - Battery name, used in the non-terminal error message.\n */\nexport const runOutputPipeline = async <C>(\n mw: Middleware<MiddlewareFn<C>>,\n ctx: C,\n label: string\n): Promise<void> => {\n let reached = false\n let caught: unknown\n await mw\n .runner()\n .errorHandler(async (error: unknown) => {\n caught = error\n })\n .finalHandler(async () => {\n reached = true\n })\n .run((fn, next) => Promise.resolve(fn(ctx, next)))\n\n if (caught !== undefined) throw caught\n if (!reached) throw new Error(`${label} output pipeline did not call next().`)\n}\n"],"mappings":";;;;;;;;;;;;;AA+CA,IAAa,iBAAiB,OAC5B,YACyB;CACzB,IAAI,OAAO,YAAY,YAAY,OAAO,EAAE,GAAI,MAAM,QAAQ,EAAG;CACjE,OAAO,EAAE,GAAI,WAAW,CAAC,EAAG;AAC9B;;AA2BA,IAAM,iBAAiB,UAA4B;CACjD,IAAI,sBAAA,SAAS,KAAK,KAAK,aAAa,OAAO;EACzC,MAAM,MAAO,MAAgC;EAC7C,IAAI,yBAAA,gBAAgB,6BAA6B,GAAG,GAAG,OAAO;CAChE;CACA,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,IAAa,kBAAkB,OAC7B,UACA,cACuC;CAEvC,IAAI,yBAAA,gBAAgB,6BAA6B,QAAQ,GAAG;EAC1D,MAAM,OAAO;EACb,aAAa;CACf;CAEA,IAAI,OAAO,aAAa,YACtB,UAAU,4EAA4E;CAExF,IAAI;CACJ,IAAI;EACF,WAAW,MAAO,SAA2B;CAC/C,SAAS,KAAK;EACZ,UAAU,4BAA4B,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG,GAAG;CAClF;CACA,WAAW,cAAc,QAAQ;CACjC,IAAI,CAAC,yBAAA,gBAAgB,6BAA6B,QAAQ,GACxD,UAAU,oEAAoE;CAEhF,MAAM,OAAO;CACb,aAAa;AACf;;;;;;;;;;AAWA,IAAa,uBACX,UACA,cACgC;CAChC,IAAI,yBAAA,gBAAgB,6BAA6B,QAAQ,GAAG;EAC1D,MAAM,OAAO;EACb,aAAa;CACf;CACA,IAAI,OAAO,aAAa,YACtB,UAAU,4EAA4E;CAExF,IAAI;CACJ,IAAI;EACF,WAAY,SAA2B;CACzC,SAAS,KAAK;EACZ,UAAU,4BAA4B,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OA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