@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.
- package/LICENSE +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +178 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +206 -0
- package/dist/cli/session.js +86 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1033 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +72 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon-socket.js +96 -0
- package/dist/core/daemon.js +97 -0
- package/dist/core/deployment.js +379 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +96 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +215 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-C9Rul5vE.css +2 -0
- package/dist/dashboard/assets/index-DXzGGAxQ.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-DMljN0LW.js +1 -0
- package/dist/dashboard/index.html +18 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +262 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +120 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +194 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +106 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +210 -0
- package/dist/triggers/webhook-ingress.js +212 -0
- package/dist/wiring/agent-services.js +151 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import { DISPLAY_NAME_MAX_LENGTH, isJsonValue } from "@wheatley-ai/protocol";
|
|
2
|
+
import { DeliveryError, parseCommandText } from "@wheatley-ai/sdk";
|
|
3
|
+
import { stageInboundFile } from "./attachments.js";
|
|
4
|
+
import { BackgroundTasks } from "./background-tasks.js";
|
|
5
|
+
import { dropOldest } from "./bounded.js";
|
|
6
|
+
import { isChatAllowed, toChatId } from "./chat-id.js";
|
|
7
|
+
import { toDeliveryError } from "./delivery-errors.js";
|
|
8
|
+
import { parseEventCallback, parseInteraction, parseSlashCommand, } from "./inbound.js";
|
|
9
|
+
import { LiveProgress } from "./live-progress.js";
|
|
10
|
+
import { WEBHOOK_PATH_SUFFIX } from "./manifest.js";
|
|
11
|
+
import { SlackOutbound } from "./outbound.js";
|
|
12
|
+
import { decodeOptional, parseJsonText, UrlVerificationSchema, } from "./schemas.js";
|
|
13
|
+
import { verifySlackSignature } from "./signature.js";
|
|
14
|
+
import { SlackStateStore } from "./state-store.js";
|
|
15
|
+
/** The number of Events API event IDs that the binding remembers to drop retried events. */
|
|
16
|
+
const MAX_SEEN_EVENTS = 1000;
|
|
17
|
+
/** The number of Chats whose latest Sender message the binding remembers for the typing reaction. */
|
|
18
|
+
const MAX_TRACKED_CHATS = 1000;
|
|
19
|
+
/** The number of Slack user display names that the binding caches. */
|
|
20
|
+
const MAX_CACHED_NAMES = 1000;
|
|
21
|
+
const HTTP_OK = 200;
|
|
22
|
+
const HTTP_BAD_REQUEST = 400;
|
|
23
|
+
const HTTP_UNAUTHORIZED = 401;
|
|
24
|
+
/** Adds `key` as the newest entry and drops the oldest entries above `max`. */
|
|
25
|
+
const remember = (map, key, value, max) => {
|
|
26
|
+
map.delete(key);
|
|
27
|
+
map.set(key, value);
|
|
28
|
+
dropOldest(map, max);
|
|
29
|
+
};
|
|
30
|
+
const plainResponse = (status, body) => body === undefined
|
|
31
|
+
? { status }
|
|
32
|
+
: { body, headers: { "content-type": "text/plain" }, status };
|
|
33
|
+
/** Removes the bot mention and decodes the three HTML entities that Slack uses in message text. */
|
|
34
|
+
const cleanText = (text, mention) => text
|
|
35
|
+
.replaceAll(mention, "")
|
|
36
|
+
.replaceAll("<", "<")
|
|
37
|
+
.replaceAll(">", ">")
|
|
38
|
+
.replaceAll("&", "&")
|
|
39
|
+
.trim();
|
|
40
|
+
/** Reads the display name from a `users.info` response: the profile display name first, the user name last. */
|
|
41
|
+
const nameOf = async (web, user) => {
|
|
42
|
+
const info = await web.users.info({ user });
|
|
43
|
+
return [
|
|
44
|
+
info.user?.profile?.display_name,
|
|
45
|
+
info.user?.profile?.real_name,
|
|
46
|
+
info.user?.real_name,
|
|
47
|
+
info.user?.name,
|
|
48
|
+
].find((candidate) => candidate !== undefined && candidate !== "");
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* One running Slack Frontend Binding (ADR 0007, ADR 0012).
|
|
52
|
+
*
|
|
53
|
+
* Inbound: Socket Mode envelopes or signed Events API requests become `sink.send`, `sink.command`, and `sink.decide`
|
|
54
|
+
* calls for allowed Chats. The binding acknowledges each envelope or request before it processes it, so Slack does not
|
|
55
|
+
* retry while attachments download. `stop` waits for inbound work in progress.
|
|
56
|
+
*
|
|
57
|
+
* Outbound: `deliver` posts Markdown chunks, uploads attachments, and posts and updates Block Kit Approval prompts.
|
|
58
|
+
*/
|
|
59
|
+
export class SlackBinding {
|
|
60
|
+
#config;
|
|
61
|
+
#ctx;
|
|
62
|
+
#deps;
|
|
63
|
+
#seenEvents = new Map();
|
|
64
|
+
#lastInbound = new Map();
|
|
65
|
+
#displayNames = new Map();
|
|
66
|
+
#inboundTasks = new BackgroundTasks();
|
|
67
|
+
#connection;
|
|
68
|
+
#socket;
|
|
69
|
+
#route;
|
|
70
|
+
#stopped = false;
|
|
71
|
+
/** Throws if the config uses `webhook` transport while the Webhook Ingress is disabled. */
|
|
72
|
+
constructor(config, ctx, deps) {
|
|
73
|
+
if (config.transport === "webhook" &&
|
|
74
|
+
ctx.registerWebhookRoute === undefined) {
|
|
75
|
+
throw new Error("Slack webhook transport needs the Webhook Ingress: set webhooks.enabled to true in config.yaml");
|
|
76
|
+
}
|
|
77
|
+
this.#config = config;
|
|
78
|
+
this.#ctx = ctx;
|
|
79
|
+
this.#deps = deps;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Loads the Slack packages, checks the bot token with `auth.test`, then opens the Socket Mode connection or mounts
|
|
83
|
+
* the webhook route. Rejects if the token is invalid or Socket Mode cannot connect.
|
|
84
|
+
*/
|
|
85
|
+
start = async (sink) => {
|
|
86
|
+
const sdk = await this.#deps.loadSdk();
|
|
87
|
+
const web = sdk.createWebClient(this.#config.botToken, this.#ctx.log);
|
|
88
|
+
const { user_id: botUserId } = await web.auth.test();
|
|
89
|
+
if (botUserId === undefined) {
|
|
90
|
+
throw new Error("Slack auth.test returned no bot user ID");
|
|
91
|
+
}
|
|
92
|
+
const store = await SlackStateStore.load(this.#ctx.dataDir, this.#ctx.log);
|
|
93
|
+
const live = new LiveProgress({
|
|
94
|
+
client: web,
|
|
95
|
+
editIntervalMs: this.#config.editIntervalMs,
|
|
96
|
+
lastInbound: (chatId) => this.#lastInbound.get(chatId),
|
|
97
|
+
log: this.#ctx.log,
|
|
98
|
+
streaming: this.#config.streaming,
|
|
99
|
+
typingReaction: this.#config.typingReaction,
|
|
100
|
+
});
|
|
101
|
+
const outbound = new SlackOutbound({
|
|
102
|
+
live,
|
|
103
|
+
maxAttachmentBytes: this.#ctx.maxAttachmentBytes,
|
|
104
|
+
store,
|
|
105
|
+
web,
|
|
106
|
+
});
|
|
107
|
+
this.#connection = { botUserId, live, outbound, sink, store, web };
|
|
108
|
+
if (this.#config.transport === "socket") {
|
|
109
|
+
await this.#startSocket(sdk);
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
this.#route = this.#ctx.registerWebhookRoute?.(WEBHOOK_PATH_SUFFIX, this.#handleWebhook);
|
|
113
|
+
}
|
|
114
|
+
this.#ctx.log.info("Slack binding started", {
|
|
115
|
+
botUserId,
|
|
116
|
+
transport: this.#config.transport,
|
|
117
|
+
});
|
|
118
|
+
};
|
|
119
|
+
deliver = async (delivery) => {
|
|
120
|
+
const connection = this.#connection;
|
|
121
|
+
if (connection === undefined || this.#stopped) {
|
|
122
|
+
throw new DeliveryError("The Slack binding is not running", {
|
|
123
|
+
kind: "retryable",
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
await connection.outbound.deliver(delivery);
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
throw toDeliveryError(error);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
onEvent = (event) => {
|
|
134
|
+
if (!this.#stopped) {
|
|
135
|
+
this.#connection?.live.onEvent(event);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
stop = async () => {
|
|
139
|
+
this.#stopped = true;
|
|
140
|
+
this.#route?.unregister();
|
|
141
|
+
try {
|
|
142
|
+
await this.#socket?.disconnect();
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
this.#ctx.log.warn("Slack Socket Mode disconnect failed", {
|
|
146
|
+
error: String(error),
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
await this.#inboundTasks.settled();
|
|
150
|
+
await this.#connection?.live.stop();
|
|
151
|
+
await this.#connection?.store.flush();
|
|
152
|
+
};
|
|
153
|
+
#startSocket = async (sdk) => {
|
|
154
|
+
const { appToken } = this.#config;
|
|
155
|
+
if (appToken === undefined) {
|
|
156
|
+
throw new Error("Slack socket transport needs appToken");
|
|
157
|
+
}
|
|
158
|
+
const socket = sdk.createSocketClient(appToken, this.#ctx.log);
|
|
159
|
+
this.#socket = socket;
|
|
160
|
+
socket.on("slack_event", (envelope) => {
|
|
161
|
+
this.#runInBackground(this.#handleEnvelope(envelope));
|
|
162
|
+
});
|
|
163
|
+
await socket.start();
|
|
164
|
+
};
|
|
165
|
+
/** Runs inbound work in the background and logs its failure. `stop` waits for it. */
|
|
166
|
+
#runInBackground = (task) => {
|
|
167
|
+
this.#inboundTasks.add(this.#logInboundFailure(task));
|
|
168
|
+
};
|
|
169
|
+
#logInboundFailure = async (task) => {
|
|
170
|
+
try {
|
|
171
|
+
await task;
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
this.#ctx.log.error("Slack inbound handling failed", {
|
|
175
|
+
error: String(error),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
#handleEnvelope = async (envelope) => {
|
|
180
|
+
await envelope.ack();
|
|
181
|
+
const body = isJsonValue(envelope.body) ? envelope.body : undefined;
|
|
182
|
+
switch (envelope.type) {
|
|
183
|
+
case "events_api": {
|
|
184
|
+
await this.#handleMessage(parseEventCallback(body));
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
case "slash_commands": {
|
|
188
|
+
await this.#handleCommand(parseSlashCommand(body));
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
case "interactive": {
|
|
192
|
+
await this.#handleAction(parseInteraction(body));
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
default: {
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
/** Verifies and acknowledges one Events API, Slash Command, or interactivity request (ADR 0012). */
|
|
201
|
+
#handleWebhook = async (request) => await Promise.resolve(this.#routeWebhook(request));
|
|
202
|
+
#routeWebhook = (request) => {
|
|
203
|
+
const secret = this.#config.signingSecret ?? "";
|
|
204
|
+
if (!verifySlackSignature(request, secret, this.#deps.now())) {
|
|
205
|
+
this.#ctx.log.warn("Rejected a Slack webhook request with a bad signature");
|
|
206
|
+
return plainResponse(HTTP_UNAUTHORIZED);
|
|
207
|
+
}
|
|
208
|
+
const text = Buffer.from(request.body).toString("utf-8");
|
|
209
|
+
const contentType = request.headers["content-type"] ?? "";
|
|
210
|
+
if (contentType.includes("application/json")) {
|
|
211
|
+
return this.#routeJson(parseJsonText(text));
|
|
212
|
+
}
|
|
213
|
+
const form = new URLSearchParams(text);
|
|
214
|
+
const interaction = form.get("payload");
|
|
215
|
+
if (interaction === null) {
|
|
216
|
+
this.#runInBackground(this.#handleCommand(parseSlashCommand(Object.fromEntries(form))));
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
this.#runInBackground(this.#handleAction(parseInteraction(parseJsonText(interaction))));
|
|
220
|
+
}
|
|
221
|
+
return plainResponse(HTTP_OK);
|
|
222
|
+
};
|
|
223
|
+
#routeJson = (payload) => {
|
|
224
|
+
const verification = decodeOptional(UrlVerificationSchema, payload);
|
|
225
|
+
if (verification !== undefined) {
|
|
226
|
+
return plainResponse(HTTP_OK, verification.challenge);
|
|
227
|
+
}
|
|
228
|
+
if (payload === undefined) {
|
|
229
|
+
return plainResponse(HTTP_BAD_REQUEST);
|
|
230
|
+
}
|
|
231
|
+
this.#runInBackground(this.#handleMessage(parseEventCallback(payload)));
|
|
232
|
+
return plainResponse(HTTP_OK);
|
|
233
|
+
};
|
|
234
|
+
/** Returns false and logs the Chat ID at `info` level if `allowedChatIds` does not list the Chat (ADR 0012). */
|
|
235
|
+
#allowed = (chatId) => {
|
|
236
|
+
if (isChatAllowed(this.#config.allowedChatIds, chatId)) {
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
this.#ctx.log.info("Dropped Slack input from a Chat that is not allowed", {
|
|
240
|
+
chatId,
|
|
241
|
+
});
|
|
242
|
+
return false;
|
|
243
|
+
};
|
|
244
|
+
/** Returns false for a duplicate of an event that the binding already handled. */
|
|
245
|
+
#firstSeen = (message) => {
|
|
246
|
+
const key = message.eventId ?? `${message.channel}:${message.ts}`;
|
|
247
|
+
if (this.#seenEvents.has(key)) {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
remember(this.#seenEvents, key, true, MAX_SEEN_EVENTS);
|
|
251
|
+
return true;
|
|
252
|
+
};
|
|
253
|
+
/** DMs always start a Run. In channels, the default needs a bot mention or a reply in a thread of the bot. */
|
|
254
|
+
#isAddressed = (connection, message, chatId, mentioned) => {
|
|
255
|
+
const isOpen = message.channelType === "im" ||
|
|
256
|
+
this.#config.channelTrigger === "all" ||
|
|
257
|
+
mentioned;
|
|
258
|
+
const isReply = message.threadTs !== undefined &&
|
|
259
|
+
(message.parentUserId === connection.botUserId ||
|
|
260
|
+
connection.store.isEngaged(chatId));
|
|
261
|
+
return isOpen || isReply;
|
|
262
|
+
};
|
|
263
|
+
#handleMessage = async (message) => {
|
|
264
|
+
const connection = this.#connection;
|
|
265
|
+
if (connection === undefined || message === undefined) {
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const isOwnMessage = message.user === connection.botUserId;
|
|
269
|
+
if (isOwnMessage || !this.#firstSeen(message)) {
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const chatId = toChatId(message.channel, message.threadTs);
|
|
273
|
+
const mention = `<@${connection.botUserId}>`;
|
|
274
|
+
const mentioned = message.text.includes(mention);
|
|
275
|
+
if (!this.#allowed(chatId) ||
|
|
276
|
+
!this.#isAddressed(connection, message, chatId, mentioned)) {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (message.threadTs !== undefined) {
|
|
280
|
+
await connection.store.engage(chatId);
|
|
281
|
+
}
|
|
282
|
+
remember(this.#lastInbound, chatId, { channel: message.channel, ts: message.ts }, MAX_TRACKED_CHATS);
|
|
283
|
+
const text = cleanText(message.text, mention);
|
|
284
|
+
const senderDisplayName = await this.#displayName(connection, message.user);
|
|
285
|
+
// Slash Command payloads carry no thread, so a thread Chat takes a command as a mention: `@bot /stop`.
|
|
286
|
+
const isThreadCommand = message.threadTs !== undefined && mentioned && message.files.length === 0;
|
|
287
|
+
const command = isThreadCommand ? parseCommandText(text) : undefined;
|
|
288
|
+
if (command !== undefined) {
|
|
289
|
+
await connection.sink.command({
|
|
290
|
+
args: command.args,
|
|
291
|
+
chatId,
|
|
292
|
+
name: command.name,
|
|
293
|
+
senderDisplayName,
|
|
294
|
+
});
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const { attachments, notes } = await this.#stageFiles(message);
|
|
298
|
+
const fullText = [text, ...notes]
|
|
299
|
+
.filter((part) => part !== "")
|
|
300
|
+
.join("\n\n");
|
|
301
|
+
if (fullText === "" && attachments.length === 0) {
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
await connection.sink.send({
|
|
305
|
+
attachments: attachments.length === 0 ? undefined : attachments,
|
|
306
|
+
chatId,
|
|
307
|
+
senderDisplayName,
|
|
308
|
+
text: fullText,
|
|
309
|
+
});
|
|
310
|
+
};
|
|
311
|
+
/** Downloads the files of a message. A skipped file becomes a note in the message text, so the Agent knows. */
|
|
312
|
+
#stageFiles = async (message) => {
|
|
313
|
+
const attachments = [];
|
|
314
|
+
const notes = [];
|
|
315
|
+
for (const file of message.files) {
|
|
316
|
+
// oxlint-disable-next-line no-await-in-loop -- Sequential downloads hold at most one file in memory.
|
|
317
|
+
const result = await stageInboundFile(file, {
|
|
318
|
+
botToken: this.#config.botToken,
|
|
319
|
+
fetch: this.#deps.fetch,
|
|
320
|
+
maxBytes: this.#ctx.maxAttachmentBytes,
|
|
321
|
+
stagingDir: this.#ctx.stagingDir,
|
|
322
|
+
});
|
|
323
|
+
if (result.ok) {
|
|
324
|
+
attachments.push(result.attachment);
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
this.#ctx.log.warn("Skipped a Slack file", {
|
|
328
|
+
fileId: file.id,
|
|
329
|
+
reason: result.reason,
|
|
330
|
+
});
|
|
331
|
+
notes.push(result.reason === "too_large"
|
|
332
|
+
? `[Attachment ${file.name} was not received: it is larger than ${this.#ctx.maxAttachmentBytes} bytes.]`
|
|
333
|
+
: `[Attachment ${file.name} was not received: the download failed.]`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return { attachments, notes };
|
|
337
|
+
};
|
|
338
|
+
#handleCommand = async (command) => {
|
|
339
|
+
const connection = this.#connection;
|
|
340
|
+
if (connection === undefined || command === undefined) {
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
const chatId = toChatId(command.channel);
|
|
344
|
+
if (!this.#allowed(chatId)) {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const parsed = parseCommandText(`${command.command} ${command.text}`);
|
|
348
|
+
if (parsed === undefined) {
|
|
349
|
+
this.#ctx.log.debug("Ignored an unknown Slack Slash Command", {
|
|
350
|
+
command: command.command,
|
|
351
|
+
});
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
await connection.sink.command({
|
|
355
|
+
args: parsed.args,
|
|
356
|
+
chatId,
|
|
357
|
+
name: parsed.name,
|
|
358
|
+
senderDisplayName: await this.#displayName(connection, command.user, command.userName),
|
|
359
|
+
});
|
|
360
|
+
};
|
|
361
|
+
#handleAction = async (action) => {
|
|
362
|
+
const connection = this.#connection;
|
|
363
|
+
if (connection === undefined || action === undefined) {
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const chatId = connection.store.approval(action.approvalId)?.chatId ??
|
|
367
|
+
toChatId(action.channel, action.threadTs);
|
|
368
|
+
if (!this.#allowed(chatId)) {
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
const resolvedBy = await this.#displayName(connection, action.user, action.userName);
|
|
372
|
+
const won = await connection.sink.decide({
|
|
373
|
+
approvalId: action.approvalId,
|
|
374
|
+
chatId,
|
|
375
|
+
resolution: { decision: action.decision, resolvedBy },
|
|
376
|
+
});
|
|
377
|
+
if (!won) {
|
|
378
|
+
this.#ctx.log.debug("A Slack Approval decision came too late", {
|
|
379
|
+
approvalId: action.approvalId,
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
/** Looks up and caches the display name of a Slack user. Falls back to `fallback` or the user ID. */
|
|
384
|
+
#displayName = async (connection, user, fallback) => {
|
|
385
|
+
const cached = this.#displayNames.get(user);
|
|
386
|
+
if (cached !== undefined) {
|
|
387
|
+
return cached;
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
const name = await nameOf(connection.web, user);
|
|
391
|
+
if (name !== undefined) {
|
|
392
|
+
const trimmed = name.slice(0, DISPLAY_NAME_MAX_LENGTH);
|
|
393
|
+
remember(this.#displayNames, user, trimmed, MAX_CACHED_NAMES);
|
|
394
|
+
return trimmed;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
catch (error) {
|
|
398
|
+
this.#ctx.log.debug("Could not look up a Slack user", {
|
|
399
|
+
error: String(error),
|
|
400
|
+
user,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
return (fallback ?? user).slice(0, DISPLAY_NAME_MAX_LENGTH);
|
|
404
|
+
};
|
|
405
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns the Chat ID of a Slack conversation or thread (ADR 0012): `<channel_id>` for a DM or channel, and
|
|
3
|
+
* `<channel_id>:<thread_ts>` for a thread.
|
|
4
|
+
*/
|
|
5
|
+
export const toChatId = (channel, threadTs) => threadTs === undefined ? channel : `${channel}:${threadTs}`;
|
|
6
|
+
/** Splits a Chat ID from `toChatId` into its channel and thread. */
|
|
7
|
+
export const parseChatId = (chatId) => {
|
|
8
|
+
const separator = chatId.indexOf(":");
|
|
9
|
+
return separator === -1
|
|
10
|
+
? { channel: chatId, threadTs: undefined }
|
|
11
|
+
: {
|
|
12
|
+
channel: chatId.slice(0, separator),
|
|
13
|
+
threadTs: chatId.slice(separator + 1),
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
/** Returns true if `allowed` lists the Chat itself or its parent channel. */
|
|
17
|
+
export const isChatAllowed = (allowed, chatId) => allowed.has(chatId) || allowed.has(parseChatId(chatId).channel);
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { decode, SecretRefSchema } from "@wheatley-ai/protocol";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { toJsonSchema } from "./schemas.js";
|
|
4
|
+
/** The default interval between two draft edits of one streamed reply (ADR 0012). */
|
|
5
|
+
export const DEFAULT_EDIT_INTERVAL_MS = 1200;
|
|
6
|
+
/** The smallest draft edit interval. Slack rate-limits `chat.update` at about one call per second per channel. */
|
|
7
|
+
export const MIN_EDIT_INTERVAL_MS = 1000;
|
|
8
|
+
/** The reaction that shows a Run in progress on the message that started it. */
|
|
9
|
+
export const DEFAULT_TYPING_REACTION = "hourglass_flowing_sand";
|
|
10
|
+
const SlackConfigSchema = Type.Object({
|
|
11
|
+
/** Slack channel, DM, or thread IDs (`<channel_id>:<thread_ts>`). A channel ID also allows its threads. */
|
|
12
|
+
allowedChatIds: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
13
|
+
/** The app-level token (`xapp-`). Socket Mode needs it. */
|
|
14
|
+
appToken: Type.Optional(SecretRefSchema),
|
|
15
|
+
/** The bot token (`xoxb-`). */
|
|
16
|
+
botToken: SecretRefSchema,
|
|
17
|
+
/** Which channel messages start a Run. The default is `mention-or-reply`. */
|
|
18
|
+
channelTrigger: Type.Optional(Type.Union([Type.Literal("mention-or-reply"), Type.Literal("all")])),
|
|
19
|
+
/** The interval between draft edits. The default is 1,200 ms. */
|
|
20
|
+
editIntervalMs: Type.Optional(Type.Integer({ minimum: MIN_EDIT_INTERVAL_MS })),
|
|
21
|
+
/** The signing secret. Events API webhook requests need it. */
|
|
22
|
+
signingSecret: Type.Optional(SecretRefSchema),
|
|
23
|
+
/** `edit` streams a draft reply. `typing` shows only the typing reaction. The default is `edit`. */
|
|
24
|
+
streaming: Type.Optional(Type.Union([Type.Literal("edit"), Type.Literal("typing")])),
|
|
25
|
+
/** `socket` (the default) uses Socket Mode. `webhook` uses the Events API through the Webhook Ingress. */
|
|
26
|
+
transport: Type.Optional(Type.Union([Type.Literal("socket"), Type.Literal("webhook")])),
|
|
27
|
+
/** The emoji name of the typing reaction, without colons. */
|
|
28
|
+
typingReaction: Type.Optional(Type.String({ pattern: "^[a-z0-9_+'-]+$" })),
|
|
29
|
+
}, { additionalProperties: false });
|
|
30
|
+
/** The JSON Schema of the `config` block of a `type: slack` entry in `frontends` of `config.yaml`. */
|
|
31
|
+
export const SLACK_CONFIG_SCHEMA = toJsonSchema(SlackConfigSchema);
|
|
32
|
+
const fail = (message) => {
|
|
33
|
+
throw new Error(`Invalid Slack binding config: ${message}`);
|
|
34
|
+
};
|
|
35
|
+
const resolveSecret = (key, ref, secrets) => {
|
|
36
|
+
if (ref === undefined) {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
const value = secrets.get(ref.secret);
|
|
40
|
+
return value === undefined || value === ""
|
|
41
|
+
? fail(`${key} names the missing secret ${ref.secret}`)
|
|
42
|
+
: value;
|
|
43
|
+
};
|
|
44
|
+
/** Applies the transport rules and defaults to a schema-valid config, and resolves its secrets. */
|
|
45
|
+
const toBindingConfig = (config, secrets) => {
|
|
46
|
+
const transport = config.transport ?? "socket";
|
|
47
|
+
const appToken = resolveSecret("appToken", config.appToken, secrets);
|
|
48
|
+
const signingSecret = resolveSecret("signingSecret", config.signingSecret, secrets);
|
|
49
|
+
if (transport === "socket" && appToken === undefined) {
|
|
50
|
+
return fail("appToken is required in socket transport");
|
|
51
|
+
}
|
|
52
|
+
if (transport === "webhook" && signingSecret === undefined) {
|
|
53
|
+
return fail("signingSecret is required in webhook transport");
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
allowedChatIds: new Set(config.allowedChatIds),
|
|
57
|
+
appToken,
|
|
58
|
+
botToken: resolveSecret("botToken", config.botToken, secrets) ??
|
|
59
|
+
fail("botToken is required"),
|
|
60
|
+
channelTrigger: config.channelTrigger ?? "mention-or-reply",
|
|
61
|
+
editIntervalMs: config.editIntervalMs ?? DEFAULT_EDIT_INTERVAL_MS,
|
|
62
|
+
signingSecret,
|
|
63
|
+
streaming: config.streaming ?? "edit",
|
|
64
|
+
transport,
|
|
65
|
+
typingReaction: config.typingReaction ?? DEFAULT_TYPING_REACTION,
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Validates a binding config and resolves its secrets.
|
|
70
|
+
*
|
|
71
|
+
* Throws an `Error` for a config that breaks `SLACK_CONFIG_SCHEMA` (for example an empty `allowedChatIds`), a missing
|
|
72
|
+
* secret, a missing `appToken` in `socket` transport, or a missing `signingSecret` in `webhook` transport.
|
|
73
|
+
*/
|
|
74
|
+
export const parseSlackConfig = (raw, secrets) => {
|
|
75
|
+
const decoded = decode(SlackConfigSchema, raw);
|
|
76
|
+
if (!decoded.ok) {
|
|
77
|
+
return fail(decoded.issues.map((issue) => `${issue.path} ${issue.message}`).join("; "));
|
|
78
|
+
}
|
|
79
|
+
return toBindingConfig(decoded.value, secrets);
|
|
80
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { DeliveryError, isDeliveryError } from "@wheatley-ai/sdk";
|
|
2
|
+
const MS_PER_SECOND = 1000;
|
|
3
|
+
const HTTP_TOO_MANY_REQUESTS = 429;
|
|
4
|
+
const HTTP_SERVER_ERROR = 500;
|
|
5
|
+
/** Slack platform errors that a retry cannot fix: a deleted Chat, a removed bot, or a revoked token. */
|
|
6
|
+
const PERMANENT_PLATFORM_ERRORS = new Set([
|
|
7
|
+
"account_inactive",
|
|
8
|
+
"cannot_dm_bot",
|
|
9
|
+
"channel_not_found",
|
|
10
|
+
"invalid_auth",
|
|
11
|
+
"is_archived",
|
|
12
|
+
"message_not_found",
|
|
13
|
+
"missing_scope",
|
|
14
|
+
"msg_too_long",
|
|
15
|
+
"no_text",
|
|
16
|
+
"not_allowed_token_type",
|
|
17
|
+
"not_authed",
|
|
18
|
+
"not_in_channel",
|
|
19
|
+
"restricted_action",
|
|
20
|
+
"team_access_not_granted",
|
|
21
|
+
"thread_not_found",
|
|
22
|
+
"token_expired",
|
|
23
|
+
"token_revoked",
|
|
24
|
+
"user_not_found",
|
|
25
|
+
]);
|
|
26
|
+
/** `@slack/web-api` errors for bad file upload arguments or an unreadable file. */
|
|
27
|
+
const PERMANENT_CODES = new Set([
|
|
28
|
+
"slack_webapi_file_upload_invalid_args_error",
|
|
29
|
+
"slack_webapi_file_upload_read_file_data_error",
|
|
30
|
+
]);
|
|
31
|
+
const isCodedError = (cause) => cause instanceof Error && "code" in cause && typeof cause.code === "string";
|
|
32
|
+
const isRateLimited = (cause) => isCodedError(cause) &&
|
|
33
|
+
cause.code === "slack_webapi_rate_limited_error" &&
|
|
34
|
+
"retryAfter" in cause &&
|
|
35
|
+
typeof cause.retryAfter === "number";
|
|
36
|
+
const isPlatformError = (cause) => isCodedError(cause) &&
|
|
37
|
+
cause.code === "slack_webapi_platform_error" &&
|
|
38
|
+
"data" in cause &&
|
|
39
|
+
typeof cause.data === "object" &&
|
|
40
|
+
cause.data !== null &&
|
|
41
|
+
"error" in cause.data &&
|
|
42
|
+
typeof cause.data.error === "string";
|
|
43
|
+
const isHttpError = (cause) => isCodedError(cause) &&
|
|
44
|
+
cause.code === "slack_webapi_http_error" &&
|
|
45
|
+
"statusCode" in cause &&
|
|
46
|
+
typeof cause.statusCode === "number";
|
|
47
|
+
const failure = (cause, permanent) => ({
|
|
48
|
+
cause,
|
|
49
|
+
kind: permanent ? "permanent" : "retryable",
|
|
50
|
+
});
|
|
51
|
+
const classify = (cause) => {
|
|
52
|
+
if (isRateLimited(cause)) {
|
|
53
|
+
return {
|
|
54
|
+
cause,
|
|
55
|
+
kind: "retryable",
|
|
56
|
+
retryAfterMs: cause.retryAfter * MS_PER_SECOND,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
if (isPlatformError(cause)) {
|
|
60
|
+
return failure(cause, PERMANENT_PLATFORM_ERRORS.has(cause.data.error));
|
|
61
|
+
}
|
|
62
|
+
if (isHttpError(cause)) {
|
|
63
|
+
const retryable = cause.statusCode === HTTP_TOO_MANY_REQUESTS ||
|
|
64
|
+
cause.statusCode >= HTTP_SERVER_ERROR;
|
|
65
|
+
return failure(cause, !retryable);
|
|
66
|
+
}
|
|
67
|
+
return failure(cause, isCodedError(cause) && PERMANENT_CODES.has(cause.code));
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Converts an error from a Slack client call into the `DeliveryError` that `FrontendBinding.deliver` rejects with.
|
|
71
|
+
*
|
|
72
|
+
* Rate limits are retryable with the `Retry-After` wait. Platform errors for a deleted Chat, a removed bot, or a bad
|
|
73
|
+
* token are permanent. Network errors, HTTP 5xx, and unknown errors are retryable.
|
|
74
|
+
*/
|
|
75
|
+
export const toDeliveryError = (cause) => {
|
|
76
|
+
if (isDeliveryError(cause)) {
|
|
77
|
+
return cause;
|
|
78
|
+
}
|
|
79
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
80
|
+
return new DeliveryError(`Slack delivery failed: ${detail}`, classify(cause));
|
|
81
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { decisionOfAction } from "./approval-blocks.js";
|
|
2
|
+
import { BlockActionsSchema, decodeOptional, MessageEventCallbackSchema, SlashCommandSchema, } from "./schemas.js";
|
|
3
|
+
/** Message subtypes that carry a Sender message. Other subtypes are edits, joins, bot posts, and similar. */
|
|
4
|
+
const USER_SUBTYPES = new Set([
|
|
5
|
+
undefined,
|
|
6
|
+
"file_share",
|
|
7
|
+
"thread_broadcast",
|
|
8
|
+
]);
|
|
9
|
+
const DEFAULT_MIME_TYPE = "application/octet-stream";
|
|
10
|
+
/**
|
|
11
|
+
* Parses an Events API `event_callback` payload. Returns `undefined` for anything other than a Sender message: other
|
|
12
|
+
* event types, bot messages, edits, and malformed payloads.
|
|
13
|
+
*/
|
|
14
|
+
export const parseEventCallback = (payload) => {
|
|
15
|
+
const decoded = decodeOptional(MessageEventCallbackSchema, payload);
|
|
16
|
+
if (decoded === undefined) {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
const { event } = decoded;
|
|
20
|
+
if (!USER_SUBTYPES.has(event.subtype) || event.bot_id !== undefined) {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
channel: event.channel,
|
|
25
|
+
channelType: event.channel_type,
|
|
26
|
+
eventId: decoded.event_id,
|
|
27
|
+
files: (event.files ?? []).map((file) => ({
|
|
28
|
+
id: file.id,
|
|
29
|
+
mimeType: file.mimetype ?? DEFAULT_MIME_TYPE,
|
|
30
|
+
name: file.name ?? file.id,
|
|
31
|
+
sizeBytes: file.size,
|
|
32
|
+
url: file.url_private_download,
|
|
33
|
+
})),
|
|
34
|
+
parentUserId: event.parent_user_id,
|
|
35
|
+
text: event.text ?? "",
|
|
36
|
+
threadTs: event.thread_ts,
|
|
37
|
+
ts: event.ts,
|
|
38
|
+
user: event.user,
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
/** Parses a Slash Command payload from Socket Mode or from the form fields of a webhook request. */
|
|
42
|
+
export const parseSlashCommand = (payload) => {
|
|
43
|
+
const decoded = decodeOptional(SlashCommandSchema, payload);
|
|
44
|
+
return decoded === undefined
|
|
45
|
+
? undefined
|
|
46
|
+
: {
|
|
47
|
+
channel: decoded.channel_id,
|
|
48
|
+
command: decoded.command,
|
|
49
|
+
text: decoded.text ?? "",
|
|
50
|
+
user: decoded.user_id,
|
|
51
|
+
userName: decoded.user_name,
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
/** Parses a `block_actions` payload. Returns `undefined` unless the first action is an Approval button. */
|
|
55
|
+
export const parseInteraction = (payload) => {
|
|
56
|
+
const decoded = decodeOptional(BlockActionsSchema, payload);
|
|
57
|
+
const [action] = decoded?.actions ?? [];
|
|
58
|
+
if (decoded === undefined || action === undefined) {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
const decision = decisionOfAction(action.action_id);
|
|
62
|
+
const approvalId = action.value;
|
|
63
|
+
const channel = decoded.channel?.id ?? decoded.container?.channel_id;
|
|
64
|
+
const isApprovalClick = decision !== undefined && approvalId !== undefined && channel !== undefined;
|
|
65
|
+
if (!isApprovalClick) {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
approvalId,
|
|
70
|
+
channel,
|
|
71
|
+
decision,
|
|
72
|
+
threadTs: decoded.message?.thread_ts,
|
|
73
|
+
user: decoded.user.id,
|
|
74
|
+
userName: decoded.user.name ?? decoded.user.username,
|
|
75
|
+
};
|
|
76
|
+
};
|