@wheatley-ai/cli 0.0.0-stage → 0.1.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 (210) 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 +178 -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 +206 -0
  17. package/dist/cli/session.js +86 -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 +1033 -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 +72 -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-socket.js +96 -0
  45. package/dist/core/daemon.js +97 -0
  46. package/dist/core/deployment.js +379 -0
  47. package/dist/core/error-message.js +4 -0
  48. package/dist/core/events.js +25 -0
  49. package/dist/core/logger.js +81 -0
  50. package/dist/core/models.js +27 -0
  51. package/dist/core/module.js +42 -0
  52. package/dist/core/rpc/agent-handlers.js +82 -0
  53. package/dist/core/rpc/deployment-handlers.js +63 -0
  54. package/dist/core/rpc/router.js +96 -0
  55. package/dist/core/server/connection.js +170 -0
  56. package/dist/core/server/control-server.js +152 -0
  57. package/dist/core/server/static-files.js +79 -0
  58. package/dist/core/supervisor.js +215 -0
  59. package/dist/core/tool-routing.js +41 -0
  60. package/dist/dashboard/assets/index-C9Rul5vE.css +2 -0
  61. package/dist/dashboard/assets/index-DXzGGAxQ.js +11 -0
  62. package/dist/dashboard/assets/sheet-presentation-DMljN0LW.js +1 -0
  63. package/dist/dashboard/index.html +18 -0
  64. package/dist/db/database.js +16 -0
  65. package/dist/db/migrations.js +184 -0
  66. package/dist/frontends/discord/approvals.js +199 -0
  67. package/dist/frontends/discord/attachments.js +115 -0
  68. package/dist/frontends/discord/binding.js +489 -0
  69. package/dist/frontends/discord/config.js +107 -0
  70. package/dist/frontends/discord/discord-runtime.js +52 -0
  71. package/dist/frontends/discord/errors.js +61 -0
  72. package/dist/frontends/discord/live-runs.js +189 -0
  73. package/dist/frontends/discord/module.js +39 -0
  74. package/dist/frontends/discord/recent-ids.js +20 -0
  75. package/dist/frontends/slack/approval-blocks.js +98 -0
  76. package/dist/frontends/slack/attachments.js +102 -0
  77. package/dist/frontends/slack/background-tasks.js +20 -0
  78. package/dist/frontends/slack/binding.js +405 -0
  79. package/dist/frontends/slack/bounded.js +9 -0
  80. package/dist/frontends/slack/chat-id.js +17 -0
  81. package/dist/frontends/slack/config.js +80 -0
  82. package/dist/frontends/slack/delivery-errors.js +81 -0
  83. package/dist/frontends/slack/inbound.js +76 -0
  84. package/dist/frontends/slack/live-progress.js +190 -0
  85. package/dist/frontends/slack/manifest.js +66 -0
  86. package/dist/frontends/slack/outbound.js +160 -0
  87. package/dist/frontends/slack/schemas.js +99 -0
  88. package/dist/frontends/slack/signature.js +30 -0
  89. package/dist/frontends/slack/slack-client.js +60 -0
  90. package/dist/frontends/slack/slack-frontend.js +38 -0
  91. package/dist/frontends/slack/state-store.js +112 -0
  92. package/dist/frontends/telegram/approvals.js +134 -0
  93. package/dist/frontends/telegram/attachments.js +126 -0
  94. package/dist/frontends/telegram/binding.js +144 -0
  95. package/dist/frontends/telegram/chat-key.js +43 -0
  96. package/dist/frontends/telegram/client.js +88 -0
  97. package/dist/frontends/telegram/config.js +93 -0
  98. package/dist/frontends/telegram/delivery.js +215 -0
  99. package/dist/frontends/telegram/frontend.js +42 -0
  100. package/dist/frontends/telegram/grammy-client.js +122 -0
  101. package/dist/frontends/telegram/http-status.js +6 -0
  102. package/dist/frontends/telegram/inbound.js +149 -0
  103. package/dist/frontends/telegram/live.js +182 -0
  104. package/dist/frontends/telegram/markdown.js +103 -0
  105. package/dist/frontends/telegram/recent-set.js +18 -0
  106. package/dist/frontends/telegram/serial-queue.js +23 -0
  107. package/dist/index.js +7 -0
  108. package/dist/mcp/content.js +61 -0
  109. package/dist/mcp/mcp-module.js +35 -0
  110. package/dist/mcp/mcp-tool-provider.js +93 -0
  111. package/dist/mcp/server-connection.js +297 -0
  112. package/dist/memory/consolidation.js +260 -0
  113. package/dist/memory/format.js +5 -0
  114. package/dist/memory/migrations.js +76 -0
  115. package/dist/memory/module.js +69 -0
  116. package/dist/memory/names.js +20 -0
  117. package/dist/memory/rows.js +22 -0
  118. package/dist/memory/rpc.js +49 -0
  119. package/dist/memory/snapshots.js +12 -0
  120. package/dist/memory/store.js +281 -0
  121. package/dist/memory/tools.js +158 -0
  122. package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +262 -0
  123. package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +120 -0
  124. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
  125. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
  126. package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
  127. package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
  128. package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
  129. package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
  130. package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
  131. package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
  132. package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
  133. package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
  134. package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
  135. package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
  136. package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
  137. package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
  138. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
  139. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
  140. package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
  141. package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
  142. package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
  143. package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
  144. package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
  145. package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
  146. package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
  147. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
  148. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
  149. package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
  150. package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
  151. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
  152. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
  153. package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
  154. package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
  155. package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
  156. package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
  157. package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
  158. package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
  159. package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
  160. package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
  161. package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
  162. package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
  163. package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
  164. package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
  165. package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
  166. package/dist/ops/backup.js +185 -0
  167. package/dist/ops/cli.js +194 -0
  168. package/dist/ops/command-runner.js +34 -0
  169. package/dist/ops/dashboard-assets.js +37 -0
  170. package/dist/ops/migrate.js +63 -0
  171. package/dist/ops/module.js +47 -0
  172. package/dist/ops/paths.js +55 -0
  173. package/dist/ops/service.js +376 -0
  174. package/dist/ops/update.js +145 -0
  175. package/dist/plugins/contributions.js +89 -0
  176. package/dist/plugins/guards.js +111 -0
  177. package/dist/plugins/load.js +76 -0
  178. package/dist/plugins/module.js +31 -0
  179. package/dist/plugins/provider.js +349 -0
  180. package/dist/plugins/schema.js +69 -0
  181. package/dist/skills/disclosure.js +142 -0
  182. package/dist/skills/discovery.js +120 -0
  183. package/dist/skills/fs-errors.js +8 -0
  184. package/dist/skills/read-skill-tool.js +3 -0
  185. package/dist/skills/skill-file.js +90 -0
  186. package/dist/skills/skills.js +140 -0
  187. package/dist/tools/builtin-tools.js +61 -0
  188. package/dist/tools/input.js +45 -0
  189. package/dist/tools/paths.js +6 -0
  190. package/dist/tools/read-file.js +65 -0
  191. package/dist/tools/shell.js +156 -0
  192. package/dist/tools/write-file.js +58 -0
  193. package/dist/triggers/delivery-codec.js +99 -0
  194. package/dist/triggers/delivery-outbox.js +313 -0
  195. package/dist/triggers/due-timer.js +14 -0
  196. package/dist/triggers/errors.js +2 -0
  197. package/dist/triggers/migrations.js +91 -0
  198. package/dist/triggers/module.js +106 -0
  199. package/dist/triggers/rpc.js +35 -0
  200. package/dist/triggers/schedule.js +52 -0
  201. package/dist/triggers/sql-row.js +59 -0
  202. package/dist/triggers/trigger-runtime.js +445 -0
  203. package/dist/triggers/trigger-tools.js +210 -0
  204. package/dist/triggers/webhook-ingress.js +212 -0
  205. package/dist/wiring/agent-services.js +151 -0
  206. package/dist/wiring/catalog.js +81 -0
  207. package/dist/wiring/daemon.js +83 -0
  208. package/dist/wiring/frontend-host.js +268 -0
  209. package/package.json +50 -3
  210. package/README.md +0 -3
@@ -0,0 +1,65 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { errorMessage } from "../core/error-message.js";
3
+ import { checkInput, integerField, stringField } from "./input.js";
4
+ import { resolveToolPath } from "./paths.js";
5
+ /** The largest text that `read_file` returns in one call. */
6
+ export const READ_FILE_MAX_CHARS = 100_000;
7
+ const text = (value, isError = false) => ({
8
+ content: [{ text: value, type: "text" }],
9
+ isError,
10
+ });
11
+ /** Reads a UTF-8 text file, optionally from a line offset and for a line count. */
12
+ export const readFileTool = {
13
+ description: "Read a UTF-8 text file. Relative paths resolve inside the Agent workspace. Use offset (0-based line) and limit (line count) to read part of a large file.",
14
+ execute: async (input, ctx) => {
15
+ const checked = checkInput(input, {
16
+ limit: "optional-integer",
17
+ offset: "optional-integer",
18
+ path: "string",
19
+ });
20
+ if (!checked.ok) {
21
+ return text(checked.message, true);
22
+ }
23
+ const target = resolveToolPath(ctx.workspaceDir, stringField(checked.value, "path") ?? "");
24
+ let content;
25
+ try {
26
+ content = await readFile(target, {
27
+ encoding: "utf-8",
28
+ signal: ctx.signal,
29
+ });
30
+ }
31
+ catch (error) {
32
+ return text(`Cannot read ${target}: ${errorMessage(error)}`, true);
33
+ }
34
+ const offset = integerField(checked.value, "offset");
35
+ const limit = integerField(checked.value, "limit");
36
+ const selected = offset === undefined && limit === undefined
37
+ ? content
38
+ : content
39
+ .split("\n")
40
+ .slice(offset ?? 0, limit === undefined ? undefined : (offset ?? 0) + limit)
41
+ .join("\n");
42
+ return selected.length > READ_FILE_MAX_CHARS
43
+ ? text(`${selected.slice(0, READ_FILE_MAX_CHARS)}\n[truncated: the file has ${selected.length} characters; read the rest with offset and limit]`)
44
+ : text(selected);
45
+ },
46
+ inputSchema: {
47
+ additionalProperties: false,
48
+ properties: {
49
+ limit: {
50
+ description: "The number of lines to read",
51
+ minimum: 0,
52
+ type: "integer",
53
+ },
54
+ offset: {
55
+ description: "The first line to read, 0-based",
56
+ minimum: 0,
57
+ type: "integer",
58
+ },
59
+ path: { description: "The file path", type: "string" },
60
+ },
61
+ required: ["path"],
62
+ type: "object",
63
+ },
64
+ name: "read_file",
65
+ };
@@ -0,0 +1,156 @@
1
+ import { spawn } from "node:child_process";
2
+ import { once } from "node:events";
3
+ import { mkdir } from "node:fs/promises";
4
+ import { errorMessage } from "../core/error-message.js";
5
+ import { checkInput, integerField, stringField } from "./input.js";
6
+ import { resolveToolPath } from "./paths.js";
7
+ /** The default command timeout. */
8
+ export const SHELL_DEFAULT_TIMEOUT_MS = 120_000;
9
+ /** The longest command timeout that a call can ask for. */
10
+ export const SHELL_MAX_TIMEOUT_MS = 600_000;
11
+ /** The combined stdout and stderr that `shell` keeps. It keeps the tail, where errors usually are. */
12
+ export const SHELL_MAX_OUTPUT_CHARS = 50_000;
13
+ const text = (value, isError = false) => ({
14
+ content: [{ text: value, type: "text" }],
15
+ isError,
16
+ });
17
+ /** Keeps the last `SHELL_MAX_OUTPUT_CHARS` characters of a stream of chunks. */
18
+ class OutputTail {
19
+ #text = "";
20
+ #dropped = 0;
21
+ add(chunk) {
22
+ this.#text += chunk;
23
+ if (this.#text.length > SHELL_MAX_OUTPUT_CHARS) {
24
+ const excess = this.#text.length - SHELL_MAX_OUTPUT_CHARS;
25
+ this.#dropped += excess;
26
+ this.#text = this.#text.slice(excess);
27
+ }
28
+ }
29
+ get text() {
30
+ return this.#text;
31
+ }
32
+ get dropped() {
33
+ return this.#dropped;
34
+ }
35
+ }
36
+ const killGroup = (pid) => {
37
+ if (pid === undefined) {
38
+ return;
39
+ }
40
+ try {
41
+ // A negative PID signals the process group, so child processes of the shell stop too.
42
+ process.kill(-pid, "SIGKILL");
43
+ }
44
+ catch {
45
+ // The group already exited.
46
+ }
47
+ };
48
+ const runCommand = async (command, cwd, timeoutMs, signal) => {
49
+ const tail = new OutputTail();
50
+ const child = spawn("/bin/sh", ["-c", command], {
51
+ cwd,
52
+ detached: true,
53
+ env: process.env,
54
+ stdio: ["ignore", "pipe", "pipe"],
55
+ });
56
+ let timedOut = false;
57
+ let aborted = false;
58
+ const timer = setTimeout(() => {
59
+ timedOut = true;
60
+ killGroup(child.pid);
61
+ }, timeoutMs);
62
+ const onAbort = () => {
63
+ aborted = true;
64
+ killGroup(child.pid);
65
+ };
66
+ signal.addEventListener("abort", onAbort, { once: true });
67
+ child.stdout.setEncoding("utf-8");
68
+ child.stderr.setEncoding("utf-8");
69
+ child.stdout.on("data", (chunk) => {
70
+ tail.add(chunk);
71
+ });
72
+ child.stderr.on("data", (chunk) => {
73
+ tail.add(chunk);
74
+ });
75
+ try {
76
+ // `once` rejects if the child emits `error`, for example when `/bin/sh` cannot start.
77
+ await once(child, "close");
78
+ }
79
+ finally {
80
+ clearTimeout(timer);
81
+ signal.removeEventListener("abort", onAbort);
82
+ }
83
+ return {
84
+ aborted,
85
+ dropped: tail.dropped,
86
+ exitCode: child.exitCode,
87
+ output: tail.text,
88
+ signal: child.signalCode,
89
+ timedOut,
90
+ };
91
+ };
92
+ const describeOutcome = (outcome, timeoutMs) => {
93
+ const header = outcome.dropped > 0
94
+ ? `[${outcome.dropped} earlier characters dropped]\n`
95
+ : "";
96
+ const body = `${header}${outcome.output}`;
97
+ if (outcome.aborted) {
98
+ return text(`${body}\n[the command was stopped]`, true);
99
+ }
100
+ if (outcome.timedOut) {
101
+ return text(`${body}\n[the command timed out after ${timeoutMs} ms]`, true);
102
+ }
103
+ if (outcome.exitCode !== 0) {
104
+ const status = outcome.exitCode === null
105
+ ? `signal ${outcome.signal ?? "unknown"}`
106
+ : `exit code ${outcome.exitCode}`;
107
+ return text(`${body}\n[${status}]`, true);
108
+ }
109
+ return text(body === "" ? "[no output, exit code 0]" : body);
110
+ };
111
+ /** Runs a command with `/bin/sh -c` in the Agent workspace and returns its combined output. */
112
+ export const shellTool = {
113
+ description: "Run a shell command with /bin/sh -c and return its combined stdout and stderr. The working directory is the Agent workspace unless cwd is set. A nonzero exit code is an error result.",
114
+ execute: async (input, ctx) => {
115
+ const checked = checkInput(input, {
116
+ command: "string",
117
+ cwd: "optional-string",
118
+ timeoutMs: "optional-integer",
119
+ });
120
+ if (!checked.ok) {
121
+ return text(checked.message, true);
122
+ }
123
+ const requested = integerField(checked.value, "timeoutMs") ?? SHELL_DEFAULT_TIMEOUT_MS;
124
+ const timeoutMs = Math.min(Math.max(requested, 1), SHELL_MAX_TIMEOUT_MS);
125
+ const cwd = resolveToolPath(ctx.workspaceDir, stringField(checked.value, "cwd") ?? ".");
126
+ if (ctx.signal.aborted) {
127
+ return text("The command was stopped before it started", true);
128
+ }
129
+ try {
130
+ await mkdir(cwd, { recursive: true });
131
+ const outcome = await runCommand(stringField(checked.value, "command") ?? "", cwd, timeoutMs, ctx.signal);
132
+ return describeOutcome(outcome, timeoutMs);
133
+ }
134
+ catch (error) {
135
+ return text(`Cannot run the command: ${errorMessage(error)}`, true);
136
+ }
137
+ },
138
+ inputSchema: {
139
+ additionalProperties: false,
140
+ properties: {
141
+ command: { description: "The shell command", type: "string" },
142
+ cwd: {
143
+ description: "The working directory, relative to the workspace",
144
+ type: "string",
145
+ },
146
+ timeoutMs: {
147
+ description: `Milliseconds before the command is killed; default ${SHELL_DEFAULT_TIMEOUT_MS}, at most ${SHELL_MAX_TIMEOUT_MS}`,
148
+ minimum: 1,
149
+ type: "integer",
150
+ },
151
+ },
152
+ required: ["command"],
153
+ type: "object",
154
+ },
155
+ name: "shell",
156
+ };
@@ -0,0 +1,58 @@
1
+ import { appendFile, mkdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { errorMessage } from "../core/error-message.js";
4
+ import { checkInput, stringField } from "./input.js";
5
+ import { resolveToolPath } from "./paths.js";
6
+ const text = (value, isError = false) => ({
7
+ content: [{ text: value, type: "text" }],
8
+ isError,
9
+ });
10
+ /** Writes or appends UTF-8 text to a file and creates missing parent folders. */
11
+ export const writeFileTool = {
12
+ description: 'Write UTF-8 text to a file, replacing it, or append with mode "append". Relative paths resolve inside the Agent workspace. Missing folders are created.',
13
+ execute: async (input, ctx) => {
14
+ const checked = checkInput(input, {
15
+ content: "string",
16
+ mode: "optional-string",
17
+ path: "string",
18
+ });
19
+ if (!checked.ok) {
20
+ return text(checked.message, true);
21
+ }
22
+ const mode = stringField(checked.value, "mode") ?? "replace";
23
+ if (mode !== "replace" && mode !== "append") {
24
+ return text('The field mode must be "replace" or "append"', true);
25
+ }
26
+ const target = resolveToolPath(ctx.workspaceDir, stringField(checked.value, "path") ?? "");
27
+ const content = stringField(checked.value, "content") ?? "";
28
+ try {
29
+ await mkdir(path.dirname(target), { recursive: true });
30
+ await (mode === "append"
31
+ ? appendFile(target, content, { encoding: "utf-8" })
32
+ : writeFile(target, content, {
33
+ encoding: "utf-8",
34
+ signal: ctx.signal,
35
+ }));
36
+ }
37
+ catch (error) {
38
+ return text(`Cannot write ${target}: ${errorMessage(error)}`, true);
39
+ }
40
+ const verb = mode === "append" ? "Appended" : "Wrote";
41
+ return text(`${verb} ${Buffer.byteLength(content, "utf-8")} bytes to ${target}`);
42
+ },
43
+ inputSchema: {
44
+ additionalProperties: false,
45
+ properties: {
46
+ content: { description: "The text to write", type: "string" },
47
+ mode: {
48
+ description: "replace (default) or append",
49
+ enum: ["replace", "append"],
50
+ type: "string",
51
+ },
52
+ path: { description: "The file path", type: "string" },
53
+ },
54
+ required: ["path", "content"],
55
+ type: "object",
56
+ },
57
+ name: "write_file",
58
+ };
@@ -0,0 +1,99 @@
1
+ import { Type } from "typebox";
2
+ import { Value } from "typebox/value";
3
+ /** An attachment as the outbox stores it: bytes become base64 text, so the whole `Delivery` fits in one JSON column. */
4
+ const StoredAttachmentSchema = Type.Union([
5
+ Type.Object({
6
+ base64: Type.String(),
7
+ filename: Type.String(),
8
+ kind: Type.Literal("bytes"),
9
+ mimeType: Type.String(),
10
+ }),
11
+ Type.Object({
12
+ filename: Type.String(),
13
+ kind: Type.Literal("file"),
14
+ mimeType: Type.String(),
15
+ path: Type.String(),
16
+ sizeBytes: Type.Number(),
17
+ }),
18
+ ]);
19
+ const StoredDeliverySchema = Type.Union([
20
+ Type.Object({
21
+ attachments: Type.Optional(Type.Array(StoredAttachmentSchema)),
22
+ chatId: Type.String(),
23
+ kind: Type.Literal("message"),
24
+ messageId: Type.String(),
25
+ runId: Type.Optional(Type.String()),
26
+ source: Type.Union([
27
+ Type.Literal("reply"),
28
+ Type.Literal("command"),
29
+ Type.Literal("trigger"),
30
+ ]),
31
+ text: Type.String(),
32
+ }),
33
+ Type.Object({
34
+ approvalId: Type.String(),
35
+ chatId: Type.String(),
36
+ expiresAt: Type.Union([Type.String(), Type.Null()]),
37
+ inputPreview: Type.String(),
38
+ kind: Type.Literal("approval_requested"),
39
+ messageId: Type.String(),
40
+ runId: Type.String(),
41
+ toolName: Type.String(),
42
+ }),
43
+ Type.Object({
44
+ approvalId: Type.String(),
45
+ chatId: Type.String(),
46
+ decision: Type.Union([
47
+ Type.Literal("allow_once"),
48
+ Type.Literal("allow_conversation"),
49
+ Type.Literal("allow_always"),
50
+ Type.Literal("deny"),
51
+ Type.Literal("timeout"),
52
+ Type.Literal("cancelled"),
53
+ ]),
54
+ kind: Type.Literal("approval_resolved"),
55
+ messageId: Type.String(),
56
+ reason: Type.Optional(Type.String()),
57
+ resolvedBy: Type.Optional(Type.String()),
58
+ }),
59
+ ]);
60
+ const storeAttachment = (attachment) => attachment.kind === "bytes"
61
+ ? {
62
+ base64: Buffer.from(attachment.data).toString("base64"),
63
+ filename: attachment.filename,
64
+ kind: "bytes",
65
+ mimeType: attachment.mimeType,
66
+ }
67
+ : attachment;
68
+ const loadAttachment = (stored) => stored.kind === "bytes"
69
+ ? {
70
+ data: new Uint8Array(Buffer.from(stored.base64, "base64")),
71
+ filename: stored.filename,
72
+ kind: "bytes",
73
+ mimeType: stored.mimeType,
74
+ }
75
+ : stored;
76
+ /** Serializes a `Delivery` for the outbox. Attachment bytes round-trip through base64. */
77
+ export const encodeDelivery = (delivery) => {
78
+ if (delivery.kind !== "message" || delivery.attachments === undefined) {
79
+ return JSON.stringify(delivery);
80
+ }
81
+ return JSON.stringify({
82
+ ...delivery,
83
+ attachments: delivery.attachments.map(storeAttachment),
84
+ });
85
+ };
86
+ /** Parses a `Delivery` that `encodeDelivery` stored. Throws a `TypeError` for any other text. */
87
+ export const decodeDelivery = (json) => {
88
+ const value = JSON.parse(json);
89
+ if (!Value.Check(StoredDeliverySchema, value)) {
90
+ throw new TypeError("Stored delivery is invalid");
91
+ }
92
+ if (value.kind !== "message") {
93
+ return value;
94
+ }
95
+ const { attachments, ...message } = value;
96
+ return attachments === undefined
97
+ ? message
98
+ : { ...message, attachments: attachments.map(loadAttachment) };
99
+ };
@@ -0,0 +1,313 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { setTimeout as sleep } from "node:timers/promises";
3
+ import { DELIVERY_PREVIEW_MAX_LENGTH } from "@wheatley-ai/protocol";
4
+ import { isDeliveryError } from "@wheatley-ai/sdk";
5
+ import { decodeDelivery, encodeDelivery } from "./delivery-codec.js";
6
+ import { armDueTimer } from "./due-timer.js";
7
+ import { errorText } from "./errors.js";
8
+ import { enumColumn, integerColumn, optionalIntegerColumn, optionalTextColumn, textColumn, } from "./sql-row.js";
9
+ /** Retries stop after this many attempts (ADR 0010). */
10
+ export const MAX_DELIVERY_ATTEMPTS = 10;
11
+ /** Retries stop when the next attempt would start later than this after the first attempt (ADR 0010). */
12
+ export const MAX_DELIVERY_RETRY_WINDOW_MS = 24 * 60 * 60 * 1000;
13
+ /** The backoff before the second attempt. Each later backoff doubles, up to `MAX_BACKOFF_MS`. */
14
+ const BASE_BACKOFF_MS = 1000;
15
+ const MAX_BACKOFF_MS = 60 * 60 * 1000;
16
+ /** The jitter factor of a backoff is in `[JITTER_MIN, JITTER_MIN + JITTER_SPAN)`. */
17
+ const JITTER_MIN = 0.5;
18
+ const JITTER_SPAN = 0.5;
19
+ /** How long `stop` waits for deliveries in progress. */
20
+ const STOP_WAIT_MS = 10_000;
21
+ /** How long the outbox keeps `delivered` and `dismissed` entries. */
22
+ const FINISHED_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
23
+ const ENTRY_COLUMNS = `delivery_id, binding_id, chat_id, delivery_json, source_conversation_id, status, attempts,
24
+ budget_started_at, next_attempt_at, last_error, permanent, created_at, finished_at`;
25
+ /** The oldest `pending` entry of each Chat. Only it may be attempted, which keeps the order FIFO per Chat. */
26
+ const CHAT_HEADS = `SELECT ${ENTRY_COLUMNS} FROM outbox_entries AS entry WHERE status = 'pending' AND seq = (
27
+ SELECT min(seq) FROM outbox_entries WHERE status = 'pending' AND binding_id = entry.binding_id
28
+ AND chat_id = entry.chat_id)`;
29
+ const STATUSES = [
30
+ "pending",
31
+ "delivered",
32
+ "failed",
33
+ "dismissed",
34
+ ];
35
+ const toStoredEntry = (row) => ({
36
+ budgetStartedAt: integerColumn(row, "budget_started_at"),
37
+ entry: {
38
+ attempts: integerColumn(row, "attempts"),
39
+ bindingId: textColumn(row, "binding_id"),
40
+ chatId: textColumn(row, "chat_id"),
41
+ createdAt: integerColumn(row, "created_at"),
42
+ delivery: decodeDelivery(textColumn(row, "delivery_json")),
43
+ deliveryId: textColumn(row, "delivery_id"),
44
+ lastError: optionalTextColumn(row, "last_error"),
45
+ nextAttemptAt: optionalIntegerColumn(row, "next_attempt_at"),
46
+ permanent: integerColumn(row, "permanent") === 1,
47
+ sourceConversationId: optionalTextColumn(row, "source_conversation_id") ?? undefined,
48
+ status: enumColumn(row, "status", STATUSES),
49
+ },
50
+ finishedAt: optionalIntegerColumn(row, "finished_at"),
51
+ });
52
+ const previewText = (delivery) => {
53
+ if (delivery.kind === "message") {
54
+ return delivery.text;
55
+ }
56
+ return delivery.kind === "approval_requested"
57
+ ? `Approval requested: ${delivery.toolName}`
58
+ : `Approval resolved: ${delivery.decision}`;
59
+ };
60
+ const previewOf = (delivery) => previewText(delivery).slice(0, DELIVERY_PREVIEW_MAX_LENGTH);
61
+ const attemptFailureOf = (cause) => {
62
+ const deliveryError = isDeliveryError(cause) ? cause : undefined;
63
+ return {
64
+ message: errorText(cause),
65
+ permanent: deliveryError?.kind === "permanent",
66
+ retryAfterMs: deliveryError?.retryAfterMs ?? 0,
67
+ };
68
+ };
69
+ /**
70
+ * The `DeliveryOutbox` of one Agent over `agent.sqlite` (ADR 0007, ADR 0010).
71
+ *
72
+ * Deliveries run between `start` and `stop`. Before `start`, `enqueue` stores entries without an attempt. Chats
73
+ * deliver independently of each other, and one Chat delivers one entry at a time, oldest first.
74
+ *
75
+ * Backoff: the attempt `n` that fails with a retryable error waits `min(1s * 2^(n-1), 1h)`, scaled by a jitter factor
76
+ * in `[0.5, 1)`, and at least the `retryAfterMs` of the error.
77
+ */
78
+ export class SqliteDeliveryOutbox {
79
+ #options;
80
+ #timer;
81
+ #pumping;
82
+ #again = false;
83
+ #running = false;
84
+ constructor(options) {
85
+ this.#options = options;
86
+ }
87
+ enqueue = async (item) => await Promise.try(() => this.#enqueue(item));
88
+ listFailed = async () => await Promise.try(() => this.#db
89
+ .prepare(`SELECT ${ENTRY_COLUMNS} FROM outbox_entries WHERE status = 'failed' ORDER BY seq`)
90
+ .all()
91
+ .map((row) => this.#failedDelivery(toStoredEntry(row))));
92
+ retry = async (deliveryId) => await Promise.try(() => this.#retry(deliveryId));
93
+ dismiss = async (deliveryId) => await Promise.try(() => this.#dismiss(deliveryId));
94
+ /** Starts deliveries, including the entries that waited while the Agent was down. Calling it twice does nothing. */
95
+ start = async () => {
96
+ await Promise.try(() => {
97
+ if (this.#running) {
98
+ return;
99
+ }
100
+ this.#running = true;
101
+ this.#db
102
+ .prepare("DELETE FROM outbox_entries WHERE status IN ('delivered', 'dismissed') AND finished_at < ?")
103
+ .run(this.#now() - FINISHED_RETENTION_MS);
104
+ this.#kick();
105
+ });
106
+ };
107
+ /**
108
+ * Stops deliveries. Waits up to 10 seconds for attempts in progress. An attempt that ends later still records its
109
+ * result. Repeated calls do nothing.
110
+ */
111
+ stop = async () => {
112
+ this.#running = false;
113
+ clearTimeout(this.#timer);
114
+ this.#timer = undefined;
115
+ const pumping = this.#pumping;
116
+ if (pumping === undefined) {
117
+ return;
118
+ }
119
+ await Promise.race([
120
+ pumping,
121
+ sleep(STOP_WAIT_MS, undefined, { ref: false }),
122
+ ]);
123
+ };
124
+ get #db() {
125
+ return this.#options.db;
126
+ }
127
+ #now = () => this.#options.clock.now();
128
+ #enqueue = (item) => {
129
+ const deliveryId = randomUUID();
130
+ const now = this.#now();
131
+ const delivery = {
132
+ ...item.delivery,
133
+ chatId: item.chatId,
134
+ messageId: deliveryId,
135
+ };
136
+ this.#db
137
+ .prepare(`INSERT INTO outbox_entries (${ENTRY_COLUMNS}) VALUES (?, ?, ?, ?, ?, 'pending', 0, ?, ?, NULL, 0, ?, NULL)`)
138
+ .run(deliveryId, item.bindingId, item.chatId, encodeDelivery(delivery), item.sourceConversationId ?? null, now, now, now);
139
+ const stored = this.#read(deliveryId);
140
+ if (stored === undefined) {
141
+ throw new Error(`Outbox entry ${deliveryId} vanished`);
142
+ }
143
+ this.#kick();
144
+ return stored.entry;
145
+ };
146
+ #retry = (deliveryId) => {
147
+ const now = this.#now();
148
+ const { changes } = this.#db
149
+ .prepare(`UPDATE outbox_entries SET status = 'pending', attempts = 0, permanent = 0, budget_started_at = ?,
150
+ next_attempt_at = ?, finished_at = NULL WHERE delivery_id = ? AND status = 'failed'`)
151
+ .run(now, now, deliveryId);
152
+ if (Number(changes) === 0) {
153
+ return false;
154
+ }
155
+ this.#cleared(deliveryId, "retried");
156
+ this.#kick();
157
+ return true;
158
+ };
159
+ #dismiss = (deliveryId) => {
160
+ const { changes } = this.#db
161
+ .prepare(`UPDATE outbox_entries SET status = 'dismissed', next_attempt_at = NULL, finished_at = ?
162
+ WHERE delivery_id = ? AND status = 'failed'`)
163
+ .run(this.#now(), deliveryId);
164
+ if (Number(changes) === 0) {
165
+ return false;
166
+ }
167
+ this.#cleared(deliveryId, "dismissed");
168
+ return true;
169
+ };
170
+ #read = (deliveryId) => {
171
+ const row = this.#db
172
+ .prepare(`SELECT ${ENTRY_COLUMNS} FROM outbox_entries WHERE delivery_id = ?`)
173
+ .get(deliveryId);
174
+ return row === undefined ? undefined : toStoredEntry(row);
175
+ };
176
+ #failedDelivery = (stored) => {
177
+ const { entry } = stored;
178
+ return {
179
+ agent: this.#options.agentName,
180
+ attempts: entry.attempts,
181
+ bindingId: entry.bindingId,
182
+ chatId: entry.chatId,
183
+ createdAt: new Date(entry.createdAt).toISOString(),
184
+ deliveryId: entry.deliveryId,
185
+ failedAt: new Date(stored.finishedAt ?? entry.createdAt).toISOString(),
186
+ kind: entry.delivery.kind,
187
+ lastError: entry.lastError ?? "",
188
+ permanent: entry.permanent,
189
+ preview: previewOf(entry.delivery),
190
+ };
191
+ };
192
+ #cleared = (deliveryId, reason) => {
193
+ this.#options.events.emit("delivery.cleared", {
194
+ agent: this.#options.agentName,
195
+ deliveryId,
196
+ reason,
197
+ });
198
+ };
199
+ /** Starts a delivery pass, or asks the pass in progress for one more round. */
200
+ #kick = () => {
201
+ if (!this.#running) {
202
+ return;
203
+ }
204
+ if (this.#pumping !== undefined) {
205
+ this.#again = true;
206
+ return;
207
+ }
208
+ clearTimeout(this.#timer);
209
+ this.#timer = undefined;
210
+ this.#pumping = this.#pump();
211
+ };
212
+ #pump = async () => {
213
+ try {
214
+ do {
215
+ this.#again = false;
216
+ // oxlint-disable-next-line no-await-in-loop -- Each round attempts the Chat heads that the last round left due.
217
+ await this.#round();
218
+ } while (this.#again && this.#running);
219
+ }
220
+ catch (error) {
221
+ this.#options.log.error("Outbox delivery pass failed", {
222
+ error: errorText(error),
223
+ });
224
+ }
225
+ finally {
226
+ this.#pumping = undefined;
227
+ this.#rearm();
228
+ }
229
+ };
230
+ /** Attempts the due head of every Chat in parallel. A confirmed delivery asks for another round. */
231
+ #round = async () => {
232
+ const heads = this.#db
233
+ .prepare(`${CHAT_HEADS} AND next_attempt_at <= ? ORDER BY seq`)
234
+ .all(this.#now())
235
+ .map(toStoredEntry);
236
+ const results = await Promise.all(heads.map(this.#attempt));
237
+ if (results.includes("delivered")) {
238
+ this.#again = true;
239
+ }
240
+ };
241
+ #attempt = async (stored) => {
242
+ const { entry } = stored;
243
+ const attempts = entry.attempts + 1;
244
+ try {
245
+ await this.#options.deps.deliver(entry.bindingId, entry.delivery);
246
+ }
247
+ catch (error) {
248
+ return this.#recordFailure(stored, attempts, attemptFailureOf(error));
249
+ }
250
+ this.#db
251
+ .prepare(`UPDATE outbox_entries SET status = 'delivered', attempts = ?, next_attempt_at = NULL, finished_at = ?
252
+ WHERE delivery_id = ?`)
253
+ .run(attempts, this.#now(), entry.deliveryId);
254
+ if (entry.sourceConversationId !== undefined) {
255
+ await this.#copy({
256
+ ...entry,
257
+ attempts,
258
+ nextAttemptAt: null,
259
+ status: "delivered",
260
+ });
261
+ }
262
+ return "delivered";
263
+ };
264
+ #copy = async (entry) => {
265
+ try {
266
+ await this.#options.deps.onDelivered(entry);
267
+ }
268
+ catch (error) {
269
+ this.#options.log.error("Copying a delivered Trigger result into its Chat failed", { deliveryId: entry.deliveryId, error: errorText(error) });
270
+ }
271
+ };
272
+ #recordFailure = (stored, attempts, failure) => {
273
+ const now = this.#now();
274
+ const { permanent } = failure;
275
+ const nextAttemptAt = now + this.#backoff(attempts, failure);
276
+ const exhausted = attempts >= MAX_DELIVERY_ATTEMPTS ||
277
+ nextAttemptAt > stored.budgetStartedAt + MAX_DELIVERY_RETRY_WINDOW_MS;
278
+ const failed = permanent || exhausted;
279
+ this.#db
280
+ .prepare(`UPDATE outbox_entries SET status = ?, attempts = ?, next_attempt_at = ?, last_error = ?, permanent = ?,
281
+ finished_at = ? WHERE delivery_id = ?`)
282
+ .run(failed ? "failed" : "pending", attempts, failed ? null : nextAttemptAt, failure.message, permanent ? 1 : 0, failed ? now : null, stored.entry.deliveryId);
283
+ if (failed) {
284
+ const updated = this.#read(stored.entry.deliveryId);
285
+ if (updated !== undefined) {
286
+ this.#options.events.emit("delivery.failed", {
287
+ agent: this.#options.agentName,
288
+ delivery: this.#failedDelivery(updated),
289
+ });
290
+ }
291
+ }
292
+ return failed ? "failed" : "pending";
293
+ };
294
+ #backoff = (attempts, failure) => {
295
+ const exponential = Math.min(BASE_BACKOFF_MS * 2 ** (attempts - 1), MAX_BACKOFF_MS);
296
+ const jitter = JITTER_MIN + this.#options.random() * JITTER_SPAN;
297
+ return Math.max(Math.round(exponential * jitter), failure.retryAfterMs);
298
+ };
299
+ /** Arms the timer for the earliest Chat head that waits for a backoff. */
300
+ #rearm = () => {
301
+ if (!this.#running || this.#pumping !== undefined) {
302
+ return;
303
+ }
304
+ clearTimeout(this.#timer);
305
+ const row = this.#db
306
+ .prepare(`SELECT min(next_attempt_at) AS due FROM (${CHAT_HEADS})`)
307
+ .get();
308
+ this.#timer = armDueTimer(row === undefined ? null : optionalIntegerColumn(row, "due"), this.#now(), () => {
309
+ this.#timer = undefined;
310
+ this.#kick();
311
+ });
312
+ };
313
+ }