@wheatley-ai/cli 0.0.0-stage → 0.0.0
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 +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +180 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +204 -0
- package/dist/cli/session.js +87 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1020 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +61 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon.js +88 -0
- package/dist/core/deployment.js +347 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +95 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +206 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-3COz_MZq.css +2 -0
- package/dist/dashboard/assets/index-RnxedkKh.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-U1UUymXc.js +1 -0
- package/dist/dashboard/index.html +13 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +252 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +110 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +195 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +104 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +207 -0
- package/dist/triggers/webhook-ingress.js +216 -0
- package/dist/wiring/agent-services.js +144 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { createMemoryConsolidation } from "./consolidation.js";
|
|
3
|
+
import { memoryMigrations } from "./migrations.js";
|
|
4
|
+
import { MEMORY_DIR_NAME } from "./names.js";
|
|
5
|
+
import { createMemoryRpcHandlers } from "./rpc.js";
|
|
6
|
+
import { createMarkdownMemoryStore } from "./store.js";
|
|
7
|
+
import { createMemoryTools } from "./tools.js";
|
|
8
|
+
export { CONSOLIDATION_JOB, DEFAULT_CONSOLIDATION_SCHEDULE, } from "./consolidation.js";
|
|
9
|
+
export { memoryMigrations } from "./migrations.js";
|
|
10
|
+
export { createMemoryRpcHandlers } from "./rpc.js";
|
|
11
|
+
export { formatSnapshotPrompt } from "./snapshots.js";
|
|
12
|
+
export { DEFAULT_MEMORY_MAX_CHARS } from "./store.js";
|
|
13
|
+
export { createMemoryTools } from "./tools.js";
|
|
14
|
+
/**
|
|
15
|
+
* The Memory module of an Agent (ADR 0009). Wave 2 wiring:
|
|
16
|
+
*
|
|
17
|
+
* 1. Run `migrationNamespace(memoryModule)` with the other modules' migrations on `agent.sqlite`.
|
|
18
|
+
* 2. Call `create` with `{ config: agentConfig.memory, maintenance }`, and mount `rpc`.
|
|
19
|
+
* 3. Add `api.tools` to the Agent's Tools. Archive each user and assistant message with `api.store.archive`.
|
|
20
|
+
* 4. Put `formatSnapshotPrompt(await api.store.snapshot())` into the Conversation instructions at Conversation start
|
|
21
|
+
* and after `/compact`. The instructions keep that text until the next `/compact`, so Memory writes during the
|
|
22
|
+
* Conversation do not change the system prompt.
|
|
23
|
+
* 5. Before each compaction, run `api.store.compactionFlushPrompt()` as a silent turn.
|
|
24
|
+
*
|
|
25
|
+
* `start` rebuilds the index from the Markdown files, so disk edits take effect on Agent restart, and starts the
|
|
26
|
+
* consolidation schedule (default on, daily at 03:00).
|
|
27
|
+
*/
|
|
28
|
+
export const memoryModule = {
|
|
29
|
+
create: (ctx, deps) => {
|
|
30
|
+
const store = createMarkdownMemoryStore({
|
|
31
|
+
clock: ctx.clock,
|
|
32
|
+
db: ctx.db,
|
|
33
|
+
dir: path.join(ctx.agentDir, MEMORY_DIR_NAME),
|
|
34
|
+
onChange: ({ change, name }) => {
|
|
35
|
+
ctx.events.emit("memory.changed", name === undefined
|
|
36
|
+
? { agent: ctx.agentName, change }
|
|
37
|
+
: { agent: ctx.agentName, change, name });
|
|
38
|
+
},
|
|
39
|
+
maxChars: deps.config?.maxChars,
|
|
40
|
+
});
|
|
41
|
+
const consolidation = createMemoryConsolidation({
|
|
42
|
+
clock: ctx.clock,
|
|
43
|
+
db: ctx.db,
|
|
44
|
+
log: ctx.log,
|
|
45
|
+
runner: deps.maintenance,
|
|
46
|
+
store,
|
|
47
|
+
config: deps.config?.consolidation,
|
|
48
|
+
});
|
|
49
|
+
return {
|
|
50
|
+
api: {
|
|
51
|
+
consolidation: { log: consolidation.log, run: consolidation.run },
|
|
52
|
+
store,
|
|
53
|
+
tools: createMemoryTools(store),
|
|
54
|
+
},
|
|
55
|
+
rpc: createMemoryRpcHandlers(store, consolidation),
|
|
56
|
+
start: async () => {
|
|
57
|
+
const files = await store.reindex();
|
|
58
|
+
ctx.log.debug("Indexed the Memory files", { files });
|
|
59
|
+
await consolidation.start();
|
|
60
|
+
},
|
|
61
|
+
stop: async () => {
|
|
62
|
+
await consolidation.stop();
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
},
|
|
66
|
+
migrations: memoryMigrations,
|
|
67
|
+
name: "memory",
|
|
68
|
+
scope: "agent",
|
|
69
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { SeamError } from "../contracts/errors.js";
|
|
3
|
+
/** The name of `MEMORY.md`. */
|
|
4
|
+
export const MEMORY_NAME = "MEMORY";
|
|
5
|
+
/** The folder of the Memory files inside the Agent folder. */
|
|
6
|
+
export const MEMORY_DIR_NAME = "memory";
|
|
7
|
+
const NAME = /^(?:MEMORY|[a-z0-9][a-z0-9-]{0,63})$/u;
|
|
8
|
+
const FILE_NAME = /^(?<name>MEMORY|[a-z0-9][a-z0-9-]{0,63})\.md$/u;
|
|
9
|
+
/** Throws `SeamError("invalid_name")` unless `name` is `MEMORY` or a valid topic slug. */
|
|
10
|
+
export const assertMemoryName = (name) => {
|
|
11
|
+
if (!NAME.test(name)) {
|
|
12
|
+
throw new SeamError("invalid_name", `Invalid Memory name: ${name}. Use MEMORY or a slug that matches ^[a-z0-9][a-z0-9-]{0,63}$.`);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
/** Returns the Memory name of a file in the Memory folder, or `undefined` for any other file. */
|
|
16
|
+
export const memoryNameOfFile = (fileName) => FILE_NAME.exec(fileName)?.groups?.name;
|
|
17
|
+
/** Returns the Markdown file name for a valid Memory name, for example `MEMORY.md`. */
|
|
18
|
+
export const memoryFileName = (name) => `${name}.md`;
|
|
19
|
+
/** Returns the path of the Markdown file for a valid Memory name. */
|
|
20
|
+
export const memoryFilePath = (dir, name) => path.join(dir, memoryFileName(name));
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const isText = (value) => typeof value === "string";
|
|
2
|
+
const isNumber = (value) => typeof value === "number";
|
|
3
|
+
const hasKind = (value, kind) => {
|
|
4
|
+
if (value === undefined) {
|
|
5
|
+
return false;
|
|
6
|
+
}
|
|
7
|
+
if (value === null) {
|
|
8
|
+
return kind.endsWith("?");
|
|
9
|
+
}
|
|
10
|
+
return kind.startsWith("text") ? isText(value) : isNumber(value);
|
|
11
|
+
};
|
|
12
|
+
const hasColumns = (row, columns) => Object.entries(columns).every(([column, kind]) => hasKind(row[column], kind));
|
|
13
|
+
/**
|
|
14
|
+
* Returns `row` typed with `columns`. The rows come from the module's own STRICT tables, so a mismatch means that the
|
|
15
|
+
* query and the schema differ. Throws an `Error` that names the columns for a mismatch.
|
|
16
|
+
*/
|
|
17
|
+
export const rowOf = (row, columns) => {
|
|
18
|
+
if (!hasColumns(row, columns)) {
|
|
19
|
+
throw new Error(`A Memory query row does not match the expected columns ${JSON.stringify(columns)}`);
|
|
20
|
+
}
|
|
21
|
+
return row;
|
|
22
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { SeamError } from "../contracts/errors.js";
|
|
2
|
+
import { memoryFileName } from "./names.js";
|
|
3
|
+
/** The default number of hits of `memory.search`. */
|
|
4
|
+
const RPC_SEARCH_LIMIT = 20;
|
|
5
|
+
/** The default number of entries of `memory.consolidationLog`. */
|
|
6
|
+
const DEFAULT_LOG_LIMIT = 20;
|
|
7
|
+
/**
|
|
8
|
+
* Creates the Operator JSON-RPC handlers of the `memory.*` methods for one Agent. Expected failures throw a
|
|
9
|
+
* `SeamError`, which the router converts with `toRpcError`:
|
|
10
|
+
* - `invalid_name` for a bad Memory name.
|
|
11
|
+
* - `memory_budget_exceeded` for a `MEMORY.md` write over the cap.
|
|
12
|
+
* - `not_found` for `memory.read` of a file that does not exist.
|
|
13
|
+
* - `conflict` for `memory.consolidate` while a consolidation runs.
|
|
14
|
+
*/
|
|
15
|
+
export const createMemoryRpcHandlers = (store, consolidation) => ({
|
|
16
|
+
"memory.consolidate": async () => await consolidation.run(),
|
|
17
|
+
"memory.consolidationLog": async (params) => await Promise.try(() => ({
|
|
18
|
+
entries: [...consolidation.log(params.limit ?? DEFAULT_LOG_LIMIT)],
|
|
19
|
+
})),
|
|
20
|
+
"memory.delete": async (params) => ({
|
|
21
|
+
deleted: await store.delete(params.name),
|
|
22
|
+
}),
|
|
23
|
+
"memory.list": async () => {
|
|
24
|
+
const { budget, files } = await store.list();
|
|
25
|
+
return { budget, files: [...files] };
|
|
26
|
+
},
|
|
27
|
+
"memory.purgeConversation": async (params) => ({
|
|
28
|
+
purgedMessages: await store.purgeConversation(params.conversationId),
|
|
29
|
+
}),
|
|
30
|
+
"memory.read": async (params) => {
|
|
31
|
+
const content = await store.read(params.name);
|
|
32
|
+
if (content === undefined) {
|
|
33
|
+
throw new SeamError("not_found", `Memory file ${memoryFileName(params.name)} does not exist`);
|
|
34
|
+
}
|
|
35
|
+
return { content, name: params.name };
|
|
36
|
+
},
|
|
37
|
+
"memory.reindex": async () => ({ files: await store.reindex() }),
|
|
38
|
+
"memory.search": async (params) => ({
|
|
39
|
+
hits: [
|
|
40
|
+
...(await store.search(params.query, {
|
|
41
|
+
limit: params.limit ?? RPC_SEARCH_LIMIT,
|
|
42
|
+
scope: params.scope ?? "all",
|
|
43
|
+
})),
|
|
44
|
+
],
|
|
45
|
+
}),
|
|
46
|
+
"memory.write": async (params) => ({
|
|
47
|
+
file: await store.write(params.name, params.content, params.mode ?? "replace"),
|
|
48
|
+
}),
|
|
49
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formats a snapshot as the Memory section of the system prompt. Returns an empty string for an empty `MEMORY.md`.
|
|
3
|
+
*/
|
|
4
|
+
export const formatSnapshotPrompt = (snapshot) => {
|
|
5
|
+
if (snapshot.text.trim() === "") {
|
|
6
|
+
return "";
|
|
7
|
+
}
|
|
8
|
+
const note = snapshot.truncated
|
|
9
|
+
? "\n\n(MEMORY.md is longer than its character cap. The text above is cut. Shorten MEMORY.md with memory_write.)"
|
|
10
|
+
: "";
|
|
11
|
+
return `# Memory (MEMORY.md)\n\nThese are your saved notes. Use memory_search and memory_read for topic files and past Conversations.\n\n${snapshot.text}${note}`;
|
|
12
|
+
};
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile, } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { SeamError } from "../contracts/errors.js";
|
|
5
|
+
import { assertMemoryName, MEMORY_NAME, memoryFileName, memoryFilePath, memoryNameOfFile, } from "./names.js";
|
|
6
|
+
import { rowOf } from "./rows.js";
|
|
7
|
+
/** The default `MEMORY.md` character cap (ADR 0009). */
|
|
8
|
+
export const DEFAULT_MEMORY_MAX_CHARS = 4000;
|
|
9
|
+
/** The number of tokens around a match in a search hit snippet. */
|
|
10
|
+
const SNIPPET_TOKENS = 24;
|
|
11
|
+
const SEARCH_TOKEN = /[\p{L}\p{N}_]+/gu;
|
|
12
|
+
const SLUG_SEPARATOR = /-/gu;
|
|
13
|
+
const FILE_HIT = { name: "text", rank: "number", snippet: "text" };
|
|
14
|
+
const MESSAGE_HIT = {
|
|
15
|
+
at: "number",
|
|
16
|
+
conversation_id: "text",
|
|
17
|
+
rank: "number",
|
|
18
|
+
role: "text",
|
|
19
|
+
snippet: "text",
|
|
20
|
+
};
|
|
21
|
+
const isMissingFile = (error) => error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
22
|
+
const readOptional = async (filePath) => {
|
|
23
|
+
try {
|
|
24
|
+
return await readFile(filePath, "utf-8");
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (isMissingFile(error)) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const titleOf = (name) => name === MEMORY_NAME ? "memory" : name.replaceAll(SLUG_SEPARATOR, " ");
|
|
34
|
+
const appendText = (previous, content) => {
|
|
35
|
+
if (previous === "") {
|
|
36
|
+
return content;
|
|
37
|
+
}
|
|
38
|
+
return previous.endsWith("\n")
|
|
39
|
+
? `${previous}${content}`
|
|
40
|
+
: `${previous}\n${content}`;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Builds an FTS5 query that matches any word of `query`. Each word becomes a quoted string, so FTS5 operators and
|
|
44
|
+
* punctuation in model or Operator input cannot cause a syntax error. Returns `undefined` if `query` has no words.
|
|
45
|
+
*/
|
|
46
|
+
const ftsQuery = (query) => {
|
|
47
|
+
const words = query.match(SEARCH_TOKEN);
|
|
48
|
+
if (words === null) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
return words.map((word) => `"${word}"`).join(" OR ");
|
|
52
|
+
};
|
|
53
|
+
/** Converts an FTS5 `bm25` rank, where lower is better, to a score where higher is better. */
|
|
54
|
+
const scoreOf = (rank) => -rank;
|
|
55
|
+
const metadataOf = (file) => ({
|
|
56
|
+
chars: file.content.length,
|
|
57
|
+
name: file.name,
|
|
58
|
+
updatedAt: file.updatedAt,
|
|
59
|
+
});
|
|
60
|
+
const runInTransaction = (db, work) => {
|
|
61
|
+
db.exec("BEGIN IMMEDIATE");
|
|
62
|
+
try {
|
|
63
|
+
work();
|
|
64
|
+
db.exec("COMMIT");
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (db.isTransaction) {
|
|
68
|
+
db.exec("ROLLBACK");
|
|
69
|
+
}
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Creates the `MemoryStore` of one Agent (ADR 0009). The Markdown files in `dir` are the source of truth. The FTS5
|
|
75
|
+
* index in `agent.sqlite` is derived from them: each write and delete updates it, and `reindex` rebuilds it from disk.
|
|
76
|
+
* The Conversation archive lives in `agent.sqlite` only.
|
|
77
|
+
*
|
|
78
|
+
* The store serializes its file changes, so concurrent `append` writes do not lose text. It writes each file to a
|
|
79
|
+
* temporary file and renames it, so a crash never leaves a half-written Memory file.
|
|
80
|
+
*/
|
|
81
|
+
export const createMarkdownMemoryStore = (options) => {
|
|
82
|
+
const { db, dir } = options;
|
|
83
|
+
const maxChars = options.maxChars ?? DEFAULT_MEMORY_MAX_CHARS;
|
|
84
|
+
let tail = Promise.resolve();
|
|
85
|
+
/** Runs file changes one at a time, in call order. A failed change does not block later changes. */
|
|
86
|
+
const serialize = async (task) => {
|
|
87
|
+
const result = tail.then(task);
|
|
88
|
+
tail = Promise.allSettled([result]);
|
|
89
|
+
return await result;
|
|
90
|
+
};
|
|
91
|
+
const readDiskFile = async (name) => {
|
|
92
|
+
const filePath = memoryFilePath(dir, name);
|
|
93
|
+
const content = await readOptional(filePath);
|
|
94
|
+
if (content === undefined) {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
const { mtimeMs } = await stat(filePath);
|
|
98
|
+
return { content, name, updatedAt: new Date(mtimeMs).toISOString() };
|
|
99
|
+
};
|
|
100
|
+
const readDisk = async () => {
|
|
101
|
+
let entries;
|
|
102
|
+
try {
|
|
103
|
+
entries = await readdir(dir);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (isMissingFile(error)) {
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
const names = entries.flatMap((entry) => {
|
|
112
|
+
const name = memoryNameOfFile(entry);
|
|
113
|
+
return name === undefined ? [] : [name];
|
|
114
|
+
});
|
|
115
|
+
const read = await Promise.all(names.map(readDiskFile));
|
|
116
|
+
const files = read.filter((file) => file !== undefined);
|
|
117
|
+
return files.toSorted((left, right) => {
|
|
118
|
+
if (left.name === MEMORY_NAME) {
|
|
119
|
+
return -1;
|
|
120
|
+
}
|
|
121
|
+
if (right.name === MEMORY_NAME) {
|
|
122
|
+
return 1;
|
|
123
|
+
}
|
|
124
|
+
return left.name.localeCompare(right.name);
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
const indexFile = (name, content) => {
|
|
128
|
+
db.prepare("DELETE FROM memory_files_fts WHERE name = ?").run(name);
|
|
129
|
+
if (content !== "") {
|
|
130
|
+
db.prepare("INSERT INTO memory_files_fts (name, title, content) VALUES (?, ?, ?)").run(name, titleOf(name), content);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
const writeAtomically = async (name, content) => {
|
|
134
|
+
await mkdir(dir, { recursive: true });
|
|
135
|
+
const temporary = path.join(dir, `.${memoryFileName(name)}.${randomUUID()}.tmp`);
|
|
136
|
+
try {
|
|
137
|
+
await writeFile(temporary, content, "utf-8");
|
|
138
|
+
await rename(temporary, memoryFilePath(dir, name));
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
await rm(temporary, { force: true });
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
const snapshot = async () => {
|
|
146
|
+
const text = (await readOptional(memoryFilePath(dir, MEMORY_NAME))) ?? "";
|
|
147
|
+
return { text: text.slice(0, maxChars), truncated: text.length > maxChars };
|
|
148
|
+
};
|
|
149
|
+
const list = async () => {
|
|
150
|
+
const files = await readDisk();
|
|
151
|
+
const memory = files.find((file) => file.name === MEMORY_NAME);
|
|
152
|
+
return {
|
|
153
|
+
budget: { maxChars, usedChars: memory?.content.length ?? 0 },
|
|
154
|
+
files: files.map(metadataOf),
|
|
155
|
+
};
|
|
156
|
+
};
|
|
157
|
+
const read = async (name) => {
|
|
158
|
+
assertMemoryName(name);
|
|
159
|
+
return await readOptional(memoryFilePath(dir, name));
|
|
160
|
+
};
|
|
161
|
+
const write = async (name, content, mode) => {
|
|
162
|
+
assertMemoryName(name);
|
|
163
|
+
return await serialize(async () => {
|
|
164
|
+
const previous = (await readOptional(memoryFilePath(dir, name))) ?? "";
|
|
165
|
+
const next = mode === "append" ? appendText(previous, content) : content;
|
|
166
|
+
if (name === MEMORY_NAME && next.length > maxChars) {
|
|
167
|
+
throw new SeamError("memory_budget_exceeded", `MEMORY.md would have ${next.length} characters, but the cap is ${maxChars}. MEMORY.md stays unchanged. Keep MEMORY.md short and move details into a topic file, for example memory_write with name "travel".`, { maxChars, requestedChars: next.length });
|
|
168
|
+
}
|
|
169
|
+
await writeAtomically(name, next);
|
|
170
|
+
runInTransaction(db, () => {
|
|
171
|
+
indexFile(name, next);
|
|
172
|
+
});
|
|
173
|
+
const file = await readDiskFile(name);
|
|
174
|
+
if (file === undefined) {
|
|
175
|
+
throw new Error(`Memory file ${name} vanished after the write`);
|
|
176
|
+
}
|
|
177
|
+
options.onChange?.({ change: "written", name });
|
|
178
|
+
return metadataOf(file);
|
|
179
|
+
});
|
|
180
|
+
};
|
|
181
|
+
const remove = async (name) => {
|
|
182
|
+
assertMemoryName(name);
|
|
183
|
+
return await serialize(async () => {
|
|
184
|
+
const filePath = memoryFilePath(dir, name);
|
|
185
|
+
if ((await readOptional(filePath)) === undefined) {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
await (name === MEMORY_NAME
|
|
189
|
+
? writeAtomically(name, "")
|
|
190
|
+
: rm(filePath, { force: true }));
|
|
191
|
+
runInTransaction(db, () => {
|
|
192
|
+
indexFile(name, "");
|
|
193
|
+
});
|
|
194
|
+
options.onChange?.({ change: "deleted", name });
|
|
195
|
+
return true;
|
|
196
|
+
});
|
|
197
|
+
};
|
|
198
|
+
const searchFiles = (match, limit) => db
|
|
199
|
+
.prepare(`SELECT name, bm25(memory_files_fts) AS rank,
|
|
200
|
+
snippet(memory_files_fts, 2, '', '', '…', ${SNIPPET_TOKENS}) AS snippet
|
|
201
|
+
FROM memory_files_fts WHERE memory_files_fts MATCH ? ORDER BY rank LIMIT ?`)
|
|
202
|
+
.all(match, limit)
|
|
203
|
+
.map((value) => rowOf(value, FILE_HIT))
|
|
204
|
+
.map((row) => ({
|
|
205
|
+
kind: "memory",
|
|
206
|
+
name: row.name,
|
|
207
|
+
score: scoreOf(row.rank),
|
|
208
|
+
snippet: row.snippet,
|
|
209
|
+
}));
|
|
210
|
+
const searchArchive = (match, limit) => db
|
|
211
|
+
.prepare(`SELECT m.conversation_id, m.role, m.at, bm25(memory_messages_fts) AS rank,
|
|
212
|
+
snippet(memory_messages_fts, 0, '', '', '…', ${SNIPPET_TOKENS}) AS snippet
|
|
213
|
+
FROM memory_messages_fts JOIN memory_messages AS m ON m.id = memory_messages_fts.rowid
|
|
214
|
+
WHERE memory_messages_fts MATCH ? ORDER BY rank LIMIT ?`)
|
|
215
|
+
.all(match, limit)
|
|
216
|
+
.map((value) => rowOf(value, MESSAGE_HIT))
|
|
217
|
+
.map((row) => ({
|
|
218
|
+
at: new Date(row.at).toISOString(),
|
|
219
|
+
conversationId: row.conversation_id,
|
|
220
|
+
kind: "conversation",
|
|
221
|
+
role: row.role === "user" ? "user" : "assistant",
|
|
222
|
+
score: scoreOf(row.rank),
|
|
223
|
+
snippet: row.snippet,
|
|
224
|
+
}));
|
|
225
|
+
const searchNow = (query, searchOptions) => {
|
|
226
|
+
const match = ftsQuery(query);
|
|
227
|
+
if (match === undefined || searchOptions.limit < 1) {
|
|
228
|
+
return [];
|
|
229
|
+
}
|
|
230
|
+
const files = searchOptions.scope === "conversations"
|
|
231
|
+
? []
|
|
232
|
+
: searchFiles(match, searchOptions.limit);
|
|
233
|
+
const messages = searchOptions.scope === "memory"
|
|
234
|
+
? []
|
|
235
|
+
: searchArchive(match, searchOptions.limit);
|
|
236
|
+
return [...files, ...messages]
|
|
237
|
+
.toSorted((left, right) => right.score - left.score)
|
|
238
|
+
.slice(0, searchOptions.limit);
|
|
239
|
+
};
|
|
240
|
+
const search = async (query, searchOptions) => await Promise.try(() => searchNow(query, searchOptions));
|
|
241
|
+
const archive = async (message) => {
|
|
242
|
+
await Promise.try(() => {
|
|
243
|
+
db.prepare("INSERT INTO memory_messages (conversation_id, role, text, at) VALUES (?, ?, ?, ?)").run(message.conversationId, message.role, message.text, message.at);
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
const purgeConversation = async (conversationId) => await Promise.try(() => {
|
|
247
|
+
const result = db
|
|
248
|
+
.prepare("DELETE FROM memory_messages WHERE conversation_id = ?")
|
|
249
|
+
.run(conversationId);
|
|
250
|
+
return Number(result.changes);
|
|
251
|
+
});
|
|
252
|
+
const reindex = async () => await serialize(async () => {
|
|
253
|
+
const files = await readDisk();
|
|
254
|
+
runInTransaction(db, () => {
|
|
255
|
+
db.exec("DELETE FROM memory_files_fts");
|
|
256
|
+
for (const file of files) {
|
|
257
|
+
indexFile(file.name, file.content);
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
options.onChange?.({ change: "reindexed" });
|
|
261
|
+
return files.length;
|
|
262
|
+
});
|
|
263
|
+
const compactionFlushPrompt = () => [
|
|
264
|
+
"This Conversation compacts next, and a summary replaces its older messages.",
|
|
265
|
+
"Save what is worth keeping before that happens: durable facts, preferences, decisions, and open tasks that are not in Memory yet.",
|
|
266
|
+
`Use memory_search and memory_read to check what Memory already has, and memory_write to save. Keep MEMORY.md under ${maxChars} characters and put details into topic files.`,
|
|
267
|
+
"If nothing new is worth keeping, do not call a Tool. Reply with one short line.",
|
|
268
|
+
].join("\n");
|
|
269
|
+
return {
|
|
270
|
+
archive,
|
|
271
|
+
compactionFlushPrompt,
|
|
272
|
+
delete: remove,
|
|
273
|
+
list,
|
|
274
|
+
purgeConversation,
|
|
275
|
+
read,
|
|
276
|
+
reindex,
|
|
277
|
+
search,
|
|
278
|
+
snapshot,
|
|
279
|
+
write,
|
|
280
|
+
};
|
|
281
|
+
};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { isJsonValue, MemoryNameSchema, MemorySearchScopeSchema, } from "@wheatley-ai/protocol";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { Value } from "typebox/value";
|
|
4
|
+
import { canonicalToolName } from "../contracts/tool-names.js";
|
|
5
|
+
import { errorMessage, fileSizeLine } from "./format.js";
|
|
6
|
+
import { MEMORY_NAME, memoryFileName } from "./names.js";
|
|
7
|
+
/** The default number of `memory_search` hits. It is lower than the Operator default to save model context. */
|
|
8
|
+
const TOOL_SEARCH_LIMIT = 10;
|
|
9
|
+
/** The maximum number of `memory_search` hits. */
|
|
10
|
+
const MAX_SEARCH_LIMIT = 50;
|
|
11
|
+
const strict = { additionalProperties: false };
|
|
12
|
+
const SearchInput = Type.Object({
|
|
13
|
+
limit: Type.Optional(Type.Integer({ maximum: MAX_SEARCH_LIMIT, minimum: 1 })),
|
|
14
|
+
query: Type.String({ minLength: 1 }),
|
|
15
|
+
scope: Type.Optional(MemorySearchScopeSchema),
|
|
16
|
+
}, strict);
|
|
17
|
+
const ReadInput = Type.Object({ name: Type.Optional(MemoryNameSchema) }, strict);
|
|
18
|
+
const WriteInput = Type.Object({
|
|
19
|
+
content: Type.String(),
|
|
20
|
+
mode: Type.Optional(Type.Union([Type.Literal("replace"), Type.Literal("append")])),
|
|
21
|
+
name: MemoryNameSchema,
|
|
22
|
+
}, strict);
|
|
23
|
+
const DeleteInput = Type.Object({ name: MemoryNameSchema }, strict);
|
|
24
|
+
const textResult = (text) => ({
|
|
25
|
+
content: [{ text, type: "text" }],
|
|
26
|
+
});
|
|
27
|
+
const errorResult = (text) => ({
|
|
28
|
+
content: [{ text, type: "text" }],
|
|
29
|
+
isError: true,
|
|
30
|
+
});
|
|
31
|
+
const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
32
|
+
/** Converts a TypeBox schema, which is plain JSON Schema, to the SDK `JsonSchema` type. */
|
|
33
|
+
const toJsonSchema = (schema) => {
|
|
34
|
+
const value = structuredClone(schema);
|
|
35
|
+
if (!isJsonValue(value) || !isJsonObject(value)) {
|
|
36
|
+
throw new TypeError("A Tool input schema must be a JSON object");
|
|
37
|
+
}
|
|
38
|
+
return value;
|
|
39
|
+
};
|
|
40
|
+
const formatHit = (hit) => hit.kind === "memory"
|
|
41
|
+
? `- ${memoryFileName(hit.name)} (memory_read name "${hit.name}"): ${hit.snippet}`
|
|
42
|
+
: `- Conversation ${hit.conversationId}, ${hit.role} at ${hit.at}: ${hit.snippet}`;
|
|
43
|
+
const defineTool = (tool) => ({
|
|
44
|
+
descriptor: {
|
|
45
|
+
defaultAction: "allow",
|
|
46
|
+
description: tool.description,
|
|
47
|
+
inputSchema: toJsonSchema(tool.schema),
|
|
48
|
+
name: canonicalToolName({ kind: "builtin" }, tool.name),
|
|
49
|
+
source: "builtin",
|
|
50
|
+
},
|
|
51
|
+
execute: async (input) => {
|
|
52
|
+
if (!Value.Check(tool.schema, input)) {
|
|
53
|
+
const issues = Value.Errors(tool.schema, input).map((error) => `${error.instancePath === "" ? "/" : error.instancePath} ${error.message}`);
|
|
54
|
+
return errorResult(`Invalid input for ${tool.name}: ${issues.join("; ")}`);
|
|
55
|
+
}
|
|
56
|
+
return await tool.run(input);
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
const searchTool = (store) => defineTool({
|
|
60
|
+
description: "Searches Memory files and past Conversations (user and assistant messages) by keywords. Returns the best matches first. Use memory_read to read a whole Memory file.",
|
|
61
|
+
name: "memory_search",
|
|
62
|
+
run: async (input) => {
|
|
63
|
+
const hits = await store.search(input.query, {
|
|
64
|
+
limit: input.limit ?? TOOL_SEARCH_LIMIT,
|
|
65
|
+
scope: input.scope ?? "all",
|
|
66
|
+
});
|
|
67
|
+
return textResult(hits.length === 0
|
|
68
|
+
? `No matches for "${input.query}".`
|
|
69
|
+
: hits.map(formatHit).join("\n"));
|
|
70
|
+
},
|
|
71
|
+
schema: SearchInput,
|
|
72
|
+
});
|
|
73
|
+
const readTool = (store) => defineTool({
|
|
74
|
+
description: 'Reads one Memory file: name "MEMORY" for MEMORY.md, or a topic slug such as "travel" for travel.md. Without a name, lists the Memory files and the MEMORY.md budget.',
|
|
75
|
+
name: "memory_read",
|
|
76
|
+
run: async (input) => {
|
|
77
|
+
if (input.name === undefined) {
|
|
78
|
+
const { budget, files } = await store.list();
|
|
79
|
+
return textResult([
|
|
80
|
+
`MEMORY.md budget: ${budget.usedChars} of ${budget.maxChars} characters.`,
|
|
81
|
+
...files.map(fileSizeLine),
|
|
82
|
+
].join("\n"));
|
|
83
|
+
}
|
|
84
|
+
const content = await store.read(input.name);
|
|
85
|
+
if (content === undefined) {
|
|
86
|
+
return errorResult(`${memoryFileName(input.name)} does not exist.`);
|
|
87
|
+
}
|
|
88
|
+
return textResult(content === "" ? `${memoryFileName(input.name)} is empty.` : content);
|
|
89
|
+
},
|
|
90
|
+
schema: ReadInput,
|
|
91
|
+
});
|
|
92
|
+
const writeTool = (store) => defineTool({
|
|
93
|
+
description: 'Saves Markdown to a Memory file: name "MEMORY" for MEMORY.md (short, always in your system prompt, with a character cap) or a topic slug such as "travel" for details. Mode "replace" (default) overwrites the file, "append" adds a new line at the end. A MEMORY.md write over the cap fails and changes nothing.',
|
|
94
|
+
name: "memory_write",
|
|
95
|
+
run: async (input) => {
|
|
96
|
+
const file = await store.write(input.name, input.content, input.mode ?? "replace");
|
|
97
|
+
if (file.name !== MEMORY_NAME) {
|
|
98
|
+
return textResult(`Saved ${memoryFileName(file.name)} (${file.chars} characters).`);
|
|
99
|
+
}
|
|
100
|
+
const { budget } = await store.list();
|
|
101
|
+
return textResult(`Saved MEMORY.md (${file.chars} of ${budget.maxChars} characters).`);
|
|
102
|
+
},
|
|
103
|
+
schema: WriteInput,
|
|
104
|
+
});
|
|
105
|
+
const deleteTool = (store) => defineTool({
|
|
106
|
+
description: 'Deletes a topic file, or empties MEMORY.md for name "MEMORY".',
|
|
107
|
+
name: "memory_delete",
|
|
108
|
+
run: async (input) => {
|
|
109
|
+
const deleted = await store.delete(input.name);
|
|
110
|
+
const fileName = memoryFileName(input.name);
|
|
111
|
+
if (!deleted) {
|
|
112
|
+
return textResult(`${fileName} does not exist.`);
|
|
113
|
+
}
|
|
114
|
+
return textResult(input.name === MEMORY_NAME
|
|
115
|
+
? "Emptied MEMORY.md."
|
|
116
|
+
: `Deleted ${fileName}.`);
|
|
117
|
+
},
|
|
118
|
+
schema: DeleteInput,
|
|
119
|
+
});
|
|
120
|
+
const noHealth = () => [];
|
|
121
|
+
const closeNothing = async () => {
|
|
122
|
+
await Promise.resolve();
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* Creates the `ToolProvider` of the built-in Memory Tools: `memory_search`, `memory_read`, `memory_write`, and
|
|
126
|
+
* `memory_delete`. Each Tool has the default action `allow` (ADR 0009). The provider has no extensions, so `health`
|
|
127
|
+
* is empty and `close` does nothing.
|
|
128
|
+
*/
|
|
129
|
+
export const createMemoryTools = (store) => {
|
|
130
|
+
const defined = new Map([
|
|
131
|
+
searchTool(store),
|
|
132
|
+
readTool(store),
|
|
133
|
+
writeTool(store),
|
|
134
|
+
deleteTool(store),
|
|
135
|
+
].map((tool) => [tool.descriptor.name, tool]));
|
|
136
|
+
const descriptors = [...defined.values()].map((tool) => tool.descriptor);
|
|
137
|
+
const execute = async (name, input, ctx) => {
|
|
138
|
+
const tool = defined.get(name);
|
|
139
|
+
if (tool === undefined) {
|
|
140
|
+
return errorResult(`Unknown Tool: ${name}`);
|
|
141
|
+
}
|
|
142
|
+
if (ctx.signal.aborted) {
|
|
143
|
+
return errorResult(`${name} was aborted`);
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
return await tool.execute(input);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
return errorResult(errorMessage(error));
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
return {
|
|
153
|
+
close: closeNothing,
|
|
154
|
+
execute,
|
|
155
|
+
health: noHealth,
|
|
156
|
+
tools: () => descriptors,
|
|
157
|
+
};
|
|
158
|
+
};
|