@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,61 @@
1
+ import { DeliveryError, isDeliveryError } from "@wheatley-ai/sdk";
2
+ /**
3
+ * Discord JSON error codes that no retry can fix: Unknown Channel, Unknown Message, Unknown User, Missing Access,
4
+ * Cannot send messages to this user, and Missing Permissions.
5
+ */
6
+ const PERMANENT_CODES = new Set([
7
+ 10_003, 10_008, 10_013, 50_001, 50_007, 50_013,
8
+ ]);
9
+ const HTTP_CLIENT_ERROR_MIN = 400;
10
+ const HTTP_SERVER_ERROR_MIN = 500;
11
+ const HTTP_REQUEST_TIMEOUT = 408;
12
+ const HTTP_TOO_MANY_REQUESTS = 429;
13
+ /** The Discord JSON error code for Unknown Message. */
14
+ export const UNKNOWN_MESSAGE_CODE = 10_008;
15
+ /** A `DiscordAPIError` from `@discordjs/rest`, which carries the Discord JSON error code. */
16
+ const hasDiscordCode = (cause) => cause instanceof Error && "code" in cause && typeof cause.code === "number";
17
+ /** A `DiscordAPIError` or `HTTPError` from `@discordjs/rest`, which carries the HTTP status. */
18
+ const hasHttpStatus = (cause) => cause instanceof Error &&
19
+ "status" in cause &&
20
+ typeof cause.status === "number";
21
+ /** A `RateLimitError` from `@discordjs/rest`, which carries the wait in milliseconds. */
22
+ const hasRetryAfter = (cause) => cause instanceof Error &&
23
+ "retryAfter" in cause &&
24
+ typeof cause.retryAfter === "number";
25
+ /** Returns the message of an `Error`, or the string form of any other thrown value, for log fields and notes. */
26
+ export const errorText = (cause) => cause instanceof Error ? cause.message : String(cause);
27
+ /** Returns the Discord JSON error code of a `DiscordAPIError`, or `undefined` for other errors. */
28
+ export const discordErrorCode = (cause) => hasDiscordCode(cause) ? cause.code : undefined;
29
+ const isPermanentStatus = (status) => status >= HTTP_CLIENT_ERROR_MIN &&
30
+ status < HTTP_SERVER_ERROR_MIN &&
31
+ status !== HTTP_REQUEST_TIMEOUT &&
32
+ status !== HTTP_TOO_MANY_REQUESTS;
33
+ const isPermanent = (cause) => {
34
+ const code = discordErrorCode(cause);
35
+ if (code !== undefined && PERMANENT_CODES.has(code)) {
36
+ return true;
37
+ }
38
+ return hasHttpStatus(cause) && isPermanentStatus(cause.status);
39
+ };
40
+ /**
41
+ * Classifies a failure of a Discord API call for the outbox.
42
+ *
43
+ * `DiscordAPIError` codes for a deleted Chat, a removed bot, or missing permissions and other HTTP 4xx answers are
44
+ * `permanent`. HTTP 429 (with `retryAfter` from a `RateLimitError`), HTTP 5xx, and network errors are `retryable`. A
45
+ * `DeliveryError` passes through unchanged.
46
+ */
47
+ export const toDeliveryError = (cause, action) => {
48
+ if (isDeliveryError(cause)) {
49
+ return cause;
50
+ }
51
+ const detail = cause instanceof Error ? `: ${cause.message}` : "";
52
+ const message = `Discord could not ${action}${detail}`;
53
+ if (isPermanent(cause)) {
54
+ return new DeliveryError(message, { cause, kind: "permanent" });
55
+ }
56
+ return new DeliveryError(message, {
57
+ cause,
58
+ kind: "retryable",
59
+ retryAfterMs: hasRetryAfter(cause) ? cause.retryAfter : undefined,
60
+ });
61
+ };
@@ -0,0 +1,189 @@
1
+ import { NO_MENTIONS } from "./discord-runtime.js";
2
+ import { errorText } from "./errors.js";
3
+ import { RecentIds } from "./recent-ids.js";
4
+ /** Discord limits message content to this many characters. */
5
+ export const DISCORD_MESSAGE_MAX_LENGTH = 2000;
6
+ /** Discord shows a typing indicator for 10 seconds, so the binding renews it before that. */
7
+ const TYPING_RENEW_MS = 8000;
8
+ /** Stops typing and forgets a draft if no `run_finished` event or final delivery arrives in this time. */
9
+ const ABANDONED_RUN_MS = 10 * 60_000;
10
+ const ELLIPSIS = "…";
11
+ /** How many finalized Runs the binding remembers, so that a late event cannot start a second draft. */
12
+ const FINALIZED_RUN_LIMIT = 1000;
13
+ const draftText = (text) => text.length > DISCORD_MESSAGE_MAX_LENGTH
14
+ ? `${text.slice(0, DISCORD_MESSAGE_MAX_LENGTH - 1)}${ELLIPSIS}`
15
+ : text;
16
+ const stopTyping = (state) => {
17
+ clearInterval(state.typingTimer);
18
+ state.typingTimer = undefined;
19
+ };
20
+ /**
21
+ * Shows live Run progress in Discord: a typing indicator from `run_started` to `run_finished`, and in `edit` mode a
22
+ * draft message that shows the `text_delta` text so far, edited at most once per `editIntervalMs`.
23
+ *
24
+ * Every Discord call of one Run runs in order on one promise chain, so an edit can never overwrite the final text
25
+ * that `finalize` hands to the delivery.
26
+ */
27
+ export class LiveRuns {
28
+ #options;
29
+ #runs = new Map();
30
+ #finalized = new RecentIds(FINALIZED_RUN_LIMIT);
31
+ constructor(options) {
32
+ this.#options = options;
33
+ }
34
+ /**
35
+ * Handles one Run event. Never throws: it logs failed Discord calls at `warn` level. Ignores events of a Run that
36
+ * `finalize` ended.
37
+ */
38
+ onEvent = (event) => {
39
+ if (this.#finalized.has(event.runId)) {
40
+ return;
41
+ }
42
+ // The live view shows no tool progress, so it ignores `tool_started` and `tool_finished`.
43
+ if (event.kind === "run_started") {
44
+ this.#startTyping(this.#state(event.runId, event.chatId));
45
+ }
46
+ else if (event.kind === "text_delta") {
47
+ this.#append(this.#state(event.runId, event.chatId), event.delta);
48
+ }
49
+ else if (event.kind === "run_finished") {
50
+ this.#finish(event.runId);
51
+ }
52
+ };
53
+ /**
54
+ * Ends the live view of `runId` and returns its draft message, if the binding sent one, after every pending Discord
55
+ * call of the Run settles. The binding ignores later events of the Run. Never rejects.
56
+ */
57
+ finalize = async (runId) => {
58
+ this.#finalized.add(runId);
59
+ const state = this.#runs.get(runId);
60
+ if (state === undefined) {
61
+ return undefined;
62
+ }
63
+ this.#close(state);
64
+ await state.chain;
65
+ return state.draft;
66
+ };
67
+ /** Stops every timer. The binding calls it when it stops. */
68
+ dispose = () => {
69
+ for (const state of this.#runs.values()) {
70
+ this.#close(state);
71
+ }
72
+ };
73
+ #state(runId, chatId) {
74
+ const existing = this.#runs.get(runId);
75
+ if (existing !== undefined) {
76
+ return existing;
77
+ }
78
+ const state = {
79
+ chain: Promise.resolve(),
80
+ channel: undefined,
81
+ chatId,
82
+ closed: false,
83
+ draft: undefined,
84
+ editTimer: undefined,
85
+ expiryTimer: undefined,
86
+ lastEditAt: 0,
87
+ runId,
88
+ shownText: "",
89
+ text: "",
90
+ typingTimer: undefined,
91
+ };
92
+ state.expiryTimer = setTimeout(() => {
93
+ this.#close(state);
94
+ }, ABANDONED_RUN_MS);
95
+ state.expiryTimer.unref();
96
+ this.#runs.set(runId, state);
97
+ return state;
98
+ }
99
+ #enqueue(state, action, step) {
100
+ const run = async () => {
101
+ if (state.closed) {
102
+ return;
103
+ }
104
+ try {
105
+ await step();
106
+ }
107
+ catch (error) {
108
+ this.#options.log.warn(`Discord could not ${action}`, {
109
+ chatId: state.chatId,
110
+ error: errorText(error),
111
+ runId: state.runId,
112
+ });
113
+ }
114
+ };
115
+ state.chain = state.chain.then(run);
116
+ }
117
+ async #channel(state) {
118
+ state.channel ??= await this.#options.resolveChannel(state.chatId);
119
+ return state.channel;
120
+ }
121
+ #startTyping(state) {
122
+ if (state.typingTimer !== undefined || state.closed) {
123
+ return;
124
+ }
125
+ const sendTyping = () => {
126
+ this.#enqueue(state, "show the typing indicator", async () => {
127
+ const channel = await this.#channel(state);
128
+ await channel.sendTyping();
129
+ });
130
+ };
131
+ sendTyping();
132
+ state.typingTimer = setInterval(sendTyping, TYPING_RENEW_MS);
133
+ state.typingTimer.unref();
134
+ }
135
+ #append(state, delta) {
136
+ if (state.closed) {
137
+ return;
138
+ }
139
+ this.#startTyping(state);
140
+ if (this.#options.mode === "typing") {
141
+ return;
142
+ }
143
+ state.text += delta;
144
+ if (state.editTimer !== undefined) {
145
+ return;
146
+ }
147
+ const wait = Math.max(0, state.lastEditAt + this.#options.editIntervalMs - Date.now());
148
+ state.editTimer = setTimeout(() => {
149
+ state.editTimer = undefined;
150
+ this.#enqueue(state, "update the draft message", async () => {
151
+ await this.#flush(state);
152
+ });
153
+ }, wait);
154
+ }
155
+ async #flush(state) {
156
+ const content = draftText(state.text);
157
+ if (content.trim() === "" || content === state.shownText) {
158
+ return;
159
+ }
160
+ if (state.draft === undefined) {
161
+ const channel = await this.#channel(state);
162
+ state.draft = await channel.send({
163
+ allowedMentions: NO_MENTIONS,
164
+ content,
165
+ });
166
+ }
167
+ else {
168
+ await state.draft.edit({ allowedMentions: NO_MENTIONS, content });
169
+ }
170
+ state.shownText = content;
171
+ state.lastEditAt = Date.now();
172
+ }
173
+ #finish(runId) {
174
+ const state = this.#runs.get(runId);
175
+ if (state !== undefined) {
176
+ stopTyping(state);
177
+ }
178
+ }
179
+ #close(state) {
180
+ state.closed = true;
181
+ stopTyping(state);
182
+ clearTimeout(state.editTimer);
183
+ clearTimeout(state.expiryTimer);
184
+ state.editTimer = undefined;
185
+ if (this.#runs.get(state.runId) === state) {
186
+ this.#runs.delete(state.runId);
187
+ }
188
+ }
189
+ }
@@ -0,0 +1,39 @@
1
+ import { DiscordBinding } from "./binding.js";
2
+ import { discordConfigSchema, parseDiscordConfig } from "./config.js";
3
+ /** The `type` of a Discord Frontend Binding in `config.yaml`. */
4
+ const DISCORD_FRONTEND_TYPE = "discord";
5
+ /** The Discord Frontend keeps no tables in `agent.sqlite`. It stores Approval prompts in the binding's `dataDir`. */
6
+ export const discordMigrations = [];
7
+ /** The Discord Frontend handles no JSON-RPC methods. Binding status comes from the Agent. */
8
+ export const discordRpcHandlers = {};
9
+ /**
10
+ * Creates the built-in Discord Frontend (ADR 0012). `discord.js` loads only when a binding starts.
11
+ *
12
+ * `createBinding` throws if the config is invalid, for example with an empty `allowedChatIds` list, or if the secret
13
+ * that `tokenSecret` names is not set.
14
+ */
15
+ export const createDiscordFrontend = (options = {}) => ({
16
+ configSchema: discordConfigSchema,
17
+ createBinding: (config, ctx) => {
18
+ const parsed = parseDiscordConfig(config);
19
+ const token = ctx.secrets.get(parsed.tokenSecret);
20
+ if (token === undefined || token === "") {
21
+ throw new Error(`Discord Frontend Binding ${ctx.bindingId} needs the secret ${parsed.tokenSecret}, which is not set`);
22
+ }
23
+ return new DiscordBinding(parsed, ctx, token, options);
24
+ },
25
+ type: DISCORD_FRONTEND_TYPE,
26
+ });
27
+ /**
28
+ * The Agent module of the Discord Frontend. Its `api` is the `Frontend` that the Agent adds to the built-in Frontends
29
+ * of its extensions. `deps` are the third-party seams; production wiring passes `{}`.
30
+ */
31
+ export const discordFrontendModule = {
32
+ create: (_ctx, deps) => ({
33
+ api: createDiscordFrontend(deps),
34
+ rpc: discordRpcHandlers,
35
+ }),
36
+ migrations: discordMigrations,
37
+ name: "frontend_discord",
38
+ scope: "agent",
39
+ };
@@ -0,0 +1,20 @@
1
+ /** Remembers the most recent IDs, oldest out first. */
2
+ export class RecentIds {
3
+ #ids = new Set();
4
+ #limit;
5
+ constructor(limit) {
6
+ this.#limit = limit;
7
+ }
8
+ has(id) {
9
+ return this.#ids.has(id);
10
+ }
11
+ add(id) {
12
+ this.#ids.add(id);
13
+ for (const oldest of this.#ids) {
14
+ if (this.#ids.size <= this.#limit) {
15
+ break;
16
+ }
17
+ this.#ids.delete(oldest);
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,98 @@
1
+ /** The `action_id` prefix of the Approval buttons. The decision follows the prefix. */
2
+ export const APPROVAL_ACTION_PREFIX = "wheatley_approval:";
3
+ const BUTTONS = [
4
+ { decision: "allow_once", label: "Allow once", style: "primary" },
5
+ { decision: "allow_conversation", label: "Allow for Conversation" },
6
+ { decision: "allow_always", label: "Always allow" },
7
+ { decision: "deny", label: "Deny", style: "danger" },
8
+ ];
9
+ const OUTCOME_LABELS = {
10
+ allow_always: "Always allowed",
11
+ allow_conversation: "Allowed for this Conversation",
12
+ allow_once: "Allowed once",
13
+ cancelled: "Cancelled",
14
+ deny: "Denied",
15
+ timeout: "Timed out",
16
+ };
17
+ const OUTCOME_ICONS = {
18
+ allow_always: ":white_check_mark:",
19
+ allow_conversation: ":white_check_mark:",
20
+ allow_once: ":white_check_mark:",
21
+ cancelled: ":no_entry_sign:",
22
+ deny: ":x:",
23
+ timeout: ":hourglass:",
24
+ };
25
+ /** Escapes the three characters that Slack `mrkdwn` reserves. */
26
+ export const escapeMrkdwn = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
27
+ /** Slack shows a code block with three backticks. A preview that contains them must not end the block early. */
28
+ const codeBlock = (text) => `\`\`\`${escapeMrkdwn(text).replaceAll("```", "`​``")}\`\`\``;
29
+ const describeTool = (prompt) => `*Tool:* \`${escapeMrkdwn(prompt.toolName)}\`\n${codeBlock(prompt.inputPreview === "" ? " " : prompt.inputPreview)}`;
30
+ /** The fallback text of an Approval prompt, for notifications and clients without Block Kit. */
31
+ export const approvalRequestText = (prompt) => `Approval needed for ${prompt.toolName}`;
32
+ /** Builds the Block Kit prompt with the four decision buttons for an `approval_requested` delivery. */
33
+ export const approvalRequestBlocks = (delivery) => {
34
+ const expiry = delivery.expiresAt === null
35
+ ? "This request does not time out."
36
+ : `This request times out at ${escapeMrkdwn(delivery.expiresAt)}.`;
37
+ return [
38
+ {
39
+ text: {
40
+ text: `:lock: *Approval needed*\n${describeTool(delivery)}`,
41
+ type: "mrkdwn",
42
+ },
43
+ type: "section",
44
+ },
45
+ {
46
+ block_id: `approval:${delivery.approvalId}`,
47
+ elements: BUTTONS.map((button) => ({
48
+ action_id: `${APPROVAL_ACTION_PREFIX}${button.decision}`,
49
+ // JSON serialization drops an undefined style, which gives the default button style.
50
+ style: button.style,
51
+ text: { text: button.label, type: "plain_text" },
52
+ type: "button",
53
+ value: delivery.approvalId,
54
+ })),
55
+ type: "actions",
56
+ },
57
+ { elements: [{ text: expiry, type: "mrkdwn" }], type: "context" },
58
+ ];
59
+ };
60
+ /** The ` by <Sender>` part of an Approval outcome, escaped for `mrkdwn`. Empty if the outcome names nobody. */
61
+ const resolvedBySuffix = (delivery) => delivery.resolvedBy === undefined
62
+ ? ""
63
+ : ` by ${escapeMrkdwn(delivery.resolvedBy)}`;
64
+ /** The reason of an Approval outcome, escaped for `mrkdwn`. */
65
+ const escapedReason = (delivery) => delivery.reason === undefined ? undefined : escapeMrkdwn(delivery.reason);
66
+ /** The fallback text of a resolved Approval prompt. */
67
+ export const approvalResolvedText = (prompt, delivery) => `${OUTCOME_LABELS[delivery.decision]}: ${prompt.toolName}`;
68
+ /** Builds the Block Kit message that replaces the prompt when the Approval ends. It has no buttons. */
69
+ export const approvalResolvedBlocks = (prompt, delivery) => {
70
+ const reason = escapedReason(delivery);
71
+ const reasonLine = reason === undefined ? "" : `\n*Reason:* ${reason}`;
72
+ return [
73
+ {
74
+ text: {
75
+ text: `${OUTCOME_ICONS[delivery.decision]} *${OUTCOME_LABELS[delivery.decision]}*${resolvedBySuffix(delivery)}\n${describeTool(prompt)}${reasonLine}`,
76
+ type: "mrkdwn",
77
+ },
78
+ type: "section",
79
+ },
80
+ ];
81
+ };
82
+ /**
83
+ * The text of an Approval outcome when the binding has no record of the prompt. Slack shows `text` as `mrkdwn`, so the
84
+ * Sender name and the reason are escaped.
85
+ */
86
+ export const approvalOutcomeText = (delivery) => {
87
+ const reason = escapedReason(delivery);
88
+ const reasonSentence = reason === undefined ? "" : ` Reason: ${reason}`;
89
+ return `${OUTCOME_ICONS[delivery.decision]} Approval ${escapeMrkdwn(delivery.approvalId)}: ${OUTCOME_LABELS[delivery.decision]}${resolvedBySuffix(delivery)}.${reasonSentence}`;
90
+ };
91
+ /** Returns the decision of an Approval button `action_id`, or `undefined` for another action. */
92
+ export const decisionOfAction = (actionId) => {
93
+ if (!actionId.startsWith(APPROVAL_ACTION_PREFIX)) {
94
+ return undefined;
95
+ }
96
+ const name = actionId.slice(APPROVAL_ACTION_PREFIX.length);
97
+ return BUTTONS.find((button) => button.decision === name)?.decision;
98
+ };
@@ -0,0 +1,102 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { DeliveryError } from "@wheatley-ai/sdk";
5
+ const UNSAFE_FILENAME_CHARACTERS = /[^A-Za-z0-9._-]+/gu;
6
+ const MAX_STAGED_NAME_LENGTH = 100;
7
+ const stagedName = (name) => `${randomUUID()}-${name.replaceAll(UNSAFE_FILENAME_CHARACTERS, "_").slice(-MAX_STAGED_NAME_LENGTH)}`;
8
+ class FileTooLargeError extends Error {
9
+ name = "FileTooLargeError";
10
+ }
11
+ const readLimited = async (response, maxBytes) => {
12
+ const declared = Number(response.headers.get("content-length") ?? Number.NaN);
13
+ if (declared > maxBytes) {
14
+ throw new FileTooLargeError(`Content-Length ${declared} exceeds the limit`);
15
+ }
16
+ const chunks = [];
17
+ let total = 0;
18
+ if (response.body === null) {
19
+ return new Uint8Array();
20
+ }
21
+ for await (const chunk of response.body) {
22
+ total += chunk.byteLength;
23
+ if (total > maxBytes) {
24
+ throw new FileTooLargeError(`The download exceeds ${maxBytes} bytes`);
25
+ }
26
+ chunks.push(chunk);
27
+ }
28
+ return Buffer.concat(chunks);
29
+ };
30
+ /**
31
+ * Downloads one file of an inbound Slack message into `stagingDir`.
32
+ *
33
+ * Skips a file that Slack reports as larger than `maxBytes`, and stops a download that grows past `maxBytes`.
34
+ * Never rejects.
35
+ */
36
+ export const stageInboundFile = async (file, options) => {
37
+ if (file.sizeBytes !== undefined && file.sizeBytes > options.maxBytes) {
38
+ return { ok: false, reason: "too_large" };
39
+ }
40
+ if (file.url === undefined) {
41
+ return { ok: false, reason: "no_url" };
42
+ }
43
+ try {
44
+ const response = await options.fetch(file.url, {
45
+ headers: { authorization: `Bearer ${options.botToken}` },
46
+ });
47
+ if (!response.ok) {
48
+ return { ok: false, reason: "download_failed" };
49
+ }
50
+ const data = await readLimited(response, options.maxBytes);
51
+ const stagedPath = path.join(options.stagingDir, stagedName(file.name));
52
+ await mkdir(options.stagingDir, { recursive: true });
53
+ await writeFile(stagedPath, data);
54
+ return {
55
+ attachment: {
56
+ filename: file.name,
57
+ kind: "file",
58
+ mimeType: file.mimeType,
59
+ path: stagedPath,
60
+ sizeBytes: data.byteLength,
61
+ },
62
+ ok: true,
63
+ };
64
+ }
65
+ catch (error) {
66
+ return {
67
+ ok: false,
68
+ reason: error instanceof FileTooLargeError ? "too_large" : "download_failed",
69
+ };
70
+ }
71
+ };
72
+ const attachmentSize = (attachment) => attachment.kind === "bytes"
73
+ ? attachment.data.byteLength
74
+ : attachment.sizeBytes;
75
+ /**
76
+ * Throws a permanent `DeliveryError` if any attachment is larger than `maxBytes`. The binding checks every attachment
77
+ * before it posts any part of a message, so a rejected delivery leaves nothing in the Chat.
78
+ */
79
+ export const assertAttachmentSizes = (attachments, maxBytes) => {
80
+ const oversized = attachments.find((attachment) => attachmentSize(attachment) > maxBytes);
81
+ if (oversized !== undefined) {
82
+ throw new DeliveryError(`Attachment ${oversized.filename} exceeds ${maxBytes} bytes`, { kind: "permanent" });
83
+ }
84
+ };
85
+ /** Uploads one outbound attachment into a Chat with `files.uploadV2`. */
86
+ export const uploadAttachment = async (client, target, attachment) => {
87
+ const file = attachment.kind === "bytes"
88
+ ? Buffer.from(attachment.data)
89
+ : attachment.path;
90
+ const common = {
91
+ file,
92
+ filename: attachment.filename,
93
+ title: attachment.filename,
94
+ };
95
+ await (target.threadTs === undefined
96
+ ? client.filesUploadV2({ ...common, channel_id: target.channel })
97
+ : client.filesUploadV2({
98
+ ...common,
99
+ channel_id: target.channel,
100
+ thread_ts: target.threadTs,
101
+ }));
102
+ };
@@ -0,0 +1,20 @@
1
+ /** Promises that run in the background, so that a stop can wait for them. */
2
+ export class BackgroundTasks {
3
+ #pending = new Set();
4
+ /**
5
+ * Adds a task. The task must never reject: a rejection becomes an unhandled rejection. The task leaves the set
6
+ * when it settles.
7
+ */
8
+ add = (task) => {
9
+ this.#pending.add(task);
10
+ void this.#removeWhenDone(task);
11
+ };
12
+ /** Resolves after every task that was added before the call settles. */
13
+ settled = async () => {
14
+ await Promise.all(this.#pending);
15
+ };
16
+ #removeWhenDone = async (task) => {
17
+ await task;
18
+ this.#pending.delete(task);
19
+ };
20
+ }