@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.
Files changed (209) hide show
  1. package/LICENSE +15 -0
  2. package/bin/wheatley.js +2 -0
  3. package/dist/approvals/gate.js +278 -0
  4. package/dist/approvals/module.js +21 -0
  5. package/dist/approvals/policy.js +30 -0
  6. package/dist/approvals/preview.js +17 -0
  7. package/dist/approvals/prompt.js +98 -0
  8. package/dist/approvals/rpc.js +16 -0
  9. package/dist/approvals/store.js +159 -0
  10. package/dist/cli/ask.js +94 -0
  11. package/dist/cli/chat.js +180 -0
  12. package/dist/cli/client.js +104 -0
  13. package/dist/cli/daemon.js +35 -0
  14. package/dist/cli/init.js +72 -0
  15. package/dist/cli/io.js +45 -0
  16. package/dist/cli/main.js +204 -0
  17. package/dist/cli/session.js +87 -0
  18. package/dist/cli/status.js +46 -0
  19. package/dist/contracts/approval-gate.js +1 -0
  20. package/dist/contracts/config-store.js +1 -0
  21. package/dist/contracts/delivery-outbox.js +1 -0
  22. package/dist/contracts/errors.js +28 -0
  23. package/dist/contracts/extension-catalog.js +1 -0
  24. package/dist/contracts/maintenance-runner.js +1 -0
  25. package/dist/contracts/memory-store.js +1 -0
  26. package/dist/contracts/module.js +7 -0
  27. package/dist/contracts/tool-names.js +43 -0
  28. package/dist/contracts/trigger-runtime.js +1 -0
  29. package/dist/contracts/webhook-ingress.js +2 -0
  30. package/dist/core/agent/agent-store.js +300 -0
  31. package/dist/core/agent/agent.js +1020 -0
  32. package/dist/core/agent/gated-models.js +89 -0
  33. package/dist/core/agent/pi-adapter.js +401 -0
  34. package/dist/core/agent/policy-gate.js +44 -0
  35. package/dist/core/builtin-catalog.js +20 -0
  36. package/dist/core/concurrency-gate.js +87 -0
  37. package/dist/core/config/atomic-file.js +61 -0
  38. package/dist/core/config/config-store.js +138 -0
  39. package/dist/core/config/pending-restart.js +53 -0
  40. package/dist/core/config/secret-references.js +69 -0
  41. package/dist/core/config/secret-store.js +147 -0
  42. package/dist/core/config/validate.js +55 -0
  43. package/dist/core/config/yaml-patch.js +57 -0
  44. package/dist/core/daemon.js +88 -0
  45. package/dist/core/deployment.js +347 -0
  46. package/dist/core/error-message.js +4 -0
  47. package/dist/core/events.js +25 -0
  48. package/dist/core/logger.js +81 -0
  49. package/dist/core/models.js +27 -0
  50. package/dist/core/module.js +42 -0
  51. package/dist/core/rpc/agent-handlers.js +82 -0
  52. package/dist/core/rpc/deployment-handlers.js +63 -0
  53. package/dist/core/rpc/router.js +95 -0
  54. package/dist/core/server/connection.js +170 -0
  55. package/dist/core/server/control-server.js +152 -0
  56. package/dist/core/server/static-files.js +79 -0
  57. package/dist/core/supervisor.js +206 -0
  58. package/dist/core/tool-routing.js +41 -0
  59. package/dist/dashboard/assets/index-3COz_MZq.css +2 -0
  60. package/dist/dashboard/assets/index-RnxedkKh.js +11 -0
  61. package/dist/dashboard/assets/sheet-presentation-U1UUymXc.js +1 -0
  62. package/dist/dashboard/index.html +13 -0
  63. package/dist/db/database.js +16 -0
  64. package/dist/db/migrations.js +184 -0
  65. package/dist/frontends/discord/approvals.js +199 -0
  66. package/dist/frontends/discord/attachments.js +115 -0
  67. package/dist/frontends/discord/binding.js +489 -0
  68. package/dist/frontends/discord/config.js +107 -0
  69. package/dist/frontends/discord/discord-runtime.js +52 -0
  70. package/dist/frontends/discord/errors.js +61 -0
  71. package/dist/frontends/discord/live-runs.js +189 -0
  72. package/dist/frontends/discord/module.js +39 -0
  73. package/dist/frontends/discord/recent-ids.js +20 -0
  74. package/dist/frontends/slack/approval-blocks.js +98 -0
  75. package/dist/frontends/slack/attachments.js +102 -0
  76. package/dist/frontends/slack/background-tasks.js +20 -0
  77. package/dist/frontends/slack/binding.js +405 -0
  78. package/dist/frontends/slack/bounded.js +9 -0
  79. package/dist/frontends/slack/chat-id.js +17 -0
  80. package/dist/frontends/slack/config.js +80 -0
  81. package/dist/frontends/slack/delivery-errors.js +81 -0
  82. package/dist/frontends/slack/inbound.js +76 -0
  83. package/dist/frontends/slack/live-progress.js +190 -0
  84. package/dist/frontends/slack/manifest.js +66 -0
  85. package/dist/frontends/slack/outbound.js +160 -0
  86. package/dist/frontends/slack/schemas.js +99 -0
  87. package/dist/frontends/slack/signature.js +30 -0
  88. package/dist/frontends/slack/slack-client.js +60 -0
  89. package/dist/frontends/slack/slack-frontend.js +38 -0
  90. package/dist/frontends/slack/state-store.js +112 -0
  91. package/dist/frontends/telegram/approvals.js +134 -0
  92. package/dist/frontends/telegram/attachments.js +126 -0
  93. package/dist/frontends/telegram/binding.js +144 -0
  94. package/dist/frontends/telegram/chat-key.js +43 -0
  95. package/dist/frontends/telegram/client.js +88 -0
  96. package/dist/frontends/telegram/config.js +93 -0
  97. package/dist/frontends/telegram/delivery.js +215 -0
  98. package/dist/frontends/telegram/frontend.js +42 -0
  99. package/dist/frontends/telegram/grammy-client.js +122 -0
  100. package/dist/frontends/telegram/http-status.js +6 -0
  101. package/dist/frontends/telegram/inbound.js +149 -0
  102. package/dist/frontends/telegram/live.js +182 -0
  103. package/dist/frontends/telegram/markdown.js +103 -0
  104. package/dist/frontends/telegram/recent-set.js +18 -0
  105. package/dist/frontends/telegram/serial-queue.js +23 -0
  106. package/dist/index.js +7 -0
  107. package/dist/mcp/content.js +61 -0
  108. package/dist/mcp/mcp-module.js +35 -0
  109. package/dist/mcp/mcp-tool-provider.js +93 -0
  110. package/dist/mcp/server-connection.js +297 -0
  111. package/dist/memory/consolidation.js +260 -0
  112. package/dist/memory/format.js +5 -0
  113. package/dist/memory/migrations.js +76 -0
  114. package/dist/memory/module.js +69 -0
  115. package/dist/memory/names.js +20 -0
  116. package/dist/memory/rows.js +22 -0
  117. package/dist/memory/rpc.js +49 -0
  118. package/dist/memory/snapshots.js +12 -0
  119. package/dist/memory/store.js +281 -0
  120. package/dist/memory/tools.js +158 -0
  121. package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +252 -0
  122. package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +110 -0
  123. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
  124. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
  125. package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
  126. package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
  127. package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
  128. package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
  129. package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
  130. package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
  131. package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
  132. package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
  133. package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
  134. package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
  135. package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
  136. package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
  137. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
  138. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
  139. package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
  140. package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
  141. package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
  142. package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
  143. package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
  144. package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
  145. package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
  146. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
  147. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
  148. package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
  149. package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
  150. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
  151. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
  152. package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
  153. package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
  154. package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
  155. package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
  156. package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
  157. package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
  158. package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
  159. package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
  160. package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
  161. package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
  162. package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
  163. package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
  164. package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
  165. package/dist/ops/backup.js +185 -0
  166. package/dist/ops/cli.js +195 -0
  167. package/dist/ops/command-runner.js +34 -0
  168. package/dist/ops/dashboard-assets.js +37 -0
  169. package/dist/ops/migrate.js +63 -0
  170. package/dist/ops/module.js +47 -0
  171. package/dist/ops/paths.js +55 -0
  172. package/dist/ops/service.js +376 -0
  173. package/dist/ops/update.js +145 -0
  174. package/dist/plugins/contributions.js +89 -0
  175. package/dist/plugins/guards.js +111 -0
  176. package/dist/plugins/load.js +76 -0
  177. package/dist/plugins/module.js +31 -0
  178. package/dist/plugins/provider.js +349 -0
  179. package/dist/plugins/schema.js +69 -0
  180. package/dist/skills/disclosure.js +142 -0
  181. package/dist/skills/discovery.js +120 -0
  182. package/dist/skills/fs-errors.js +8 -0
  183. package/dist/skills/read-skill-tool.js +3 -0
  184. package/dist/skills/skill-file.js +90 -0
  185. package/dist/skills/skills.js +140 -0
  186. package/dist/tools/builtin-tools.js +61 -0
  187. package/dist/tools/input.js +45 -0
  188. package/dist/tools/paths.js +6 -0
  189. package/dist/tools/read-file.js +65 -0
  190. package/dist/tools/shell.js +156 -0
  191. package/dist/tools/write-file.js +58 -0
  192. package/dist/triggers/delivery-codec.js +99 -0
  193. package/dist/triggers/delivery-outbox.js +313 -0
  194. package/dist/triggers/due-timer.js +14 -0
  195. package/dist/triggers/errors.js +2 -0
  196. package/dist/triggers/migrations.js +91 -0
  197. package/dist/triggers/module.js +104 -0
  198. package/dist/triggers/rpc.js +35 -0
  199. package/dist/triggers/schedule.js +52 -0
  200. package/dist/triggers/sql-row.js +59 -0
  201. package/dist/triggers/trigger-runtime.js +445 -0
  202. package/dist/triggers/trigger-tools.js +207 -0
  203. package/dist/triggers/webhook-ingress.js +216 -0
  204. package/dist/wiring/agent-services.js +144 -0
  205. package/dist/wiring/catalog.js +81 -0
  206. package/dist/wiring/daemon.js +83 -0
  207. package/dist/wiring/frontend-host.js +268 -0
  208. package/package.json +50 -3
  209. package/README.md +0 -3
@@ -0,0 +1,297 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import { Client, StreamableHTTPClientTransport, } from "@modelcontextprotocol/client";
4
+ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
5
+ import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
6
+ import { isJsonValue } from "@wheatley-ai/protocol";
7
+ import { canonicalToolName } from "../contracts/tool-names.js";
8
+ import { errorResult, toToolResult } from "./content.js";
9
+ const isPackageManifest = (value) => typeof value === "object" &&
10
+ value !== null &&
11
+ "version" in value &&
12
+ typeof value.version === "string";
13
+ const readPackageVersion = () => {
14
+ // The package root is two levels up from both `src/mcp/` and `dist/mcp/`.
15
+ const manifest = createRequire(import.meta.url)("../../package.json");
16
+ if (!isPackageManifest(manifest)) {
17
+ throw new Error("The wheatley package.json has no version");
18
+ }
19
+ return manifest.version;
20
+ };
21
+ const CLIENT_INFO = { name: "wheatley", version: readPackageVersion() };
22
+ /**
23
+ * True if the input schema of an MCP Tool holds only JSON values. AJV checks the JSON Schema keywords when
24
+ * `getValidator` compiles the document, and throws for a schema that it cannot compile.
25
+ */
26
+ const isJsonSchemaDocument = (schema) => isJsonValue(schema);
27
+ /** Returns true if `value` is a JSON object, not an array or `null`. */
28
+ const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29
+ const errorMessage = (cause) => cause instanceof Error ? cause.message : String(cause);
30
+ const isSecretRef = (value) => typeof value !== "string";
31
+ const resolveValue = (value, secrets) => {
32
+ if (!isSecretRef(value)) {
33
+ return value;
34
+ }
35
+ const secret = secrets.get(value.secret);
36
+ if (secret === undefined) {
37
+ throw new Error(`Unknown secret: ${value.secret}`);
38
+ }
39
+ return secret;
40
+ };
41
+ /** Resolves the `{ secret }` references of stdio `env` or HTTP `headers`. Throws for an unknown secret. */
42
+ const resolveValues = (values, secrets) => Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [
43
+ key,
44
+ resolveValue(value, secrets),
45
+ ]));
46
+ /**
47
+ * One MCP Server of one Agent: its client, its Tools, and its status.
48
+ *
49
+ * A failure of this server changes only its own status and Tools. No method throws or rejects.
50
+ */
51
+ export class McpServerConnection {
52
+ name;
53
+ #input;
54
+ #validator = new AjvJsonSchemaValidator();
55
+ #state;
56
+ #error;
57
+ #client;
58
+ #tools = new Map();
59
+ constructor(input) {
60
+ this.name = input.name;
61
+ this.#input = input;
62
+ this.#state = input.config.enabled === false ? "disabled" : "starting";
63
+ }
64
+ /** The Tools of this server while it is `ready`, otherwise none. */
65
+ tools = () => this.#state === "ready"
66
+ ? [...this.#tools.values()].map((entry) => entry.descriptor)
67
+ : [];
68
+ /** True if `name` is a canonical Tool name of this server. Matches also while the server is not `ready`. */
69
+ owns = (name) => this.#tools.has(name);
70
+ /** The state of this server, with the error message while it is `failed`. */
71
+ status = () => this.#error === undefined
72
+ ? { name: this.name, state: this.#state }
73
+ : { error: this.#error, name: this.name, state: this.#state };
74
+ /**
75
+ * Connects the client with protocol version negotiation `auto`, then lists the Tools.
76
+ *
77
+ * Resolves after the server is `ready` or `failed`. Never rejects. A disabled server stays `disabled` and starts no
78
+ * process. Call it at most once. `signal` aborts the connect and fails the server.
79
+ */
80
+ connect = async (signal) => {
81
+ if (this.#state !== "starting") {
82
+ return;
83
+ }
84
+ try {
85
+ const client = new Client(CLIENT_INFO, {
86
+ jsonSchemaValidator: this.#validator,
87
+ listChanged: {
88
+ tools: {
89
+ onChanged: (error, tools) => {
90
+ this.#onToolsChanged(error, tools);
91
+ },
92
+ },
93
+ },
94
+ versionNegotiation: { mode: "auto" },
95
+ });
96
+ // oxlint-disable-next-line unicorn/prefer-add-event-listener -- The MCP SDK Protocol exposes only `onerror`.
97
+ client.onerror = (error) => {
98
+ this.#input.log.warn("MCP Server error", {
99
+ error: error.message,
100
+ server: this.name,
101
+ });
102
+ };
103
+ // oxlint-disable-next-line unicorn/prefer-add-event-listener -- The MCP SDK Protocol exposes only `onclose`.
104
+ client.onclose = () => {
105
+ this.#onClose();
106
+ };
107
+ this.#client = client;
108
+ await client.connect(this.#createTransport(), {
109
+ signal,
110
+ timeout: this.#input.timeouts.connectMs,
111
+ });
112
+ const { tools } = await client.listTools(undefined, {
113
+ signal,
114
+ timeout: this.#input.timeouts.connectMs,
115
+ });
116
+ if (this.#state !== "starting") {
117
+ return;
118
+ }
119
+ this.#tools = this.#indexTools(tools);
120
+ this.#state = "ready";
121
+ this.#input.log.info("MCP Server connected", {
122
+ server: this.name,
123
+ tools: this.#tools.size,
124
+ });
125
+ }
126
+ catch (error) {
127
+ this.#fail(errorMessage(error));
128
+ await this.#closeClient();
129
+ }
130
+ };
131
+ /**
132
+ * Runs one Tool of this server. Validates `input` against the Tool's input schema before the call.
133
+ *
134
+ * Resolves `{ isError: true }` for an unknown Tool, a server that is not `ready`, invalid input, an error from the
135
+ * server, or an abort of `signal`. Never rejects.
136
+ */
137
+ execute = async (name, input, signal) => {
138
+ const entry = this.#tools.get(name);
139
+ const client = this.#client;
140
+ if (entry === undefined) {
141
+ return errorResult(`Unknown Tool: ${name}`);
142
+ }
143
+ if (this.#state !== "ready" || client === undefined) {
144
+ return errorResult(`MCP Server ${this.name} is not available: ${this.#error ?? this.#state}`);
145
+ }
146
+ const validation = entry.validate(input);
147
+ if (!validation.valid || !isJsonObject(input)) {
148
+ return errorResult(`Invalid input for ${name}: ${validation.errorMessage ?? "input must be an object"}`);
149
+ }
150
+ if (signal.aborted) {
151
+ return errorResult(`${name} was aborted`);
152
+ }
153
+ try {
154
+ const result = await client.callTool({ arguments: input, name: entry.remoteName }, {
155
+ signal,
156
+ timeout: this.#input.timeouts.callMs,
157
+ toolDefinition: entry.definition,
158
+ });
159
+ return toToolResult(result);
160
+ }
161
+ catch (error) {
162
+ return signal.aborted
163
+ ? errorResult(`${name} was aborted`)
164
+ : errorResult(`${name} failed: ${errorMessage(error)}`);
165
+ }
166
+ };
167
+ /**
168
+ * Closes the client and, for stdio, ends the server process. The state becomes `stopped`, except for `disabled`.
169
+ *
170
+ * Call it after `connect` settles. Never rejects.
171
+ */
172
+ close = async () => {
173
+ if (this.#state !== "disabled") {
174
+ this.#state = "stopped";
175
+ this.#error = undefined;
176
+ }
177
+ await this.#closeClient();
178
+ };
179
+ #closeClient = async () => {
180
+ const client = this.#client;
181
+ this.#client = undefined;
182
+ try {
183
+ await client?.close();
184
+ }
185
+ catch (error) {
186
+ this.#input.log.warn("MCP Server close failed", {
187
+ error: errorMessage(error),
188
+ server: this.name,
189
+ });
190
+ }
191
+ };
192
+ #fail = (message) => {
193
+ if (this.#state === "stopped" || this.#state === "disabled") {
194
+ return;
195
+ }
196
+ this.#state = "failed";
197
+ this.#error = message;
198
+ this.#input.log.warn("MCP Server failed", {
199
+ error: message,
200
+ server: this.name,
201
+ });
202
+ };
203
+ #onClose = () => {
204
+ if (this.#state === "ready") {
205
+ this.#fail("Connection closed");
206
+ }
207
+ };
208
+ #onToolsChanged = (error, tools) => {
209
+ if (error !== null) {
210
+ this.#input.log.warn("MCP Tool list refresh failed", {
211
+ error: error.message,
212
+ server: this.name,
213
+ });
214
+ return;
215
+ }
216
+ if (tools !== null && this.#state === "ready") {
217
+ this.#tools = this.#indexTools(tools);
218
+ this.#input.log.info("MCP Tool list changed", {
219
+ server: this.name,
220
+ tools: this.#tools.size,
221
+ });
222
+ }
223
+ };
224
+ #createTransport = () => {
225
+ const { agentDir, config, secrets } = this.#input;
226
+ if (config.transport === "http") {
227
+ return new StreamableHTTPClientTransport(new URL(config.url), {
228
+ requestInit: { headers: resolveValues(config.headers, secrets) },
229
+ });
230
+ }
231
+ const transport = new StdioClientTransport({
232
+ args: [...(config.args ?? [])],
233
+ command: config.command,
234
+ cwd: config.cwd === undefined
235
+ ? undefined
236
+ : path.resolve(agentDir, config.cwd),
237
+ env: resolveValues(config.env, secrets),
238
+ stderr: "pipe",
239
+ });
240
+ transport.stderr?.on("data", (chunk) => {
241
+ this.#input.log.debug("MCP Server stderr", {
242
+ server: this.name,
243
+ text: chunk.toString(),
244
+ });
245
+ });
246
+ return transport;
247
+ };
248
+ /** Builds the canonical Tool index. Skips Tools with invalid names, duplicate names, or unusable input schemas. */
249
+ #indexTools = (tools) => {
250
+ const index = new Map();
251
+ for (const tool of tools) {
252
+ const entry = this.#toEntry(tool);
253
+ if (entry === undefined) {
254
+ continue;
255
+ }
256
+ if (index.has(entry.descriptor.name)) {
257
+ this.#skipTool(tool.name, "duplicate Tool name");
258
+ continue;
259
+ }
260
+ index.set(entry.descriptor.name, entry);
261
+ }
262
+ return index;
263
+ };
264
+ #toEntry = (tool) => {
265
+ const { inputSchema } = tool;
266
+ if (!isJsonSchemaDocument(inputSchema)) {
267
+ this.#skipTool(tool.name, "input schema is not JSON");
268
+ return undefined;
269
+ }
270
+ try {
271
+ const name = canonicalToolName({ kind: "mcp", server: this.name }, tool.name);
272
+ return {
273
+ definition: tool,
274
+ descriptor: {
275
+ defaultAction: "ask",
276
+ description: tool.description ?? tool.title ?? "",
277
+ inputSchema,
278
+ name,
279
+ source: "mcp",
280
+ },
281
+ remoteName: tool.name,
282
+ validate: this.#validator.getValidator(inputSchema),
283
+ };
284
+ }
285
+ catch (error) {
286
+ this.#skipTool(tool.name, errorMessage(error));
287
+ return undefined;
288
+ }
289
+ };
290
+ #skipTool = (tool, reason) => {
291
+ this.#input.log.warn("MCP Tool skipped", {
292
+ reason,
293
+ server: this.name,
294
+ tool,
295
+ });
296
+ };
297
+ }
@@ -0,0 +1,260 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Cron } from "croner";
3
+ import { SeamError } from "../contracts/errors.js";
4
+ import { errorMessage, fileSizeLine } from "./format.js";
5
+ import { rowOf } from "./rows.js";
6
+ /** The `RunOrigin.job` of a consolidation Run. */
7
+ export const CONSOLIDATION_JOB = "memory.consolidate";
8
+ /** The default consolidation schedule: every day at 03:00 in the consolidation timezone. */
9
+ export const DEFAULT_CONSOLIDATION_SCHEDULE = "0 3 * * *";
10
+ /** The maximum length of the stored summary of a consolidation Run. */
11
+ const SUMMARY_MAX_LENGTH = 2000;
12
+ /** The longest delay that `setTimeout` supports. A longer wait uses several timers. */
13
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
14
+ /**
15
+ * Validates the schedule and timezone, and returns the cron job that computes run times. The job has no callback, so
16
+ * it schedules nothing by itself. Throws an `Error` with the config path for an invalid expression or timezone.
17
+ */
18
+ const parseSchedule = (config) => {
19
+ const schedule = config?.schedule ?? DEFAULT_CONSOLIDATION_SCHEDULE;
20
+ try {
21
+ const cron = new Cron(schedule, config?.timezone === undefined
22
+ ? { mode: "5-part" }
23
+ : { mode: "5-part", timezone: config.timezone });
24
+ cron.nextRun();
25
+ return cron;
26
+ }
27
+ catch (error) {
28
+ throw new Error(`Invalid memory.consolidation schedule "${schedule}"${config?.timezone === undefined ? "" : ` in timezone ${config.timezone}`}`, { cause: error });
29
+ }
30
+ };
31
+ const LOG_ROW = {
32
+ ended_at: "number?",
33
+ error: "text?",
34
+ id: "text",
35
+ run_id: "text?",
36
+ started_at: "number",
37
+ status: "text",
38
+ summary: "text?",
39
+ };
40
+ const RUNNING_ROW = { id: "text", run_id: "text?" };
41
+ const LAST_ROW = { last: "number?" };
42
+ const toLogEntry = (value) => {
43
+ const row = rowOf(value, LOG_ROW);
44
+ const entry = {
45
+ endedAt: row.ended_at === null ? null : new Date(row.ended_at).toISOString(),
46
+ id: row.id,
47
+ startedAt: new Date(row.started_at).toISOString(),
48
+ status: row.status === "completed" || row.status === "failed"
49
+ ? row.status
50
+ : "running",
51
+ };
52
+ if (row.run_id !== null) {
53
+ entry.runId = row.run_id;
54
+ }
55
+ if (row.summary !== null) {
56
+ entry.summary = row.summary;
57
+ }
58
+ if (row.error !== null) {
59
+ entry.error = row.error;
60
+ }
61
+ return entry;
62
+ };
63
+ /**
64
+ * Creates the consolidation job. If consolidation is enabled, it validates the schedule at once and throws an `Error`
65
+ * if it is invalid. A disabled job ignores the schedule and the timezone.
66
+ */
67
+ export const createMemoryConsolidation = (options) => {
68
+ const { clock, config, db, log, runner, store } = options;
69
+ const enabled = config?.enabled ?? true;
70
+ const cron = enabled ? parseSchedule(config) : undefined;
71
+ let active = false;
72
+ let stopped = false;
73
+ let timer;
74
+ const buildPrompt = async () => {
75
+ const { budget, files } = await store.list();
76
+ const inventory = files.length === 0
77
+ ? "Memory has no files yet."
78
+ : files.map(fileSizeLine).join("\n");
79
+ return [
80
+ "Consolidate your Memory. This is a scheduled maintenance Run, and nobody reads your reply live.",
81
+ "",
82
+ "Memory files now:",
83
+ inventory,
84
+ `MEMORY.md uses ${budget.usedChars} of ${budget.maxChars} characters.`,
85
+ "",
86
+ "1. Read each Memory file with memory_read.",
87
+ "2. Merge duplicate facts, and remove facts that are stale or that newer facts contradict. Use memory_search with scope conversations to check recent Conversations when a fact is unclear.",
88
+ "3. Keep MEMORY.md short: the key facts and preferences, and the names of the topic files. Move details into topic files.",
89
+ "4. Delete topic files that are empty or obsolete with memory_delete.",
90
+ "5. Do not invent facts. Change only what the files and Conversations support.",
91
+ "",
92
+ "End with a short summary of your changes.",
93
+ ].join("\n");
94
+ };
95
+ const finish = (id, result) => {
96
+ const summary = result.text.trim().slice(0, SUMMARY_MAX_LENGTH);
97
+ const status = result.status === "completed" ? "completed" : "failed";
98
+ const error = result.error ??
99
+ (result.status === "stopped"
100
+ ? "The consolidation Run was stopped."
101
+ : undefined);
102
+ db.prepare("UPDATE memory_consolidations SET status = ?, ended_at = ?, summary = ?, error = ? WHERE id = ?").run(status, clock.now(), summary === "" ? null : summary, status === "failed" ? (error ?? null) : null, id);
103
+ };
104
+ /** Waits for a Run and records its end. Never rejects. */
105
+ const track = async (id, runId) => {
106
+ let result;
107
+ try {
108
+ result = await runner.wait(runId);
109
+ }
110
+ catch (error) {
111
+ result = {
112
+ error: errorMessage(error),
113
+ status: "failed",
114
+ text: "",
115
+ };
116
+ }
117
+ // After `stop`, the database can be closed. The next `start` resumes the entry.
118
+ if (stopped) {
119
+ return;
120
+ }
121
+ try {
122
+ finish(id, result);
123
+ }
124
+ catch (error) {
125
+ log.error("Failed to record the end of a Memory consolidation", {
126
+ error: errorMessage(error),
127
+ runId,
128
+ });
129
+ }
130
+ finally {
131
+ active = false;
132
+ }
133
+ };
134
+ const run = async () => {
135
+ if (active) {
136
+ throw new SeamError("conflict", "A Memory consolidation is already running for this Agent.");
137
+ }
138
+ active = true;
139
+ const id = randomUUID();
140
+ try {
141
+ db.prepare("INSERT INTO memory_consolidations (id, status, started_at) VALUES (?, 'running', ?)").run(id, clock.now());
142
+ }
143
+ catch (error) {
144
+ active = false;
145
+ throw error;
146
+ }
147
+ let runId;
148
+ try {
149
+ const prompt = await buildPrompt();
150
+ const request = config?.model === undefined
151
+ ? { job: CONSOLIDATION_JOB, prompt }
152
+ : { job: CONSOLIDATION_JOB, model: config.model, prompt };
153
+ ({ runId } = await runner.start(request));
154
+ db.prepare("UPDATE memory_consolidations SET run_id = ? WHERE id = ?").run(runId, id);
155
+ }
156
+ catch (error) {
157
+ finish(id, {
158
+ error: errorMessage(error),
159
+ status: "failed",
160
+ text: "",
161
+ });
162
+ active = false;
163
+ throw error;
164
+ }
165
+ void track(id, runId);
166
+ return { runId };
167
+ };
168
+ const logEntries = (limit) => db
169
+ .prepare(`SELECT id, run_id, status, started_at, ended_at, summary, error FROM memory_consolidations
170
+ ORDER BY started_at DESC, rowid DESC LIMIT ?`)
171
+ .all(limit)
172
+ .map(toLogEntry);
173
+ const runScheduled = async () => {
174
+ try {
175
+ const { runId } = await run();
176
+ log.info("Started a scheduled Memory consolidation", { runId });
177
+ }
178
+ catch (error) {
179
+ if (error instanceof SeamError && error.code === "conflict") {
180
+ log.info("Skipped a scheduled Memory consolidation because one is already running");
181
+ return;
182
+ }
183
+ log.error("Failed to start a scheduled Memory consolidation", {
184
+ error: errorMessage(error),
185
+ });
186
+ }
187
+ };
188
+ const scheduleNext = (schedule) => {
189
+ if (stopped) {
190
+ return;
191
+ }
192
+ const next = schedule.nextRun(new Date(clock.now()));
193
+ if (next === null) {
194
+ return;
195
+ }
196
+ const target = next.getTime();
197
+ const wake = () => {
198
+ if (stopped) {
199
+ return;
200
+ }
201
+ const remaining = target - clock.now();
202
+ if (remaining > 0) {
203
+ timer = setTimeout(wake, Math.min(remaining, MAX_TIMER_DELAY_MS)).unref();
204
+ return;
205
+ }
206
+ void runScheduled().finally(() => {
207
+ scheduleNext(schedule);
208
+ });
209
+ };
210
+ timer = setTimeout(wake, Math.min(Math.max(target - clock.now(), 0), MAX_TIMER_DELAY_MS)).unref();
211
+ };
212
+ const resume = () => {
213
+ const rows = db
214
+ .prepare("SELECT id, run_id FROM memory_consolidations WHERE status = 'running'")
215
+ .all()
216
+ .map((value) => rowOf(value, RUNNING_ROW));
217
+ for (const row of rows) {
218
+ if (row.run_id === null) {
219
+ finish(row.id, {
220
+ error: "The daemon stopped before the consolidation Run started.",
221
+ status: "failed",
222
+ text: "",
223
+ });
224
+ }
225
+ else {
226
+ active = true;
227
+ void track(row.id, row.run_id);
228
+ }
229
+ }
230
+ };
231
+ const missedSlot = (schedule) => {
232
+ const value = db
233
+ .prepare("SELECT max(started_at) AS last FROM memory_consolidations")
234
+ .get();
235
+ const last = value === undefined ? null : rowOf(value, LAST_ROW).last;
236
+ const [previous] = schedule.previousRuns(1, new Date(clock.now()));
237
+ return last !== null && previous !== undefined && previous.getTime() > last;
238
+ };
239
+ const start = async () => {
240
+ await Promise.try(() => {
241
+ stopped = false;
242
+ resume();
243
+ if (cron === undefined) {
244
+ return;
245
+ }
246
+ if (missedSlot(cron)) {
247
+ void runScheduled();
248
+ }
249
+ scheduleNext(cron);
250
+ });
251
+ };
252
+ const stop = async () => {
253
+ await Promise.try(() => {
254
+ stopped = true;
255
+ clearTimeout(timer);
256
+ timer = undefined;
257
+ });
258
+ };
259
+ return { log: logEntries, run, start, stop };
260
+ };
@@ -0,0 +1,5 @@
1
+ import { memoryFileName } from "./names.js";
2
+ /** Returns the message of a thrown value. */
3
+ export const errorMessage = (cause) => cause instanceof Error ? cause.message : String(cause);
4
+ /** Formats one inventory line of a Memory file, for example `- travel.md: 13 characters`. */
5
+ export const fileSizeLine = (file) => `- ${memoryFileName(file.name)}: ${file.chars} characters`;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The `memory` migration namespace of `agent.sqlite` (ADR 0009).
3
+ *
4
+ * - `memory_files_fts`: the derived FTS5 index of the Markdown files. `reindex` rebuilds it from disk.
5
+ * - `memory_messages` and `memory_messages_fts`: the user and assistant Conversation archive and its index. Triggers
6
+ * keep the external-content index in step with the archive.
7
+ * - `memory_consolidations`: the consolidation log.
8
+ */
9
+ export const memoryMigrations = [
10
+ {
11
+ name: "create memory index, archive, snapshots, and consolidation log",
12
+ up: (db) => {
13
+ db.exec(`
14
+ CREATE VIRTUAL TABLE memory_files_fts USING fts5(
15
+ name UNINDEXED,
16
+ title,
17
+ content,
18
+ tokenize = 'porter unicode61 remove_diacritics 2'
19
+ );
20
+
21
+ CREATE TABLE memory_messages (
22
+ id INTEGER PRIMARY KEY,
23
+ conversation_id TEXT NOT NULL,
24
+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
25
+ text TEXT NOT NULL,
26
+ at INTEGER NOT NULL
27
+ ) STRICT;
28
+
29
+ CREATE INDEX memory_messages_conversation ON memory_messages (conversation_id);
30
+
31
+ CREATE VIRTUAL TABLE memory_messages_fts USING fts5(
32
+ text,
33
+ content = 'memory_messages',
34
+ content_rowid = 'id',
35
+ tokenize = 'porter unicode61 remove_diacritics 2'
36
+ );
37
+
38
+ CREATE TRIGGER memory_messages_ai AFTER INSERT ON memory_messages BEGIN
39
+ INSERT INTO memory_messages_fts (rowid, text) VALUES (new.id, new.text);
40
+ END;
41
+
42
+ CREATE TRIGGER memory_messages_ad AFTER DELETE ON memory_messages BEGIN
43
+ INSERT INTO memory_messages_fts (memory_messages_fts, rowid, text) VALUES ('delete', old.id, old.text);
44
+ END;
45
+
46
+ CREATE TABLE memory_snapshots (
47
+ conversation_id TEXT PRIMARY KEY,
48
+ text TEXT NOT NULL,
49
+ truncated INTEGER NOT NULL CHECK (truncated IN (0, 1)),
50
+ taken_at INTEGER NOT NULL
51
+ ) STRICT;
52
+
53
+ CREATE TABLE memory_consolidations (
54
+ id TEXT PRIMARY KEY,
55
+ run_id TEXT,
56
+ status TEXT NOT NULL CHECK (status IN ('running', 'completed', 'failed')),
57
+ started_at INTEGER NOT NULL,
58
+ ended_at INTEGER,
59
+ summary TEXT,
60
+ error TEXT
61
+ ) STRICT;
62
+
63
+ CREATE INDEX memory_consolidations_started ON memory_consolidations (started_at);
64
+ `);
65
+ },
66
+ version: 1,
67
+ },
68
+ {
69
+ name: "drop memory snapshots",
70
+ // The Conversation instructions in `harness.sqlite` hold the frozen `MEMORY.md` snapshot, so this table is unused.
71
+ up: (db) => {
72
+ db.exec("DROP TABLE memory_snapshots;");
73
+ },
74
+ version: 2,
75
+ },
76
+ ];