@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":"memory.cjs","names":[],"sources":["../../../src/batteries/tools/memory/index.ts"],"sourcesContent":["/**\n * Pre-constructed CRUD tools for model-visible ADK memory management.\n *\n * @module @nhtio/adk/batteries/tools/memory\n *\n * @remarks\n * Pre-constructed CRUD tools that expose the ADK's {@link @nhtio/adk!Memory} surface to the model.\n * Each tool delegates to the corresponding callback on the active {@link @nhtio/adk!DispatchContext}\n * (`fetchMemories`, `storeMemory`, `mutateMemory`, `deleteMemory`) — the persistence layer is\n * whatever the consumer wired into the runner.\n *\n * Memory entries carry agent-internal `confidence` / `importance` scores and are rendered\n * through the LLM battery's recall-tier envelope. Letting the model author and curate its own\n * memories is the canonical use case for these tools; deployers who do not want the model to\n * mutate memory should simply not register the relevant tools.\n *\n * Output is JSON for every tool so consumers can parse the result without re-tokenising — the\n * artifact constructor is set to {@link @nhtio/adk!SpooledJsonArtifact}.\n *\n * Tools:\n * - {@link listMemoriesTool} — read-only list of every memory currently held by the context.\n * - {@link storeMemoryTool} — create a new memory (auto-generates `id` / `createdAt` /\n * `updatedAt` unless explicit values are supplied).\n * - {@link updateMemoryTool} — replace an existing memory by `id`. Bumps `updatedAt`.\n * - {@link deleteMemoryTool} — remove a memory by `id`.\n */\n\nimport { DateTime } from 'luxon'\nimport { v6 as uuidv6 } from 'uuid'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\nimport { Memory, SpooledJsonArtifact, Tool } from '@nhtio/adk/common'\n\nconst serialiseMemory = (m: Memory): Record<string, unknown> => ({\n id: m.id,\n content: m.content.toString(),\n confidence: m.confidence,\n importance: m.importance,\n createdAt: m.createdAt.toISO(),\n updatedAt: m.updatedAt.toISO(),\n})\n\n/**\n * List every memory currently held by the active execution context.\n *\n * @remarks\n * Delegates to `ctx.fetchMemories()`. Returns a JSON-encoded array of memory records (id,\n * content, confidence, importance, createdAt, updatedAt). The model can use the `id` values\n * to drive subsequent `update_memory` / `delete_memory` calls.\n */\nexport const listMemoriesTool = new Tool({\n name: 'list_memories',\n description:\n 'List every memory currently held by the agent. Returns a JSON array of memory records with id, content, confidence, importance, createdAt, and updatedAt.',\n inputSchema: validator.object({}),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (_args, ctx) => {\n try {\n const memories = await ctx.fetchMemories()\n return JSON.stringify(memories.map(serialiseMemory), null, 2)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Create a new {@link @nhtio/adk!Memory} record and persist it via the context's `storeMemory` callback.\n *\n * @remarks\n * When `id` is omitted, a UUID v6 is generated. When `createdAt` / `updatedAt` are omitted,\n * the current time is used. The model authors `content`, `confidence`, and `importance`\n * directly. The resulting record is added to `ctx.turnMemories` and flushed to the consumer's\n * persistence layer.\n */\nexport const storeMemoryTool = new Tool({\n name: 'store_memory',\n description:\n 'Store a new memory record. Provide the content, your confidence (0–1) that the memory is accurate, and the importance (0–1) of the memory for future recall. id and timestamps are auto-generated if omitted.',\n inputSchema: validator.object({\n content: validator.string().required().description('The memory content as a plain string.'),\n confidence: validator\n .number()\n .min(0)\n .max(1)\n .required()\n .description('Confidence in [0, 1] that this memory is accurate.'),\n importance: validator\n .number()\n .min(0)\n .max(1)\n .required()\n .description('Importance in [0, 1] — how much weight the memory should carry on recall.'),\n id: validator\n .string()\n .optional()\n .description('Optional stable id. Auto-generated when absent.'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args, ctx) => {\n const { content, confidence, importance, id } = args as {\n content: string\n confidence: number\n importance: number\n id?: string\n }\n try {\n const now = DateTime.now()\n const memory = new Memory({\n id: id ?? uuidv6(),\n content,\n confidence,\n importance,\n createdAt: now,\n updatedAt: now,\n })\n await ctx.storeMemory(memory)\n return JSON.stringify({ ok: true, memory: serialiseMemory(memory) }, null, 2)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Replace an existing {@link @nhtio/adk!Memory} by `id`.\n *\n * @remarks\n * The model supplies `id` plus any subset of `content` / `confidence` / `importance`; fields\n * left undefined retain their prior values. `updatedAt` is always bumped to the current time;\n * `createdAt` is preserved. Returns an error when no memory with the supplied `id` is found.\n */\nexport const updateMemoryTool = new Tool({\n name: 'update_memory',\n description:\n 'Update an existing memory by id. Supply any subset of content / confidence / importance — omitted fields retain their prior values. updatedAt is always refreshed.',\n inputSchema: validator.object({\n id: validator.string().required().description('Id of the memory to update.'),\n content: validator.string().optional().description('Replacement content.'),\n confidence: validator\n .number()\n .min(0)\n .max(1)\n .optional()\n .description('Replacement confidence in [0, 1].'),\n importance: validator\n .number()\n .min(0)\n .max(1)\n .optional()\n .description('Replacement importance in [0, 1].'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args, ctx) => {\n const { id, content, confidence, importance } = args as {\n id: string\n content?: string\n confidence?: number\n importance?: number\n }\n try {\n const memories = await ctx.fetchMemories()\n const existing = memories.find((m) => m.id === id)\n if (!existing) {\n return `Error: No memory found with id \"${id}\".`\n }\n const updated = new Memory({\n id: existing.id,\n content: content ?? existing.content,\n confidence: confidence ?? existing.confidence,\n importance: importance ?? existing.importance,\n createdAt: existing.createdAt,\n updatedAt: DateTime.now(),\n })\n await ctx.mutateMemory(updated)\n return JSON.stringify({ ok: true, memory: serialiseMemory(updated) }, null, 2)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Remove an existing {@link @nhtio/adk!Memory} by `id`.\n *\n * @remarks\n * Delegates to `ctx.deleteMemory(id)`. Returns `{ ok: true, id }` on success regardless of\n * whether a memory was actually present — `deleteMemory` is idempotent at the ADK level.\n */\nexport const deleteMemoryTool = new Tool({\n name: 'delete_memory',\n description: 'Delete a memory by id.',\n inputSchema: validator.object({\n id: validator.string().required().description('Id of the memory to delete.'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args, ctx) => {\n const { id } = args as { id: string }\n try {\n await ctx.deleteMemory(id)\n return JSON.stringify({ ok: true, id }, null, 2)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Convenience tuple of every memory CRUD tool. Spread into a {@link @nhtio/adk!ToolRegistry} to register\n * the entire category at once: `registry.register(...memoryTools)`.\n */\nexport const memoryTools = [\n listMemoriesTool,\n storeMemoryTool,\n updateMemoryTool,\n deleteMemoryTool,\n] as const\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAM,mBAAmB,OAAwC;CAC/D,IAAI,EAAE;CACN,SAAS,EAAE,QAAQ,SAAS;CAC5B,YAAY,EAAE;CACd,YAAY,EAAE;CACd,WAAW,EAAE,UAAU,MAAM;CAC7B,WAAW,EAAE,UAAU,MAAM;AAC/B;;;;;;;;;AAUA,IAAa,mBAAmB,IAAI,aAAA,KAAK;CACvC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO,CAAC,CAAC;CAChC,2BAA2B,kCAAA;CAC3B,SAAS,OAAO,OAAO,QAAQ;EAC7B,IAAI;GACF,MAAM,WAAW,MAAM,IAAI,cAAc;GACzC,OAAO,KAAK,UAAU,SAAS,IAAI,eAAe,GAAG,MAAM,CAAC;EAC9D,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;;;;;;AAWD,IAAa,kBAAkB,IAAI,aAAA,KAAK;CACtC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO;EAC5B,SAAS,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,uCAAuC;EAC1F,YAAY,kBAAA,UACT,OAAO,EACP,IAAI,CAAC,EACL,IAAI,CAAC,EACL,SAAS,EACT,YAAY,oDAAoD;EACnE,YAAY,kBAAA,UACT,OAAO,EACP,IAAI,CAAC,EACL,IAAI,CAAC,EACL,SAAS,EACT,YAAY,2EAA2E;EAC1F,IAAI,kBAAA,U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AAO;IACzB,IAAI,SAAS;IACb,SAAS,WAAW,SAAS;IAC7B,YAAY,cAAc,SAAS;IACnC,YAAY,cAAc,SAAS;IACnC,WAAW,SAAS;IACpB,WAAW,MAAA,SAAS,IAAI;GAC1B,CAAC;GACD,MAAM,IAAI,aAAa,OAAO;GAC9B,OAAO,KAAK,UAAU;IAAE,IAAI;IAAM,QAAQ,gBAAgB,OAAO;GAAE,GAAG,MAAM,CAAC;EAC/E,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;;;;AASD,IAAa,mBAAmB,IAAI,aAAA,KAAK;CACvC,MAAM;CACN,aAAa;CACb,aAAa,kBAAA,UAAU,OAAO,EAC5B,IAAI,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,6BAA6B,EAC7E,CAAC;CACD,2BAA2B,kCAAA;CAC3B,SAAS,OAAO,MAAM,QAAQ;EAC5B,MAAM,EAAE,OAAO;EACf,IAAI;GACF,MAAM,IAAI,aAAa,EAAE;GACzB,OAAO,KAAK,UAAU;IAAE,IAAI;IAAM;GAAG,GAAG,MAAM,CAAC;EACjD,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;AAMD,IAAa,cAAc;CACzB;CACA;CACA;CACA;AACF"}
@@ -0,0 +1,187 @@
1
+ import { o as isError } from "../../tool_registry-DqLOyGyG.mjs";
2
+ import { r as Memory } from "../../thought-CDb457b4.mjs";
3
+ import "../../common-DeZaonK1.mjs";
4
+ import { t as Tool } from "../../tool-D2WB1EA1.mjs";
5
+ import { n as SpooledJsonArtifact } from "../../spooled_markdown_artifact-BpUJol0W.mjs";
6
+ import "../../guards.mjs";
7
+ import { validator } from "@nhtio/validation";
8
+ import { v6 } from "uuid";
9
+ import { DateTime } from "luxon";
10
+ //#region src/batteries/tools/memory/index.ts
11
+ /**
12
+ * Pre-constructed CRUD tools for model-visible ADK memory management.
13
+ *
14
+ * @module @nhtio/adk/batteries/tools/memory
15
+ *
16
+ * @remarks
17
+ * Pre-constructed CRUD tools that expose the ADK's {@link @nhtio/adk!Memory} surface to the model.
18
+ * Each tool delegates to the corresponding callback on the active {@link @nhtio/adk!DispatchContext}
19
+ * (`fetchMemories`, `storeMemory`, `mutateMemory`, `deleteMemory`) — the persistence layer is
20
+ * whatever the consumer wired into the runner.
21
+ *
22
+ * Memory entries carry agent-internal `confidence` / `importance` scores and are rendered
23
+ * through the LLM battery's recall-tier envelope. Letting the model author and curate its own
24
+ * memories is the canonical use case for these tools; deployers who do not want the model to
25
+ * mutate memory should simply not register the relevant tools.
26
+ *
27
+ * Output is JSON for every tool so consumers can parse the result without re-tokenising — the
28
+ * artifact constructor is set to {@link @nhtio/adk!SpooledJsonArtifact}.
29
+ *
30
+ * Tools:
31
+ * - {@link listMemoriesTool} — read-only list of every memory currently held by the context.
32
+ * - {@link storeMemoryTool} — create a new memory (auto-generates `id` / `createdAt` /
33
+ * `updatedAt` unless explicit values are supplied).
34
+ * - {@link updateMemoryTool} — replace an existing memory by `id`. Bumps `updatedAt`.
35
+ * - {@link deleteMemoryTool} — remove a memory by `id`.
36
+ */
37
+ var serialiseMemory = (m) => ({
38
+ id: m.id,
39
+ content: m.content.toString(),
40
+ confidence: m.confidence,
41
+ importance: m.importance,
42
+ createdAt: m.createdAt.toISO(),
43
+ updatedAt: m.updatedAt.toISO()
44
+ });
45
+ /**
46
+ * List every memory currently held by the active execution context.
47
+ *
48
+ * @remarks
49
+ * Delegates to `ctx.fetchMemories()`. Returns a JSON-encoded array of memory records (id,
50
+ * content, confidence, importance, createdAt, updatedAt). The model can use the `id` values
51
+ * to drive subsequent `update_memory` / `delete_memory` calls.
52
+ */
53
+ var listMemoriesTool = new Tool({
54
+ name: "list_memories",
55
+ description: "List every memory currently held by the agent. Returns a JSON array of memory records with id, content, confidence, importance, createdAt, and updatedAt.",
56
+ inputSchema: validator.object({}),
57
+ artifactConstructor: () => SpooledJsonArtifact,
58
+ handler: async (_args, ctx) => {
59
+ try {
60
+ const memories = await ctx.fetchMemories();
61
+ return JSON.stringify(memories.map(serialiseMemory), null, 2);
62
+ } catch (err) {
63
+ return `Error: ${isError(err) ? err.message : String(err)}`;
64
+ }
65
+ }
66
+ });
67
+ /**
68
+ * Create a new {@link @nhtio/adk!Memory} record and persist it via the context's `storeMemory` callback.
69
+ *
70
+ * @remarks
71
+ * When `id` is omitted, a UUID v6 is generated. When `createdAt` / `updatedAt` are omitted,
72
+ * the current time is used. The model authors `content`, `confidence`, and `importance`
73
+ * directly. The resulting record is added to `ctx.turnMemories` and flushed to the consumer's
74
+ * persistence layer.
75
+ */
76
+ var storeMemoryTool = new Tool({
77
+ name: "store_memory",
78
+ description: "Store a new memory record. Provide the content, your confidence (0–1) that the memory is accurate, and the importance (0–1) of the memory for future recall. id and timestamps are auto-generated if omitted.",
79
+ inputSchema: validator.object({
80
+ content: validator.string().required().description("The memory content as a plain string."),
81
+ confidence: validator.number().min(0).max(1).required().description("Confidence in [0, 1] that this memory is accurate."),
82
+ importance: validator.number().min(0).max(1).required().description("Importance in [0, 1] — how much weight the memory should carry on recall."),
83
+ id: validator.string().optional().description("Optional stable id. Auto-generated when absent.")
84
+ }),
85
+ artifactConstructor: () => SpooledJsonArtifact,
86
+ handler: async (args, ctx) => {
87
+ const { content, confidence, importance, id } = args;
88
+ try {
89
+ const now = DateTime.now();
90
+ const memory = new Memory({
91
+ id: id ?? v6(),
92
+ content,
93
+ confidence,
94
+ importance,
95
+ createdAt: now,
96
+ updatedAt: now
97
+ });
98
+ await ctx.storeMemory(memory);
99
+ return JSON.stringify({
100
+ ok: true,
101
+ memory: serialiseMemory(memory)
102
+ }, null, 2);
103
+ } catch (err) {
104
+ return `Error: ${isError(err) ? err.message : String(err)}`;
105
+ }
106
+ }
107
+ });
108
+ /**
109
+ * Replace an existing {@link @nhtio/adk!Memory} by `id`.
110
+ *
111
+ * @remarks
112
+ * The model supplies `id` plus any subset of `content` / `confidence` / `importance`; fields
113
+ * left undefined retain their prior values. `updatedAt` is always bumped to the current time;
114
+ * `createdAt` is preserved. Returns an error when no memory with the supplied `id` is found.
115
+ */
116
+ var updateMemoryTool = new Tool({
117
+ name: "update_memory",
118
+ description: "Update an existing memory by id. Supply any subset of content / confidence / importance — omitted fields retain their prior values. updatedAt is always refreshed.",
119
+ inputSchema: validator.object({
120
+ id: validator.string().required().description("Id of the memory to update."),
121
+ content: validator.string().optional().description("Replacement content."),
122
+ confidence: validator.number().min(0).max(1).optional().description("Replacement confidence in [0, 1]."),
123
+ importance: validator.number().min(0).max(1).optional().description("Replacement importance in [0, 1].")
124
+ }),
125
+ artifactConstructor: () => SpooledJsonArtifact,
126
+ handler: async (args, ctx) => {
127
+ const { id, content, confidence, importance } = args;
128
+ try {
129
+ const existing = (await ctx.fetchMemories()).find((m) => m.id === id);
130
+ if (!existing) return `Error: No memory found with id "${id}".`;
131
+ const updated = new Memory({
132
+ id: existing.id,
133
+ content: content ?? existing.content,
134
+ confidence: confidence ?? existing.confidence,
135
+ importance: importance ?? existing.importance,
136
+ createdAt: existing.createdAt,
137
+ updatedAt: DateTime.now()
138
+ });
139
+ await ctx.mutateMemory(updated);
140
+ return JSON.stringify({
141
+ ok: true,
142
+ memory: serialiseMemory(updated)
143
+ }, null, 2);
144
+ } catch (err) {
145
+ return `Error: ${isError(err) ? err.message : String(err)}`;
146
+ }
147
+ }
148
+ });
149
+ /**
150
+ * Remove an existing {@link @nhtio/adk!Memory} by `id`.
151
+ *
152
+ * @remarks
153
+ * Delegates to `ctx.deleteMemory(id)`. Returns `{ ok: true, id }` on success regardless of
154
+ * whether a memory was actually present — `deleteMemory` is idempotent at the ADK level.
155
+ */
156
+ var deleteMemoryTool = new Tool({
157
+ name: "delete_memory",
158
+ description: "Delete a memory by id.",
159
+ inputSchema: validator.object({ id: validator.string().required().description("Id of the memory to delete.") }),
160
+ artifactConstructor: () => SpooledJsonArtifact,
161
+ handler: async (args, ctx) => {
162
+ const { id } = args;
163
+ try {
164
+ await ctx.deleteMemory(id);
165
+ return JSON.stringify({
166
+ ok: true,
167
+ id
168
+ }, null, 2);
169
+ } catch (err) {
170
+ return `Error: ${isError(err) ? err.message : String(err)}`;
171
+ }
172
+ }
173
+ });
174
+ /**
175
+ * Convenience tuple of every memory CRUD tool. Spread into a {@link @nhtio/adk!ToolRegistry} to register
176
+ * the entire category at once: `registry.register(...memoryTools)`.
177
+ */
178
+ var memoryTools = [
179
+ listMemoriesTool,
180
+ storeMemoryTool,
181
+ updateMemoryTool,
182
+ deleteMemoryTool
183
+ ];
184
+ //#endregion
185
+ export { deleteMemoryTool, listMemoriesTool, memoryTools, storeMemoryTool, updateMemoryTool };
186
+
187
+ //# sourceMappingURL=memory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.mjs","names":[],"sources":["../../../src/batteries/tools/memory/index.ts"],"sourcesContent":["/**\n * Pre-constructed CRUD tools for model-visible ADK memory management.\n *\n * @module @nhtio/adk/batteries/tools/memory\n *\n * @remarks\n * Pre-constructed CRUD tools that expose the ADK's {@link @nhtio/adk!Memory} surface to the model.\n * Each tool delegates to the corresponding callback on the active {@link @nhtio/adk!DispatchContext}\n * (`fetchMemories`, `storeMemory`, `mutateMemory`, `deleteMemory`) — the persistence layer is\n * whatever the consumer wired into the runner.\n *\n * Memory entries carry agent-internal `confidence` / `importance` scores and are rendered\n * through the LLM battery's recall-tier envelope. Letting the model author and curate its own\n * memories is the canonical use case for these tools; deployers who do not want the model to\n * mutate memory should simply not register the relevant tools.\n *\n * Output is JSON for every tool so consumers can parse the result without re-tokenising — the\n * artifact constructor is set to {@link @nhtio/adk!SpooledJsonArtifact}.\n *\n * Tools:\n * - {@link listMemoriesTool} — read-only list of every memory currently held by the context.\n * - {@link storeMemoryTool} — create a new memory (auto-generates `id` / `createdAt` /\n * `updatedAt` unless explicit values are supplied).\n * - {@link updateMemoryTool} — replace an existing memory by `id`. Bumps `updatedAt`.\n * - {@link deleteMemoryTool} — remove a memory by `id`.\n */\n\nimport { DateTime } from 'luxon'\nimport { v6 as uuidv6 } from 'uuid'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\nimport { Memory, SpooledJsonArtifact, Tool } from '@nhtio/adk/common'\n\nconst serialiseMemory = (m: Memory): Record<string, unknown> => ({\n id: m.id,\n content: m.content.toString(),\n confidence: m.confidence,\n importance: m.importance,\n createdAt: m.createdAt.toISO(),\n updatedAt: m.updatedAt.toISO(),\n})\n\n/**\n * List every memory currently held by the active execution context.\n *\n * @remarks\n * Delegates to `ctx.fetchMemories()`. Returns a JSON-encoded array of memory records (id,\n * content, confidence, importance, createdAt, updatedAt). The model can use the `id` values\n * to drive subsequent `update_memory` / `delete_memory` calls.\n */\nexport const listMemoriesTool = new Tool({\n name: 'list_memories',\n description:\n 'List every memory currently held by the agent. Returns a JSON array of memory records with id, content, confidence, importance, createdAt, and updatedAt.',\n inputSchema: validator.object({}),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (_args, ctx) => {\n try {\n const memories = await ctx.fetchMemories()\n return JSON.stringify(memories.map(serialiseMemory), null, 2)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Create a new {@link @nhtio/adk!Memory} record and persist it via the context's `storeMemory` callback.\n *\n * @remarks\n * When `id` is omitted, a UUID v6 is generated. When `createdAt` / `updatedAt` are omitted,\n * the current time is used. The model authors `content`, `confidence`, and `importance`\n * directly. The resulting record is added to `ctx.turnMemories` and flushed to the consumer's\n * persistence layer.\n */\nexport const storeMemoryTool = new Tool({\n name: 'store_memory',\n description:\n 'Store a new memory record. Provide the content, your confidence (0–1) that the memory is accurate, and the importance (0–1) of the memory for future recall. id and timestamps are auto-generated if omitted.',\n inputSchema: validator.object({\n content: validator.string().required().description('The memory content as a plain string.'),\n confidence: validator\n .number()\n .min(0)\n .max(1)\n .required()\n .description('Confidence in [0, 1] that this memory is accurate.'),\n importance: validator\n .number()\n .min(0)\n .max(1)\n .required()\n .description('Importance in [0, 1] — how much weight the memory should carry on recall.'),\n id: validator\n .string()\n .optional()\n .description('Optional stable id. Auto-generated when absent.'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args, ctx) => {\n const { content, confidence, importance, id } = args as {\n content: string\n confidence: number\n importance: number\n id?: string\n }\n try {\n const now = DateTime.now()\n const memory = new Memory({\n id: id ?? uuidv6(),\n content,\n confidence,\n importance,\n createdAt: now,\n updatedAt: now,\n })\n await ctx.storeMemory(memory)\n return JSON.stringify({ ok: true, memory: serialiseMemory(memory) }, null, 2)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Replace an existing {@link @nhtio/adk!Memory} by `id`.\n *\n * @remarks\n * The model supplies `id` plus any subset of `content` / `confidence` / `importance`; fields\n * left undefined retain their prior values. `updatedAt` is always bumped to the current time;\n * `createdAt` is preserved. Returns an error when no memory with the supplied `id` is found.\n */\nexport const updateMemoryTool = new Tool({\n name: 'update_memory',\n description:\n 'Update an existing memory by id. Supply any subset of content / confidence / importance — omitted fields retain their prior values. updatedAt is always refreshed.',\n inputSchema: validator.object({\n id: validator.string().required().description('Id of the memory to update.'),\n content: validator.string().optional().description('Replacement content.'),\n confidence: validator\n .number()\n .min(0)\n .max(1)\n .optional()\n .description('Replacement confidence in [0, 1].'),\n importance: validator\n .number()\n .min(0)\n .max(1)\n .optional()\n .description('Replacement importance in [0, 1].'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args, ctx) => {\n const { id, content, confidence, importance } = args as {\n id: string\n content?: string\n confidence?: number\n importance?: number\n }\n try {\n const memories = await ctx.fetchMemories()\n const existing = memories.find((m) => m.id === id)\n if (!existing) {\n return `Error: No memory found with id \"${id}\".`\n }\n const updated = new Memory({\n id: existing.id,\n content: content ?? existing.content,\n confidence: confidence ?? existing.confidence,\n importance: importance ?? existing.importance,\n createdAt: existing.createdAt,\n updatedAt: DateTime.now(),\n })\n await ctx.mutateMemory(updated)\n return JSON.stringify({ ok: true, memory: serialiseMemory(updated) }, null, 2)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Remove an existing {@link @nhtio/adk!Memory} by `id`.\n *\n * @remarks\n * Delegates to `ctx.deleteMemory(id)`. Returns `{ ok: true, id }` on success regardless of\n * whether a memory was actually present — `deleteMemory` is idempotent at the ADK level.\n */\nexport const deleteMemoryTool = new Tool({\n name: 'delete_memory',\n description: 'Delete a memory by id.',\n inputSchema: validator.object({\n id: validator.string().required().description('Id of the memory to delete.'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args, ctx) => {\n const { id } = args as { id: string }\n try {\n await ctx.deleteMemory(id)\n return JSON.stringify({ ok: true, id }, null, 2)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Convenience tuple of every memory CRUD tool. Spread into a {@link @nhtio/adk!ToolRegistry} to register\n * the entire category at once: `registry.register(...memoryTools)`.\n */\nexport const memoryTools = [\n listMemoriesTool,\n storeMemoryTool,\n updateMemoryTool,\n deleteMemoryTool,\n] as const\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAM,mBAAmB,OAAwC;CAC/D,IAAI,EAAE;CACN,SAAS,EAAE,QAAQ,SAAS;CAC5B,YAAY,EAAE;CACd,YAAY,EAAE;CACd,WAAW,EAAE,UAAU,MAAM;CAC7B,WAAW,EAAE,UAAU,MAAM;AAC/B;;;;;;;;;AAUA,IAAa,mBAAmB,IAAI,KAAK;CACvC,MAAM;CACN,aACE;CACF,aAAa,UAAU,OAAO,CAAC,CAAC;CAChC,2BAA2B;CAC3B,SAAS,OAAO,OAAO,QAAQ;EAC7B,IAAI;GACF,MAAM,WAAW,MAAM,IAAI,cAAc;GACzC,OAAO,KAAK,U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;AACF"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Pre-constructed tools for parsing CSV, TSV, JSON, YAML, and other structured text formats.
3
+ *
4
+ * @module @nhtio/adk/batteries/tools/parsing
5
+ *
6
+ * @remarks
7
+ * Pre-constructed bundled tools for the `parsing` category. Import individually, the whole
8
+ * category, or import every tool via `@nhtio/adk/batteries`.
9
+ */
10
+ import { Tool, SpooledJsonArtifact } from "../../../common";
11
+ /**
12
+ * Parse a CSV or TSV string into a JSON array.
13
+ *
14
+ * @remarks
15
+ * With `has_header: true` (default), each row becomes an object keyed by column name. Without a
16
+ * header, rows are returned as positional arrays. `delimiter` auto-detects when omitted; pass
17
+ * `"\t"` for TSV. Rows are clipped to `limit` (default 1000, max 10000). Parse warnings are
18
+ * prepended to the output.
19
+ */
20
+ export declare const parseCsvTool: Tool<SpooledJsonArtifact<unknown>>;
21
+ /**
22
+ * Parse a YAML string into JSON.
23
+ *
24
+ * @remarks
25
+ * Returns a pretty-printed JSON representation of the parsed YAML document. Invalid YAML
26
+ * returns an error string.
27
+ */
28
+ export declare const parseYamlTool: Tool<SpooledJsonArtifact<unknown>>;
29
+ /**
30
+ * Extract key-value pairs from text.
31
+ *
32
+ * @remarks
33
+ * Handles `.env` files, config files, and query strings. `kv_delimiter` chooses the
34
+ * key→value separator (`=`, `:`, or `auto`); `pair_delimiter` selects how pairs are separated
35
+ * (`newline`, `comma`, `semicolon`, `ampersand`). Surrounding single or double quotes around
36
+ * values are stripped. Comment lines starting with `#` are skipped by default.
37
+ */
38
+ export declare const parseKvTool: Tool<SpooledJsonArtifact<unknown>>;
39
+ /**
40
+ * Detect the most likely field delimiter in a CSV-like text sample.
41
+ *
42
+ * @remarks
43
+ * Tries comma, tab, semicolon, pipe, and colon. Scores each by mean field count divided by
44
+ * variance (so consistent row widths beat noisy splits). Looks at up to the first 20 lines of
45
+ * the first 5000 characters.
46
+ */
47
+ export declare const detectDelimiterTool: Tool<import("../../../common").SpooledArtifact>;
@@ -0,0 +1,191 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_chunk = require("../../chunk-KmRHZBOW.js");
3
+ const require_tool_registry = require("../../tool_registry-Dkfprsck.js");
4
+ require("../../common-Od8edUXU.js");
5
+ const require_tool = require("../../tool-COSeH8I6.js");
6
+ const require_spooled_markdown_artifact = require("../../spooled_markdown_artifact-RRB113sy.js");
7
+ require("../../guards.cjs");
8
+ let _nhtio_validation = require("@nhtio/validation");
9
+ let js_yaml = require("js-yaml");
10
+ let papaparse = require("papaparse");
11
+ papaparse = require_chunk.__toESM(papaparse);
12
+ //#region src/batteries/tools/parsing/index.ts
13
+ /**
14
+ * Pre-constructed tools for parsing CSV, TSV, JSON, YAML, and other structured text formats.
15
+ *
16
+ * @module @nhtio/adk/batteries/tools/parsing
17
+ *
18
+ * @remarks
19
+ * Pre-constructed bundled tools for the `parsing` category. Import individually, the whole
20
+ * category, or import every tool via `@nhtio/adk/batteries`.
21
+ */
22
+ /**
23
+ * Parse a CSV or TSV string into a JSON array.
24
+ *
25
+ * @remarks
26
+ * With `has_header: true` (default), each row becomes an object keyed by column name. Without a
27
+ * header, rows are returned as positional arrays. `delimiter` auto-detects when omitted; pass
28
+ * `"\t"` for TSV. Rows are clipped to `limit` (default 1000, max 10000). Parse warnings are
29
+ * prepended to the output.
30
+ */
31
+ var parseCsvTool = new require_tool.Tool({
32
+ name: "parse_csv",
33
+ description: "Parse a CSV or TSV string into a JSON array. With a header row, returns objects keyed by column name. Without, returns arrays of values.",
34
+ inputSchema: _nhtio_validation.validator.object({
35
+ text: _nhtio_validation.validator.string().required().description("CSV or TSV text to parse"),
36
+ has_header: _nhtio_validation.validator.boolean().default(true).description("First row is a header row (default: true)"),
37
+ delimiter: _nhtio_validation.validator.string().default("").allow("").description("Field delimiter — auto-detected if omitted. Use \"\\t\" for TSV."),
38
+ limit: _nhtio_validation.validator.number().default(1e3).description("Maximum rows to return (default: 1000)")
39
+ }),
40
+ artifactConstructor: () => require_spooled_markdown_artifact.SpooledJsonArtifact,
41
+ handler: async (args) => {
42
+ const { text, has_header: hasHeader, delimiter, limit: rawLimit } = args;
43
+ const limit = Math.min(1e4, Math.max(1, Math.floor(rawLimit)));
44
+ try {
45
+ const result = papaparse.default.parse(text.trim(), {
46
+ header: hasHeader,
47
+ delimiter: delimiter || void 0,
48
+ skipEmptyLines: true,
49
+ dynamicTyping: true
50
+ });
51
+ const rows = result.data.slice(0, limit);
52
+ const warnings = result.errors.length > 0 ? `Parse warnings: ${result.errors.slice(0, 3).map((e) => e.message).join("; ")}\n\n` : "";
53
+ const truncated = result.data.length > limit ? `\n\n(Showing ${limit} of ${result.data.length} rows)` : "";
54
+ return warnings + JSON.stringify(rows, null, 2) + truncated;
55
+ } catch (err) {
56
+ return `Error: ${require_tool_registry.isError(err) ? err.message : String(err)}`;
57
+ }
58
+ }
59
+ });
60
+ /**
61
+ * Parse a YAML string into JSON.
62
+ *
63
+ * @remarks
64
+ * Returns a pretty-printed JSON representation of the parsed YAML document. Invalid YAML
65
+ * returns an error string.
66
+ */
67
+ var parseYamlTool = new require_tool.Tool({
68
+ name: "parse_yaml",
69
+ description: "Parse a YAML string and return the equivalent JSON.",
70
+ inputSchema: _nhtio_validation.validator.object({ text: _nhtio_validation.validator.string().required().description("YAML text to parse") }),
71
+ artifactConstructor: () => require_spooled_markdown_artifact.SpooledJsonArtifact,
72
+ handler: async (args) => {
73
+ const { text } = args;
74
+ try {
75
+ const parsed = (0, js_yaml.load)(text);
76
+ return JSON.stringify(parsed, null, 2);
77
+ } catch (err) {
78
+ return `Error: Invalid YAML — ${require_tool_registry.isError(err) ? err.message : String(err)}`;
79
+ }
80
+ }
81
+ });
82
+ /**
83
+ * Extract key-value pairs from text.
84
+ *
85
+ * @remarks
86
+ * Handles `.env` files, config files, and query strings. `kv_delimiter` chooses the
87
+ * key→value separator (`=`, `:`, or `auto`); `pair_delimiter` selects how pairs are separated
88
+ * (`newline`, `comma`, `semicolon`, `ampersand`). Surrounding single or double quotes around
89
+ * values are stripped. Comment lines starting with `#` are skipped by default.
90
+ */
91
+ var parseKvTool = new require_tool.Tool({
92
+ name: "parse_kv",
93
+ description: "Extract key-value pairs from text (e.g. .env files, config files, query strings). Returns a JSON object.",
94
+ inputSchema: _nhtio_validation.validator.object({
95
+ text: _nhtio_validation.validator.string().required().description("Text containing key-value pairs"),
96
+ kv_delimiter: _nhtio_validation.validator.string().valid("=", ":", "auto").default("auto").description("Separator between key and value (default: auto-detect)"),
97
+ pair_delimiter: _nhtio_validation.validator.string().valid("newline", "comma", "semicolon", "ampersand").default("newline").description("Separator between pairs (default: newline)"),
98
+ skip_comments: _nhtio_validation.validator.boolean().default(true).description("Skip lines starting with # (default: true)")
99
+ }),
100
+ artifactConstructor: () => require_spooled_markdown_artifact.SpooledJsonArtifact,
101
+ handler: async (args) => {
102
+ const { text, kv_delimiter: kvDelim, pair_delimiter: pairDelimKey, skip_comments: skipComments } = args;
103
+ const pairDelim = {
104
+ newline: "\n",
105
+ comma: ",",
106
+ semicolon: ";",
107
+ ampersand: "&"
108
+ }[pairDelimKey] ?? "\n";
109
+ const result = {};
110
+ for (const raw of text.split(pairDelim)) {
111
+ const line = raw.trim();
112
+ if (line === "") continue;
113
+ if (skipComments && line.startsWith("#")) continue;
114
+ const delim = kvDelim === "auto" ? line.includes("=") ? "=" : line.includes(":") ? ":" : null : kvDelim;
115
+ if (!delim) continue;
116
+ const sepIdx = line.indexOf(delim);
117
+ if (sepIdx === -1) continue;
118
+ const key = line.slice(0, sepIdx).trim();
119
+ let value = line.slice(sepIdx + delim.length).trim();
120
+ if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
121
+ if (key) result[key] = value;
122
+ }
123
+ return JSON.stringify(result, null, 2);
124
+ }
125
+ });
126
+ /**
127
+ * Detect the most likely field delimiter in a CSV-like text sample.
128
+ *
129
+ * @remarks
130
+ * Tries comma, tab, semicolon, pipe, and colon. Scores each by mean field count divided by
131
+ * variance (so consistent row widths beat noisy splits). Looks at up to the first 20 lines of
132
+ * the first 5000 characters.
133
+ */
134
+ var detectDelimiterTool = new require_tool.Tool({
135
+ name: "detect_delimiter",
136
+ description: "Detect the most likely field delimiter in a CSV-like text sample.",
137
+ inputSchema: _nhtio_validation.validator.object({ text: _nhtio_validation.validator.string().required().description("Sample of the delimited text to analyze") }),
138
+ handler: async (args) => {
139
+ const { text } = args;
140
+ const lines = text.slice(0, 5e3).split("\n").map((l) => l.trim()).filter((l) => l.length > 0).slice(0, 20);
141
+ if (lines.length === 0) return "Error: No lines to analyze.";
142
+ const candidates = [
143
+ {
144
+ delim: ",",
145
+ name: "comma"
146
+ },
147
+ {
148
+ delim: " ",
149
+ name: "tab"
150
+ },
151
+ {
152
+ delim: ";",
153
+ name: "semicolon"
154
+ },
155
+ {
156
+ delim: "|",
157
+ name: "pipe"
158
+ },
159
+ {
160
+ delim: ":",
161
+ name: "colon"
162
+ }
163
+ ];
164
+ let best = {
165
+ name: "comma",
166
+ delim: ",",
167
+ score: -1,
168
+ avgFields: 0
169
+ };
170
+ for (const { delim, name } of candidates) {
171
+ const counts = lines.map((l) => l.split(delim).length - 1);
172
+ const avg = counts.reduce((a, b) => a + b, 0) / counts.length;
173
+ if (avg === 0) continue;
174
+ const score = avg / (1 + counts.reduce((a, b) => a + (b - avg) ** 2, 0) / counts.length);
175
+ if (score > best.score) best = {
176
+ name,
177
+ delim,
178
+ score,
179
+ avgFields: Number.parseFloat((avg + 1).toFixed(1))
180
+ };
181
+ }
182
+ return `Detected delimiter: ${best.name} ("${best.delim === " " ? "\\t" : best.delim}") — ~${best.avgFields} fields per row`;
183
+ }
184
+ });
185
+ //#endregion
186
+ exports.detectDelimiterTool = detectDelimiterTool;
187
+ exports.parseCsvTool = parseCsvTool;
188
+ exports.parseKvTool = parseKvTool;
189
+ exports.parseYamlTool = parseYamlTool;
190
+
191
+ //# sourceMappingURL=parsing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parsing.cjs","names":[],"sources":["../../../src/batteries/tools/parsing/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for parsing CSV, TSV, JSON, YAML, and other structured text formats.\n *\n * @module @nhtio/adk/batteries/tools/parsing\n *\n * @remarks\n * Pre-constructed bundled tools for the `parsing` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { load as parseYaml } from 'js-yaml'\nimport { default as Papa } from 'papaparse'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\nimport { Tool, SpooledJsonArtifact } from '@nhtio/adk/common'\n\n/**\n * Parse a CSV or TSV string into a JSON array.\n *\n * @remarks\n * With `has_header: true` (default), each row becomes an object keyed by column name. Without a\n * header, rows are returned as positional arrays. `delimiter` auto-detects when omitted; pass\n * `\"\\t\"` for TSV. Rows are clipped to `limit` (default 1000, max 10000). Parse warnings are\n * prepended to the output.\n */\nexport const parseCsvTool = new Tool({\n name: 'parse_csv',\n description:\n 'Parse a CSV or TSV string into a JSON array. With a header row, returns objects keyed by column name. Without, returns arrays of values.',\n inputSchema: validator.object({\n text: validator.string().required().description('CSV or TSV text to parse'),\n has_header: validator\n .boolean()\n .default(true)\n .description('First row is a header row (default: true)'),\n delimiter: validator\n .string()\n .default('')\n .allow('')\n .description('Field delimiter — auto-detected if omitted. Use \"\\\\t\" for TSV.'),\n limit: validator.number().default(1000).description('Maximum rows to return (default: 1000)'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args) => {\n const {\n text,\n has_header: hasHeader,\n delimiter,\n limit: rawLimit,\n } = args as {\n text: string\n has_header: boolean\n delimiter: string\n limit: number\n }\n const limit = Math.min(10_000, Math.max(1, Math.floor(rawLimit)))\n\n try {\n const result = Papa.parse<unknown>(text.trim(), {\n header: hasHeader,\n delimiter: delimiter || undefined,\n skipEmptyLines: true,\n dynamicTyping: true,\n })\n\n const rows = (result.data as unknown[]).slice(0, limit)\n const warnings =\n result.errors.length > 0\n ? `Parse warnings: ${result.errors\n .slice(0, 3)\n .map((e) => e.message)\n .join('; ')}\\n\\n`\n : ''\n const truncated =\n result.data.length > limit ? `\\n\\n(Showing ${limit} of ${result.data.length} rows)` : ''\n\n return warnings + JSON.stringify(rows, null, 2) + truncated\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Parse a YAML string into JSON.\n *\n * @remarks\n * Returns a pretty-printed JSON representation of the parsed YAML document. Invalid YAML\n * returns an error string.\n */\nexport const parseYamlTool = new Tool({\n name: 'parse_yaml',\n description: 'Parse a YAML string and return the equivalent JSON.',\n inputSchema: validator.object({\n text: validator.string().required().description('YAML text to parse'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args) => {\n const { text } = args as { text: string }\n try {\n const parsed = parseYaml(text)\n return JSON.stringify(parsed, null, 2)\n } catch (err) {\n return `Error: Invalid YAML — ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Extract key-value pairs from text.\n *\n * @remarks\n * Handles `.env` files, config files, and query strings. `kv_delimiter` chooses the\n * key→value separator (`=`, `:`, or `auto`); `pair_delimiter` selects how pairs are separated\n * (`newline`, `comma`, `semicolon`, `ampersand`). Surrounding single or double quotes around\n * values are stripped. Comment lines starting with `#` are skipped by default.\n */\nexport const parseKvTool = new Tool({\n name: 'parse_kv',\n description:\n 'Extract key-value pairs from text (e.g. .env files, config files, query strings). Returns a JSON object.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text containing key-value pairs'),\n kv_delimiter: validator\n .string()\n .valid('=', ':', 'auto')\n .default('auto')\n .description('Separator between key and value (default: auto-detect)'),\n pair_delimiter: validator\n .string()\n .valid('newline', 'comma', 'semicolon', 'ampersand')\n .default('newline')\n .description('Separator between pairs (default: newline)'),\n skip_comments: validator\n .boolean()\n .default(true)\n .description('Skip lines starting with # (default: true)'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (args) => {\n const {\n text,\n kv_delimiter: kvDelim,\n pair_delimiter: pairDelimKey,\n skip_comments: skipComments,\n } = args as {\n text: string\n kv_delimiter: string\n pair_delimiter: string\n skip_comments: boolean\n }\n\n const pairDelimMap: Record<string, string> = {\n newline: '\\n',\n comma: ',',\n semicolon: ';',\n ampersand: '&',\n }\n const pairDelim = pairDelimMap[pairDelimKey] ?? '\\n'\n\n const result: Record<string, string> = {}\n\n for (const raw of text.split(pairDelim)) {\n const line = raw.trim()\n if (line === '') continue\n if (skipComments && line.startsWith('#')) continue\n\n const delim =\n kvDelim === 'auto' ? (line.includes('=') ? '=' : line.includes(':') ? ':' : null) : kvDelim\n if (!delim) continue\n\n const sepIdx = line.indexOf(delim)\n if (sepIdx === -1) continue\n\n const key = line.slice(0, sepIdx).trim()\n let value = line.slice(sepIdx + delim.length).trim()\n\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1)\n }\n\n if (key) result[key] = value\n }\n\n return JSON.stringify(result, null, 2)\n },\n})\n\n/**\n * Detect the most likely field delimiter in a CSV-like text sample.\n *\n * @remarks\n * Tries comma, tab, semicolon, pipe, and colon. Scores each by mean field count divided by\n * variance (so consistent row widths beat noisy splits). Looks at up to the first 20 lines of\n * the first 5000 characters.\n */\nexport const detectDelimiterTool = new Tool({\n name: 'detect_delimiter',\n description: 'Detect the most likely field delimiter in a CSV-like text sample.',\n inputSchema: validator.object({\n text: validator.string().required().description('Sample of the delimited text to analyze'),\n }),\n handler: async (args) => {\n const { text } = args as { text: string }\n const sample = text.slice(0, 5000)\n const lines = sample\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l.length > 0)\n .slice(0, 20)\n\n if (lines.length === 0) return 'Error: No lines to analyze.'\n\n const candidates: Array<{ delim: string; name: string }> = [\n { delim: ',', name: 'comma' },\n { delim: '\\t', name: 'tab' },\n { delim: ';', name: 'semicolon' },\n { delim: '|', name: 'pipe' },\n { delim: ':', name: 'colon' },\n ]\n\n let best = { name: 'comma', delim: ',', score: -1, avgFields: 0 }\n\n for (const { delim, name } of candidates) {\n const counts = lines.map((l) => l.split(delim).length - 1)\n const avg = counts.reduce((a, b) => a + b, 0) / counts.length\n if (avg === 0) continue\n const fieldVariance = counts.reduce((a, b) => a + (b - avg) ** 2, 0) / counts.length\n const score = avg / (1 + fieldVariance)\n if (score > best.score) {\n best = { name, delim, score, avgFields: Number.parseFloat((avg + 1).toFixed(1)) }\n }\n }\n\n return `Detected delimiter: ${best.name} (\"${best.delim === '\\t' ? '\\\\t' : best.delim}\") — ~${best.avgFields} fields per row`\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,eAAe,IAAI,aAAA,KAAK;CACnC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO;EAC5B,MAAM,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,0BAA0B;EAC1E,YAAY,kBAAA,UACT,QAAQ,EACR,QAAQ,IAAI,EACZ,YAAY,2CAA2C;EAC1D,WAAW,kBAAA,UACR,OAAO,EACP,QAAQ,EAAE,EACV,MAAM,EAAE,EACR,YAAY,kEAAgE;EAC/E,OAAO,kBAAA,UAAU,OAAO,EAAE,QAAQ,GAAI,EAAE,YAAY,wCAAwC;CAC9F,CAAC;CACD,2BAA2B,kCAAA;CAC3B,SAAS,OAAO,SAAS;EACvB,MAAM,EACJ,MACA,YAAY,WACZ,WACA,OAAO,aACL;EAMJ,MAAM,QAAQ,KAAK,IAAI,KAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,CAAC,CAAC;EAEhE,IAAI;GACF,MAAM,SAAS,UAAA,QAAK,MAAe,KAAK,KAAK,GAAG;IAC9C,QAAQ;IACR,WAAW,aAAa,KAAA;IACxB,gBAAgB;IAChB,eAAe;GACjB,CAAC;GAED,MAAM,OAAQ,OAAO,KAAmB,MAAM,GAAG,KAAK;GACtD,MAAM,WACJ,OAAO,OAAO,SAAS,IAC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