@nhtio/adk 0.1.0-master-f0aa531d

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 (297) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +3 -0
  3. package/batteries/index.d.ts +28 -0
  4. package/batteries/llm/index.d.ts +11 -0
  5. package/batteries/llm/openai_chat_completions/adapter.cjs +916 -0
  6. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -0
  7. package/batteries/llm/openai_chat_completions/adapter.d.ts +101 -0
  8. package/batteries/llm/openai_chat_completions/adapter.mjs +914 -0
  9. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -0
  10. package/batteries/llm/openai_chat_completions/exceptions.cjs +89 -0
  11. package/batteries/llm/openai_chat_completions/exceptions.cjs.map +1 -0
  12. package/batteries/llm/openai_chat_completions/exceptions.d.ts +97 -0
  13. package/batteries/llm/openai_chat_completions/exceptions.mjs +81 -0
  14. package/batteries/llm/openai_chat_completions/exceptions.mjs.map +1 -0
  15. package/batteries/llm/openai_chat_completions/helpers.cjs +819 -0
  16. package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -0
  17. package/batteries/llm/openai_chat_completions/helpers.d.ts +233 -0
  18. package/batteries/llm/openai_chat_completions/helpers.mjs +783 -0
  19. package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -0
  20. package/batteries/llm/openai_chat_completions/index.d.ts +27 -0
  21. package/batteries/llm/openai_chat_completions/types.cjs +1 -0
  22. package/batteries/llm/openai_chat_completions/types.d.ts +524 -0
  23. package/batteries/llm/openai_chat_completions/types.mjs +0 -0
  24. package/batteries/llm/openai_chat_completions/validation.cjs +190 -0
  25. package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -0
  26. package/batteries/llm/openai_chat_completions/validation.d.ts +31 -0
  27. package/batteries/llm/openai_chat_completions/validation.mjs +187 -0
  28. package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -0
  29. package/batteries/llm/openai_chat_completions.cjs +51 -0
  30. package/batteries/llm/openai_chat_completions.mjs +5 -0
  31. package/batteries/llm/webllm_chat_completions/adapter.cjs +658 -0
  32. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -0
  33. package/batteries/llm/webllm_chat_completions/adapter.d.ts +103 -0
  34. package/batteries/llm/webllm_chat_completions/adapter.mjs +656 -0
  35. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -0
  36. package/batteries/llm/webllm_chat_completions/exceptions.cjs +70 -0
  37. package/batteries/llm/webllm_chat_completions/exceptions.cjs.map +1 -0
  38. package/batteries/llm/webllm_chat_completions/exceptions.d.ts +74 -0
  39. package/batteries/llm/webllm_chat_completions/exceptions.mjs +65 -0
  40. package/batteries/llm/webllm_chat_completions/exceptions.mjs.map +1 -0
  41. package/batteries/llm/webllm_chat_completions/helpers.cjs +38 -0
  42. package/batteries/llm/webllm_chat_completions/helpers.d.ts +6 -0
  43. package/batteries/llm/webllm_chat_completions/helpers.mjs +2 -0
  44. package/batteries/llm/webllm_chat_completions/index.d.ts +25 -0
  45. package/batteries/llm/webllm_chat_completions/types.d.ts +31 -0
  46. package/batteries/llm/webllm_chat_completions/validation.cjs +115 -0
  47. package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -0
  48. package/batteries/llm/webllm_chat_completions/validation.d.ts +8 -0
  49. package/batteries/llm/webllm_chat_completions/validation.mjs +112 -0
  50. package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -0
  51. package/batteries/llm/webllm_chat_completions.cjs +50 -0
  52. package/batteries/llm/webllm_chat_completions.mjs +6 -0
  53. package/batteries/llm.cjs +63 -0
  54. package/batteries/llm.mjs +10 -0
  55. package/batteries/storage/flydrive/index.d.ts +167 -0
  56. package/batteries/storage/flydrive.cjs +249 -0
  57. package/batteries/storage/flydrive.cjs.map +1 -0
  58. package/batteries/storage/flydrive.mjs +249 -0
  59. package/batteries/storage/flydrive.mjs.map +1 -0
  60. package/batteries/storage/in_memory/index.d.ts +106 -0
  61. package/batteries/storage/in_memory.cjs +121 -0
  62. package/batteries/storage/in_memory.cjs.map +1 -0
  63. package/batteries/storage/in_memory.mjs +119 -0
  64. package/batteries/storage/in_memory.mjs.map +1 -0
  65. package/batteries/storage/index.d.ts +18 -0
  66. package/batteries/storage/opfs/index.d.ts +299 -0
  67. package/batteries/storage/opfs.cjs +368 -0
  68. package/batteries/storage/opfs.cjs.map +1 -0
  69. package/batteries/storage/opfs.mjs +366 -0
  70. package/batteries/storage/opfs.mjs.map +1 -0
  71. package/batteries/storage.cjs +4 -0
  72. package/batteries/storage.mjs +2 -0
  73. package/batteries/tools/color/index.d.ts +37 -0
  74. package/batteries/tools/color.cjs +659 -0
  75. package/batteries/tools/color.cjs.map +1 -0
  76. package/batteries/tools/color.mjs +655 -0
  77. package/batteries/tools/color.mjs.map +1 -0
  78. package/batteries/tools/comparison/index.d.ts +29 -0
  79. package/batteries/tools/comparison.cjs +171 -0
  80. package/batteries/tools/comparison.cjs.map +1 -0
  81. package/batteries/tools/comparison.mjs +168 -0
  82. package/batteries/tools/comparison.mjs.map +1 -0
  83. package/batteries/tools/data_structure/index.d.ts +30 -0
  84. package/batteries/tools/data_structure.cjs +270 -0
  85. package/batteries/tools/data_structure.cjs.map +1 -0
  86. package/batteries/tools/data_structure.mjs +267 -0
  87. package/batteries/tools/data_structure.mjs.map +1 -0
  88. package/batteries/tools/datetime_extended/index.d.ts +51 -0
  89. package/batteries/tools/datetime_extended.cjs +309 -0
  90. package/batteries/tools/datetime_extended.cjs.map +1 -0
  91. package/batteries/tools/datetime_extended.mjs +302 -0
  92. package/batteries/tools/datetime_extended.mjs.map +1 -0
  93. package/batteries/tools/datetime_math/index.d.ts +36 -0
  94. package/batteries/tools/datetime_math.cjs +175 -0
  95. package/batteries/tools/datetime_math.cjs.map +1 -0
  96. package/batteries/tools/datetime_math.mjs +171 -0
  97. package/batteries/tools/datetime_math.mjs.map +1 -0
  98. package/batteries/tools/encoding/index.d.ts +36 -0
  99. package/batteries/tools/encoding.cjs +156 -0
  100. package/batteries/tools/encoding.cjs.map +1 -0
  101. package/batteries/tools/encoding.mjs +152 -0
  102. package/batteries/tools/encoding.mjs.map +1 -0
  103. package/batteries/tools/formatting/index.d.ts +28 -0
  104. package/batteries/tools/formatting.cjs +120 -0
  105. package/batteries/tools/formatting.cjs.map +1 -0
  106. package/batteries/tools/formatting.mjs +117 -0
  107. package/batteries/tools/formatting.mjs.map +1 -0
  108. package/batteries/tools/geo_basics/index.d.ts +33 -0
  109. package/batteries/tools/geo_basics.cjs +136 -0
  110. package/batteries/tools/geo_basics.cjs.map +1 -0
  111. package/batteries/tools/geo_basics.mjs +132 -0
  112. package/batteries/tools/geo_basics.mjs.map +1 -0
  113. package/batteries/tools/index.d.ts +32 -0
  114. package/batteries/tools/math/index.d.ts +37 -0
  115. package/batteries/tools/math.cjs +136 -0
  116. package/batteries/tools/math.cjs.map +1 -0
  117. package/batteries/tools/math.mjs +133 -0
  118. package/batteries/tools/math.mjs.map +1 -0
  119. package/batteries/tools/memory/index.d.ts +73 -0
  120. package/batteries/tools/memory.cjs +193 -0
  121. package/batteries/tools/memory.cjs.map +1 -0
  122. package/batteries/tools/memory.mjs +187 -0
  123. package/batteries/tools/memory.mjs.map +1 -0
  124. package/batteries/tools/parsing/index.d.ts +47 -0
  125. package/batteries/tools/parsing.cjs +191 -0
  126. package/batteries/tools/parsing.cjs.map +1 -0
  127. package/batteries/tools/parsing.mjs +185 -0
  128. package/batteries/tools/parsing.mjs.map +1 -0
  129. package/batteries/tools/retrievables/index.d.ts +81 -0
  130. package/batteries/tools/retrievables.cjs +215 -0
  131. package/batteries/tools/retrievables.cjs.map +1 -0
  132. package/batteries/tools/retrievables.mjs +209 -0
  133. package/batteries/tools/retrievables.mjs.map +1 -0
  134. package/batteries/tools/standing_instructions/index.d.ts +64 -0
  135. package/batteries/tools/standing_instructions.cjs +126 -0
  136. package/batteries/tools/standing_instructions.cjs.map +1 -0
  137. package/batteries/tools/standing_instructions.mjs +121 -0
  138. package/batteries/tools/standing_instructions.mjs.map +1 -0
  139. package/batteries/tools/statistics/index.d.ts +46 -0
  140. package/batteries/tools/statistics.cjs +253 -0
  141. package/batteries/tools/statistics.cjs.map +1 -0
  142. package/batteries/tools/statistics.mjs +248 -0
  143. package/batteries/tools/statistics.mjs.map +1 -0
  144. package/batteries/tools/string_processing/index.d.ts +29 -0
  145. package/batteries/tools/string_processing.cjs +154 -0
  146. package/batteries/tools/string_processing.cjs.map +1 -0
  147. package/batteries/tools/string_processing.mjs +151 -0
  148. package/batteries/tools/string_processing.mjs.map +1 -0
  149. package/batteries/tools/structured_data/index.d.ts +34 -0
  150. package/batteries/tools/structured_data.cjs +189 -0
  151. package/batteries/tools/structured_data.cjs.map +1 -0
  152. package/batteries/tools/structured_data.mjs +185 -0
  153. package/batteries/tools/structured_data.mjs.map +1 -0
  154. package/batteries/tools/text_analysis/index.d.ts +31 -0
  155. package/batteries/tools/text_analysis.cjs +120 -0
  156. package/batteries/tools/text_analysis.cjs.map +1 -0
  157. package/batteries/tools/text_analysis.mjs +117 -0
  158. package/batteries/tools/text_analysis.mjs.map +1 -0
  159. package/batteries/tools/text_comparison/index.d.ts +28 -0
  160. package/batteries/tools/text_comparison.cjs +96 -0
  161. package/batteries/tools/text_comparison.cjs.map +1 -0
  162. package/batteries/tools/text_comparison.mjs +93 -0
  163. package/batteries/tools/text_comparison.mjs.map +1 -0
  164. package/batteries/tools/time/index.d.ts +27 -0
  165. package/batteries/tools/time.cjs +63 -0
  166. package/batteries/tools/time.cjs.map +1 -0
  167. package/batteries/tools/time.mjs +60 -0
  168. package/batteries/tools/time.mjs.map +1 -0
  169. package/batteries/tools/unit_conversion/index.d.ts +19 -0
  170. package/batteries/tools/unit_conversion.cjs +452 -0
  171. package/batteries/tools/unit_conversion.cjs.map +1 -0
  172. package/batteries/tools/unit_conversion.mjs +450 -0
  173. package/batteries/tools/unit_conversion.mjs.map +1 -0
  174. package/batteries/tools.cjs +80 -0
  175. package/batteries/tools.mjs +21 -0
  176. package/batteries.cjs +142 -0
  177. package/batteries.mjs +30 -0
  178. package/chunk-KmRHZBOW.js +35 -0
  179. package/common-DeZaonK1.mjs +208 -0
  180. package/common-DeZaonK1.mjs.map +1 -0
  181. package/common-Od8edUXU.js +232 -0
  182. package/common-Od8edUXU.js.map +1 -0
  183. package/common.cjs +31 -0
  184. package/common.d.ts +108 -0
  185. package/common.mjs +8 -0
  186. package/dispatch_runner-9j6bXHL3.mjs +1609 -0
  187. package/dispatch_runner-9j6bXHL3.mjs.map +1 -0
  188. package/dispatch_runner-CsoH0nld.js +1627 -0
  189. package/dispatch_runner-CsoH0nld.js.map +1 -0
  190. package/dispatch_runner.cjs +3 -0
  191. package/dispatch_runner.d.ts +17 -0
  192. package/dispatch_runner.mjs +2 -0
  193. package/exceptions-D5YrO9Vm.js +280 -0
  194. package/exceptions-D5YrO9Vm.js.map +1 -0
  195. package/exceptions-NrzIHw_R.mjs +244 -0
  196. package/exceptions-NrzIHw_R.mjs.map +1 -0
  197. package/exceptions.cjs +33 -0
  198. package/exceptions.d.ts +52 -0
  199. package/exceptions.mjs +3 -0
  200. package/factories.cjs +4 -0
  201. package/factories.d.ts +39 -0
  202. package/factories.mjs +2 -0
  203. package/forge.cjs +9 -0
  204. package/forge.d.ts +49 -0
  205. package/forge.mjs +5 -0
  206. package/guards.cjs +96 -0
  207. package/guards.cjs.map +1 -0
  208. package/guards.d.ts +83 -0
  209. package/guards.mjs +72 -0
  210. package/guards.mjs.map +1 -0
  211. package/index.cjs +107 -0
  212. package/index.cjs.map +1 -0
  213. package/index.d.ts +18 -0
  214. package/index.mjs +31 -0
  215. package/index.mjs.map +1 -0
  216. package/lib/classes/artifact_tool.d.ts +129 -0
  217. package/lib/classes/base_exception.d.ts +83 -0
  218. package/lib/classes/identity.d.ts +71 -0
  219. package/lib/classes/media.d.ts +326 -0
  220. package/lib/classes/memory.d.ts +72 -0
  221. package/lib/classes/message.d.ts +137 -0
  222. package/lib/classes/registry.d.ts +79 -0
  223. package/lib/classes/retrievable.d.ts +100 -0
  224. package/lib/classes/spooled_artifact.d.ts +296 -0
  225. package/lib/classes/spooled_json_artifact.d.ts +158 -0
  226. package/lib/classes/spooled_markdown_artifact.d.ts +202 -0
  227. package/lib/classes/thought.d.ts +142 -0
  228. package/lib/classes/tokenizable.d.ts +124 -0
  229. package/lib/classes/tool.d.ts +228 -0
  230. package/lib/classes/tool_call.d.ts +190 -0
  231. package/lib/classes/tool_registry.d.ts +159 -0
  232. package/lib/classes/turn_gate.d.ts +109 -0
  233. package/lib/contracts/dispatch_context.d.ts +345 -0
  234. package/lib/contracts/media_reader.d.ts +60 -0
  235. package/lib/contracts/spool_reader.d.ts +80 -0
  236. package/lib/contracts/spooled_artifact_constructor.d.ts +38 -0
  237. package/lib/contracts/turn_runner_config.d.ts +101 -0
  238. package/lib/contracts/turn_runner_context.d.ts +267 -0
  239. package/lib/dispatch_runner.d.ts +98 -0
  240. package/lib/exceptions/runtime.d.ts +370 -0
  241. package/lib/helpers/media_readers.d.ts +39 -0
  242. package/lib/turn_runner.d.ts +144 -0
  243. package/lib/types/dispatch_context.d.ts +233 -0
  244. package/lib/types/dispatch_runner.d.ts +387 -0
  245. package/lib/types/turn_runner.d.ts +322 -0
  246. package/lib/utils/canonical_json.d.ts +18 -0
  247. package/lib/utils/exceptions.d.ts +78 -0
  248. package/lib/utils/guards.d.ts +32 -0
  249. package/lib/utils/validation.d.ts +77 -0
  250. package/package.json +334 -0
  251. package/runtime-BJVkrGQe.js +519 -0
  252. package/runtime-BJVkrGQe.js.map +1 -0
  253. package/runtime-CrEPIFgr.mjs +346 -0
  254. package/runtime-CrEPIFgr.mjs.map +1 -0
  255. package/skills/adk-assembly/SKILL.md +109 -0
  256. package/skills/adk-assembly/references/assembly-contract.md +66 -0
  257. package/skills/adk-assembly/references/executors-tools-pipelines-events.md +113 -0
  258. package/skills/adk-assembly/references/first-integration.md +93 -0
  259. package/skills/adk-assembly/references/storage-and-context.md +102 -0
  260. package/spooled_artifact-C5ZtGxuJ.mjs +544 -0
  261. package/spooled_artifact-C5ZtGxuJ.mjs.map +1 -0
  262. package/spooled_artifact-Cm9Te22K.js +568 -0
  263. package/spooled_artifact-Cm9Te22K.js.map +1 -0
  264. package/spooled_artifact.cjs +7 -0
  265. package/spooled_artifact.d.ts +40 -0
  266. package/spooled_artifact.mjs +3 -0
  267. package/spooled_markdown_artifact-BpUJol0W.mjs +771 -0
  268. package/spooled_markdown_artifact-BpUJol0W.mjs.map +1 -0
  269. package/spooled_markdown_artifact-RRB113sy.js +786 -0
  270. package/spooled_markdown_artifact-RRB113sy.js.map +1 -0
  271. package/thought-CDb457b4.mjs +470 -0
  272. package/thought-CDb457b4.mjs.map +1 -0
  273. package/thought-DuN2PgdO.js +494 -0
  274. package/thought-DuN2PgdO.js.map +1 -0
  275. package/tool-COSeH8I6.js +302 -0
  276. package/tool-COSeH8I6.js.map +1 -0
  277. package/tool-D2WB1EA1.mjs +296 -0
  278. package/tool-D2WB1EA1.mjs.map +1 -0
  279. package/tool_call-BKyyxGaZ.mjs +578 -0
  280. package/tool_call-BKyyxGaZ.mjs.map +1 -0
  281. package/tool_call-DFgzcVcU.js +608 -0
  282. package/tool_call-DFgzcVcU.js.map +1 -0
  283. package/tool_registry-Dkfprsck.js +641 -0
  284. package/tool_registry-Dkfprsck.js.map +1 -0
  285. package/tool_registry-DqLOyGyG.mjs +592 -0
  286. package/tool_registry-DqLOyGyG.mjs.map +1 -0
  287. package/turn_runner-CMm2BHdX.js +615 -0
  288. package/turn_runner-CMm2BHdX.js.map +1 -0
  289. package/turn_runner-y7eyEcJH.mjs +603 -0
  290. package/turn_runner-y7eyEcJH.mjs.map +1 -0
  291. package/turn_runner.cjs +3 -0
  292. package/turn_runner.d.ts +21 -0
  293. package/turn_runner.mjs +2 -0
  294. package/types.cjs +1 -0
  295. package/types.d.ts +56 -0
  296. package/types.mjs +0 -0
  297. package/vite-env.d.ts +23 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opfs.cjs","names":["#handle","#threshold","#load","#readRange","#ready","#init","#buildStreamingIndex","#resolveRoot","#prefix","#defaultThreshold","#keyFor","#getRoot","#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 } 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 {\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 * @param callId - Identifier used to retrieve the bytes via {@link OpfsSpoolStore.read}.\n * @param bytes - The bytes to store, as a `string` or `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,\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 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 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 #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,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,sBAAA,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;CA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S,CAAC;GACf,KAAK,MAAM,SAAS,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,iBAAiB,KAAuB;EACtC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU,OAAO;EAEpD,OADc,IAA2B,SACzB;CAClB;AACF"}
@@ -0,0 +1,366 @@
1
+ import { s as isInstanceOf } from "../../tool_registry-DqLOyGyG.mjs";
2
+ import "../../guards.mjs";
3
+ //#region src/batteries/storage/opfs/index.ts
4
+ /**
5
+ * Browser-only Origin Private File System storage for spooled artifacts.
6
+ *
7
+ * @module @nhtio/adk/batteries/storage/opfs
8
+ *
9
+ * @remarks
10
+ * Opt-in **browser-only** storage battery backed by the
11
+ * [Origin Private File System](https://developer.mozilla.org/docs/Web/API/File_System_API/Origin_private_file_system)
12
+ * (OPFS). Provides {@link OpfsSpoolReader} (a {@link @nhtio/adk!SpoolReader} over a `OpfsFileHandle`)
13
+ * and {@link OpfsSpoolStore} (a `write(callId, bytes) → reader` persistence layer that wraps an
14
+ * OPFS directory).
15
+ *
16
+ * The reader has two modes selected lazily on first method invocation based on the size of the
17
+ * underlying file:
18
+ *
19
+ * - **Eager mode** — when `file.size` is below `streamThresholdBytes` (default 10 MiB), the
20
+ * reader calls `file.text()` once, splits the content on `\n`, and caches lines + byte count.
21
+ * All subsequent calls resolve from memory.
22
+ * - **Streaming mode** — when `file.size` meets or exceeds the threshold, the reader streams the
23
+ * file once via `file.stream().getReader()` to build a line-offset index (`number[]` of byte
24
+ * offsets per line), then serves each `line(i)` request by slicing the underlying `Blob` —
25
+ * `Blob.slice(start, end).text()` decodes only the requested range, no head-of-file scan.
26
+ * Caps RAM at one index + one line buffer regardless of file size.
27
+ *
28
+ * The store auto-selects its write API by execution scope:
29
+ *
30
+ * - In **worker scopes** (`self instanceof WorkerGlobalScope`), it acquires a
31
+ * `FileSystemSyncAccessHandle` and writes synchronously. Sync handles are the only API
32
+ * available in workers and the fastest path for the spool-write hot path.
33
+ * - On the **main thread**, it uses `OpfsFileHandle.createWritable()` and the async
34
+ * stream API. Sync access handles are not exposed on the main thread.
35
+ *
36
+ * This module assumes a browser-equivalent runtime — `navigator.storage`,
37
+ * `OpfsFileHandle`, `TextEncoder`/`TextDecoder`, and `Blob` must all exist. It must not
38
+ * be imported from Node code; do so and you will fail at resolve time when `navigator` is
39
+ * referenced.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'
44
+ *
45
+ * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })
46
+ * const reader = await store.write(callId, bytes)
47
+ * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact
48
+ * const artifact = new Ctor(reader)
49
+ * ```
50
+ */
51
+ var DEFAULT_STREAM_THRESHOLD_BYTES = 10 * 1024 * 1024;
52
+ var LF = 10;
53
+ var isNonNegativeFiniteNumber = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
54
+ /**
55
+ * Returns `true` when the current global scope is a Web Worker (`DedicatedWorkerGlobalScope`,
56
+ * `SharedWorkerGlobalScope`, or `ServiceWorkerGlobalScope` all inherit from `WorkerGlobalScope`).
57
+ *
58
+ * @remarks
59
+ * The check is needed at runtime because `FileSystemSyncAccessHandle` is only exposed in worker
60
+ * scopes — calling it from the main thread throws. We pick the write strategy based on the
61
+ * answer here.
62
+ *
63
+ * @internal
64
+ */
65
+ var isWorkerScope = () => {
66
+ if (typeof WorkerGlobalScope === "undefined") return false;
67
+ return self instanceof WorkerGlobalScope;
68
+ };
69
+ /**
70
+ * Reads an OPFS-backed file as a {@link @nhtio/adk!SpoolReader}.
71
+ *
72
+ * @remarks
73
+ * Constructor is **not** async — but the first method call awaits a private readiness promise
74
+ * that fetches the underlying `File` (and in eager mode, its contents). Subsequent calls reuse
75
+ * the cached state. This keeps construction call sites synchronous while still doing real I/O
76
+ * lazily.
77
+ *
78
+ * All four `SpoolReader` methods on this reader return promises. The `SpoolReader` contract
79
+ * supports both sync and async return; consumers of `SpooledArtifact` handle either.
80
+ */
81
+ var OpfsSpoolReader = class OpfsSpoolReader {
82
+ #handle;
83
+ #threshold;
84
+ #ready;
85
+ constructor(handle, opts = {}) {
86
+ this.#handle = handle;
87
+ const raw = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES;
88
+ if (typeof raw !== "number" || Number.isNaN(raw) || raw < 0) throw new TypeError(`OpfsSpoolReader: streamThresholdBytes must be a non-negative number or Infinity, got ${String(raw)}`);
89
+ this.#threshold = raw;
90
+ }
91
+ /**
92
+ * Returns `true` if `value` is an {@link OpfsSpoolReader} instance.
93
+ *
94
+ * @remarks
95
+ * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.
96
+ *
97
+ * @param value - The value to test.
98
+ * @returns `true` when `value` is an {@link OpfsSpoolReader} instance.
99
+ */
100
+ static isOpfsSpoolReader(value) {
101
+ return isInstanceOf(value, "OpfsSpoolReader", OpfsSpoolReader);
102
+ }
103
+ async line(index) {
104
+ const state = await this.#load();
105
+ if (state.mode === "eager") return state.lines[index];
106
+ if (index < 0 || index >= state.offsets.length - 1) return void 0;
107
+ return this.#readRange(state.file, state.offsets[index], state.offsets[index + 1]);
108
+ }
109
+ async byteLength() {
110
+ return (await this.#load()).bytes;
111
+ }
112
+ async lineCount() {
113
+ const state = await this.#load();
114
+ return state.mode === "eager" ? state.lines.length : state.offsets.length - 1;
115
+ }
116
+ /**
117
+ * Returns the full underlying content as a single decoded string, byte-faithful to the source.
118
+ *
119
+ * @remarks
120
+ * In **eager mode** the content is already cached at first-call load and this method is
121
+ * effectively a property access. In **streaming mode** there is no cache: the file is re-read
122
+ * (as a single `File.text()` call) on every invocation. Use `SpooledArtifact.asString()`
123
+ * judiciously on large streaming-mode artifacts.
124
+ */
125
+ async readAll() {
126
+ const state = await this.#load();
127
+ if (state.mode === "eager") return state.content;
128
+ return state.file.text();
129
+ }
130
+ /**
131
+ * Lazily initialise the reader's mode-specific state. Called by every public method; the
132
+ * promise is cached so the work runs at most once.
133
+ */
134
+ #load() {
135
+ if (!this.#ready) this.#ready = this.#init();
136
+ return this.#ready;
137
+ }
138
+ async #init() {
139
+ const file = await this.#handle.getFile();
140
+ const bytes = file.size;
141
+ if (!isNonNegativeFiniteNumber(bytes)) throw new Error(`OpfsSpoolReader: file handle returned a non-finite size (${String(bytes)})`);
142
+ if (bytes < this.#threshold) {
143
+ const content = await file.text();
144
+ return {
145
+ mode: "eager",
146
+ lines: content === "" ? [] : content.split("\n"),
147
+ bytes,
148
+ content
149
+ };
150
+ }
151
+ return this.#buildStreamingIndex(file, bytes);
152
+ }
153
+ async #buildStreamingIndex(file, bytes) {
154
+ if (bytes === 0) return {
155
+ mode: "streaming",
156
+ file,
157
+ offsets: [0],
158
+ bytes
159
+ };
160
+ const offsets = [0];
161
+ let position = 0;
162
+ let lastByte = -1;
163
+ const reader = file.stream().getReader();
164
+ try {
165
+ for (;;) {
166
+ const { done, value } = await reader.read();
167
+ if (done) break;
168
+ for (const byte of value) {
169
+ position++;
170
+ if (byte === LF) offsets.push(position);
171
+ lastByte = byte;
172
+ }
173
+ }
174
+ } finally {
175
+ reader.releaseLock();
176
+ }
177
+ if (lastByte === LF) offsets.push(position);
178
+ else if (offsets[offsets.length - 1] !== position) offsets.push(position);
179
+ return {
180
+ mode: "streaming",
181
+ file,
182
+ offsets,
183
+ bytes
184
+ };
185
+ }
186
+ /**
187
+ * Slices the byte range `[start, end)` from the backing file and returns it as a UTF-8
188
+ * string, stripping a trailing `\n` if present.
189
+ *
190
+ * @remarks
191
+ * `Blob.slice` is O(1) metadata; `Blob.text()` only decodes the slice. The line-offset index
192
+ * brackets each line *with* its trailing LF (so `offsets[i+1]` points at the start of the
193
+ * next line) and the `SpoolReader` contract returns lines *without* their trailing newline,
194
+ * so we strip a single trailing LF if present.
195
+ */
196
+ async #readRange(file, start, end) {
197
+ if (start === end) return "";
198
+ const text = await file.slice(start, end).text();
199
+ if (text.length > 0 && text.charCodeAt(text.length - 1) === LF) return text.slice(0, -1);
200
+ return text;
201
+ }
202
+ };
203
+ /**
204
+ * "Give bytes, get a reader" persistence layer over an OPFS directory.
205
+ *
206
+ * @remarks
207
+ * `write(callId, bytes)` resolves the root directory (lazily, on first call), opens or creates
208
+ * the file named `keyPrefix + callId`, then writes via the API matching the current scope:
209
+ * a `FileSystemSyncAccessHandle` in worker scopes, `OpfsFileHandle.createWritable()` on
210
+ * the main thread. A fresh {@link OpfsSpoolReader} pointed at the same file is returned.
211
+ *
212
+ * `read(callId)` returns a reader without re-writing; `delete(callId)` removes the entry.
213
+ *
214
+ * The store is otherwise stateless — it owns no in-memory cache of writes. Multiple
215
+ * `OpfsSpoolStore` instances sharing the same root directory and key prefix see the same data.
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * import { OpfsSpoolStore } from '@nhtio/adk/batteries/storage/opfs'
220
+ *
221
+ * const store = new OpfsSpoolStore({ keyPrefix: 'agent-runs/' })
222
+ *
223
+ * const bytes = await tool.executor(ctx)(args)
224
+ * const reader = await store.write(callId, bytes)
225
+ * const Ctor = tool.artifactConstructor?.() ?? SpooledArtifact
226
+ * const artifact = new Ctor(reader)
227
+ * ```
228
+ */
229
+ var OpfsSpoolStore = class OpfsSpoolStore {
230
+ #resolveRoot;
231
+ #prefix;
232
+ #defaultThreshold;
233
+ #root;
234
+ constructor(opts = {}) {
235
+ this.#resolveRoot = opts.directory ?? (() => navigator.storage.getDirectory());
236
+ this.#prefix = opts.keyPrefix ?? "";
237
+ this.#defaultThreshold = opts.streamThresholdBytes ?? DEFAULT_STREAM_THRESHOLD_BYTES;
238
+ }
239
+ /**
240
+ * Returns `true` if `value` is an {@link OpfsSpoolStore} instance.
241
+ *
242
+ * @remarks
243
+ * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.
244
+ *
245
+ * @param value - The value to test.
246
+ * @returns `true` when `value` is an {@link OpfsSpoolStore} instance.
247
+ */
248
+ static isOpfsSpoolStore(value) {
249
+ return isInstanceOf(value, "OpfsSpoolStore", OpfsSpoolStore);
250
+ }
251
+ /**
252
+ * Persists `bytes` under `callId` and returns a reader bound to the stored key.
253
+ *
254
+ * @param callId - Identifier used to retrieve the bytes via {@link OpfsSpoolStore.read}.
255
+ * @param bytes - The bytes to store, as a `string` or `Uint8Array`.
256
+ * @param opts - Per-call override for `streamThresholdBytes`.
257
+ * @returns An {@link OpfsSpoolReader} over the stored bytes.
258
+ */
259
+ async write(callId, bytes, opts) {
260
+ const name = this.#keyFor(callId);
261
+ const handle = await (await this.#getRoot()).getFileHandle(name, { create: true });
262
+ const payload = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
263
+ if (isWorkerScope()) await this.#writeViaSyncHandle(handle, payload);
264
+ else await this.#writeViaWritable(handle, payload);
265
+ return new OpfsSpoolReader(handle, { streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold });
266
+ }
267
+ /**
268
+ * Returns a reader over the bytes previously written under `callId`.
269
+ *
270
+ * @remarks
271
+ * Returns `undefined` if the file does not exist.
272
+ *
273
+ * @param callId - Identifier supplied to a prior {@link OpfsSpoolStore.write} call.
274
+ * @param opts - Per-call override for `streamThresholdBytes`.
275
+ * @returns An {@link OpfsSpoolReader}, or `undefined` if the key is missing.
276
+ */
277
+ async read(callId, opts) {
278
+ const name = this.#keyFor(callId);
279
+ const root = await this.#getRoot();
280
+ let handle;
281
+ try {
282
+ handle = await root.getFileHandle(name);
283
+ } catch (err) {
284
+ if (this.#isNotFoundError(err)) return void 0;
285
+ throw err;
286
+ }
287
+ return new OpfsSpoolReader(handle, { streamThresholdBytes: opts?.streamThresholdBytes ?? this.#defaultThreshold });
288
+ }
289
+ /**
290
+ * Removes the entry under `callId`.
291
+ *
292
+ * @param callId - Identifier whose entry should be removed.
293
+ * @returns `true` if the entry existed and was removed; `false` if it didn't exist.
294
+ */
295
+ async delete(callId) {
296
+ const name = this.#keyFor(callId);
297
+ const root = await this.#getRoot();
298
+ try {
299
+ await root.removeEntry(name);
300
+ return true;
301
+ } catch (err) {
302
+ if (this.#isNotFoundError(err)) return false;
303
+ throw err;
304
+ }
305
+ }
306
+ /**
307
+ * Returns `true` if a file is present under `callId`.
308
+ *
309
+ * @param callId - Identifier to test.
310
+ * @returns `true` when the file exists, `false` otherwise.
311
+ */
312
+ async has(callId) {
313
+ const name = this.#keyFor(callId);
314
+ const root = await this.#getRoot();
315
+ try {
316
+ await root.getFileHandle(name);
317
+ return true;
318
+ } catch (err) {
319
+ if (this.#isNotFoundError(err)) return false;
320
+ throw err;
321
+ }
322
+ }
323
+ /**
324
+ * Returns the full filename for a given `callId` (i.e. `keyPrefix + callId`).
325
+ *
326
+ * @remarks
327
+ * Useful for tests or for callers that want to interact with the underlying OPFS directory
328
+ * directly.
329
+ */
330
+ keyFor(callId) {
331
+ return this.#keyFor(callId);
332
+ }
333
+ #keyFor(callId) {
334
+ return this.#prefix + callId;
335
+ }
336
+ async #getRoot() {
337
+ if (!this.#root) this.#root = await this.#resolveRoot();
338
+ return this.#root;
339
+ }
340
+ async #writeViaSyncHandle(handle, payload) {
341
+ const sync = await handle.createSyncAccessHandle();
342
+ try {
343
+ sync.truncate(0);
344
+ sync.write(payload, { at: 0 });
345
+ sync.flush();
346
+ } finally {
347
+ sync.close();
348
+ }
349
+ }
350
+ async #writeViaWritable(handle, payload) {
351
+ const writable = await handle.createWritable();
352
+ try {
353
+ await writable.write(payload);
354
+ } finally {
355
+ await writable.close();
356
+ }
357
+ }
358
+ #isNotFoundError(err) {
359
+ if (err === null || typeof err !== "object") return false;
360
+ return err.name === "NotFoundError";
361
+ }
362
+ };
363
+ //#endregion
364
+ export { OpfsSpoolReader, OpfsSpoolStore };
365
+
366
+ //# sourceMappingURL=opfs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opfs.mjs","names":["#handle","#threshold","#load","#readRange","#ready","#init","#buildStreamingIndex","#resolveRoot","#prefix","#defaultThreshold","#keyFor","#getRoot","#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 } 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 {\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 * @param callId - Identifier used to retrieve the bytes via {@link OpfsSpoolStore.read}.\n * @param bytes - The bytes to store, as a `string` or `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,\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 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 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 #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,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,M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EACnF,IAAI;GACF,KAAK,SAAS,CAAC;GACf,KAAK,MAAM,SAAS,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,iBAAiB,KAAuB;EACtC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU,OAAO;EAEpD,OADc,IAA2B,SACzB;CAClB;AACF"}
@@ -0,0 +1,4 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_batteries_storage_in_memory = require("./storage/in_memory.cjs");
3
+ exports.InMemorySpoolReader = require_batteries_storage_in_memory.InMemorySpoolReader;
4
+ exports.InMemorySpoolStore = require_batteries_storage_in_memory.InMemorySpoolStore;
@@ -0,0 +1,2 @@
1
+ import { InMemorySpoolReader, InMemorySpoolStore } from "./storage/in_memory.mjs";
2
+ export { InMemorySpoolReader, InMemorySpoolStore };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Pre-constructed tools for color conversion and palette-oriented calculations.
3
+ *
4
+ * @module @nhtio/adk/batteries/tools/color
5
+ *
6
+ * @remarks
7
+ * Pre-constructed bundled tools for the `color` category. Import individually, the whole
8
+ * category, or import every tool via `@nhtio/adk/batteries`.
9
+ */
10
+ import { Tool } from "../../../common";
11
+ /**
12
+ * Compute the WCAG 2.1 contrast ratio between two colours.
13
+ *
14
+ * @remarks
15
+ * Accepts hex (`#rgb`, `#rrggbb`), `rgb()`, `hsl()`, or one of the CSS / Material Design named
16
+ * colours. Reports the ratio and pass/fail against WCAG AA and AAA at both normal and large text
17
+ * sizes. If the foreground/background combination fails AA Normal (4.5:1), the tool suggests
18
+ * lightened or darkened variants that would pass.
19
+ */
20
+ export declare const colorContrastTool: Tool<import("../../../common").SpooledArtifact>;
21
+ /**
22
+ * Generate a colour palette from a base colour using a named harmony.
23
+ *
24
+ * @remarks
25
+ * Supported schemes: `complementary`, `analogous`, `triadic`, `split-complementary`,
26
+ * `monochromatic`. Each entry reports its hex, rgb, and hsl forms, plus the contrast ratio
27
+ * relative to the base colour.
28
+ */
29
+ export declare const colorSchemeTool: Tool<import("../../../common").SpooledArtifact>;
30
+ /**
31
+ * Lighten or darken a colour by a percentage of HSL lightness.
32
+ *
33
+ * @remarks
34
+ * `amount` is clamped to `[1, 100]`; `steps` is clamped to `[1, 10]`. With `steps > 1` the tool
35
+ * emits a ramp of progressively-adjusted colours, useful for generating tint/shade scales.
36
+ */
37
+ export declare const colorAdjustTool: Tool<import("../../../common").SpooledArtifact>;