@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.
- package/LICENSE.md +9 -0
- package/README.md +3 -0
- package/batteries/index.d.ts +28 -0
- package/batteries/llm/index.d.ts +11 -0
- package/batteries/llm/openai_chat_completions/adapter.cjs +916 -0
- package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -0
- package/batteries/llm/openai_chat_completions/adapter.d.ts +101 -0
- package/batteries/llm/openai_chat_completions/adapter.mjs +914 -0
- package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -0
- package/batteries/llm/openai_chat_completions/exceptions.cjs +89 -0
- package/batteries/llm/openai_chat_completions/exceptions.cjs.map +1 -0
- package/batteries/llm/openai_chat_completions/exceptions.d.ts +97 -0
- package/batteries/llm/openai_chat_completions/exceptions.mjs +81 -0
- package/batteries/llm/openai_chat_completions/exceptions.mjs.map +1 -0
- package/batteries/llm/openai_chat_completions/helpers.cjs +819 -0
- package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -0
- package/batteries/llm/openai_chat_completions/helpers.d.ts +233 -0
- package/batteries/llm/openai_chat_completions/helpers.mjs +783 -0
- package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -0
- package/batteries/llm/openai_chat_completions/index.d.ts +27 -0
- package/batteries/llm/openai_chat_completions/types.cjs +1 -0
- package/batteries/llm/openai_chat_completions/types.d.ts +524 -0
- package/batteries/llm/openai_chat_completions/types.mjs +0 -0
- package/batteries/llm/openai_chat_completions/validation.cjs +190 -0
- package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -0
- package/batteries/llm/openai_chat_completions/validation.d.ts +31 -0
- package/batteries/llm/openai_chat_completions/validation.mjs +187 -0
- package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -0
- package/batteries/llm/openai_chat_completions.cjs +51 -0
- package/batteries/llm/openai_chat_completions.mjs +5 -0
- package/batteries/llm/webllm_chat_completions/adapter.cjs +658 -0
- package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -0
- package/batteries/llm/webllm_chat_completions/adapter.d.ts +103 -0
- package/batteries/llm/webllm_chat_completions/adapter.mjs +656 -0
- package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -0
- package/batteries/llm/webllm_chat_completions/exceptions.cjs +70 -0
- package/batteries/llm/webllm_chat_completions/exceptions.cjs.map +1 -0
- package/batteries/llm/webllm_chat_completions/exceptions.d.ts +74 -0
- package/batteries/llm/webllm_chat_completions/exceptions.mjs +65 -0
- package/batteries/llm/webllm_chat_completions/exceptions.mjs.map +1 -0
- package/batteries/llm/webllm_chat_completions/helpers.cjs +38 -0
- package/batteries/llm/webllm_chat_completions/helpers.d.ts +6 -0
- package/batteries/llm/webllm_chat_completions/helpers.mjs +2 -0
- package/batteries/llm/webllm_chat_completions/index.d.ts +25 -0
- package/batteries/llm/webllm_chat_completions/types.d.ts +31 -0
- package/batteries/llm/webllm_chat_completions/validation.cjs +115 -0
- package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -0
- package/batteries/llm/webllm_chat_completions/validation.d.ts +8 -0
- package/batteries/llm/webllm_chat_completions/validation.mjs +112 -0
- package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -0
- package/batteries/llm/webllm_chat_completions.cjs +50 -0
- package/batteries/llm/webllm_chat_completions.mjs +6 -0
- package/batteries/llm.cjs +63 -0
- package/batteries/llm.mjs +10 -0
- package/batteries/storage/flydrive/index.d.ts +167 -0
- package/batteries/storage/flydrive.cjs +249 -0
- package/batteries/storage/flydrive.cjs.map +1 -0
- package/batteries/storage/flydrive.mjs +249 -0
- package/batteries/storage/flydrive.mjs.map +1 -0
- package/batteries/storage/in_memory/index.d.ts +106 -0
- package/batteries/storage/in_memory.cjs +121 -0
- package/batteries/storage/in_memory.cjs.map +1 -0
- package/batteries/storage/in_memory.mjs +119 -0
- package/batteries/storage/in_memory.mjs.map +1 -0
- package/batteries/storage/index.d.ts +18 -0
- package/batteries/storage/opfs/index.d.ts +299 -0
- package/batteries/storage/opfs.cjs +368 -0
- package/batteries/storage/opfs.cjs.map +1 -0
- package/batteries/storage/opfs.mjs +366 -0
- package/batteries/storage/opfs.mjs.map +1 -0
- package/batteries/storage.cjs +4 -0
- package/batteries/storage.mjs +2 -0
- package/batteries/tools/color/index.d.ts +37 -0
- package/batteries/tools/color.cjs +659 -0
- package/batteries/tools/color.cjs.map +1 -0
- package/batteries/tools/color.mjs +655 -0
- package/batteries/tools/color.mjs.map +1 -0
- package/batteries/tools/comparison/index.d.ts +29 -0
- package/batteries/tools/comparison.cjs +171 -0
- package/batteries/tools/comparison.cjs.map +1 -0
- package/batteries/tools/comparison.mjs +168 -0
- package/batteries/tools/comparison.mjs.map +1 -0
- package/batteries/tools/data_structure/index.d.ts +30 -0
- package/batteries/tools/data_structure.cjs +270 -0
- package/batteries/tools/data_structure.cjs.map +1 -0
- package/batteries/tools/data_structure.mjs +267 -0
- package/batteries/tools/data_structure.mjs.map +1 -0
- package/batteries/tools/datetime_extended/index.d.ts +51 -0
- package/batteries/tools/datetime_extended.cjs +309 -0
- package/batteries/tools/datetime_extended.cjs.map +1 -0
- package/batteries/tools/datetime_extended.mjs +302 -0
- package/batteries/tools/datetime_extended.mjs.map +1 -0
- package/batteries/tools/datetime_math/index.d.ts +36 -0
- package/batteries/tools/datetime_math.cjs +175 -0
- package/batteries/tools/datetime_math.cjs.map +1 -0
- package/batteries/tools/datetime_math.mjs +171 -0
- package/batteries/tools/datetime_math.mjs.map +1 -0
- package/batteries/tools/encoding/index.d.ts +36 -0
- package/batteries/tools/encoding.cjs +156 -0
- package/batteries/tools/encoding.cjs.map +1 -0
- package/batteries/tools/encoding.mjs +152 -0
- package/batteries/tools/encoding.mjs.map +1 -0
- package/batteries/tools/formatting/index.d.ts +28 -0
- package/batteries/tools/formatting.cjs +120 -0
- package/batteries/tools/formatting.cjs.map +1 -0
- package/batteries/tools/formatting.mjs +117 -0
- package/batteries/tools/formatting.mjs.map +1 -0
- package/batteries/tools/geo_basics/index.d.ts +33 -0
- package/batteries/tools/geo_basics.cjs +136 -0
- package/batteries/tools/geo_basics.cjs.map +1 -0
- package/batteries/tools/geo_basics.mjs +132 -0
- package/batteries/tools/geo_basics.mjs.map +1 -0
- package/batteries/tools/index.d.ts +32 -0
- package/batteries/tools/math/index.d.ts +37 -0
- package/batteries/tools/math.cjs +136 -0
- package/batteries/tools/math.cjs.map +1 -0
- package/batteries/tools/math.mjs +133 -0
- package/batteries/tools/math.mjs.map +1 -0
- package/batteries/tools/memory/index.d.ts +73 -0
- package/batteries/tools/memory.cjs +193 -0
- package/batteries/tools/memory.cjs.map +1 -0
- package/batteries/tools/memory.mjs +187 -0
- package/batteries/tools/memory.mjs.map +1 -0
- package/batteries/tools/parsing/index.d.ts +47 -0
- package/batteries/tools/parsing.cjs +191 -0
- package/batteries/tools/parsing.cjs.map +1 -0
- package/batteries/tools/parsing.mjs +185 -0
- package/batteries/tools/parsing.mjs.map +1 -0
- package/batteries/tools/retrievables/index.d.ts +81 -0
- package/batteries/tools/retrievables.cjs +215 -0
- package/batteries/tools/retrievables.cjs.map +1 -0
- package/batteries/tools/retrievables.mjs +209 -0
- package/batteries/tools/retrievables.mjs.map +1 -0
- package/batteries/tools/standing_instructions/index.d.ts +64 -0
- package/batteries/tools/standing_instructions.cjs +126 -0
- package/batteries/tools/standing_instructions.cjs.map +1 -0
- package/batteries/tools/standing_instructions.mjs +121 -0
- package/batteries/tools/standing_instructions.mjs.map +1 -0
- package/batteries/tools/statistics/index.d.ts +46 -0
- package/batteries/tools/statistics.cjs +253 -0
- package/batteries/tools/statistics.cjs.map +1 -0
- package/batteries/tools/statistics.mjs +248 -0
- package/batteries/tools/statistics.mjs.map +1 -0
- package/batteries/tools/string_processing/index.d.ts +29 -0
- package/batteries/tools/string_processing.cjs +154 -0
- package/batteries/tools/string_processing.cjs.map +1 -0
- package/batteries/tools/string_processing.mjs +151 -0
- package/batteries/tools/string_processing.mjs.map +1 -0
- package/batteries/tools/structured_data/index.d.ts +34 -0
- package/batteries/tools/structured_data.cjs +189 -0
- package/batteries/tools/structured_data.cjs.map +1 -0
- package/batteries/tools/structured_data.mjs +185 -0
- package/batteries/tools/structured_data.mjs.map +1 -0
- package/batteries/tools/text_analysis/index.d.ts +31 -0
- package/batteries/tools/text_analysis.cjs +120 -0
- package/batteries/tools/text_analysis.cjs.map +1 -0
- package/batteries/tools/text_analysis.mjs +117 -0
- package/batteries/tools/text_analysis.mjs.map +1 -0
- package/batteries/tools/text_comparison/index.d.ts +28 -0
- package/batteries/tools/text_comparison.cjs +96 -0
- package/batteries/tools/text_comparison.cjs.map +1 -0
- package/batteries/tools/text_comparison.mjs +93 -0
- package/batteries/tools/text_comparison.mjs.map +1 -0
- package/batteries/tools/time/index.d.ts +27 -0
- package/batteries/tools/time.cjs +63 -0
- package/batteries/tools/time.cjs.map +1 -0
- package/batteries/tools/time.mjs +60 -0
- package/batteries/tools/time.mjs.map +1 -0
- package/batteries/tools/unit_conversion/index.d.ts +19 -0
- package/batteries/tools/unit_conversion.cjs +452 -0
- package/batteries/tools/unit_conversion.cjs.map +1 -0
- package/batteries/tools/unit_conversion.mjs +450 -0
- package/batteries/tools/unit_conversion.mjs.map +1 -0
- package/batteries/tools.cjs +80 -0
- package/batteries/tools.mjs +21 -0
- package/batteries.cjs +142 -0
- package/batteries.mjs +30 -0
- package/chunk-KmRHZBOW.js +35 -0
- package/common-DeZaonK1.mjs +208 -0
- package/common-DeZaonK1.mjs.map +1 -0
- package/common-Od8edUXU.js +232 -0
- package/common-Od8edUXU.js.map +1 -0
- package/common.cjs +31 -0
- package/common.d.ts +108 -0
- package/common.mjs +8 -0
- package/dispatch_runner-9j6bXHL3.mjs +1609 -0
- package/dispatch_runner-9j6bXHL3.mjs.map +1 -0
- package/dispatch_runner-CsoH0nld.js +1627 -0
- package/dispatch_runner-CsoH0nld.js.map +1 -0
- package/dispatch_runner.cjs +3 -0
- package/dispatch_runner.d.ts +17 -0
- package/dispatch_runner.mjs +2 -0
- package/exceptions-D5YrO9Vm.js +280 -0
- package/exceptions-D5YrO9Vm.js.map +1 -0
- package/exceptions-NrzIHw_R.mjs +244 -0
- package/exceptions-NrzIHw_R.mjs.map +1 -0
- package/exceptions.cjs +33 -0
- package/exceptions.d.ts +52 -0
- package/exceptions.mjs +3 -0
- package/factories.cjs +4 -0
- package/factories.d.ts +39 -0
- package/factories.mjs +2 -0
- package/forge.cjs +9 -0
- package/forge.d.ts +49 -0
- package/forge.mjs +5 -0
- package/guards.cjs +96 -0
- package/guards.cjs.map +1 -0
- package/guards.d.ts +83 -0
- package/guards.mjs +72 -0
- package/guards.mjs.map +1 -0
- package/index.cjs +107 -0
- package/index.cjs.map +1 -0
- package/index.d.ts +18 -0
- package/index.mjs +31 -0
- package/index.mjs.map +1 -0
- package/lib/classes/artifact_tool.d.ts +129 -0
- package/lib/classes/base_exception.d.ts +83 -0
- package/lib/classes/identity.d.ts +71 -0
- package/lib/classes/media.d.ts +326 -0
- package/lib/classes/memory.d.ts +72 -0
- package/lib/classes/message.d.ts +137 -0
- package/lib/classes/registry.d.ts +79 -0
- package/lib/classes/retrievable.d.ts +100 -0
- package/lib/classes/spooled_artifact.d.ts +296 -0
- package/lib/classes/spooled_json_artifact.d.ts +158 -0
- package/lib/classes/spooled_markdown_artifact.d.ts +202 -0
- package/lib/classes/thought.d.ts +142 -0
- package/lib/classes/tokenizable.d.ts +124 -0
- package/lib/classes/tool.d.ts +228 -0
- package/lib/classes/tool_call.d.ts +190 -0
- package/lib/classes/tool_registry.d.ts +159 -0
- package/lib/classes/turn_gate.d.ts +109 -0
- package/lib/contracts/dispatch_context.d.ts +345 -0
- package/lib/contracts/media_reader.d.ts +60 -0
- package/lib/contracts/spool_reader.d.ts +80 -0
- package/lib/contracts/spooled_artifact_constructor.d.ts +38 -0
- package/lib/contracts/turn_runner_config.d.ts +101 -0
- package/lib/contracts/turn_runner_context.d.ts +267 -0
- package/lib/dispatch_runner.d.ts +98 -0
- package/lib/exceptions/runtime.d.ts +370 -0
- package/lib/helpers/media_readers.d.ts +39 -0
- package/lib/turn_runner.d.ts +144 -0
- package/lib/types/dispatch_context.d.ts +233 -0
- package/lib/types/dispatch_runner.d.ts +387 -0
- package/lib/types/turn_runner.d.ts +322 -0
- package/lib/utils/canonical_json.d.ts +18 -0
- package/lib/utils/exceptions.d.ts +78 -0
- package/lib/utils/guards.d.ts +32 -0
- package/lib/utils/validation.d.ts +77 -0
- package/package.json +334 -0
- package/runtime-BJVkrGQe.js +519 -0
- package/runtime-BJVkrGQe.js.map +1 -0
- package/runtime-CrEPIFgr.mjs +346 -0
- package/runtime-CrEPIFgr.mjs.map +1 -0
- package/skills/adk-assembly/SKILL.md +109 -0
- package/skills/adk-assembly/references/assembly-contract.md +66 -0
- package/skills/adk-assembly/references/executors-tools-pipelines-events.md +113 -0
- package/skills/adk-assembly/references/first-integration.md +93 -0
- package/skills/adk-assembly/references/storage-and-context.md +102 -0
- package/spooled_artifact-C5ZtGxuJ.mjs +544 -0
- package/spooled_artifact-C5ZtGxuJ.mjs.map +1 -0
- package/spooled_artifact-Cm9Te22K.js +568 -0
- package/spooled_artifact-Cm9Te22K.js.map +1 -0
- package/spooled_artifact.cjs +7 -0
- package/spooled_artifact.d.ts +40 -0
- package/spooled_artifact.mjs +3 -0
- package/spooled_markdown_artifact-BpUJol0W.mjs +771 -0
- package/spooled_markdown_artifact-BpUJol0W.mjs.map +1 -0
- package/spooled_markdown_artifact-RRB113sy.js +786 -0
- package/spooled_markdown_artifact-RRB113sy.js.map +1 -0
- package/thought-CDb457b4.mjs +470 -0
- package/thought-CDb457b4.mjs.map +1 -0
- package/thought-DuN2PgdO.js +494 -0
- package/thought-DuN2PgdO.js.map +1 -0
- package/tool-COSeH8I6.js +302 -0
- package/tool-COSeH8I6.js.map +1 -0
- package/tool-D2WB1EA1.mjs +296 -0
- package/tool-D2WB1EA1.mjs.map +1 -0
- package/tool_call-BKyyxGaZ.mjs +578 -0
- package/tool_call-BKyyxGaZ.mjs.map +1 -0
- package/tool_call-DFgzcVcU.js +608 -0
- package/tool_call-DFgzcVcU.js.map +1 -0
- package/tool_registry-Dkfprsck.js +641 -0
- package/tool_registry-Dkfprsck.js.map +1 -0
- package/tool_registry-DqLOyGyG.mjs +592 -0
- package/tool_registry-DqLOyGyG.mjs.map +1 -0
- package/turn_runner-CMm2BHdX.js +615 -0
- package/turn_runner-CMm2BHdX.js.map +1 -0
- package/turn_runner-y7eyEcJH.mjs +603 -0
- package/turn_runner-y7eyEcJH.mjs.map +1 -0
- package/turn_runner.cjs +3 -0
- package/turn_runner.d.ts +21 -0
- package/turn_runner.mjs +2 -0
- package/types.cjs +1 -0
- package/types.d.ts +56 -0
- package/types.mjs +0 -0
- package/vite-env.d.ts +23 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Aggregate barrel for every pre-constructed bundled tool category.
|
|
3
|
+
*
|
|
4
|
+
* @module @nhtio/adk/batteries/tools
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* Aggregate barrel of every bundled tool category. Re-exports each category's tools as named
|
|
8
|
+
* exports so consumers can
|
|
9
|
+
* `import { calculateTool, formatTableTool } from '@nhtio/adk/batteries/tools'`. Each category
|
|
10
|
+
* is also exposed as its own subpath (`@nhtio/adk/batteries/tools/<category>`) for
|
|
11
|
+
* finer-grained tree-shaking.
|
|
12
|
+
*/
|
|
13
|
+
export * from "./color/index";
|
|
14
|
+
export * from "./comparison/index";
|
|
15
|
+
export * from "./data_structure/index";
|
|
16
|
+
export * from "./datetime_extended/index";
|
|
17
|
+
export * from "./datetime_math/index";
|
|
18
|
+
export * from "./encoding/index";
|
|
19
|
+
export * from "./formatting/index";
|
|
20
|
+
export * from "./geo_basics/index";
|
|
21
|
+
export * from "./math/index";
|
|
22
|
+
export * from "./memory/index";
|
|
23
|
+
export * from "./parsing/index";
|
|
24
|
+
export * from "./retrievables/index";
|
|
25
|
+
export * from "./standing_instructions/index";
|
|
26
|
+
export * from "./statistics/index";
|
|
27
|
+
export * from "./string_processing/index";
|
|
28
|
+
export * from "./structured_data/index";
|
|
29
|
+
export * from "./text_analysis/index";
|
|
30
|
+
export * from "./text_comparison/index";
|
|
31
|
+
export * from "./time/index";
|
|
32
|
+
export * from "./unit_conversion/index";
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-constructed tools for safe arithmetic, expression evaluation, and numeric operations.
|
|
3
|
+
*
|
|
4
|
+
* @module @nhtio/adk/batteries/tools/math
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* Pre-constructed bundled tools for the `math` category. Import individually, the whole
|
|
8
|
+
* category, or import every tool via `@nhtio/adk/batteries`.
|
|
9
|
+
*/
|
|
10
|
+
import { Tool } from "../../../common";
|
|
11
|
+
/**
|
|
12
|
+
* Evaluates a mathjs-syntax expression and returns the numeric result alongside the KaTeX
|
|
13
|
+
* representation of the parsed expression.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* Supports arithmetic, trigonometric, logarithmic, exponential, factorial, matrix, and unit
|
|
17
|
+
* operations via `mathjs`. The mathjs instance is hardened: dangerous functions (`import`,
|
|
18
|
+
* `createUnit`, `simplify`, `derivative`, `compile`, `chain`, `reviver`, `replacer`) are
|
|
19
|
+
* disabled to prevent interpreter-surface exposure.
|
|
20
|
+
*
|
|
21
|
+
* Expressions over 1000 characters are rejected with an error string (not thrown). Parse and
|
|
22
|
+
* evaluation errors are also returned as error strings — the tool surfaces math errors as
|
|
23
|
+
* content rather than exceptions, so the model can react to them in-line.
|
|
24
|
+
*/
|
|
25
|
+
export declare const calculateTool: Tool<import("../../../common").SpooledArtifact>;
|
|
26
|
+
/**
|
|
27
|
+
* Translates a LaTeX/KaTeX expression into mathjs syntax, evaluates it, and returns the result.
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* Translates common LaTeX constructs (`\frac{a}{b}`, `\sqrt{...}`, `\cdot`, `\times`, Greek
|
|
31
|
+
* macros like `\pi`, `\left`/`\right` delimiters, `\text{...}`, subscripts, etc.) into their
|
|
32
|
+
* mathjs equivalents before evaluation. Both the source and the translated mathjs expression
|
|
33
|
+
* are subject to the 1000-character length cap.
|
|
34
|
+
*
|
|
35
|
+
* Parse and evaluation errors are returned as error strings rather than thrown.
|
|
36
|
+
*/
|
|
37
|
+
export declare const evaluateKatexTool: Tool<import("../../../common").SpooledArtifact>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
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
|
+
require("../../guards.cjs");
|
|
7
|
+
let _nhtio_validation = require("@nhtio/validation");
|
|
8
|
+
let mathjs = require("mathjs");
|
|
9
|
+
//#region src/batteries/tools/math/index.ts
|
|
10
|
+
/**
|
|
11
|
+
* Pre-constructed tools for safe arithmetic, expression evaluation, and numeric operations.
|
|
12
|
+
*
|
|
13
|
+
* @module @nhtio/adk/batteries/tools/math
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* Pre-constructed bundled tools for the `math` category. Import individually, the whole
|
|
17
|
+
* category, or import every tool via `@nhtio/adk/batteries`.
|
|
18
|
+
*/
|
|
19
|
+
var math = (0, mathjs.create)(mathjs.all);
|
|
20
|
+
for (const fn of [
|
|
21
|
+
"import",
|
|
22
|
+
"createUnit",
|
|
23
|
+
"simplify",
|
|
24
|
+
"derivative",
|
|
25
|
+
"compile",
|
|
26
|
+
"chain",
|
|
27
|
+
"reviver",
|
|
28
|
+
"replacer"
|
|
29
|
+
]) if (fn in math) math[fn] = void 0;
|
|
30
|
+
var MAX_EXPRESSION_LENGTH = 1e3;
|
|
31
|
+
function validateExpression(expr) {
|
|
32
|
+
if (expr.length > MAX_EXPRESSION_LENGTH) return `Expression too long (max ${MAX_EXPRESSION_LENGTH} characters).`;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Convert common LaTeX/KaTeX notation to a mathjs-evaluable expression.
|
|
36
|
+
*/
|
|
37
|
+
function latexToMathjs(latex) {
|
|
38
|
+
let expr = latex.trim();
|
|
39
|
+
expr = expr.replace(/^\$\$?|\$\$?$/g, "");
|
|
40
|
+
expr = expr.replace(/^\\[[(]|\\[\])]$/g, "");
|
|
41
|
+
for (let i = 0; i < 10; i++) {
|
|
42
|
+
const before = expr;
|
|
43
|
+
expr = expr.replace(/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g, "(($1)/($2))");
|
|
44
|
+
if (expr === before) break;
|
|
45
|
+
}
|
|
46
|
+
expr = expr.replace(/\\sqrt\[([^\]]+)\]\s*\{([^{}]*)\}/g, "nthRoot($2, $1)");
|
|
47
|
+
expr = expr.replace(/\\sqrt\s*\{([^{}]*)\}/g, "sqrt($1)");
|
|
48
|
+
expr = expr.replace(/\\(sin|cos|tan|cot|sec|csc|arcsin|arccos|arctan|sinh|cosh|tanh|ln|log|exp|abs|det)/g, "$1");
|
|
49
|
+
expr = expr.replace(/log_\{?(\w+)\}?\s*\(([^)]+)\)/g, "log($2, $1)");
|
|
50
|
+
expr = expr.replace(/\^{([^{}]*)}/g, "^($1)");
|
|
51
|
+
expr = expr.replace(/_\{[^{}]*\}/g, "");
|
|
52
|
+
expr = expr.replace(/_\w/g, "");
|
|
53
|
+
expr = expr.replace(/\\pi/g, "pi");
|
|
54
|
+
expr = expr.replace(/\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g, "$1");
|
|
55
|
+
expr = expr.replace(/\\cdot/g, "*");
|
|
56
|
+
expr = expr.replace(/\\times/g, "*");
|
|
57
|
+
expr = expr.replace(/\\div/g, "/");
|
|
58
|
+
expr = expr.replace(/\\infty/g, "Infinity");
|
|
59
|
+
expr = expr.replace(/\\left\s*([([{|])/g, "$1");
|
|
60
|
+
expr = expr.replace(/\\right\s*([)\]}|])/g, "$1");
|
|
61
|
+
expr = expr.replace(/\\sum/g, "sum");
|
|
62
|
+
expr = expr.replace(/\\prod/g, "prod");
|
|
63
|
+
expr = expr.replace(/\\,/g, " ");
|
|
64
|
+
expr = expr.replace(/\\;/g, " ");
|
|
65
|
+
expr = expr.replace(/\\quad/g, " ");
|
|
66
|
+
expr = expr.replace(/\\qquad/g, " ");
|
|
67
|
+
expr = expr.replace(/\\text\{([^{}]*)\}/g, "");
|
|
68
|
+
expr = expr.replace(/(\d)([a-zA-Z(])/g, "$1*$2");
|
|
69
|
+
expr = expr.replace(/\)\s*\(/g, ")*(");
|
|
70
|
+
expr = expr.replace(/\s+/g, " ").trim();
|
|
71
|
+
return expr;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Evaluates a mathjs-syntax expression and returns the numeric result alongside the KaTeX
|
|
75
|
+
* representation of the parsed expression.
|
|
76
|
+
*
|
|
77
|
+
* @remarks
|
|
78
|
+
* Supports arithmetic, trigonometric, logarithmic, exponential, factorial, matrix, and unit
|
|
79
|
+
* operations via `mathjs`. The mathjs instance is hardened: dangerous functions (`import`,
|
|
80
|
+
* `createUnit`, `simplify`, `derivative`, `compile`, `chain`, `reviver`, `replacer`) are
|
|
81
|
+
* disabled to prevent interpreter-surface exposure.
|
|
82
|
+
*
|
|
83
|
+
* Expressions over 1000 characters are rejected with an error string (not thrown). Parse and
|
|
84
|
+
* evaluation errors are also returned as error strings — the tool surfaces math errors as
|
|
85
|
+
* content rather than exceptions, so the model can react to them in-line.
|
|
86
|
+
*/
|
|
87
|
+
var calculateTool = new require_tool.Tool({
|
|
88
|
+
name: "calculate",
|
|
89
|
+
description: "Evaluate a math expression. Supports arithmetic, trig, log, sqrt, factorial, matrices.",
|
|
90
|
+
inputSchema: _nhtio_validation.validator.object({ expression: _nhtio_validation.validator.string().required().description("Math expression, e.g. \"sin(pi/4) + 5!\"") }),
|
|
91
|
+
handler: async (args) => {
|
|
92
|
+
const { expression } = args;
|
|
93
|
+
const lengthError = validateExpression(expression);
|
|
94
|
+
if (lengthError) return lengthError;
|
|
95
|
+
try {
|
|
96
|
+
const result = math.evaluate(expression);
|
|
97
|
+
return `Result: ${result}\nKaTeX: $${math.parse(expression).toTex()} = ${result}$`;
|
|
98
|
+
} catch (err) {
|
|
99
|
+
return `Error: ${require_tool_registry.isError(err) ? err.message : String(err)}`;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
/**
|
|
104
|
+
* Translates a LaTeX/KaTeX expression into mathjs syntax, evaluates it, and returns the result.
|
|
105
|
+
*
|
|
106
|
+
* @remarks
|
|
107
|
+
* Translates common LaTeX constructs (`\frac{a}{b}`, `\sqrt{...}`, `\cdot`, `\times`, Greek
|
|
108
|
+
* macros like `\pi`, `\left`/`\right` delimiters, `\text{...}`, subscripts, etc.) into their
|
|
109
|
+
* mathjs equivalents before evaluation. Both the source and the translated mathjs expression
|
|
110
|
+
* are subject to the 1000-character length cap.
|
|
111
|
+
*
|
|
112
|
+
* Parse and evaluation errors are returned as error strings rather than thrown.
|
|
113
|
+
*/
|
|
114
|
+
var evaluateKatexTool = new require_tool.Tool({
|
|
115
|
+
name: "evaluate_katex",
|
|
116
|
+
description: "Evaluate a KaTeX/LaTeX math expression and return the numeric result.",
|
|
117
|
+
inputSchema: _nhtio_validation.validator.object({ katex: _nhtio_validation.validator.string().required().description("LaTeX expression, e.g. \"\\frac{1}{2} + \\sqrt{9}\"") }),
|
|
118
|
+
handler: async (args) => {
|
|
119
|
+
const { katex } = args;
|
|
120
|
+
const lengthError = validateExpression(katex);
|
|
121
|
+
if (lengthError) return lengthError;
|
|
122
|
+
try {
|
|
123
|
+
const mathjsExpr = latexToMathjs(katex);
|
|
124
|
+
const translatedLengthError = validateExpression(mathjsExpr);
|
|
125
|
+
if (translatedLengthError) return translatedLengthError;
|
|
126
|
+
return `Converted: ${mathjsExpr}\nResult: ${math.evaluate(mathjsExpr)}`;
|
|
127
|
+
} catch (err) {
|
|
128
|
+
return `Error: ${require_tool_registry.isError(err) ? err.message : String(err)}`;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
//#endregion
|
|
133
|
+
exports.calculateTool = calculateTool;
|
|
134
|
+
exports.evaluateKatexTool = evaluateKatexTool;
|
|
135
|
+
|
|
136
|
+
//# sourceMappingURL=math.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"math.cjs","names":[],"sources":["../../../src/batteries/tools/math/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for safe arithmetic, expression evaluation, and numeric operations.\n *\n * @module @nhtio/adk/batteries/tools/math\n *\n * @remarks\n * Pre-constructed bundled tools for the `math` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { create, all } from 'mathjs'\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\nconst math = create(all)\n\nconst BLOCKED_FUNCTIONS = [\n 'import',\n 'createUnit',\n 'simplify',\n 'derivative',\n 'compile',\n 'chain',\n 'reviver',\n 'replacer',\n]\n\nfor (const fn of BLOCKED_FUNCTIONS) {\n if (fn in math) {\n ;(math as any)[fn] = undefined\n }\n}\n\nconst MAX_EXPRESSION_LENGTH = 1000\n\nfunction validateExpression(expr: string): string | undefined {\n if (expr.length > MAX_EXPRESSION_LENGTH) {\n return `Expression too long (max ${MAX_EXPRESSION_LENGTH} characters).`\n }\n return undefined\n}\n\n/**\n * Convert common LaTeX/KaTeX notation to a mathjs-evaluable expression.\n */\nfunction latexToMathjs(latex: string): string {\n let expr = latex.trim()\n\n expr = expr.replace(/^\\$\\$?|\\$\\$?$/g, '')\n expr = expr.replace(/^\\\\[[(]|\\\\[\\])]$/g, '')\n\n for (let i = 0; i < 10; i++) {\n const before = expr\n expr = expr.replace(/\\\\frac\\s*\\{([^{}]*)\\}\\s*\\{([^{}]*)\\}/g, '(($1)/($2))')\n if (expr === before) break\n }\n\n expr = expr.replace(/\\\\sqrt\\[([^\\]]+)\\]\\s*\\{([^{}]*)\\}/g, 'nthRoot($2, $1)')\n expr = expr.replace(/\\\\sqrt\\s*\\{([^{}]*)\\}/g, 'sqrt($1)')\n\n expr = expr.replace(\n /\\\\(sin|cos|tan|cot|sec|csc|arcsin|arccos|arctan|sinh|cosh|tanh|ln|log|exp|abs|det)/g,\n '$1'\n )\n\n expr = expr.replace(/log_\\{?(\\w+)\\}?\\s*\\(([^)]+)\\)/g, 'log($2, $1)')\n expr = expr.replace(/\\^{([^{}]*)}/g, '^($1)')\n expr = expr.replace(/_\\{[^{}]*\\}/g, '')\n expr = expr.replace(/_\\w/g, '')\n\n expr = expr.replace(/\\\\pi/g, 'pi')\n expr = expr.replace(\n /\\\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g,\n '$1'\n )\n\n expr = expr.replace(/\\\\cdot/g, '*')\n expr = expr.replace(/\\\\times/g, '*')\n expr = expr.replace(/\\\\div/g, '/')\n expr = expr.replace(/\\\\infty/g, 'Infinity')\n expr = expr.replace(/\\\\left\\s*([([{|])/g, '$1')\n expr = expr.replace(/\\\\right\\s*([)\\]}|])/g, '$1')\n expr = expr.replace(/\\\\sum/g, 'sum')\n expr = expr.replace(/\\\\prod/g, 'prod')\n expr = expr.replace(/\\\\,/g, ' ')\n expr = expr.replace(/\\\\;/g, ' ')\n expr = expr.replace(/\\\\quad/g, ' ')\n expr = expr.replace(/\\\\qquad/g, ' ')\n expr = expr.replace(/\\\\text\\{([^{}]*)\\}/g, '')\n expr = expr.replace(/(\\d)([a-zA-Z(])/g, '$1*$2')\n expr = expr.replace(/\\)\\s*\\(/g, ')*(')\n expr = expr.replace(/\\s+/g, ' ').trim()\n\n return expr\n}\n\n/**\n * Evaluates a mathjs-syntax expression and returns the numeric result alongside the KaTeX\n * representation of the parsed expression.\n *\n * @remarks\n * Supports arithmetic, trigonometric, logarithmic, exponential, factorial, matrix, and unit\n * operations via `mathjs`. The mathjs instance is hardened: dangerous functions (`import`,\n * `createUnit`, `simplify`, `derivative`, `compile`, `chain`, `reviver`, `replacer`) are\n * disabled to prevent interpreter-surface exposure.\n *\n * Expressions over 1000 characters are rejected with an error string (not thrown). Parse and\n * evaluation errors are also returned as error strings — the tool surfaces math errors as\n * content rather than exceptions, so the model can react to them in-line.\n */\nexport const calculateTool = new Tool({\n name: 'calculate',\n description:\n 'Evaluate a math expression. Supports arithmetic, trig, log, sqrt, factorial, matrices.',\n inputSchema: validator.object({\n expression: validator.string().required().description('Math expression, e.g. \"sin(pi/4) + 5!\"'),\n }),\n handler: async (args) => {\n const { expression } = args as { expression: string }\n\n const lengthError = validateExpression(expression)\n if (lengthError) return lengthError\n\n try {\n const result = math.evaluate!(expression)\n const node = math.parse!(expression)\n const katex = node.toTex()\n return `Result: ${result}\\nKaTeX: $${katex} = ${result}$`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Translates a LaTeX/KaTeX expression into mathjs syntax, evaluates it, and returns the result.\n *\n * @remarks\n * Translates common LaTeX constructs (`\\frac{a}{b}`, `\\sqrt{...}`, `\\cdot`, `\\times`, Greek\n * macros like `\\pi`, `\\left`/`\\right` delimiters, `\\text{...}`, subscripts, etc.) into their\n * mathjs equivalents before evaluation. Both the source and the translated mathjs expression\n * are subject to the 1000-character length cap.\n *\n * Parse and evaluation errors are returned as error strings rather than thrown.\n */\nexport const evaluateKatexTool = new Tool({\n name: 'evaluate_katex',\n description: 'Evaluate a KaTeX/LaTeX math expression and return the numeric result.',\n inputSchema: validator.object({\n katex: validator\n .string()\n .required()\n .description('LaTeX expression, e.g. \"\\\\frac{1}{2} + \\\\sqrt{9}\"'),\n }),\n handler: async (args) => {\n const { katex } = args as { katex: string }\n\n const lengthError = validateExpression(katex)\n if (lengthError) return lengthError\n\n try {\n const mathjsExpr = latexToMathjs(katex)\n\n const translatedLengthError = validateExpression(mathjsExpr)\n if (translatedLengthError) return translatedLengthError\n\n const result = math.evaluate!(mathjsExpr)\n return `Converted: ${mathjsExpr}\\nResult: ${result}`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,IAAM,QAAA,GAAA,OAAA,QAAc,OAAA,GAAG;AAavB,KAAK,MAAM,MAAM;CAVf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAGe,GACf,IAAI,MAAM,MACP,KAAc,MAAM,KAAA;AAIzB,IAAM,wBAAwB;AAE9B,SAAS,mBAAmB,MAAkC;CAC5D,IAAI,KAAK,SAAS,uBAChB,OAAO,4BAA4B,sBAAsB;AAG7D;;;;AAKA,SAAS,cAAc,OAAuB;CAC5C,IAAI,OAAO,MAAM,KAAK;CAEtB,OAAO,KAAK,QAAQ,kBAAkB,EAAE;CACxC,OAAO,KAAK,QAAQ,qBAAqB,EAAE;CAE3C,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK;EAC3B,MAAM,SAAS;EACf,OAAO,KAAK,QAAQ,yCAAyC,aAAa;EAC1E,IAAI,SAAS,QAAQ;CACvB;CAEA,OAAO,KAAK,QAAQ,sCAAsC,iBAAiB;CAC3E,OAAO,KAAK,QAAQ,0BAA0B,UAAU;CAExD,OAAO,KAAK,QACV,uFACA,IACF;CAEA,OAAO,KAAK,QAAQ,kCAAkC,aAAa;CACnE,OAAO,KAAK,QAAQ,iBAAiB,OAAO;CAC5C,OAAO,KAAK,QAAQ,gBAAgB,EAAE;CACtC,OAAO,KAAK,QAAQ,QAAQ,EAAE;CAE9B,OAAO,KAAK,QAAQ,SAAS,IAAI;CACjC,OAAO,KAAK,QACV,2EACA,IACF;CAEA,OAAO,KAAK,QAAQ,WAAW,GAAG;CAClC,OAAO,KAAK,QAAQ,YAAY,GAAG;CACnC,OAAO,KAAK,QAAQ,UAAU,GAAG;CACjC,OAAO,KAAK,QAAQ,YAAY,UAAU;CAC1C,OAAO,KAAK,QAAQ,sBAAsB,IAAI;CAC9C,OAAO,KAAK,QAAQ,wBAAwB,IAAI;CAChD,OAAO,KAAK,QAAQ,UAAU,KAAK;CACnC,OAAO,KAAK,QAAQ,WAAW,MAAM;CACrC,OAAO,KAAK,QAAQ,QAAQ,GAAG;CAC/B,OAAO,KAAK,QAAQ,QAAQ,GAAG;CAC/B,OAAO,KAAK,QAAQ,WAAW,GAAG;CAClC,OAAO,KAAK,QAAQ,YAAY,GAAG;CACnC,OAAO,KAAK,QAAQ,uBAAuB,EAAE;CAC7C,OAAO,KAAK,QAAQ,oBAAoB,OAAO;CAC/C,OAAO,KAAK,QAAQ,YAAY,KAAK;CACrC,OAAO,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK;CAEtC,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,IAAa,gBAAgB,IAAI,aAAA,KAAK;CACpC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO,EAC5B,YAAY,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,0CAAwC,EAChG,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,eAAe;EAEvB,MAAM,cAAc,mBAAmB,UAAU;EACjD,IAAI,aAAa,OAAO;EAExB,IAAI;GACF,MAAM,SAAS,KAAK,SAAU,UAAU;GAGxC,OAAO,WAAW,OAAO,YAFZ,KAAK,MAAO,UACX,EAAK,MACkB,EAAM,KAAK,OAAO;EACzD,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;;;;;;;;AAaD,IAAa,oBAAoB,IAAI,aAAA,KAAK;CACxC,MAAM;CACN,aAAa;CACb,aAAa,kBAAA,UAAU,OAAO,EAC5B,OAAO,kBAAA,UACJ,OAAO,EACP,SAAS,EACT,YAAY,qDAAmD,EACpE,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,UAAU;EAElB,MAAM,cAAc,mBAAmB,KAAK;EAC5C,IAAI,aAAa,OAAO;EAExB,IAAI;GACF,MAAM,aAAa,cAAc,KAAK;GAEtC,MAAM,wBAAwB,mBAAmB,UAAU;GAC3D,IAAI,uBAAuB,OAAO;GAGlC,OAAO,cAAc,WAAW,YADjB,KAAK,SAAU,UACc;EAC9C,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC"}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { o as isError } from "../../tool_registry-DqLOyGyG.mjs";
|
|
2
|
+
import "../../common-DeZaonK1.mjs";
|
|
3
|
+
import { t as Tool } from "../../tool-D2WB1EA1.mjs";
|
|
4
|
+
import "../../guards.mjs";
|
|
5
|
+
import { validator } from "@nhtio/validation";
|
|
6
|
+
import { all, create } from "mathjs";
|
|
7
|
+
//#region src/batteries/tools/math/index.ts
|
|
8
|
+
/**
|
|
9
|
+
* Pre-constructed tools for safe arithmetic, expression evaluation, and numeric operations.
|
|
10
|
+
*
|
|
11
|
+
* @module @nhtio/adk/batteries/tools/math
|
|
12
|
+
*
|
|
13
|
+
* @remarks
|
|
14
|
+
* Pre-constructed bundled tools for the `math` category. Import individually, the whole
|
|
15
|
+
* category, or import every tool via `@nhtio/adk/batteries`.
|
|
16
|
+
*/
|
|
17
|
+
var math = create(all);
|
|
18
|
+
for (const fn of [
|
|
19
|
+
"import",
|
|
20
|
+
"createUnit",
|
|
21
|
+
"simplify",
|
|
22
|
+
"derivative",
|
|
23
|
+
"compile",
|
|
24
|
+
"chain",
|
|
25
|
+
"reviver",
|
|
26
|
+
"replacer"
|
|
27
|
+
]) if (fn in math) math[fn] = void 0;
|
|
28
|
+
var MAX_EXPRESSION_LENGTH = 1e3;
|
|
29
|
+
function validateExpression(expr) {
|
|
30
|
+
if (expr.length > MAX_EXPRESSION_LENGTH) return `Expression too long (max ${MAX_EXPRESSION_LENGTH} characters).`;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Convert common LaTeX/KaTeX notation to a mathjs-evaluable expression.
|
|
34
|
+
*/
|
|
35
|
+
function latexToMathjs(latex) {
|
|
36
|
+
let expr = latex.trim();
|
|
37
|
+
expr = expr.replace(/^\$\$?|\$\$?$/g, "");
|
|
38
|
+
expr = expr.replace(/^\\[[(]|\\[\])]$/g, "");
|
|
39
|
+
for (let i = 0; i < 10; i++) {
|
|
40
|
+
const before = expr;
|
|
41
|
+
expr = expr.replace(/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g, "(($1)/($2))");
|
|
42
|
+
if (expr === before) break;
|
|
43
|
+
}
|
|
44
|
+
expr = expr.replace(/\\sqrt\[([^\]]+)\]\s*\{([^{}]*)\}/g, "nthRoot($2, $1)");
|
|
45
|
+
expr = expr.replace(/\\sqrt\s*\{([^{}]*)\}/g, "sqrt($1)");
|
|
46
|
+
expr = expr.replace(/\\(sin|cos|tan|cot|sec|csc|arcsin|arccos|arctan|sinh|cosh|tanh|ln|log|exp|abs|det)/g, "$1");
|
|
47
|
+
expr = expr.replace(/log_\{?(\w+)\}?\s*\(([^)]+)\)/g, "log($2, $1)");
|
|
48
|
+
expr = expr.replace(/\^{([^{}]*)}/g, "^($1)");
|
|
49
|
+
expr = expr.replace(/_\{[^{}]*\}/g, "");
|
|
50
|
+
expr = expr.replace(/_\w/g, "");
|
|
51
|
+
expr = expr.replace(/\\pi/g, "pi");
|
|
52
|
+
expr = expr.replace(/\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g, "$1");
|
|
53
|
+
expr = expr.replace(/\\cdot/g, "*");
|
|
54
|
+
expr = expr.replace(/\\times/g, "*");
|
|
55
|
+
expr = expr.replace(/\\div/g, "/");
|
|
56
|
+
expr = expr.replace(/\\infty/g, "Infinity");
|
|
57
|
+
expr = expr.replace(/\\left\s*([([{|])/g, "$1");
|
|
58
|
+
expr = expr.replace(/\\right\s*([)\]}|])/g, "$1");
|
|
59
|
+
expr = expr.replace(/\\sum/g, "sum");
|
|
60
|
+
expr = expr.replace(/\\prod/g, "prod");
|
|
61
|
+
expr = expr.replace(/\\,/g, " ");
|
|
62
|
+
expr = expr.replace(/\\;/g, " ");
|
|
63
|
+
expr = expr.replace(/\\quad/g, " ");
|
|
64
|
+
expr = expr.replace(/\\qquad/g, " ");
|
|
65
|
+
expr = expr.replace(/\\text\{([^{}]*)\}/g, "");
|
|
66
|
+
expr = expr.replace(/(\d)([a-zA-Z(])/g, "$1*$2");
|
|
67
|
+
expr = expr.replace(/\)\s*\(/g, ")*(");
|
|
68
|
+
expr = expr.replace(/\s+/g, " ").trim();
|
|
69
|
+
return expr;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Evaluates a mathjs-syntax expression and returns the numeric result alongside the KaTeX
|
|
73
|
+
* representation of the parsed expression.
|
|
74
|
+
*
|
|
75
|
+
* @remarks
|
|
76
|
+
* Supports arithmetic, trigonometric, logarithmic, exponential, factorial, matrix, and unit
|
|
77
|
+
* operations via `mathjs`. The mathjs instance is hardened: dangerous functions (`import`,
|
|
78
|
+
* `createUnit`, `simplify`, `derivative`, `compile`, `chain`, `reviver`, `replacer`) are
|
|
79
|
+
* disabled to prevent interpreter-surface exposure.
|
|
80
|
+
*
|
|
81
|
+
* Expressions over 1000 characters are rejected with an error string (not thrown). Parse and
|
|
82
|
+
* evaluation errors are also returned as error strings — the tool surfaces math errors as
|
|
83
|
+
* content rather than exceptions, so the model can react to them in-line.
|
|
84
|
+
*/
|
|
85
|
+
var calculateTool = new Tool({
|
|
86
|
+
name: "calculate",
|
|
87
|
+
description: "Evaluate a math expression. Supports arithmetic, trig, log, sqrt, factorial, matrices.",
|
|
88
|
+
inputSchema: validator.object({ expression: validator.string().required().description("Math expression, e.g. \"sin(pi/4) + 5!\"") }),
|
|
89
|
+
handler: async (args) => {
|
|
90
|
+
const { expression } = args;
|
|
91
|
+
const lengthError = validateExpression(expression);
|
|
92
|
+
if (lengthError) return lengthError;
|
|
93
|
+
try {
|
|
94
|
+
const result = math.evaluate(expression);
|
|
95
|
+
return `Result: ${result}\nKaTeX: $${math.parse(expression).toTex()} = ${result}$`;
|
|
96
|
+
} catch (err) {
|
|
97
|
+
return `Error: ${isError(err) ? err.message : String(err)}`;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
/**
|
|
102
|
+
* Translates a LaTeX/KaTeX expression into mathjs syntax, evaluates it, and returns the result.
|
|
103
|
+
*
|
|
104
|
+
* @remarks
|
|
105
|
+
* Translates common LaTeX constructs (`\frac{a}{b}`, `\sqrt{...}`, `\cdot`, `\times`, Greek
|
|
106
|
+
* macros like `\pi`, `\left`/`\right` delimiters, `\text{...}`, subscripts, etc.) into their
|
|
107
|
+
* mathjs equivalents before evaluation. Both the source and the translated mathjs expression
|
|
108
|
+
* are subject to the 1000-character length cap.
|
|
109
|
+
*
|
|
110
|
+
* Parse and evaluation errors are returned as error strings rather than thrown.
|
|
111
|
+
*/
|
|
112
|
+
var evaluateKatexTool = new Tool({
|
|
113
|
+
name: "evaluate_katex",
|
|
114
|
+
description: "Evaluate a KaTeX/LaTeX math expression and return the numeric result.",
|
|
115
|
+
inputSchema: validator.object({ katex: validator.string().required().description("LaTeX expression, e.g. \"\\frac{1}{2} + \\sqrt{9}\"") }),
|
|
116
|
+
handler: async (args) => {
|
|
117
|
+
const { katex } = args;
|
|
118
|
+
const lengthError = validateExpression(katex);
|
|
119
|
+
if (lengthError) return lengthError;
|
|
120
|
+
try {
|
|
121
|
+
const mathjsExpr = latexToMathjs(katex);
|
|
122
|
+
const translatedLengthError = validateExpression(mathjsExpr);
|
|
123
|
+
if (translatedLengthError) return translatedLengthError;
|
|
124
|
+
return `Converted: ${mathjsExpr}\nResult: ${math.evaluate(mathjsExpr)}`;
|
|
125
|
+
} catch (err) {
|
|
126
|
+
return `Error: ${isError(err) ? err.message : String(err)}`;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
//#endregion
|
|
131
|
+
export { calculateTool, evaluateKatexTool };
|
|
132
|
+
|
|
133
|
+
//# sourceMappingURL=math.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"math.mjs","names":[],"sources":["../../../src/batteries/tools/math/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for safe arithmetic, expression evaluation, and numeric operations.\n *\n * @module @nhtio/adk/batteries/tools/math\n *\n * @remarks\n * Pre-constructed bundled tools for the `math` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { create, all } from 'mathjs'\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\nconst math = create(all)\n\nconst BLOCKED_FUNCTIONS = [\n 'import',\n 'createUnit',\n 'simplify',\n 'derivative',\n 'compile',\n 'chain',\n 'reviver',\n 'replacer',\n]\n\nfor (const fn of BLOCKED_FUNCTIONS) {\n if (fn in math) {\n ;(math as any)[fn] = undefined\n }\n}\n\nconst MAX_EXPRESSION_LENGTH = 1000\n\nfunction validateExpression(expr: string): string | undefined {\n if (expr.length > MAX_EXPRESSION_LENGTH) {\n return `Expression too long (max ${MAX_EXPRESSION_LENGTH} characters).`\n }\n return undefined\n}\n\n/**\n * Convert common LaTeX/KaTeX notation to a mathjs-evaluable expression.\n */\nfunction latexToMathjs(latex: string): string {\n let expr = latex.trim()\n\n expr = expr.replace(/^\\$\\$?|\\$\\$?$/g, '')\n expr = expr.replace(/^\\\\[[(]|\\\\[\\])]$/g, '')\n\n for (let i = 0; i < 10; i++) {\n const before = expr\n expr = expr.replace(/\\\\frac\\s*\\{([^{}]*)\\}\\s*\\{([^{}]*)\\}/g, '(($1)/($2))')\n if (expr === before) break\n }\n\n expr = expr.replace(/\\\\sqrt\\[([^\\]]+)\\]\\s*\\{([^{}]*)\\}/g, 'nthRoot($2, $1)')\n expr = expr.replace(/\\\\sqrt\\s*\\{([^{}]*)\\}/g, 'sqrt($1)')\n\n expr = expr.replace(\n /\\\\(sin|cos|tan|cot|sec|csc|arcsin|arccos|arctan|sinh|cosh|tanh|ln|log|exp|abs|det)/g,\n '$1'\n )\n\n expr = expr.replace(/log_\\{?(\\w+)\\}?\\s*\\(([^)]+)\\)/g, 'log($2, $1)')\n expr = expr.replace(/\\^{([^{}]*)}/g, '^($1)')\n expr = expr.replace(/_\\{[^{}]*\\}/g, '')\n expr = expr.replace(/_\\w/g, '')\n\n expr = expr.replace(/\\\\pi/g, 'pi')\n expr = expr.replace(\n /\\\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g,\n '$1'\n )\n\n expr = expr.replace(/\\\\cdot/g, '*')\n expr = expr.replace(/\\\\times/g, '*')\n expr = expr.replace(/\\\\div/g, '/')\n expr = expr.replace(/\\\\infty/g, 'Infinity')\n expr = expr.replace(/\\\\left\\s*([([{|])/g, '$1')\n expr = expr.replace(/\\\\right\\s*([)\\]}|])/g, '$1')\n expr = expr.replace(/\\\\sum/g, 'sum')\n expr = expr.replace(/\\\\prod/g, 'prod')\n expr = expr.replace(/\\\\,/g, ' ')\n expr = expr.replace(/\\\\;/g, ' ')\n expr = expr.replace(/\\\\quad/g, ' ')\n expr = expr.replace(/\\\\qquad/g, ' ')\n expr = expr.replace(/\\\\text\\{([^{}]*)\\}/g, '')\n expr = expr.replace(/(\\d)([a-zA-Z(])/g, '$1*$2')\n expr = expr.replace(/\\)\\s*\\(/g, ')*(')\n expr = expr.replace(/\\s+/g, ' ').trim()\n\n return expr\n}\n\n/**\n * Evaluates a mathjs-syntax expression and returns the numeric result alongside the KaTeX\n * representation of the parsed expression.\n *\n * @remarks\n * Supports arithmetic, trigonometric, logarithmic, exponential, factorial, matrix, and unit\n * operations via `mathjs`. The mathjs instance is hardened: dangerous functions (`import`,\n * `createUnit`, `simplify`, `derivative`, `compile`, `chain`, `reviver`, `replacer`) are\n * disabled to prevent interpreter-surface exposure.\n *\n * Expressions over 1000 characters are rejected with an error string (not thrown). Parse and\n * evaluation errors are also returned as error strings — the tool surfaces math errors as\n * content rather than exceptions, so the model can react to them in-line.\n */\nexport const calculateTool = new Tool({\n name: 'calculate',\n description:\n 'Evaluate a math expression. Supports arithmetic, trig, log, sqrt, factorial, matrices.',\n inputSchema: validator.object({\n expression: validator.string().required().description('Math expression, e.g. \"sin(pi/4) + 5!\"'),\n }),\n handler: async (args) => {\n const { expression } = args as { expression: string }\n\n const lengthError = validateExpression(expression)\n if (lengthError) return lengthError\n\n try {\n const result = math.evaluate!(expression)\n const node = math.parse!(expression)\n const katex = node.toTex()\n return `Result: ${result}\\nKaTeX: $${katex} = ${result}$`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Translates a LaTeX/KaTeX expression into mathjs syntax, evaluates it, and returns the result.\n *\n * @remarks\n * Translates common LaTeX constructs (`\\frac{a}{b}`, `\\sqrt{...}`, `\\cdot`, `\\times`, Greek\n * macros like `\\pi`, `\\left`/`\\right` delimiters, `\\text{...}`, subscripts, etc.) into their\n * mathjs equivalents before evaluation. Both the source and the translated mathjs expression\n * are subject to the 1000-character length cap.\n *\n * Parse and evaluation errors are returned as error strings rather than thrown.\n */\nexport const evaluateKatexTool = new Tool({\n name: 'evaluate_katex',\n description: 'Evaluate a KaTeX/LaTeX math expression and return the numeric result.',\n inputSchema: validator.object({\n katex: validator\n .string()\n .required()\n .description('LaTeX expression, e.g. \"\\\\frac{1}{2} + \\\\sqrt{9}\"'),\n }),\n handler: async (args) => {\n const { katex } = args as { katex: string }\n\n const lengthError = validateExpression(katex)\n if (lengthError) return lengthError\n\n try {\n const mathjsExpr = latexToMathjs(katex)\n\n const translatedLengthError = validateExpression(mathjsExpr)\n if (translatedLengthError) return translatedLengthError\n\n const result = math.evaluate!(mathjsExpr)\n return `Converted: ${mathjsExpr}\\nResult: ${result}`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":"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"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-constructed CRUD tools for model-visible ADK memory management.
|
|
3
|
+
*
|
|
4
|
+
* @module @nhtio/adk/batteries/tools/memory
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* Pre-constructed CRUD tools that expose the ADK's {@link @nhtio/adk!Memory} surface to the model.
|
|
8
|
+
* Each tool delegates to the corresponding callback on the active {@link @nhtio/adk!DispatchContext}
|
|
9
|
+
* (`fetchMemories`, `storeMemory`, `mutateMemory`, `deleteMemory`) — the persistence layer is
|
|
10
|
+
* whatever the consumer wired into the runner.
|
|
11
|
+
*
|
|
12
|
+
* Memory entries carry agent-internal `confidence` / `importance` scores and are rendered
|
|
13
|
+
* through the LLM battery's recall-tier envelope. Letting the model author and curate its own
|
|
14
|
+
* memories is the canonical use case for these tools; deployers who do not want the model to
|
|
15
|
+
* mutate memory should simply not register the relevant tools.
|
|
16
|
+
*
|
|
17
|
+
* Output is JSON for every tool so consumers can parse the result without re-tokenising — the
|
|
18
|
+
* artifact constructor is set to {@link @nhtio/adk!SpooledJsonArtifact}.
|
|
19
|
+
*
|
|
20
|
+
* Tools:
|
|
21
|
+
* - {@link listMemoriesTool} — read-only list of every memory currently held by the context.
|
|
22
|
+
* - {@link storeMemoryTool} — create a new memory (auto-generates `id` / `createdAt` /
|
|
23
|
+
* `updatedAt` unless explicit values are supplied).
|
|
24
|
+
* - {@link updateMemoryTool} — replace an existing memory by `id`. Bumps `updatedAt`.
|
|
25
|
+
* - {@link deleteMemoryTool} — remove a memory by `id`.
|
|
26
|
+
*/
|
|
27
|
+
import { SpooledJsonArtifact, Tool } from "../../../common";
|
|
28
|
+
/**
|
|
29
|
+
* List every memory currently held by the active execution context.
|
|
30
|
+
*
|
|
31
|
+
* @remarks
|
|
32
|
+
* Delegates to `ctx.fetchMemories()`. Returns a JSON-encoded array of memory records (id,
|
|
33
|
+
* content, confidence, importance, createdAt, updatedAt). The model can use the `id` values
|
|
34
|
+
* to drive subsequent `update_memory` / `delete_memory` calls.
|
|
35
|
+
*/
|
|
36
|
+
export declare const listMemoriesTool: Tool<SpooledJsonArtifact<unknown>>;
|
|
37
|
+
/**
|
|
38
|
+
* Create a new {@link @nhtio/adk!Memory} record and persist it via the context's `storeMemory` callback.
|
|
39
|
+
*
|
|
40
|
+
* @remarks
|
|
41
|
+
* When `id` is omitted, a UUID v6 is generated. When `createdAt` / `updatedAt` are omitted,
|
|
42
|
+
* the current time is used. The model authors `content`, `confidence`, and `importance`
|
|
43
|
+
* directly. The resulting record is added to `ctx.turnMemories` and flushed to the consumer's
|
|
44
|
+
* persistence layer.
|
|
45
|
+
*/
|
|
46
|
+
export declare const storeMemoryTool: Tool<SpooledJsonArtifact<unknown>>;
|
|
47
|
+
/**
|
|
48
|
+
* Replace an existing {@link @nhtio/adk!Memory} by `id`.
|
|
49
|
+
*
|
|
50
|
+
* @remarks
|
|
51
|
+
* The model supplies `id` plus any subset of `content` / `confidence` / `importance`; fields
|
|
52
|
+
* left undefined retain their prior values. `updatedAt` is always bumped to the current time;
|
|
53
|
+
* `createdAt` is preserved. Returns an error when no memory with the supplied `id` is found.
|
|
54
|
+
*/
|
|
55
|
+
export declare const updateMemoryTool: Tool<SpooledJsonArtifact<unknown>>;
|
|
56
|
+
/**
|
|
57
|
+
* Remove an existing {@link @nhtio/adk!Memory} by `id`.
|
|
58
|
+
*
|
|
59
|
+
* @remarks
|
|
60
|
+
* Delegates to `ctx.deleteMemory(id)`. Returns `{ ok: true, id }` on success regardless of
|
|
61
|
+
* whether a memory was actually present — `deleteMemory` is idempotent at the ADK level.
|
|
62
|
+
*/
|
|
63
|
+
export declare const deleteMemoryTool: Tool<SpooledJsonArtifact<unknown>>;
|
|
64
|
+
/**
|
|
65
|
+
* Convenience tuple of every memory CRUD tool. Spread into a {@link @nhtio/adk!ToolRegistry} to register
|
|
66
|
+
* the entire category at once: `registry.register(...memoryTools)`.
|
|
67
|
+
*/
|
|
68
|
+
export declare const memoryTools: readonly [
|
|
69
|
+
Tool<SpooledJsonArtifact<unknown>>,
|
|
70
|
+
Tool<SpooledJsonArtifact<unknown>>,
|
|
71
|
+
Tool<SpooledJsonArtifact<unknown>>,
|
|
72
|
+
Tool<SpooledJsonArtifact<unknown>>
|
|
73
|
+
];
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
require("../../chunk-KmRHZBOW.js");
|
|
3
|
+
const require_tool_registry = require("../../tool_registry-Dkfprsck.js");
|
|
4
|
+
const require_thought = require("../../thought-DuN2PgdO.js");
|
|
5
|
+
require("../../common-Od8edUXU.js");
|
|
6
|
+
const require_tool = require("../../tool-COSeH8I6.js");
|
|
7
|
+
const require_spooled_markdown_artifact = require("../../spooled_markdown_artifact-RRB113sy.js");
|
|
8
|
+
require("../../guards.cjs");
|
|
9
|
+
let _nhtio_validation = require("@nhtio/validation");
|
|
10
|
+
let uuid = require("uuid");
|
|
11
|
+
let luxon = require("luxon");
|
|
12
|
+
//#region src/batteries/tools/memory/index.ts
|
|
13
|
+
/**
|
|
14
|
+
* Pre-constructed CRUD tools for model-visible ADK memory management.
|
|
15
|
+
*
|
|
16
|
+
* @module @nhtio/adk/batteries/tools/memory
|
|
17
|
+
*
|
|
18
|
+
* @remarks
|
|
19
|
+
* Pre-constructed CRUD tools that expose the ADK's {@link @nhtio/adk!Memory} surface to the model.
|
|
20
|
+
* Each tool delegates to the corresponding callback on the active {@link @nhtio/adk!DispatchContext}
|
|
21
|
+
* (`fetchMemories`, `storeMemory`, `mutateMemory`, `deleteMemory`) — the persistence layer is
|
|
22
|
+
* whatever the consumer wired into the runner.
|
|
23
|
+
*
|
|
24
|
+
* Memory entries carry agent-internal `confidence` / `importance` scores and are rendered
|
|
25
|
+
* through the LLM battery's recall-tier envelope. Letting the model author and curate its own
|
|
26
|
+
* memories is the canonical use case for these tools; deployers who do not want the model to
|
|
27
|
+
* mutate memory should simply not register the relevant tools.
|
|
28
|
+
*
|
|
29
|
+
* Output is JSON for every tool so consumers can parse the result without re-tokenising — the
|
|
30
|
+
* artifact constructor is set to {@link @nhtio/adk!SpooledJsonArtifact}.
|
|
31
|
+
*
|
|
32
|
+
* Tools:
|
|
33
|
+
* - {@link listMemoriesTool} — read-only list of every memory currently held by the context.
|
|
34
|
+
* - {@link storeMemoryTool} — create a new memory (auto-generates `id` / `createdAt` /
|
|
35
|
+
* `updatedAt` unless explicit values are supplied).
|
|
36
|
+
* - {@link updateMemoryTool} — replace an existing memory by `id`. Bumps `updatedAt`.
|
|
37
|
+
* - {@link deleteMemoryTool} — remove a memory by `id`.
|
|
38
|
+
*/
|
|
39
|
+
var serialiseMemory = (m) => ({
|
|
40
|
+
id: m.id,
|
|
41
|
+
content: m.content.toString(),
|
|
42
|
+
confidence: m.confidence,
|
|
43
|
+
importance: m.importance,
|
|
44
|
+
createdAt: m.createdAt.toISO(),
|
|
45
|
+
updatedAt: m.updatedAt.toISO()
|
|
46
|
+
});
|
|
47
|
+
/**
|
|
48
|
+
* List every memory currently held by the active execution context.
|
|
49
|
+
*
|
|
50
|
+
* @remarks
|
|
51
|
+
* Delegates to `ctx.fetchMemories()`. Returns a JSON-encoded array of memory records (id,
|
|
52
|
+
* content, confidence, importance, createdAt, updatedAt). The model can use the `id` values
|
|
53
|
+
* to drive subsequent `update_memory` / `delete_memory` calls.
|
|
54
|
+
*/
|
|
55
|
+
var listMemoriesTool = new require_tool.Tool({
|
|
56
|
+
name: "list_memories",
|
|
57
|
+
description: "List every memory currently held by the agent. Returns a JSON array of memory records with id, content, confidence, importance, createdAt, and updatedAt.",
|
|
58
|
+
inputSchema: _nhtio_validation.validator.object({}),
|
|
59
|
+
artifactConstructor: () => require_spooled_markdown_artifact.SpooledJsonArtifact,
|
|
60
|
+
handler: async (_args, ctx) => {
|
|
61
|
+
try {
|
|
62
|
+
const memories = await ctx.fetchMemories();
|
|
63
|
+
return JSON.stringify(memories.map(serialiseMemory), null, 2);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
return `Error: ${require_tool_registry.isError(err) ? err.message : String(err)}`;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
/**
|
|
70
|
+
* Create a new {@link @nhtio/adk!Memory} record and persist it via the context's `storeMemory` callback.
|
|
71
|
+
*
|
|
72
|
+
* @remarks
|
|
73
|
+
* When `id` is omitted, a UUID v6 is generated. When `createdAt` / `updatedAt` are omitted,
|
|
74
|
+
* the current time is used. The model authors `content`, `confidence`, and `importance`
|
|
75
|
+
* directly. The resulting record is added to `ctx.turnMemories` and flushed to the consumer's
|
|
76
|
+
* persistence layer.
|
|
77
|
+
*/
|
|
78
|
+
var storeMemoryTool = new require_tool.Tool({
|
|
79
|
+
name: "store_memory",
|
|
80
|
+
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.",
|
|
81
|
+
inputSchema: _nhtio_validation.validator.object({
|
|
82
|
+
content: _nhtio_validation.validator.string().required().description("The memory content as a plain string."),
|
|
83
|
+
confidence: _nhtio_validation.validator.number().min(0).max(1).required().description("Confidence in [0, 1] that this memory is accurate."),
|
|
84
|
+
importance: _nhtio_validation.validator.number().min(0).max(1).required().description("Importance in [0, 1] — how much weight the memory should carry on recall."),
|
|
85
|
+
id: _nhtio_validation.validator.string().optional().description("Optional stable id. Auto-generated when absent.")
|
|
86
|
+
}),
|
|
87
|
+
artifactConstructor: () => require_spooled_markdown_artifact.SpooledJsonArtifact,
|
|
88
|
+
handler: async (args, ctx) => {
|
|
89
|
+
const { content, confidence, importance, id } = args;
|
|
90
|
+
try {
|
|
91
|
+
const now = luxon.DateTime.now();
|
|
92
|
+
const memory = new require_thought.Memory({
|
|
93
|
+
id: id ?? (0, uuid.v6)(),
|
|
94
|
+
content,
|
|
95
|
+
confidence,
|
|
96
|
+
importance,
|
|
97
|
+
createdAt: now,
|
|
98
|
+
updatedAt: now
|
|
99
|
+
});
|
|
100
|
+
await ctx.storeMemory(memory);
|
|
101
|
+
return JSON.stringify({
|
|
102
|
+
ok: true,
|
|
103
|
+
memory: serialiseMemory(memory)
|
|
104
|
+
}, null, 2);
|
|
105
|
+
} catch (err) {
|
|
106
|
+
return `Error: ${require_tool_registry.isError(err) ? err.message : String(err)}`;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
/**
|
|
111
|
+
* Replace an existing {@link @nhtio/adk!Memory} by `id`.
|
|
112
|
+
*
|
|
113
|
+
* @remarks
|
|
114
|
+
* The model supplies `id` plus any subset of `content` / `confidence` / `importance`; fields
|
|
115
|
+
* left undefined retain their prior values. `updatedAt` is always bumped to the current time;
|
|
116
|
+
* `createdAt` is preserved. Returns an error when no memory with the supplied `id` is found.
|
|
117
|
+
*/
|
|
118
|
+
var updateMemoryTool = new require_tool.Tool({
|
|
119
|
+
name: "update_memory",
|
|
120
|
+
description: "Update an existing memory by id. Supply any subset of content / confidence / importance — omitted fields retain their prior values. updatedAt is always refreshed.",
|
|
121
|
+
inputSchema: _nhtio_validation.validator.object({
|
|
122
|
+
id: _nhtio_validation.validator.string().required().description("Id of the memory to update."),
|
|
123
|
+
content: _nhtio_validation.validator.string().optional().description("Replacement content."),
|
|
124
|
+
confidence: _nhtio_validation.validator.number().min(0).max(1).optional().description("Replacement confidence in [0, 1]."),
|
|
125
|
+
importance: _nhtio_validation.validator.number().min(0).max(1).optional().description("Replacement importance in [0, 1].")
|
|
126
|
+
}),
|
|
127
|
+
artifactConstructor: () => require_spooled_markdown_artifact.SpooledJsonArtifact,
|
|
128
|
+
handler: async (args, ctx) => {
|
|
129
|
+
const { id, content, confidence, importance } = args;
|
|
130
|
+
try {
|
|
131
|
+
const existing = (await ctx.fetchMemories()).find((m) => m.id === id);
|
|
132
|
+
if (!existing) return `Error: No memory found with id "${id}".`;
|
|
133
|
+
const updated = new require_thought.Memory({
|
|
134
|
+
id: existing.id,
|
|
135
|
+
content: content ?? existing.content,
|
|
136
|
+
confidence: confidence ?? existing.confidence,
|
|
137
|
+
importance: importance ?? existing.importance,
|
|
138
|
+
createdAt: existing.createdAt,
|
|
139
|
+
updatedAt: luxon.DateTime.now()
|
|
140
|
+
});
|
|
141
|
+
await ctx.mutateMemory(updated);
|
|
142
|
+
return JSON.stringify({
|
|
143
|
+
ok: true,
|
|
144
|
+
memory: serialiseMemory(updated)
|
|
145
|
+
}, null, 2);
|
|
146
|
+
} catch (err) {
|
|
147
|
+
return `Error: ${require_tool_registry.isError(err) ? err.message : String(err)}`;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
/**
|
|
152
|
+
* Remove an existing {@link @nhtio/adk!Memory} by `id`.
|
|
153
|
+
*
|
|
154
|
+
* @remarks
|
|
155
|
+
* Delegates to `ctx.deleteMemory(id)`. Returns `{ ok: true, id }` on success regardless of
|
|
156
|
+
* whether a memory was actually present — `deleteMemory` is idempotent at the ADK level.
|
|
157
|
+
*/
|
|
158
|
+
var deleteMemoryTool = new require_tool.Tool({
|
|
159
|
+
name: "delete_memory",
|
|
160
|
+
description: "Delete a memory by id.",
|
|
161
|
+
inputSchema: _nhtio_validation.validator.object({ id: _nhtio_validation.validator.string().required().description("Id of the memory to delete.") }),
|
|
162
|
+
artifactConstructor: () => require_spooled_markdown_artifact.SpooledJsonArtifact,
|
|
163
|
+
handler: async (args, ctx) => {
|
|
164
|
+
const { id } = args;
|
|
165
|
+
try {
|
|
166
|
+
await ctx.deleteMemory(id);
|
|
167
|
+
return JSON.stringify({
|
|
168
|
+
ok: true,
|
|
169
|
+
id
|
|
170
|
+
}, null, 2);
|
|
171
|
+
} catch (err) {
|
|
172
|
+
return `Error: ${require_tool_registry.isError(err) ? err.message : String(err)}`;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
/**
|
|
177
|
+
* Convenience tuple of every memory CRUD tool. Spread into a {@link @nhtio/adk!ToolRegistry} to register
|
|
178
|
+
* the entire category at once: `registry.register(...memoryTools)`.
|
|
179
|
+
*/
|
|
180
|
+
var memoryTools = [
|
|
181
|
+
listMemoriesTool,
|
|
182
|
+
storeMemoryTool,
|
|
183
|
+
updateMemoryTool,
|
|
184
|
+
deleteMemoryTool
|
|
185
|
+
];
|
|
186
|
+
//#endregion
|
|
187
|
+
exports.deleteMemoryTool = deleteMemoryTool;
|
|
188
|
+
exports.listMemoriesTool = listMemoriesTool;
|
|
189
|
+
exports.memoryTools = memoryTools;
|
|
190
|
+
exports.storeMemoryTool = storeMemoryTool;
|
|
191
|
+
exports.updateMemoryTool = updateMemoryTool;
|
|
192
|
+
|
|
193
|
+
//# sourceMappingURL=memory.cjs.map
|