@arnilo/prism-hosts 0.13.0 → 0.14.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/CHANGELOG.md +2 -0
- package/a2a/README.md +195 -0
- package/a2a/src/card.ts +208 -0
- package/a2a/src/codec.ts +523 -0
- package/a2a/src/connect.ts +415 -0
- package/a2a/src/errors.ts +87 -0
- package/a2a/src/index.ts +40 -0
- package/a2a/src/limits.ts +43 -0
- package/a2a/src/pending.ts +28 -0
- package/a2a/src/proxy.ts +526 -0
- package/a2a/src/serve.ts +886 -0
- package/acp/README.md +3 -1
- package/acp/src/limits.ts +3 -16
- package/acp/src/mapper.ts +26 -5
- package/acp/src/serve.ts +6 -5
- package/ag-ui/README.md +2 -1
- package/ag-ui/src/a2ui.ts +8 -31
- package/ag-ui/src/ag-ui-mapper.ts +27 -1
- package/ag-ui/src/encrypted-value.ts +3 -3
- package/ag-ui/src/handler.ts +4 -4
- package/ag-ui/src/index.ts +0 -33
- package/ag-ui/src/limits.ts +5 -88
- package/ag-ui/src/projectors.ts +8 -6
- package/ag-ui/src/renderer/bind.ts +2 -1
- package/channels/README.md +61 -5
- package/channels/src/discord-gateway.ts +354 -0
- package/channels/src/discord.ts +873 -0
- package/channels/src/index.ts +4 -2
- package/channels/src/limits.ts +3 -19
- package/channels/src/pairing.ts +1 -2
- package/channels/src/runtime-turn.ts +10 -2
- package/channels/src/signal.ts +11 -19
- package/channels/src/slack.ts +854 -0
- package/channels/src/telegram.ts +22 -44
- package/channels/src/types.ts +5 -2
- package/devtools/README.md +1 -1
- package/driver-process/src/driver.ts +3 -1
- package/driver-process/src/testing.ts +1 -1
- package/driver-process/src/turn.ts +5 -1
- package/evals/README.md +11 -7
- package/evals/src/calibration.ts +5 -13
- package/evals/src/compare-experiments.ts +1 -2
- package/evals/src/comparison.ts +7 -25
- package/evals/src/curate.ts +3 -9
- package/evals/src/dataset.ts +0 -2
- package/evals/src/index.ts +3 -20
- package/evals/src/injection.ts +33 -6
- package/evals/src/judge.ts +9 -13
- package/evals/src/limits.ts +0 -17
- package/evals/src/rubric-judge.ts +5 -10
- package/evals/src/scenario-runner.ts +8 -4
- package/evals/src/scenarios.ts +5 -5
- package/evals/src/score.ts +3 -5
- package/evals/src/stats.ts +0 -2
- package/evals/src/threshold.ts +3 -3
- package/evals/src/toolless-session.ts +7 -3
- package/evals/src/trace.ts +8 -14
- package/evals/src/trajectory.ts +45 -11
- package/evals/src/types.ts +2 -2
- package/evals/src/user-simulator.ts +1 -7
- package/evals/src/util.ts +3 -9
- package/headless/README.md +20 -1
- package/headless/src/authority.ts +14 -1
- package/headless/src/errors.ts +3 -1
- package/headless/src/index.ts +10 -1
- package/headless/src/limits.ts +2 -2
- package/headless/src/pending.ts +4 -3
- package/headless/src/recover.ts +126 -0
- package/headless/src/resume.ts +1 -1
- package/host-builder/data/api.json +1308 -1367
- package/host-builder/data/errors.json +207 -181
- package/host-builder/data/examples/a2a-client.ts +125 -0
- package/host-builder/data/examples/a2a-server.ts +133 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +1 -1
- package/host-builder/data/examples/build-workflow.ts +2 -2
- package/host-builder/data/examples/caveman-ponytail.ts +1 -1
- package/host-builder/data/examples/channel-discord.ts +176 -0
- package/host-builder/data/examples/channel-slack.ts +146 -0
- package/host-builder/data/examples/continue-after-failure.ts +80 -0
- package/host-builder/data/examples/custom-adapter.ts +1 -1
- package/host-builder/data/examples/decision-models.ts +1 -1
- package/host-builder/data/examples/define-package.ts +1 -1
- package/host-builder/data/examples/delegate.ts +74 -9
- package/host-builder/data/examples/durable-loops-and-approvals.ts +11 -10
- package/host-builder/data/examples/governance-deny.ts +1 -1
- package/host-builder/data/examples/guardrail-content.ts +126 -0
- package/host-builder/data/examples/headless-host.ts +1 -1
- package/host-builder/data/examples/long-running-job.ts +129 -0
- package/host-builder/data/examples/long-term-memory.ts +1 -1
- package/host-builder/data/examples/mcp-oauth.ts +197 -0
- package/host-builder/data/examples/mcp-trust.ts +1 -1
- package/host-builder/data/examples/memory-and-wiki.ts +3 -3
- package/host-builder/data/examples/memory-system.ts +31 -18
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +1 -1
- package/host-builder/data/examples/parallel-tools.ts +70 -0
- package/host-builder/data/examples/remote-agent.ts +1 -1
- package/host-builder/data/examples/serve-tools.ts +1 -1
- package/host-builder/data/examples/session-memory.ts +29 -26
- package/host-builder/data/examples/side-call.ts +9 -5
- package/host-builder/data/examples/sqlite-resume.ts +1 -1
- package/host-builder/data/examples/structured-output.ts +57 -0
- package/host-builder/data/examples.json +15 -5
- package/host-builder/skills/prism-host-builder/SKILL.md +1 -1
- package/host-builder/skills/prism-host-builder/references/choosing.md +14 -10
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +5 -3
- package/host-builder/skills/prism-host-builder/references/recipes.md +5 -5
- package/host-builder/skills/prism-host-builder/references/verification.md +1 -1
- package/host-builder/src/check/runner.ts +2 -3
- package/host-builder/src/server.ts +2 -2
- package/mcp-server/README.md +3 -3
- package/mcp-server/src/bounds.ts +3 -3
- package/mcp-server/src/serve-tools.ts +2 -9
- package/mcp-server/src/serve.ts +2 -4
- package/mcp-server/src/server.ts +10 -20
- package/package.json +12 -6
- package/remote/README.md +7 -4
- package/remote/src/channel.ts +6 -2
- package/remote/src/connect.ts +9 -3
- package/remote/src/errors.ts +3 -1
- package/remote/src/limits.ts +3 -13
- package/remote/src/mirror.ts +2 -1
- package/remote/src/pending.ts +4 -3
- package/remote/src/protocol.ts +3 -0
- package/remote/src/serve.ts +43 -5
- package/remote/src/session-proxy.ts +28 -5
- package/remote/src/testing.ts +3 -1
- package/remote/src/wire.ts +74 -14
|
@@ -0,0 +1,854 @@
|
|
|
1
|
+
// Plan 236 Task 4: native-fetch Slack adapter on the shared channel runtime. Importing and
|
|
2
|
+
// constructing are inert; Socket Mode opens only in `start`, and the Events API handler is
|
|
3
|
+
// host-mounted. Both transports feed one payload parser and await `admit` before acknowledging.
|
|
4
|
+
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
5
|
+
import type { Agent } from "@arnilo/prism";
|
|
6
|
+
import type { CheckpointStore, LeaseStore } from "./checkpoint-contract.js";
|
|
7
|
+
import { bindChannelHostUi } from "./host-ui.js";
|
|
8
|
+
import { retryableAdmission } from "./admission.js";
|
|
9
|
+
import { type ChannelSecretSource, resolveChannelSecretRef, createChannelRedactor } from "./secret-ref.js";
|
|
10
|
+
import { createMemoryCheckpointStore, createMemoryLeaseStore } from "./memory-stores.js";
|
|
11
|
+
import { createChannelRuntime } from "./runtime.js";
|
|
12
|
+
import type {
|
|
13
|
+
ChannelAdapter,
|
|
14
|
+
ChannelAssistantDelta,
|
|
15
|
+
ChannelAuthorizeInput,
|
|
16
|
+
ChannelAuthorization,
|
|
17
|
+
ChannelConnectionHandle,
|
|
18
|
+
ChannelInboundEvent,
|
|
19
|
+
ChannelLimits,
|
|
20
|
+
ChannelReceive,
|
|
21
|
+
ChannelReplyControl,
|
|
22
|
+
} from "./types.js";
|
|
23
|
+
|
|
24
|
+
export type { ChannelConnectionHandle, ChannelSecretSource };
|
|
25
|
+
|
|
26
|
+
const DEFAULT_API_ORIGIN = "https://slack.com";
|
|
27
|
+
/** `chat.postMessage` truncates `text` past 40,000 characters. */
|
|
28
|
+
const SLACK_TEXT_CODE_UNITS = 40_000;
|
|
29
|
+
/** A Block Kit `section` text object holds at most 3,000 characters. */
|
|
30
|
+
const SLACK_SECTION_CODE_UNITS = 3_000;
|
|
31
|
+
/** A preview shows the newest part of the answer; escaped it stays far below the text limit. */
|
|
32
|
+
const SLACK_DRAFT_CODE_UNITS = 4_000;
|
|
33
|
+
/** Slack's replay window for signed requests. */
|
|
34
|
+
const SIGNATURE_WINDOW_SECONDS = 300;
|
|
35
|
+
const DEFAULT_MAX_REQUEST_BYTES = 128 * 1024;
|
|
36
|
+
const MAX_SEND_ATTEMPTS = 5;
|
|
37
|
+
const MAX_RETRY_AFTER_SECONDS = 60;
|
|
38
|
+
const DEFAULT_DRAFT_INTERVAL_MS = 1_000;
|
|
39
|
+
const MAX_PREVIEWS = 256;
|
|
40
|
+
const SOCKET_OPEN_TIMEOUT_MS = 10_000;
|
|
41
|
+
const MAX_RECONNECT_DELAY_MS = 30_000;
|
|
42
|
+
const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
43
|
+
const TS_PATTERN = /^\d{1,12}\.\d{1,8}$/;
|
|
44
|
+
/** Commands the runtime understands; Slack intercepts a leading `/` as a slash command, so `!new` is accepted too. */
|
|
45
|
+
const BANG_COMMAND = /^!(help|status|new|cancel|approve|deny|answer)(?=\s|$)/i;
|
|
46
|
+
|
|
47
|
+
/** The subset of the WHATWG `WebSocket` the Socket Mode client uses. */
|
|
48
|
+
export interface SlackSocket {
|
|
49
|
+
send(data: string): void;
|
|
50
|
+
close(code?: number, reason?: string): void;
|
|
51
|
+
addEventListener(type: "open" | "message" | "close" | "error", listener: (event: { readonly data?: unknown }) => void): void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface SlackAdapterOptions {
|
|
55
|
+
/** Stable host-selected connection id; it is never read from Slack input. */
|
|
56
|
+
readonly connectionId: string;
|
|
57
|
+
/** Bot token (`xoxb-`), resolved only for Web API calls; it never reaches events or errors. */
|
|
58
|
+
readonly botToken: ChannelSecretSource;
|
|
59
|
+
/** App-level token (`xapp-`, `connections:write`). Required for Socket Mode `start`. */
|
|
60
|
+
readonly appToken?: ChannelSecretSource;
|
|
61
|
+
/** Opt-in preview message, updated at most once per `draftIntervalMs` and deleted after the reply. */
|
|
62
|
+
readonly sendDrafts?: boolean;
|
|
63
|
+
/** Minimum interval between preview writes (default 1,000 ms, 100–60,000). */
|
|
64
|
+
readonly draftIntervalMs?: number;
|
|
65
|
+
/** Bounds Socket Mode frames and Web API response bodies (default 128 KiB, hard 1 MiB). */
|
|
66
|
+
readonly maxRequestBytes?: number;
|
|
67
|
+
/** Trusted exact HTTPS API origin; defaults to `https://slack.com`. */
|
|
68
|
+
readonly apiOrigin?: string;
|
|
69
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
70
|
+
/** Socket factory for Socket Mode; defaults to the global `WebSocket`. */
|
|
71
|
+
readonly webSocket?: (url: string) => SlackSocket;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Channel adapter with Slack's rate-bounded preview message. */
|
|
75
|
+
export interface SlackAdapter extends ChannelAdapter {
|
|
76
|
+
/** Fire-and-forget preview of the answer being produced. No-op unless `sendDrafts` is on. */
|
|
77
|
+
sendDraft(delta: ChannelAssistantDelta): void;
|
|
78
|
+
/** Verified Events API / interactivity handler. Without a signing secret it answers 401. */
|
|
79
|
+
handleRequest(request: Request, receive: ChannelReceive, signingSecret: ChannelSecretSource | undefined): Promise<Response>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
class SlackApiError extends Error {
|
|
83
|
+
readonly status?: number;
|
|
84
|
+
readonly retryAfter?: number;
|
|
85
|
+
readonly error?: string;
|
|
86
|
+
readonly kind: "api" | "credential" | "network" | "response";
|
|
87
|
+
|
|
88
|
+
constructor(shape: { kind: SlackApiError["kind"]; status?: number; retryAfter?: number; error?: string }) {
|
|
89
|
+
super("Slack API request failed");
|
|
90
|
+
this.name = "SlackApiError";
|
|
91
|
+
this.kind = shape.kind;
|
|
92
|
+
this.status = shape.status;
|
|
93
|
+
this.retryAfter = shape.retryAfter;
|
|
94
|
+
this.error = shape.error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
class SlackDeliveryUnknownError extends Error {
|
|
99
|
+
constructor() {
|
|
100
|
+
super("Slack delivery outcome unknown");
|
|
101
|
+
this.name = "SlackDeliveryUnknownError";
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
106
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function asId(value: unknown): string | undefined {
|
|
110
|
+
return typeof value === "string" && ID_PATTERN.test(value) ? value : undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function asTs(value: unknown): string | undefined {
|
|
114
|
+
return typeof value === "string" && TS_PATTERN.test(value) ? value : undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function apiOrigin(value: string | undefined): string {
|
|
118
|
+
const raw = value ?? DEFAULT_API_ORIGIN;
|
|
119
|
+
let parsed: URL;
|
|
120
|
+
try {
|
|
121
|
+
parsed = new URL(raw);
|
|
122
|
+
} catch {
|
|
123
|
+
throw new TypeError("Slack apiOrigin must be an exact HTTPS origin");
|
|
124
|
+
}
|
|
125
|
+
if (
|
|
126
|
+
parsed.protocol !== "https:" ||
|
|
127
|
+
parsed.username ||
|
|
128
|
+
parsed.password ||
|
|
129
|
+
parsed.pathname !== "/" ||
|
|
130
|
+
parsed.search ||
|
|
131
|
+
parsed.hash ||
|
|
132
|
+
parsed.origin !== raw
|
|
133
|
+
) {
|
|
134
|
+
throw new TypeError("Slack apiOrigin must be an exact HTTPS origin");
|
|
135
|
+
}
|
|
136
|
+
return parsed.origin;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** A host-set adapter limit, at least `min`. The host's value is the cap (plan 239 Task 5). */
|
|
140
|
+
function boundedInteger(value: number | undefined, fallback: number, min: number, name: string): number {
|
|
141
|
+
const resolved = value ?? fallback;
|
|
142
|
+
if (!Number.isSafeInteger(resolved) || resolved < min) {
|
|
143
|
+
throw new TypeError(`Slack ${name} must be an integer of at least ${min}`);
|
|
144
|
+
}
|
|
145
|
+
return resolved;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function constantTimeEqual(expected: string, actual: string | null): boolean {
|
|
149
|
+
if (actual === null) return false;
|
|
150
|
+
return timingSafeEqual(createHash("sha256").update(expected).digest(), createHash("sha256").update(actual).digest());
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Slack `mrkdwn` control characters; escaping keeps model text from forming `<!channel>` or links. */
|
|
154
|
+
function escapeCodePoint(codePoint: string): string {
|
|
155
|
+
return codePoint === "&" ? "&" : codePoint === "<" ? "<" : codePoint === ">" ? ">" : codePoint;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Escape, then split on code points so no chunk exceeds `limit` and no entity or pair is split. */
|
|
159
|
+
export function chunkSlackText(text: string, limit: number): readonly string[] {
|
|
160
|
+
const chunks: string[] = [];
|
|
161
|
+
let chunk = "";
|
|
162
|
+
for (const codePoint of text) {
|
|
163
|
+
const piece = escapeCodePoint(codePoint);
|
|
164
|
+
if (chunk.length > 0 && chunk.length + piece.length > limit) {
|
|
165
|
+
chunks.push(chunk);
|
|
166
|
+
chunk = "";
|
|
167
|
+
}
|
|
168
|
+
chunk += piece;
|
|
169
|
+
}
|
|
170
|
+
if (chunk.length) chunks.push(chunk);
|
|
171
|
+
return chunks;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function draftText(text: string): string {
|
|
175
|
+
let start = Math.max(0, text.length - SLACK_DRAFT_CODE_UNITS);
|
|
176
|
+
const code = text.charCodeAt(start);
|
|
177
|
+
if (start > 0 && code >= 0xdc00 && code <= 0xdfff) start += 1;
|
|
178
|
+
return chunkSlackText(text.slice(start), Number.MAX_SAFE_INTEGER)[0] ?? "";
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** `<team>:<channel>` is the bound conversation; only the adapter ever builds it. */
|
|
182
|
+
function destination(conversationId: string): { readonly teamId: string; readonly channel: string } | undefined {
|
|
183
|
+
const [teamId, channel, extra] = conversationId.split(":");
|
|
184
|
+
if (extra !== undefined || asId(teamId) === undefined || asId(channel) === undefined) return undefined;
|
|
185
|
+
return { teamId: teamId as string, channel: channel as string };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function commandText(text: string): string {
|
|
189
|
+
const trimmed = text.replace(/^(?:\s*<@[A-Z0-9]+>)+\s*/, "").trim();
|
|
190
|
+
return BANG_COMMAND.test(trimmed) ? `/${trimmed.slice(1)}` : trimmed;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Parse one `event_callback` body (HTTP or a Socket Mode `events_api` payload). */
|
|
194
|
+
export function parseSlackEventCallback(connectionId: string, body: unknown): ChannelInboundEvent | undefined {
|
|
195
|
+
const envelope = asRecord(body);
|
|
196
|
+
const event = asRecord(envelope?.event);
|
|
197
|
+
if (envelope?.type !== "event_callback" || event === undefined) return undefined;
|
|
198
|
+
const eventId = asId(envelope.event_id);
|
|
199
|
+
const teamId = asId(envelope.team_id) ?? asId(event.team);
|
|
200
|
+
// The bot's own messages and every edit, join, or file share carry `bot_id` or a `subtype`.
|
|
201
|
+
if (eventId === undefined || teamId === undefined || event.bot_id !== undefined || event.subtype !== undefined) return undefined;
|
|
202
|
+
const isMention = event.type === "app_mention";
|
|
203
|
+
const isDirect = event.type === "message" && event.channel_type === "im";
|
|
204
|
+
if (!isMention && !isDirect) return undefined;
|
|
205
|
+
const user = asId(event.user);
|
|
206
|
+
const channel = asId(event.channel);
|
|
207
|
+
const ts = asTs(event.ts);
|
|
208
|
+
if (user === undefined || channel === undefined || ts === undefined || typeof event.text !== "string") return undefined;
|
|
209
|
+
const text = commandText(event.text);
|
|
210
|
+
if (text.length === 0) return undefined;
|
|
211
|
+
// A mention starts (or continues) a thread on the mentioning message; a DM threads only when the user did.
|
|
212
|
+
const threadId = isMention ? (asTs(event.thread_ts) ?? ts) : asTs(event.thread_ts);
|
|
213
|
+
return {
|
|
214
|
+
connectionId,
|
|
215
|
+
externalConversationId: `${teamId}:${channel}`,
|
|
216
|
+
externalActorId: `${teamId}:${user}`,
|
|
217
|
+
eventId,
|
|
218
|
+
text,
|
|
219
|
+
...(threadId === undefined ? {} : { threadId }),
|
|
220
|
+
receivedAt: new Date().toISOString(),
|
|
221
|
+
claims: { platform: "slack", teamId, channelType: isDirect ? "im" : "channel", eventType: String(event.type) },
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Parse one `block_actions` payload whose value is a server-issued approval or host-UI control. */
|
|
226
|
+
export function parseSlackBlockActions(connectionId: string, body: unknown): ChannelInboundEvent | undefined {
|
|
227
|
+
const payload = asRecord(body);
|
|
228
|
+
if (payload?.type !== "block_actions") return undefined;
|
|
229
|
+
const user = asRecord(payload.user);
|
|
230
|
+
const container = asRecord(payload.container);
|
|
231
|
+
const message = asRecord(payload.message);
|
|
232
|
+
const action = Array.isArray(payload.actions) && payload.actions.length === 1 ? asRecord(payload.actions[0]) : undefined;
|
|
233
|
+
const userId = asId(user?.id);
|
|
234
|
+
const teamId = asId(asRecord(payload.team)?.id) ?? asId(user?.team_id);
|
|
235
|
+
const channel = asId(asRecord(payload.channel)?.id) ?? asId(container?.channel_id);
|
|
236
|
+
const messageTs = asTs(container?.message_ts);
|
|
237
|
+
const actionTs = asTs(action?.action_ts);
|
|
238
|
+
const value = typeof action?.value === "string" ? action.value : undefined;
|
|
239
|
+
if (
|
|
240
|
+
userId === undefined ||
|
|
241
|
+
teamId === undefined ||
|
|
242
|
+
channel === undefined ||
|
|
243
|
+
messageTs === undefined ||
|
|
244
|
+
actionTs === undefined ||
|
|
245
|
+
value === undefined
|
|
246
|
+
) {
|
|
247
|
+
return undefined;
|
|
248
|
+
}
|
|
249
|
+
const uiMatch = /^q:([A-Za-z0-9_-]{43}):([0-7])$/.exec(value);
|
|
250
|
+
const match = /^p:([ad]):([A-Za-z0-9_-]{32,64})$/.exec(value);
|
|
251
|
+
if (uiMatch === null && match === null) return undefined;
|
|
252
|
+
const parent = asTs(container?.thread_ts) ?? asTs(message?.thread_ts);
|
|
253
|
+
// A thread parent reports its own ts as `thread_ts`; only a reply belongs to a thread.
|
|
254
|
+
const threadId = parent !== undefined && parent !== messageTs ? parent : undefined;
|
|
255
|
+
return {
|
|
256
|
+
connectionId,
|
|
257
|
+
externalConversationId: `${teamId}:${channel}`,
|
|
258
|
+
externalActorId: `${teamId}:${userId}`,
|
|
259
|
+
eventId: `${messageTs}:${actionTs}:${userId}`,
|
|
260
|
+
text: uiMatch ? `/answer ${uiMatch[1]} ${uiMatch[2]}` : "",
|
|
261
|
+
...(match
|
|
262
|
+
? { approval: { token: match[2] as string, outcome: match[1] === "a" ? ("allow_once" as const) : ("reject_once" as const) } }
|
|
263
|
+
: {}),
|
|
264
|
+
...(threadId === undefined ? {} : { threadId }),
|
|
265
|
+
receivedAt: new Date().toISOString(),
|
|
266
|
+
claims: { platform: "slack", teamId, control: "approval" },
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function parsePayload(connectionId: string, body: unknown): ChannelInboundEvent | undefined {
|
|
271
|
+
return parseSlackEventCallback(connectionId, body) ?? parseSlackBlockActions(connectionId, body);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function actionsBlock(controls: readonly ChannelReplyControl[] | undefined): Record<string, unknown> | null | undefined {
|
|
275
|
+
if (controls === undefined) return undefined;
|
|
276
|
+
if (controls.length === 0 || controls.length > 8) return null;
|
|
277
|
+
const elements: Record<string, unknown>[] = [];
|
|
278
|
+
for (const [index, control] of controls.entries()) {
|
|
279
|
+
if (
|
|
280
|
+
typeof control?.label !== "string" ||
|
|
281
|
+
typeof control.value !== "string" ||
|
|
282
|
+
control.label.length === 0 ||
|
|
283
|
+
control.label.length > 75 ||
|
|
284
|
+
control.value.length > 2000
|
|
285
|
+
) {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
elements.push({
|
|
289
|
+
type: "button",
|
|
290
|
+
action_id: `prism_${index}`,
|
|
291
|
+
text: { type: "plain_text", text: control.label, emoji: false },
|
|
292
|
+
value: control.value,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
return { type: "actions", elements };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function knownSendFailure(error: SlackApiError): string {
|
|
299
|
+
if (error.status === 429 || error.error === "ratelimited") return "slack_rate_limited";
|
|
300
|
+
if (error.kind === "credential" || ["invalid_auth", "not_authed", "token_revoked", "account_inactive"].includes(error.error ?? ""))
|
|
301
|
+
return "slack_unauthorized";
|
|
302
|
+
if (["not_in_channel", "channel_not_found", "is_archived", "restricted_action"].includes(error.error ?? "")) return "slack_forbidden";
|
|
303
|
+
return "slack_api_error";
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
307
|
+
return new Promise((resolve) => {
|
|
308
|
+
if (signal.aborted) return resolve();
|
|
309
|
+
const timer = setTimeout(done, ms);
|
|
310
|
+
function done() {
|
|
311
|
+
clearTimeout(timer);
|
|
312
|
+
signal.removeEventListener("abort", done);
|
|
313
|
+
resolve();
|
|
314
|
+
}
|
|
315
|
+
signal.addEventListener("abort", done, { once: true });
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function readBody(body: ReadableStream<Uint8Array> | null, maxBytes: number): Promise<Buffer> {
|
|
320
|
+
const reader = body?.getReader();
|
|
321
|
+
if (reader === undefined) return Buffer.alloc(0);
|
|
322
|
+
const chunks: Uint8Array[] = [];
|
|
323
|
+
let size = 0;
|
|
324
|
+
try {
|
|
325
|
+
for (;;) {
|
|
326
|
+
const next = await reader.read();
|
|
327
|
+
if (next.done) break;
|
|
328
|
+
size += next.value.byteLength;
|
|
329
|
+
if (size > maxBytes) {
|
|
330
|
+
await reader.cancel();
|
|
331
|
+
throw new RangeError("body too large");
|
|
332
|
+
}
|
|
333
|
+
chunks.push(next.value);
|
|
334
|
+
}
|
|
335
|
+
} finally {
|
|
336
|
+
reader.releaseLock();
|
|
337
|
+
}
|
|
338
|
+
return Buffer.concat(chunks);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
interface SlackApi {
|
|
342
|
+
call(method: string, body: Record<string, unknown>, signal: AbortSignal, token?: ChannelSecretSource): Promise<Record<string, unknown>>;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function slackApi(options: {
|
|
346
|
+
botToken: ChannelSecretSource;
|
|
347
|
+
apiOrigin?: string;
|
|
348
|
+
fetch?: typeof globalThis.fetch;
|
|
349
|
+
maxResponseBytes: number;
|
|
350
|
+
}): SlackApi {
|
|
351
|
+
const origin = apiOrigin(options.apiOrigin);
|
|
352
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
353
|
+
return {
|
|
354
|
+
async call(method, body, signal, token = options.botToken) {
|
|
355
|
+
let secret: string;
|
|
356
|
+
try {
|
|
357
|
+
secret = await token();
|
|
358
|
+
} catch {
|
|
359
|
+
throw new SlackApiError({ kind: "credential" });
|
|
360
|
+
}
|
|
361
|
+
if (!secret || Buffer.byteLength(secret, "utf8") > 1024) throw new SlackApiError({ kind: "credential" });
|
|
362
|
+
let response: Response;
|
|
363
|
+
try {
|
|
364
|
+
response = await fetcher(`${origin}/api/${method}`, {
|
|
365
|
+
method: "POST",
|
|
366
|
+
headers: { authorization: `Bearer ${secret}`, "content-type": "application/json; charset=utf-8" },
|
|
367
|
+
body: JSON.stringify(body),
|
|
368
|
+
redirect: "error",
|
|
369
|
+
signal,
|
|
370
|
+
});
|
|
371
|
+
} catch {
|
|
372
|
+
throw new SlackApiError({ kind: "network" });
|
|
373
|
+
}
|
|
374
|
+
if (response.status === 429) {
|
|
375
|
+
const seconds = Number(response.headers.get("retry-after"));
|
|
376
|
+
await response.body?.cancel().catch(() => undefined);
|
|
377
|
+
throw new SlackApiError({
|
|
378
|
+
kind: "api",
|
|
379
|
+
status: 429,
|
|
380
|
+
retryAfter: Number.isFinite(seconds) && seconds >= 0 ? Math.min(seconds, MAX_RETRY_AFTER_SECONDS) : 1,
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
let payload: Record<string, unknown> | undefined;
|
|
384
|
+
try {
|
|
385
|
+
payload = asRecord(JSON.parse((await readBody(response.body, options.maxResponseBytes)).toString("utf8")));
|
|
386
|
+
} catch {
|
|
387
|
+
throw new SlackApiError({ kind: "response", status: response.status });
|
|
388
|
+
}
|
|
389
|
+
if (!response.ok || payload?.ok !== true) {
|
|
390
|
+
const error = typeof payload?.error === "string" && /^[a-z_]{1,64}$/.test(payload.error) ? payload.error : undefined;
|
|
391
|
+
throw new SlackApiError({ kind: "api", status: response.status, ...(error === undefined ? {} : { error }) });
|
|
392
|
+
}
|
|
393
|
+
return payload;
|
|
394
|
+
},
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
interface Preview {
|
|
399
|
+
readonly channel: string;
|
|
400
|
+
readonly threadTs?: string;
|
|
401
|
+
ts?: string;
|
|
402
|
+
text?: string;
|
|
403
|
+
lastAt: number;
|
|
404
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
405
|
+
inFlight?: Promise<void>;
|
|
406
|
+
closed: boolean;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function previewKey(conversationId: string, threadId: string | undefined): string {
|
|
410
|
+
return `${conversationId}\u0000${threadId ?? ""}`;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Creates the Slack adapter. `start` opens Socket Mode (it needs `appToken`); the Events API path is
|
|
415
|
+
* `handleRequest`, which the host mounts. Neither path holds a receiver lease: Slack fans one event
|
|
416
|
+
* to one acknowledged receiver, and the runtime deduplicates by event id.
|
|
417
|
+
*/
|
|
418
|
+
export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
|
|
419
|
+
if (
|
|
420
|
+
typeof options.connectionId !== "string" ||
|
|
421
|
+
options.connectionId.length === 0 ||
|
|
422
|
+
Buffer.byteLength(options.connectionId, "utf8") > 256
|
|
423
|
+
) {
|
|
424
|
+
throw new TypeError("Slack connectionId must be a bounded non-empty string");
|
|
425
|
+
}
|
|
426
|
+
if (typeof options.botToken !== "function") throw new TypeError("Slack botToken must be a secret source, not a literal");
|
|
427
|
+
if (options.appToken !== undefined && typeof options.appToken !== "function")
|
|
428
|
+
throw new TypeError("Slack appToken must be a secret source, not a literal");
|
|
429
|
+
const maxRequestBytes = boundedInteger(options.maxRequestBytes, DEFAULT_MAX_REQUEST_BYTES, 1024, "maxRequestBytes");
|
|
430
|
+
const draftIntervalMs = boundedInteger(options.draftIntervalMs, DEFAULT_DRAFT_INTERVAL_MS, 100, "draftIntervalMs");
|
|
431
|
+
const api = slackApi({
|
|
432
|
+
botToken: options.botToken,
|
|
433
|
+
apiOrigin: options.apiOrigin,
|
|
434
|
+
fetch: options.fetch,
|
|
435
|
+
maxResponseBytes: maxRequestBytes,
|
|
436
|
+
});
|
|
437
|
+
const openSocket = options.webSocket ?? ((url: string) => new WebSocket(url) as unknown as SlackSocket);
|
|
438
|
+
const connectionId = options.connectionId;
|
|
439
|
+
const sendDrafts = options.sendDrafts === true;
|
|
440
|
+
const previews = new Map<string, Preview>();
|
|
441
|
+
let controller: AbortController | undefined;
|
|
442
|
+
let socket: SlackSocket | undefined;
|
|
443
|
+
let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
|
|
444
|
+
let reconnectAttempts = 0;
|
|
445
|
+
let started = false;
|
|
446
|
+
let stopped = false;
|
|
447
|
+
|
|
448
|
+
function signal(): AbortSignal {
|
|
449
|
+
return controller?.signal ?? new AbortController().signal;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Waits out `Retry-After` and retries a send Slack refused before accepting it. */
|
|
453
|
+
async function postMessage(body: Record<string, unknown>, abort: AbortSignal): Promise<Record<string, unknown>> {
|
|
454
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
455
|
+
try {
|
|
456
|
+
return await api.call("chat.postMessage", body, abort);
|
|
457
|
+
} catch (error) {
|
|
458
|
+
if (!(error instanceof SlackApiError) || error.retryAfter === undefined || attempt >= MAX_SEND_ATTEMPTS || abort.aborted)
|
|
459
|
+
throw error;
|
|
460
|
+
await delay(error.retryAfter * 1000, abort);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function schedulePreview(preview: Preview): void {
|
|
466
|
+
if (preview.timer !== undefined || preview.inFlight !== undefined || preview.closed || preview.text === undefined) return;
|
|
467
|
+
const wait = Math.max(0, preview.lastAt + draftIntervalMs - Date.now());
|
|
468
|
+
preview.timer = setTimeout(() => {
|
|
469
|
+
preview.timer = undefined;
|
|
470
|
+
flushPreview(preview);
|
|
471
|
+
}, wait);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function flushPreview(preview: Preview): void {
|
|
475
|
+
const text = preview.text;
|
|
476
|
+
if (preview.closed || stopped || text === undefined) return;
|
|
477
|
+
preview.text = undefined;
|
|
478
|
+
preview.lastAt = Date.now();
|
|
479
|
+
preview.inFlight = (async () => {
|
|
480
|
+
try {
|
|
481
|
+
if (preview.ts === undefined) {
|
|
482
|
+
const result = await api.call(
|
|
483
|
+
"chat.postMessage",
|
|
484
|
+
{
|
|
485
|
+
channel: preview.channel,
|
|
486
|
+
text,
|
|
487
|
+
unfurl_links: false,
|
|
488
|
+
unfurl_media: false,
|
|
489
|
+
...(preview.threadTs === undefined ? {} : { thread_ts: preview.threadTs }),
|
|
490
|
+
},
|
|
491
|
+
signal(),
|
|
492
|
+
);
|
|
493
|
+
preview.ts = asTs(result.ts);
|
|
494
|
+
} else {
|
|
495
|
+
await api.call("chat.update", { channel: preview.channel, ts: preview.ts, text }, signal());
|
|
496
|
+
}
|
|
497
|
+
} catch {
|
|
498
|
+
// A preview is best effort: a refused or rate-limited write is dropped, never retried.
|
|
499
|
+
}
|
|
500
|
+
})().finally(() => {
|
|
501
|
+
preview.inFlight = undefined;
|
|
502
|
+
schedulePreview(preview);
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** Stops one conversation's preview and deletes its message once the reply has landed. */
|
|
507
|
+
async function closePreview(key: string): Promise<void> {
|
|
508
|
+
const preview = previews.get(key);
|
|
509
|
+
if (preview === undefined) return;
|
|
510
|
+
previews.delete(key);
|
|
511
|
+
preview.closed = true;
|
|
512
|
+
if (preview.timer !== undefined) clearTimeout(preview.timer);
|
|
513
|
+
await preview.inFlight;
|
|
514
|
+
if (preview.ts === undefined) return;
|
|
515
|
+
try {
|
|
516
|
+
await api.call("chat.delete", { channel: preview.channel, ts: preview.ts }, signal());
|
|
517
|
+
} catch {
|
|
518
|
+
// Best effort: a preview that cannot be deleted stays as an earlier partial answer.
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
async function dispatch(receive: ChannelReceive, body: unknown): Promise<"ack" | "retry"> {
|
|
523
|
+
const event = parsePayload(connectionId, body);
|
|
524
|
+
if (event === undefined) return "ack";
|
|
525
|
+
return retryableAdmission(await receive(event)) ? "retry" : "ack";
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
async function onSocketFrame(current: SlackSocket, receive: ChannelReceive, data: unknown): Promise<void> {
|
|
529
|
+
const raw =
|
|
530
|
+
typeof data === "string"
|
|
531
|
+
? data
|
|
532
|
+
: data instanceof ArrayBuffer || ArrayBuffer.isView(data)
|
|
533
|
+
? Buffer.from(data as ArrayBuffer).toString("utf8")
|
|
534
|
+
: undefined;
|
|
535
|
+
if (raw === undefined || Buffer.byteLength(raw, "utf8") > maxRequestBytes) return;
|
|
536
|
+
let frame: Record<string, unknown> | undefined;
|
|
537
|
+
try {
|
|
538
|
+
frame = asRecord(JSON.parse(raw));
|
|
539
|
+
} catch {
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (frame?.type === "hello") {
|
|
543
|
+
reconnectAttempts = 0;
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
if (frame?.type === "disconnect") {
|
|
547
|
+
current.close(4000, "disconnect requested");
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
const envelopeId = typeof frame?.envelope_id === "string" && frame.envelope_id.length <= 128 ? frame.envelope_id : undefined;
|
|
551
|
+
if (envelopeId === undefined) return;
|
|
552
|
+
let outcome: "ack" | "retry" = "ack";
|
|
553
|
+
try {
|
|
554
|
+
if (frame?.type === "events_api" || frame?.type === "interactive") outcome = await dispatch(receive, frame.payload);
|
|
555
|
+
} catch {
|
|
556
|
+
outcome = "retry";
|
|
557
|
+
}
|
|
558
|
+
// An unacknowledged envelope is redelivered by Slack, so a retryable admission stays unacked.
|
|
559
|
+
if (outcome === "ack" && !stopped) {
|
|
560
|
+
try {
|
|
561
|
+
current.send(JSON.stringify({ envelope_id: envelopeId }));
|
|
562
|
+
} catch {
|
|
563
|
+
// The socket closed under us; Slack redelivers the envelope on the next connection.
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
async function connectSocket(receive: ChannelReceive): Promise<void> {
|
|
569
|
+
const appToken = options.appToken;
|
|
570
|
+
if (appToken === undefined) throw new Error("Slack Socket Mode needs an appToken");
|
|
571
|
+
let url: string;
|
|
572
|
+
try {
|
|
573
|
+
const opened = await api.call("apps.connections.open", {}, signal(), appToken);
|
|
574
|
+
url = typeof opened.url === "string" ? opened.url : "";
|
|
575
|
+
} catch {
|
|
576
|
+
throw new Error("Slack Socket Mode connection failed");
|
|
577
|
+
}
|
|
578
|
+
if (!url.startsWith("wss://")) throw new Error("Slack Socket Mode connection failed");
|
|
579
|
+
const current = openSocket(url);
|
|
580
|
+
socket = current;
|
|
581
|
+
let opened = false;
|
|
582
|
+
await new Promise<void>((resolve, reject) => {
|
|
583
|
+
const timer = setTimeout(() => {
|
|
584
|
+
reject(new Error("Slack Socket Mode connection failed"));
|
|
585
|
+
if (!opened) current.close(4000, "open timeout");
|
|
586
|
+
}, SOCKET_OPEN_TIMEOUT_MS);
|
|
587
|
+
current.addEventListener("open", () => {
|
|
588
|
+
clearTimeout(timer);
|
|
589
|
+
opened = true;
|
|
590
|
+
resolve();
|
|
591
|
+
});
|
|
592
|
+
current.addEventListener("error", () => {
|
|
593
|
+
clearTimeout(timer);
|
|
594
|
+
reject(new Error("Slack Socket Mode connection failed"));
|
|
595
|
+
});
|
|
596
|
+
current.addEventListener("message", (event) => {
|
|
597
|
+
void onSocketFrame(current, receive, event.data);
|
|
598
|
+
});
|
|
599
|
+
current.addEventListener("close", () => {
|
|
600
|
+
clearTimeout(timer);
|
|
601
|
+
reject(new Error("Slack Socket Mode connection failed"));
|
|
602
|
+
if (socket === current) socket = undefined;
|
|
603
|
+
// Only a connection that opened reconnects; a failed first `start` reports its error instead.
|
|
604
|
+
if (opened && !stopped && socket === undefined) scheduleReconnect(receive);
|
|
605
|
+
});
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function scheduleReconnect(receive: ChannelReceive): void {
|
|
610
|
+
if (stopped || reconnectTimer !== undefined) return;
|
|
611
|
+
const wait = Math.min(MAX_RECONNECT_DELAY_MS, 1000 * 2 ** reconnectAttempts);
|
|
612
|
+
reconnectAttempts += 1;
|
|
613
|
+
reconnectTimer = setTimeout(() => {
|
|
614
|
+
reconnectTimer = undefined;
|
|
615
|
+
connectSocket(receive).catch(() => scheduleReconnect(receive));
|
|
616
|
+
}, wait);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
return {
|
|
620
|
+
connectionId,
|
|
621
|
+
capabilities: { acknowledgement: "deadline", controls: "callback", maxTextCodeUnits: SLACK_TEXT_CODE_UNITS },
|
|
622
|
+
async start(receive) {
|
|
623
|
+
if (stopped) throw new Error("Slack adapter is stopped");
|
|
624
|
+
if (started) throw new Error("Slack adapter is already started");
|
|
625
|
+
started = true;
|
|
626
|
+
controller = new AbortController();
|
|
627
|
+
try {
|
|
628
|
+
await connectSocket(receive);
|
|
629
|
+
} catch (error) {
|
|
630
|
+
started = false;
|
|
631
|
+
throw error;
|
|
632
|
+
}
|
|
633
|
+
},
|
|
634
|
+
async send(reply) {
|
|
635
|
+
const target = reply.connectionId === connectionId ? destination(reply.externalConversationId) : undefined;
|
|
636
|
+
if (target === undefined) return { delivered: false, reason: "invalid_destination" };
|
|
637
|
+
const threadTs = reply.threadId === undefined ? undefined : asTs(reply.threadId);
|
|
638
|
+
if (reply.threadId !== undefined && threadTs === undefined) return { delivered: false, reason: "invalid_destination" };
|
|
639
|
+
const actions = actionsBlock(reply.controls);
|
|
640
|
+
if (actions === null) return { delivered: false, reason: "invalid_controls" };
|
|
641
|
+
const chunks = chunkSlackText(reply.text, actions === undefined ? SLACK_TEXT_CODE_UNITS : SLACK_SECTION_CODE_UNITS);
|
|
642
|
+
if (chunks.length === 0) return { delivered: false, reason: "empty_reply" };
|
|
643
|
+
const abort = signal();
|
|
644
|
+
let messageId: string | undefined;
|
|
645
|
+
let sent = false;
|
|
646
|
+
try {
|
|
647
|
+
for (const [index, text] of chunks.entries()) {
|
|
648
|
+
const last = index + 1 === chunks.length;
|
|
649
|
+
const result = await postMessage(
|
|
650
|
+
{
|
|
651
|
+
channel: target.channel,
|
|
652
|
+
text,
|
|
653
|
+
unfurl_links: false,
|
|
654
|
+
unfurl_media: false,
|
|
655
|
+
...(threadTs === undefined ? {} : { thread_ts: threadTs }),
|
|
656
|
+
...(last && actions !== undefined ? { blocks: [{ type: "section", text: { type: "mrkdwn", text } }, actions] } : {}),
|
|
657
|
+
},
|
|
658
|
+
abort,
|
|
659
|
+
);
|
|
660
|
+
messageId = asTs(result.ts) ?? messageId;
|
|
661
|
+
sent = true;
|
|
662
|
+
}
|
|
663
|
+
} catch (error) {
|
|
664
|
+
// A network error, or any failure after a chunk landed, cannot prove non-delivery.
|
|
665
|
+
if (sent || !(error instanceof SlackApiError) || error.kind === "network" || error.kind === "response")
|
|
666
|
+
throw new SlackDeliveryUnknownError();
|
|
667
|
+
return { delivered: false, reason: knownSendFailure(error) };
|
|
668
|
+
}
|
|
669
|
+
await closePreview(previewKey(reply.externalConversationId, reply.threadId));
|
|
670
|
+
return { delivered: true, ...(messageId === undefined ? {} : { messageId }) };
|
|
671
|
+
},
|
|
672
|
+
async stop() {
|
|
673
|
+
stopped = true;
|
|
674
|
+
if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);
|
|
675
|
+
reconnectTimer = undefined;
|
|
676
|
+
const current = socket;
|
|
677
|
+
socket = undefined;
|
|
678
|
+
try {
|
|
679
|
+
current?.close(1000, "stopped");
|
|
680
|
+
} catch {
|
|
681
|
+
// Already closed.
|
|
682
|
+
}
|
|
683
|
+
for (const preview of previews.values()) {
|
|
684
|
+
preview.closed = true;
|
|
685
|
+
if (preview.timer !== undefined) clearTimeout(preview.timer);
|
|
686
|
+
}
|
|
687
|
+
previews.clear();
|
|
688
|
+
controller?.abort(new Error("Slack adapter stopped"));
|
|
689
|
+
},
|
|
690
|
+
sendDraft(delta) {
|
|
691
|
+
if (!sendDrafts || stopped || delta.connectionId !== connectionId) return;
|
|
692
|
+
const target = destination(delta.externalConversationId);
|
|
693
|
+
const threadTs = delta.threadId === undefined ? undefined : asTs(delta.threadId);
|
|
694
|
+
if (target === undefined || (delta.threadId !== undefined && threadTs === undefined)) return;
|
|
695
|
+
const text = draftText(delta.text);
|
|
696
|
+
if (text.trim().length === 0) return;
|
|
697
|
+
const key = previewKey(delta.externalConversationId, delta.threadId);
|
|
698
|
+
let preview = previews.get(key);
|
|
699
|
+
if (preview === undefined) {
|
|
700
|
+
if (previews.size >= MAX_PREVIEWS) return;
|
|
701
|
+
preview = { channel: target.channel, ...(threadTs === undefined ? {} : { threadTs }), lastAt: 0, closed: false };
|
|
702
|
+
previews.set(key, preview);
|
|
703
|
+
}
|
|
704
|
+
preview.text = text;
|
|
705
|
+
schedulePreview(preview);
|
|
706
|
+
},
|
|
707
|
+
async handleRequest(request, receive, signingSecret) {
|
|
708
|
+
if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
709
|
+
if (signingSecret === undefined) return new Response("Unauthorized", { status: 401 });
|
|
710
|
+
let raw: Buffer;
|
|
711
|
+
try {
|
|
712
|
+
raw = await readBody(request.body, maxRequestBytes);
|
|
713
|
+
} catch (error) {
|
|
714
|
+
return new Response(error instanceof RangeError ? "Payload too large" : "Malformed request", {
|
|
715
|
+
status: error instanceof RangeError ? 413 : 400,
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
// Verify before parsing anything: the signature covers the timestamp and the raw body.
|
|
719
|
+
const timestamp = request.headers.get("x-slack-request-timestamp") ?? "";
|
|
720
|
+
if (!/^\d{1,12}$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > SIGNATURE_WINDOW_SECONDS) {
|
|
721
|
+
return new Response("Unauthorized", { status: 401 });
|
|
722
|
+
}
|
|
723
|
+
let secret: string;
|
|
724
|
+
try {
|
|
725
|
+
secret = await signingSecret();
|
|
726
|
+
} catch {
|
|
727
|
+
return new Response("Unavailable", { status: 503 });
|
|
728
|
+
}
|
|
729
|
+
const expected = `v0=${createHmac("sha256", secret).update(`v0:${timestamp}:`).update(raw).digest("hex")}`;
|
|
730
|
+
if (!constantTimeEqual(expected, request.headers.get("x-slack-signature"))) return new Response("Unauthorized", { status: 401 });
|
|
731
|
+
let body: unknown;
|
|
732
|
+
try {
|
|
733
|
+
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
|
|
734
|
+
if (contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
735
|
+
const payload = new URLSearchParams(raw.toString("utf8")).get("payload");
|
|
736
|
+
body = payload === null ? undefined : JSON.parse(payload);
|
|
737
|
+
} else if (contentType.startsWith("application/json")) {
|
|
738
|
+
body = JSON.parse(raw.toString("utf8"));
|
|
739
|
+
} else {
|
|
740
|
+
return new Response("Unsupported media type", { status: 415 });
|
|
741
|
+
}
|
|
742
|
+
} catch {
|
|
743
|
+
return new Response("Malformed request", { status: 400 });
|
|
744
|
+
}
|
|
745
|
+
const record = asRecord(body);
|
|
746
|
+
if (record?.type === "url_verification") {
|
|
747
|
+
const challenge = typeof record.challenge === "string" && record.challenge.length <= 256 ? record.challenge : undefined;
|
|
748
|
+
return challenge === undefined ? new Response("Malformed request", { status: 400 }) : Response.json({ challenge });
|
|
749
|
+
}
|
|
750
|
+
try {
|
|
751
|
+
return (await dispatch(receive, body)) === "retry"
|
|
752
|
+
? new Response("Unavailable", { status: 503 })
|
|
753
|
+
: new Response(null, { status: 200 });
|
|
754
|
+
} catch {
|
|
755
|
+
return new Response("Unavailable", { status: 503 });
|
|
756
|
+
}
|
|
757
|
+
},
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
export interface SlackConnectOptions {
|
|
762
|
+
/** Bot token reference (`env:` or `keyring:`). A literal fails with `ChannelTokenLiteralError`. */
|
|
763
|
+
readonly token: string;
|
|
764
|
+
/** Signing secret reference for the Events API over HTTP (`handle(request)`). */
|
|
765
|
+
readonly signingSecret?: string;
|
|
766
|
+
/** App-level token reference for Socket Mode (`start()`). */
|
|
767
|
+
readonly appToken?: string;
|
|
768
|
+
/**
|
|
769
|
+
* Maps a sender (`externalActorId` = `<team>:<user>`, `claims.teamId`) to a verified grant. Without it,
|
|
770
|
+
* every event is denied: Slack never falls back to the runtime's open default.
|
|
771
|
+
*/
|
|
772
|
+
readonly authorize: (
|
|
773
|
+
input: ChannelAuthorizeInput,
|
|
774
|
+
) => ChannelAuthorization | false | undefined | Promise<ChannelAuthorization | false | undefined>;
|
|
775
|
+
readonly connectionId?: string;
|
|
776
|
+
readonly checkpoints?: CheckpointStore;
|
|
777
|
+
readonly leases?: LeaseStore;
|
|
778
|
+
readonly limits?: ChannelLimits;
|
|
779
|
+
readonly sendDrafts?: boolean;
|
|
780
|
+
readonly draftIntervalMs?: number;
|
|
781
|
+
readonly maxRequestBytes?: number;
|
|
782
|
+
readonly apiOrigin?: string;
|
|
783
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
784
|
+
readonly webSocket?: (url: string) => SlackSocket;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** Binds one agent to a Slack app over the Events API, Socket Mode, or both. */
|
|
788
|
+
export async function connectSlack(agent: Agent, options: SlackConnectOptions): Promise<ChannelConnectionHandle> {
|
|
789
|
+
if (options.signingSecret === undefined && options.appToken === undefined) {
|
|
790
|
+
throw new TypeError("connectSlack needs signingSecret (Events API) or appToken (Socket Mode)");
|
|
791
|
+
}
|
|
792
|
+
const resolvedToken = await resolveChannelSecretRef(agent, options.token);
|
|
793
|
+
const resolvedSigning = options.signingSecret === undefined ? undefined : await resolveChannelSecretRef(agent, options.signingSecret);
|
|
794
|
+
const resolvedApp = options.appToken === undefined ? undefined : await resolveChannelSecretRef(agent, options.appToken);
|
|
795
|
+
const secrets = [resolvedToken, resolvedSigning, resolvedApp].filter((value): value is string => value !== undefined);
|
|
796
|
+
const redactor = createChannelRedactor(secrets, agent.config?.redactor);
|
|
797
|
+
const connectionId = options.connectionId ?? "slack-default";
|
|
798
|
+
const checkpoints = options.checkpoints ?? createMemoryCheckpointStore();
|
|
799
|
+
const leases = options.leases ?? createMemoryLeaseStore();
|
|
800
|
+
const signingSecret: ChannelSecretSource | undefined = resolvedSigning === undefined ? undefined : async () => resolvedSigning;
|
|
801
|
+
|
|
802
|
+
const adapter = createSlackAdapter({
|
|
803
|
+
connectionId,
|
|
804
|
+
botToken: async () => resolvedToken,
|
|
805
|
+
...(resolvedApp === undefined ? {} : { appToken: async () => resolvedApp }),
|
|
806
|
+
sendDrafts: options.sendDrafts,
|
|
807
|
+
draftIntervalMs: options.draftIntervalMs,
|
|
808
|
+
maxRequestBytes: options.maxRequestBytes,
|
|
809
|
+
apiOrigin: options.apiOrigin,
|
|
810
|
+
fetch: options.fetch,
|
|
811
|
+
webSocket: options.webSocket,
|
|
812
|
+
});
|
|
813
|
+
const authorize = typeof options.authorize === "function" ? options.authorize : () => false as const;
|
|
814
|
+
const runtime = createChannelRuntime(agent, {
|
|
815
|
+
deliver: (reply) => adapter.send(reply),
|
|
816
|
+
checkpoints,
|
|
817
|
+
leases,
|
|
818
|
+
redactor,
|
|
819
|
+
authorize,
|
|
820
|
+
limits: options.limits,
|
|
821
|
+
onAssistantDelta: options.sendDrafts ? (delta) => adapter.sendDraft(delta) : undefined,
|
|
822
|
+
});
|
|
823
|
+
const receive: ChannelReceive = (event) => runtime.admit(event);
|
|
824
|
+
|
|
825
|
+
const handle: ChannelConnectionHandle = {
|
|
826
|
+
async handle(update: unknown): Promise<unknown> {
|
|
827
|
+
if (update instanceof Request) return await adapter.handleRequest(update, receive, signingSecret);
|
|
828
|
+
if (typeof update !== "object" || update === null) return undefined;
|
|
829
|
+
if ("connectionId" in update && "externalActorId" in update && "eventId" in update)
|
|
830
|
+
return await runtime.admit(update as ChannelInboundEvent);
|
|
831
|
+
const event = parsePayload(connectionId, update);
|
|
832
|
+
return event === undefined ? undefined : await runtime.admit(event);
|
|
833
|
+
},
|
|
834
|
+
async start() {
|
|
835
|
+
if (resolvedApp !== undefined) await adapter.start(receive);
|
|
836
|
+
},
|
|
837
|
+
async close() {
|
|
838
|
+
const stopping = runtime.stop();
|
|
839
|
+
try {
|
|
840
|
+
await adapter.stop();
|
|
841
|
+
} finally {
|
|
842
|
+
await stopping;
|
|
843
|
+
}
|
|
844
|
+
},
|
|
845
|
+
async stop() {
|
|
846
|
+
await handle.close();
|
|
847
|
+
},
|
|
848
|
+
async drain(opts) {
|
|
849
|
+
return await runtime.drain(opts);
|
|
850
|
+
},
|
|
851
|
+
};
|
|
852
|
+
bindChannelHostUi(handle, runtime, connectionId);
|
|
853
|
+
return handle;
|
|
854
|
+
}
|