omp-superagent 0.0.0-stage → 0.1.1

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 (76) hide show
  1. package/DESIGN.md +1361 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +184 -0
  4. package/README.md +205 -2
  5. package/THIRD_PARTY_NOTICES.md +313 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1030 -0
  12. package/docs/releases/0.1.0.md +222 -0
  13. package/docs/releases/0.1.1.md +60 -0
  14. package/package.json +59 -4
  15. package/scripts/check-omp.ts +4 -0
  16. package/scripts/ci.ts +28 -0
  17. package/scripts/prepare-ulw.ts +18 -0
  18. package/scripts/release.ts +50 -0
  19. package/scripts/setup.sh +25 -0
  20. package/skills/head/SKILL.md +259 -0
  21. package/skills/head/references/model-selection.md +263 -0
  22. package/skills/head/references/routing.md +356 -0
  23. package/skills/head/references/supervision.md +312 -0
  24. package/skills/lane/SKILL.md +188 -0
  25. package/skills/lane/references/workflow.md +349 -0
  26. package/src/autostart.ts +295 -0
  27. package/src/board-extension.ts +217 -0
  28. package/src/board.ts +396 -0
  29. package/src/cli.ts +167 -0
  30. package/src/config.ts +191 -0
  31. package/src/contracts.ts +317 -0
  32. package/src/credentials.ts +172 -0
  33. package/src/delivery.ts +7 -0
  34. package/src/dialog.ts +73 -0
  35. package/src/discord-command-registration.ts +201 -0
  36. package/src/discord-commands.ts +29 -0
  37. package/src/discord-markdown.ts +172 -0
  38. package/src/discord.ts +745 -0
  39. package/src/extension.ts +289 -0
  40. package/src/gateway-client.ts +222 -0
  41. package/src/gateway-protocol.ts +85 -0
  42. package/src/gateway-restart.ts +151 -0
  43. package/src/gateway-server.ts +392 -0
  44. package/src/gateway-store.ts +237 -0
  45. package/src/gateway.ts +638 -0
  46. package/src/head-recovery.ts +61 -0
  47. package/src/host-extension.ts +449 -0
  48. package/src/host-owner.ts +350 -0
  49. package/src/host-protocol.ts +136 -0
  50. package/src/host.ts +414 -0
  51. package/src/installed-omp.ts +63 -0
  52. package/src/lane-extension.ts +179 -0
  53. package/src/lane-models.ts +75 -0
  54. package/src/lane-report.ts +70 -0
  55. package/src/managed-ulw-probe.ts +172 -0
  56. package/src/managed-ulw.ts +471 -0
  57. package/src/message-order.ts +21 -0
  58. package/src/messenger-commands.ts +16 -0
  59. package/src/messengers.ts +114 -0
  60. package/src/native-presets.ts +282 -0
  61. package/src/native-sessions.ts +32 -0
  62. package/src/native-settings.ts +129 -0
  63. package/src/repository.ts +12 -0
  64. package/src/runtime.ts +3864 -0
  65. package/src/setup-judge.ts +34 -0
  66. package/src/setup-memory.ts +39 -0
  67. package/src/setup-profiles.ts +84 -0
  68. package/src/setup.ts +300 -0
  69. package/src/slack-command-registration.ts +217 -0
  70. package/src/slack-commands.ts +18 -0
  71. package/src/slack.ts +776 -0
  72. package/src/store.ts +806 -0
  73. package/src/telegram-command-registration.ts +155 -0
  74. package/src/telegram.ts +661 -0
  75. package/src/workflow.ts +94 -0
  76. package/upstream/ulw.json +9 -0
package/src/slack.ts ADDED
@@ -0,0 +1,776 @@
1
+ import { createHash } from "node:crypto";
2
+ import { LogLevel, WebClient, type WebClientOptions } from "@slack/web-api";
3
+ import { SocketModeClient } from "@slack/socket-mode";
4
+ import { physicalRoute, physicalRouteKey, routeKey, type Approval, type Attachment, type DialogResponse, type Inbound, type MessageActivity, type MessageReference, type Messenger, type OutputRecord, type Route } from "./contracts.ts";
5
+ import { parseDialog, type Dialog } from "./dialog.ts";
6
+ import { DeliveryError } from "./delivery.ts";
7
+ import { compareMessageIds } from "./message-order.ts";
8
+ import { parseSlackCommand } from "./slack-commands.ts";
9
+
10
+ type RecordValue = Record<string, unknown>;
11
+ type Handlers = Parameters<Messenger["start"]>[0];
12
+ type Socket = Pick<SocketModeClient, "on" | "off" | "start" | "disconnect">;
13
+ type Http = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
14
+ type Envelope = { type: string; envelope_id?: string; body: RecordValue; accepts_response_payload?: boolean; ack(response?: unknown): Promise<void> };
15
+ type Block = RecordValue;
16
+ type Answer = NonNullable<DialogResponse["answers"]>[number];
17
+ interface Pending {
18
+ approval: Approval; token: string; dialog: Dialog; messageId: string | null;
19
+ active: boolean; question: number; answers: Answer[];
20
+ selected: string[]; customInput?: string;
21
+ modal?: { id: string; metadata: string; action: string };
22
+ }
23
+
24
+ export interface SlackMessengerOptions {
25
+ botToken: string;
26
+ appToken: string;
27
+ ownerId: string;
28
+ teamId: string;
29
+ allowedChannelIds: string[];
30
+ onError?: (error: unknown) => void;
31
+ /** Supported WebClient HTTP boundary; retry and logging safety are not overridable. */
32
+ webClientOptions?: Pick<WebClientOptions, "fetch" | "slackApiUrl">;
33
+ /** Official SocketModeClient, or a deterministic SDK event boundary in tests. */
34
+ socket?: Socket;
35
+ /** External upload/download HTTP boundary; never used for Socket Mode bootstrap. */
36
+ fetch?: Http;
37
+ }
38
+
39
+ const FILE_LIMIT = 8 * 1024 * 1024;
40
+ const TEXT_LIMIT = 3000;
41
+ const object = (value: unknown): value is RecordValue => !!value && typeof value === "object" && !Array.isArray(value);
42
+ const string = (value: unknown): value is string => typeof value === "string";
43
+ const timestamp = (value: unknown): value is string => string(value) && /^[0-9]{1,20}\.[0-9]{6}$/.test(value);
44
+ const slackId = (value: unknown): value is string => string(value) && /^[A-Z][A-Z0-9]+$/.test(value);
45
+ const hash = (value: string): string => createHash("sha256").update(value).digest("hex").slice(0, 24);
46
+ const plain = (value: string) => ({ type: "plain_text", text: value || "(empty)", emoji: false });
47
+ const escapeText = (value: string): string => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
48
+ // Slack reserves leading slash commands in its composer. These are ordinary
49
+ // authenticated owner messages, sharing the runtime's existing command parser,
50
+ // including the head's bare query and argument forms of /model, /effort, /stop,
51
+ // /compact, and the rest of the ordinary-text command surface.
52
+ // Only an exact first token converts; lookalikes such as "!models" stay plain text.
53
+ const controlText = (value: string): string => value.replace(/^!(new|main|stop|restart|resume|resolve|model|effort|help|status|context|compact|usage)(?=$|\s)/, "/$1");
54
+ const tokenFor = (approval: Approval): string => hash(JSON.stringify([approval.id, approval.generation, approval.target, approval.requestId, routeKey(approval.route)]));
55
+ const compare = (left: string, right: string): number => {
56
+ const result = compareMessageIds("slack", left, right);
57
+ if (result === null) throw new DeliveryError("Invalid Slack message timestamp", "rejected");
58
+ return result;
59
+ };
60
+
61
+ /** SDK exceptions may contain request headers, payloads, or signed URLs. Never retain their cause. */
62
+ function failure(error: unknown): DeliveryError {
63
+ if (error instanceof DeliveryError) return error;
64
+ const record = object(error) ? error : {};
65
+ const data = object(record.data) ? record.data : {};
66
+ const code = string(data.error) && /^[a-z_]+$/.test(data.error) ? data.error : undefined;
67
+ const retryAfter = typeof record.retryAfter === "number" && Number.isFinite(record.retryAfter) ? Math.max(0, record.retryAfter * 1000) : undefined;
68
+ if (record.code === "slack_webapi_rate_limited_error") return new DeliveryError("Slack request rate limited", "rejected", retryAfter);
69
+ if (record.code === "slack_webapi_platform_error" && code) {
70
+ const uncertain = ["internal_error", "fatal_error", "request_timeout", "service_unavailable"].includes(code);
71
+ return new DeliveryError(`Slack API rejected request: ${code}`, uncertain ? "uncertain" : "rejected");
72
+ }
73
+ const status = typeof record.statusCode === "number" ? record.statusCode : undefined;
74
+ return new DeliveryError("Slack transport failed", status && status >= 400 && status < 500 && status !== 408 ? "rejected" : "uncertain");
75
+ }
76
+
77
+ function sections(text: string): Block[] {
78
+ const chunks: string[] = [];
79
+ // Split only at Unicode code-point boundaries. No user text is ever interpreted as mrkdwn.
80
+ let chunk = "";
81
+ for (const point of text || "(empty)") {
82
+ if (chunk.length + point.length > TEXT_LIMIT) { chunks.push(chunk); chunk = ""; }
83
+ chunk += point;
84
+ }
85
+ chunks.push(chunk);
86
+ return chunks.map(value => ({ type: "section", text: plain(value) }));
87
+ }
88
+
89
+ /** Official WebClient/SocketMode SDKs own HTTP and WebSocket protocol handling. */
90
+ export class SlackMessenger implements Messenger {
91
+ readonly client: WebClient;
92
+ readonly socket: Socket;
93
+ private accountId: string | null = null;
94
+ private botUserId: string | null = null;
95
+ private botId: string | null = null;
96
+ private appId: string | null = null;
97
+ private socketAppId: string | null = null;
98
+ private handlers: Handlers | null = null;
99
+ private connected = false;
100
+ private intake: Promise<void> = Promise.resolve();
101
+ private stopSignal = Promise.withResolvers<void>();
102
+ private ready: Promise<boolean> = Promise.resolve(false);
103
+ private readonly interactions = new Set<Promise<void>>();
104
+ private readonly interactionQueues = new Map<string, Promise<void>>();
105
+ private readonly interactionReceipts = new Map<string, Map<string, Promise<void>>>();
106
+ private readonly pending = new Map<string, Pending>();
107
+ private readonly channels: Set<string>;
108
+ private readonly http: Http;
109
+ private readonly report: (error: unknown) => void;
110
+ private readonly onEnvelope = (envelope: Envelope) => {
111
+ if (!this.appId || this.socketAppId !== this.appId) return;
112
+ if (envelope.type === "interactive") {
113
+ const task = this.queueInteraction(envelope).catch(error => this.report(failure(error)));
114
+ this.interactions.add(task);
115
+ void task.finally(() => { this.interactions.delete(task); });
116
+ return;
117
+ }
118
+ this.intake = this.intake.then(async () => { if (await this.ready) await this.receive(envelope); }).catch(error => this.report(failure(error)));
119
+ };
120
+ private readonly onConnected = () => {
121
+ if (!this.connected) return;
122
+ this.intake = this.intake.then(async () => { if (await this.ready && this.socketAppId === this.appId) await this.handlers?.reconnect?.(); }).catch(error => this.report(failure(error)));
123
+ };
124
+ private readonly onWireMessage = (data: unknown, isBinary: boolean) => {
125
+ if (isBinary || !string(data)) return;
126
+ let value: unknown;
127
+ try { value = JSON.parse(data); } catch { return; }
128
+ if (!object(value) || value.type !== "hello") return;
129
+ this.socketAppId = object(value.connection_info) && slackId(value.connection_info.app_id) ? value.connection_info.app_id : null;
130
+ if (this.socketAppId !== this.appId) this.report(new Error("Slack Socket Mode application does not match the authenticated bot"));
131
+ };
132
+ private readonly onConnecting = () => { this.socketAppId = null; };
133
+ private readonly onSocketError = () => { this.report(new Error("Slack Socket Mode transport failed")); };
134
+
135
+ constructor(private readonly options: SlackMessengerOptions) {
136
+ this.channels = new Set(options.allowedChannelIds);
137
+ this.http = options.fetch ?? globalThis.fetch;
138
+ this.report = options.onError ?? (error => console.error("Slack event failed:", error));
139
+ // SDK debug/error payloads can contain tokens or request bodies. Only fixed,
140
+ // credential-free transport diagnostics cross the logging boundary.
141
+ const logger = {
142
+ debug() {}, info() {}, warn() {}, error: () => this.onSocketError(),
143
+ setLevel(_level: LogLevel) {}, getLevel: () => LogLevel.ERROR, setName(_name: string) {},
144
+ };
145
+ this.client = new WebClient(options.botToken, {
146
+ ...options.webClientOptions, retryConfig: { retries: 0 }, rejectRateLimitedCalls: true,
147
+ allowAbsoluteUrls: false, logger, teamId: options.teamId,
148
+ });
149
+ this.socket = options.socket ?? new SocketModeClient({
150
+ appToken: options.appToken, logger,
151
+ clientOptions: { retryConfig: { retries: 0 }, rejectRateLimitedCalls: true },
152
+ });
153
+ }
154
+
155
+ private async api(method: string, args: RecordValue = {}): Promise<RecordValue> {
156
+ try {
157
+ const result = await this.client.apiCall(method, args);
158
+ if (!result.ok) throw new DeliveryError("Slack API returned an unsuccessful result", "uncertain");
159
+ if (result.response_metadata?.warnings?.includes("message_truncated")) throw new DeliveryError("Slack reports that published content was truncated", "uncertain");
160
+ return result as unknown as RecordValue;
161
+ } catch (error) { throw failure(error); }
162
+ }
163
+
164
+ async start(handlers: Handlers): Promise<void> {
165
+ if (this.handlers) throw new Error("Slack messenger is already started");
166
+ try {
167
+ const identity = await this.api("auth.test");
168
+ if (identity.team_id !== this.options.teamId || !slackId(identity.user_id) || !slackId(identity.bot_id)) throw new DeliveryError("Slack bot authentication does not match the configured workspace", "rejected");
169
+ const botResult = await this.api("bots.info", { bot: identity.bot_id });
170
+ const bot = botResult.bot;
171
+ if (!object(bot) || bot.id !== identity.bot_id || bot.user_id !== identity.user_id || !slackId(bot.app_id)
172
+ || (bot.team_id !== undefined && bot.team_id !== this.options.teamId)) throw new DeliveryError("Slack bot application identity could not be verified", "rejected");
173
+ const ownerResult = await this.api("users.info", { user: this.options.ownerId });
174
+ const owner = ownerResult.user;
175
+ if (!object(owner) || owner.id !== this.options.ownerId || owner.team_id !== this.options.teamId || owner.is_bot !== false || owner.deleted === true || owner.is_app_user === true) throw new DeliveryError("Slack owner must be an active human in the configured workspace", "rejected");
176
+ this.botUserId = identity.user_id;
177
+ this.botId = identity.bot_id;
178
+ this.appId = bot.app_id;
179
+ this.accountId = `${this.options.teamId}:${this.botUserId}`;
180
+ this.handlers = handlers;
181
+ this.stopSignal = Promise.withResolvers<void>();
182
+ const authenticatedSocket = Promise.withResolvers<void>();
183
+ this.ready = Promise.race([
184
+ Promise.all([handlers.ready ?? Promise.resolve(), authenticatedSocket.promise]).then(() => true),
185
+ this.stopSignal.promise.then(() => false),
186
+ ]).catch(error => { this.report(failure(error)); return false; });
187
+ this.socket.on("slack_event", this.onEnvelope);
188
+ this.socket.on("ws_message", this.onWireMessage);
189
+ this.socket.on("connecting", this.onConnecting);
190
+ this.socket.on("reconnecting", this.onConnecting);
191
+ this.socket.on("disconnected", this.onConnecting);
192
+ this.socket.on("connected", this.onConnected);
193
+ this.socket.on("error", this.onSocketError);
194
+ await this.socket.start();
195
+ // apps.connections.open does not promise app_id. The SDK's public raw
196
+ // event exposes hello.connection_info.app_id without private-field access.
197
+ if (this.socketAppId !== this.appId) throw new DeliveryError("Slack Socket Mode application does not match the authenticated bot", "rejected");
198
+ this.connected = true;
199
+ authenticatedSocket.resolve();
200
+ } catch (error) { await this.stop(); throw failure(error); }
201
+ }
202
+
203
+ private assertRoute(route: Route): void {
204
+ if (!this.accountId || route.platform !== "slack" || route.accountId !== this.accountId || route.authorityId !== this.options.ownerId || !slackId(route.channelId) ||
205
+ (route.threadId !== null && !timestamp(route.threadId)) ||
206
+ (route.guildId !== null && (route.guildId !== this.options.teamId || !this.channels.has(route.channelId)))) throw new DeliveryError("Slack route is not authorized for this workspace, bot, and owner", "rejected");
207
+ }
208
+
209
+ private async destination(route: Route): Promise<void> {
210
+ this.assertRoute(route);
211
+ const response = await this.api("conversations.info", { channel: route.channelId });
212
+ const channel = response.channel;
213
+ if (!object(channel) || channel.id !== route.channelId || channel.is_mpim === true || channel.is_archived === true ||
214
+ (channel.context_team_id !== undefined && channel.context_team_id !== this.options.teamId)) throw new DeliveryError("Slack destination identity is not authorized", "rejected");
215
+ if (route.guildId === null) {
216
+ if (channel.is_im !== true || channel.user !== this.options.ownerId) throw new DeliveryError("Slack direct message is not the configured owner's one-to-one DM", "rejected");
217
+ } else if (channel.is_im === true || channel.is_member !== true) throw new DeliveryError("Slack bot must be a member of the configured channel", "rejected");
218
+ }
219
+
220
+ private async incomingRoute(channelId: string, threadId: string | null): Promise<Route | null> {
221
+ if (!this.accountId) return null;
222
+ // DMs are verified using conversations.info; an event's channel_type is not authority.
223
+ const route: Route = { platform: "slack", accountId: this.accountId, authorityId: this.options.ownerId, guildId: channelId.startsWith("D") ? null : this.options.teamId, channelId, threadId };
224
+ if (route.guildId !== null && !this.channels.has(channelId)) return null;
225
+ await this.destination(route);
226
+ return route;
227
+ }
228
+
229
+ private normalize(message: RecordValue, route: Route): (Inbound & MessageReference) | null {
230
+ if (message.type !== "message" || message.user !== this.options.ownerId || message.bot_id || message.app_id ||
231
+ (message.subtype !== undefined && message.subtype !== "file_share") || !timestamp(message.ts) ||
232
+ (message.team !== undefined && message.team !== this.options.teamId) ||
233
+ (message.user_team !== undefined && message.user_team !== this.options.teamId) ||
234
+ (message.source_team !== undefined && message.source_team !== this.options.teamId) ||
235
+ (message.text !== undefined && !string(message.text))) return null;
236
+ if (message.thread_ts !== undefined && !timestamp(message.thread_ts)) return null;
237
+ const threadId = timestamp(message.thread_ts) && message.thread_ts !== message.ts ? message.thread_ts : null;
238
+ const actual = { ...route, threadId };
239
+ const attachments: Attachment[] = [];
240
+ for (const file of Array.isArray(message.files) ? message.files : []) {
241
+ if (!object(file) || !slackId(file.id) || !file.id.startsWith("F") || file.user !== this.options.ownerId || file.is_external === true ||
242
+ !string(file.name) || typeof file.size !== "number" || !Number.isSafeInteger(file.size) || file.size < 0) throw new DeliveryError("Slack message contains an unsupported or nonowner attachment; use the local OMP interface", "rejected");
243
+ attachments.push({ id: file.id, name: file.name, url: `slack-file:${file.id}`, size: file.size, ...(string(file.mimetype) ? { contentType: file.mimetype } : {}) });
244
+ }
245
+ const edited = object(message.edited) ? message.edited : undefined;
246
+ if (edited && (!timestamp(edited.ts) || edited.user !== this.options.ownerId)) return null;
247
+ const revision = edited ? `edit:${edited.ts}:${hash(JSON.stringify([message.text ?? "", attachments.map(file => [file.id, file.name, file.size, file.contentType]).sort()]))}` : "original";
248
+ return {
249
+ id: `slack:${this.accountId}:${route.channelId}:${message.ts}:${revision}`,
250
+ route: actual, messageId: message.ts, text: controlText((message.text as string | undefined) ?? ""),
251
+ // Number is only a lossy display/age timestamp, never used to order Slack IDs.
252
+ receivedAt: Number((edited?.ts as string | undefined) ?? message.ts) * 1000,
253
+ attachments,
254
+ };
255
+ }
256
+
257
+ private async receive(envelope: Envelope): Promise<void> {
258
+ if (!this.appId || this.socketAppId !== this.appId) throw new DeliveryError("Slack Socket Mode application is not authorized", "rejected");
259
+ const body = envelope.body;
260
+ if (envelope.type === "slash_commands") { await this.receiveCommand(envelope); return; }
261
+ if (envelope.type !== "events_api" || body.team_id !== this.options.teamId || (body.api_app_id !== undefined && body.api_app_id !== this.appId) || !object(body.event)) { await envelope.ack(); return; }
262
+ const event = body.event;
263
+ if (event.type !== "message" || !slackId(event.channel) || (event.channel_type !== undefined && !["im", "channel", "group"].includes(String(event.channel_type)))) { await envelope.ack(); return; }
264
+ let message = event;
265
+ if (event.subtype === "message_changed") {
266
+ if (!object(event.message) || !object(event.message.edited)) { await envelope.ack(); return; }
267
+ message = event.message;
268
+ } else if (event.subtype !== undefined && event.subtype !== "file_share") { await envelope.ack(); return; }
269
+ if (message.user !== this.options.ownerId || message.bot_id || message.app_id) { await envelope.ack(); return; }
270
+ const route = await this.incomingRoute(event.channel, null);
271
+ const input = route ? this.normalize(message, route) : null;
272
+ if (input) await this.handlers!.message(input);
273
+ // A failed durable admission deliberately leaves the envelope unacknowledged.
274
+ await envelope.ack();
275
+ }
276
+
277
+ private async receiveCommand(envelope: Envelope): Promise<void> {
278
+ const body = envelope.body;
279
+ const refuse = async () => envelope.ack({ response_type: "ephemeral", text: "Superagent refused this command: use a configured command as the authorized owner in this app's workspace and an allowed channel or owner DM. Slash commands cannot target threads." });
280
+ // Real Slack slash commands carry no message/thread identity. Neither the
281
+ // opaque trigger nor a claimed channel name can supply those identities.
282
+ if (body.team_id !== this.options.teamId || body.user_id !== this.options.ownerId || !this.appId
283
+ || (body.api_app_id !== undefined && body.api_app_id !== this.appId)
284
+ || (body.app_id !== undefined && body.app_id !== this.appId)
285
+ || (body.bot_id !== undefined && body.bot_id !== this.botId)
286
+ || !slackId(body.channel_id) || !string(body.trigger_id) || !body.trigger_id.length
287
+ || !string(body.command) || !string(body.text)
288
+ || ["ts", "message_ts", "thread_ts", "thread_id", "message", "container"].some(field => field in body)) { await refuse(); return; }
289
+ const text = parseSlackCommand(body.command, body.text);
290
+ if (text === null) { await refuse(); return; }
291
+ let route: Route | null;
292
+ try { route = await this.incomingRoute(body.channel_id, null); }
293
+ catch { await refuse(); return; }
294
+ if (!route) { await refuse(); return; }
295
+ const invocationId = createHash("sha256").update(JSON.stringify([this.appId, this.options.teamId, this.options.ownerId, body.channel_id, body.trigger_id])).digest("hex");
296
+ await this.handlers!.message({
297
+ id: `slack:${this.accountId}:${body.channel_id}:invocation:${invocationId}`,
298
+ route, messageId: null, invocationId, text, receivedAt: Date.now(), attachments: [],
299
+ });
300
+ // The receipt admits only. Results always use the ordinary durable outbox;
301
+ // response_url, token, and trigger_id never cross the adapter boundary.
302
+ await envelope.ack(envelope.accepts_response_payload ? { response_type: "ephemeral", text: "Superagent command admitted. The result will appear in this conversation." } : undefined);
303
+ }
304
+
305
+ private messagePayload(text: string, blocks = sections(text)): RecordValue {
306
+ if (blocks.length > 50) throw new DeliveryError("Slack card exceeds 50 blocks; use the local OMP interface", "rejected");
307
+ const fallback = escapeText(text || "(empty output)");
308
+ // A long top-level text can be split by Slack. Omit it rather than truncate:
309
+ // Slack's documented accessibility path derives fallback from plain blocks.
310
+ return { ...(fallback.length <= TEXT_LIMIT ? { text: fallback } : {}), blocks, parse: "none", link_names: false };
311
+ }
312
+
313
+ private async post(route: Route, text: string, blocks?: Block[]): Promise<string> {
314
+ const result = await this.api("chat.postMessage", { channel: route.channelId, ...(route.threadId ? { thread_ts: route.threadId } : {}), ...this.messagePayload(text, blocks), mrkdwn: false, unfurl_links: false, unfurl_media: false });
315
+ if (result.channel !== route.channelId || !timestamp(result.ts)) throw new DeliveryError("Slack send has no authoritative destination receipt", "uncertain");
316
+ return result.ts;
317
+ }
318
+
319
+ async send(output: OutputRecord): Promise<string> {
320
+ await this.destination(output.route);
321
+ if (Buffer.byteLength(output.text, "utf8") > FILE_LIMIT) throw new DeliveryError("Slack text output exceeds the safe 8 MiB upload limit", "rejected");
322
+ if (output.text.length <= TEXT_LIMIT) return this.post(output.route, output.text);
323
+ // No partial multi-message output. The external upload is unpublished until
324
+ // completeUploadExternal; no deprecated files.upload or SDK mutation retries.
325
+ const bytes = Buffer.from(output.text, "utf8");
326
+ const filename = `omp-${hash(JSON.stringify([output.id, routeKey(output.route)]))}.txt`;
327
+ const ticket = await this.api("files.getUploadURLExternal", { filename, length: bytes.byteLength });
328
+ if (!slackId(ticket.file_id) || !ticket.file_id.startsWith("F") || !string(ticket.upload_url)) throw new DeliveryError("Slack returned an invalid upload ticket", "rejected");
329
+ let upload: URL;
330
+ try { upload = new URL(ticket.upload_url); } catch { throw new DeliveryError("Slack returned an invalid upload URL", "rejected"); }
331
+ if (upload.protocol !== "https:" || upload.hostname !== "files.slack.com" || upload.username || upload.password || (upload.port && upload.port !== "443") || !upload.pathname.startsWith("/upload/v1/")) throw new DeliveryError("Slack returned an unauthorized upload URL", "rejected");
332
+ try {
333
+ const response = await this.http(upload, { method: "POST", body: bytes, redirect: "error", headers: { "Content-Type": "application/octet-stream" } });
334
+ await response.body?.cancel();
335
+ if (!response.ok) throw new DeliveryError("Slack file bytes were not accepted; publication was not attempted", "rejected");
336
+ } catch { throw new DeliveryError("Slack file upload failed before publication was attempted", "rejected"); }
337
+ const completed = await this.api("files.completeUploadExternal", {
338
+ files: [{ id: ticket.file_id, title: filename }], channel_id: output.route.channelId,
339
+ ...(output.route.threadId ? { thread_ts: output.route.threadId } : {}),
340
+ });
341
+ if (!Array.isArray(completed.files) || !completed.files.some(file => object(file) && file.id === ticket.file_id)) throw new DeliveryError("Slack file publication has no authoritative receipt", "uncertain");
342
+ return `file:${ticket.file_id}`;
343
+ }
344
+
345
+ async setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
346
+ if (!timestamp(message.messageId)) throw new DeliveryError("Activity requires a Slack message timestamp", "rejected");
347
+ await this.destination(message.route);
348
+ const args = { channel: message.route.channelId, timestamp: message.messageId, name: activity === "received" ? "eyes" : "thought_balloon" };
349
+ try {
350
+ if (activity === "idle") await this.client.reactions.remove(args);
351
+ else await this.client.reactions.add(args);
352
+ } catch (error) {
353
+ if (object(error) && error.code === "slack_webapi_platform_error" && object(error.data) &&
354
+ error.data.error === (activity === "idle" ? "no_reaction" : "already_reacted")) return;
355
+ throw failure(error);
356
+ }
357
+ }
358
+
359
+ private control(pending: Pending, action: string): string { return `omp:${pending.token}:${action}`; }
360
+ private button(pending: Pending, action: string, label: string): RecordValue { return { type: "button", action_id: this.control(pending, action), text: plain(label), value: action }; }
361
+
362
+ private validateDialog(dialog: Dialog): void {
363
+ const labels: string[] = dialog.method === "select" ? dialog.options : dialog.method === "ask" ? dialog.questions.flatMap(question => question.options.map(option => option.label)) : [];
364
+ if (labels.some(label => label.length > 75)) throw new DeliveryError("Slack choice labels exceed 75 characters; use the local OMP interface (labels cannot be truncated)", "rejected");
365
+ if (dialog.method === "select" && (dialog.options.length > 100 || dialog.details.some(detail => detail && detail.length > 75))) throw new DeliveryError("Slack select exceeds native option limits; use the local OMP interface", "rejected");
366
+ if (dialog.method === "ask" && dialog.questions.some(question => question.options.length > 100 || question.options.some(option => option.description && option.description.length > 75))) throw new DeliveryError("Slack ask exceeds native option limits; use the local OMP interface", "rejected");
367
+ if ((dialog.method === "input" || dialog.method === "editor") && ((dialog.prefill?.length ?? 0) > 3000 || (dialog.placeholder?.length ?? 0) > 150)) throw new DeliveryError("Slack input exceeds native 3000-character input/150-character placeholder limits; use the local OMP interface", "rejected");
368
+ if (Buffer.byteLength(JSON.stringify(dialog), "utf8") > 100 * 1024) throw new DeliveryError("Slack dialog exceeds the safe card size; use the local OMP interface", "rejected");
369
+ }
370
+
371
+ private view(pending: Pending): { text: string; blocks: Block[] } {
372
+ const dialog = pending.dialog;
373
+ let text: string;
374
+ const controls: Block[] = [];
375
+ let row = 0;
376
+ const actions = (elements: RecordValue[]) => ({ type: "actions", block_id: this.control(pending, `row-${pending.question}-${row++}`), elements });
377
+ const cancel = this.button(pending, "cancel", "Cancel");
378
+ if (dialog.method === "confirm") {
379
+ text = `${dialog.title}\n\n${dialog.message}`;
380
+ controls.push(actions([this.button(pending, "yes", "Confirm"), this.button(pending, "no", "Decline"), cancel]));
381
+ } else if (dialog.method === "input" || dialog.method === "editor") {
382
+ text = `${dialog.title}\nRespond in the editor (not secret; maximum 3000 characters).`;
383
+ controls.push(actions([this.button(pending, "open", "Respond"), cancel]));
384
+ } else if (dialog.method === "select") {
385
+ text = dialog.title;
386
+ if (dialog.marker) text += `\n${dialog.options.map((label, index) => `${index < dialog.markableCount ? dialog.marker === "checkbox" ? dialog.checked.includes(index) ? "[x]" : "[ ]" : dialog.checked.includes(index) ? "(x)" : "( )" : "—"} ${label}${index === dialog.initialIndex ? " (initial focus)" : ""}`).join("\n")}\nChoose one row; OMP supplies the checked state on each request.`;
387
+ controls.push(actions([{ type: "static_select", action_id: this.control(pending, "select"), placeholder: plain("Choose one option"), options: dialog.options.map((label, index) => ({ text: plain(label), value: String(index), ...(dialog.details[index] ? { description: plain(dialog.details[index]!) } : {}) })) }]), actions([cancel]));
388
+ } else {
389
+ const question = dialog.questions[pending.question]!;
390
+ text = `Question ${pending.question + 1}/${dialog.questions.length}${question.header ? ` — ${question.header}` : ""}\n${question.question}\n${question.multi ? "Multiple answers allowed." : "Choose one option OR free text."}\n${question.options.map((option, index) => `${index + 1}. ${option.label}${index === question.recommended ? " (recommended, not preselected)" : ""}${option.preview ? `\n${option.preview}` : ""}`).join("\n")}${pending.customInput !== undefined ? `\nFree text: ${pending.customInput}` : ""}`;
391
+ if (question.options.length) {
392
+ const options = question.options.map((option, index) => ({ text: plain(option.label), value: String(index), ...(option.description ? { description: plain(option.description) } : {}) }));
393
+ const selected = options.filter((_, index) => pending.selected.includes(question.options[index]!.label));
394
+ controls.push(actions([{
395
+ type: question.multi ? "multi_static_select" : "static_select", action_id: this.control(pending, `choose-${pending.question}`), placeholder: plain("Choose options"), options,
396
+ ...(question.multi ? { ...(selected.length ? { initial_options: selected } : {}), max_selected_items: options.length } : selected[0] ? { initial_option: selected[0] } : {}),
397
+ }]));
398
+ }
399
+ controls.push(actions([this.button(pending, `other-${pending.question}`, "Other / free text"), this.button(pending, `next-${pending.question}`, pending.question + 1 === dialog.questions.length ? "Submit all answers" : "Next question"), cancel]));
400
+ }
401
+ const blocks = [...sections(text), ...controls];
402
+ // A compact correlation is required even on cards with no active controls.
403
+ blocks[0] = { ...blocks[0], block_id: this.control(pending, "card") };
404
+ this.messagePayload(text, blocks);
405
+ if (text.length > 39000) throw new DeliveryError("Slack dialog exceeds the message text limit; use the local OMP interface", "rejected");
406
+ return { text, blocks };
407
+ }
408
+
409
+ private async historyMessage(route: Route, messageId: string): Promise<RecordValue> {
410
+ if (!timestamp(messageId)) throw new DeliveryError("Invalid Slack stored message timestamp", "rejected");
411
+ if (!route.threadId || route.threadId === messageId) {
412
+ const result = await this.api("conversations.history", { channel: route.channelId, oldest: messageId, latest: messageId, inclusive: true, limit: 1, include_all_metadata: true });
413
+ const message = Array.isArray(result.messages) ? result.messages.find(value => object(value) && value.ts === messageId) : undefined;
414
+ if (!object(message)) throw new DeliveryError("Slack stored message is not accessible in authoritative history", "rejected");
415
+ return message;
416
+ }
417
+ const result = await this.api("conversations.replies", { channel: route.channelId, ts: route.threadId, oldest: messageId, latest: messageId, inclusive: true, limit: 2, include_all_metadata: true });
418
+ const message = Array.isArray(result.messages) ? result.messages.find(value => object(value) && value.ts === messageId) : undefined;
419
+ if (!object(message) || message.thread_ts !== route.threadId) throw new DeliveryError("Slack stored card is not in its original thread", "rejected");
420
+ return message;
421
+ }
422
+
423
+ private assertCard(message: RecordValue, pending: Pending): void {
424
+ if (message.ts !== pending.messageId || message.user !== this.botUserId || message.bot_id !== this.botId ||
425
+ (message.team !== undefined && message.team !== this.options.teamId) ||
426
+ (pending.approval.route.threadId ? message.thread_ts !== pending.approval.route.threadId : timestamp(message.thread_ts) && message.thread_ts !== message.ts) ||
427
+ !Array.isArray(message.blocks) || !message.blocks.some(block => object(block) && block.block_id === this.control(pending, "card"))) throw new DeliveryError("Slack message is not the matching owned approval card", "rejected");
428
+ for (const block of message.blocks) {
429
+ if (!object(block)) continue;
430
+ if (string(block.block_id) && block.block_id.startsWith("omp:") && !block.block_id.startsWith(`omp:${pending.token}:`)) throw new DeliveryError("Slack card correlation does not match the approval generation", "rejected");
431
+ for (const element of Array.isArray(block.elements) ? block.elements : []) if (object(element) && string(element.action_id) && !element.action_id.startsWith(`omp:${pending.token}:`)) throw new DeliveryError("Slack card controls belong to another approval", "rejected");
432
+ }
433
+ }
434
+
435
+ private async update(pending: Pending, inactive = false): Promise<void> {
436
+ if (!pending.messageId) return;
437
+ await this.destination(pending.approval.route);
438
+ const message = await this.historyMessage(pending.approval.route, pending.messageId);
439
+ this.assertCard(message, pending);
440
+ const view = this.view(pending);
441
+ const blocks = inactive ? view.blocks.filter(block => block.type !== "actions") : view.blocks;
442
+ await this.api("chat.update", { channel: pending.approval.route.channelId, ts: pending.messageId, as_user: true, ...this.messagePayload(view.text, blocks) });
443
+ }
444
+
445
+ async showApproval(approval: Approval): Promise<string> {
446
+ await this.destination(approval.route);
447
+ if (!this.handlers || approval.state !== "pending") throw new DeliveryError("Slack approval is not pending on a started messenger", "rejected");
448
+ const token = tokenFor(approval);
449
+ const existing = this.pending.get(token);
450
+ if (existing?.active && existing.messageId) {
451
+ if (approval.remoteId && approval.remoteId !== existing.messageId) throw new DeliveryError("Slack approval receipt does not match its active card", "rejected");
452
+ return existing.messageId;
453
+ }
454
+ for (const pending of this.pending.values()) if (pending.approval.id === approval.id) await this.dismissApproval(pending.approval);
455
+ let dialog: Dialog;
456
+ let initialView: { text: string; blocks: Block[] };
457
+ try {
458
+ dialog = parseDialog(approval.request);
459
+ this.validateDialog(dialog);
460
+ initialView = this.view({ approval, token, dialog, messageId: approval.remoteId, active: false, question: 0, answers: [], selected: [] });
461
+ }
462
+ catch {
463
+ // No unsupported/secret question is silently left pending on the native host.
464
+ const notice = "Request cancelled: this dialog cannot be represented safely in Slack. Use the local OMP interface; secret input is never collected here.";
465
+ // An existing receipt cannot be safely edited without its original parsed
466
+ // card; verify its identity with a minimal safe confirm view first.
467
+ const rejected: Pending = { approval: { ...approval, route: { ...approval.route } }, token, dialog: { method: "confirm", title: "Request cancelled", message: notice }, messageId: approval.remoteId, active: false, question: 0, answers: [], selected: [] };
468
+ if (rejected.messageId) await this.update(rejected, true);
469
+ else rejected.messageId = await this.post(approval.route, notice, [{ type: "section", block_id: this.control(rejected, "card"), text: plain(notice) }]);
470
+ await this.handlers.answer(approval.id, { cancelled: true }, rejected.approval.route);
471
+ return rejected.messageId;
472
+ }
473
+ const pending: Pending = { approval: { ...approval, route: { ...approval.route } }, token, dialog, messageId: approval.remoteId, active: false, question: 0, answers: [], selected: [] };
474
+ try {
475
+ this.pending.set(token, pending);
476
+ if (pending.messageId) await this.update(pending);
477
+ else pending.messageId = await this.post(approval.route, initialView.text, initialView.blocks);
478
+ pending.active = true;
479
+ return pending.messageId;
480
+ } catch (error) { this.pending.delete(token); throw failure(error); }
481
+ }
482
+
483
+ async dismissApproval(approval: Approval): Promise<void> {
484
+ this.assertRoute(approval.route);
485
+ const token = tokenFor(approval);
486
+ let pending = this.pending.get(token);
487
+ if (!pending && approval.remoteId) {
488
+ let dialog: Dialog;
489
+ try { dialog = parseDialog(approval.request); this.validateDialog(dialog); }
490
+ catch { dialog = { method: "confirm", title: "Request closed", message: "Use the local OMP interface." }; }
491
+ pending = { approval: { ...approval, route: { ...approval.route } }, token, dialog, messageId: approval.remoteId, active: false, question: 0, answers: [], selected: [] };
492
+ }
493
+ if (!pending) return;
494
+ pending.active = false;
495
+ pending.modal = undefined;
496
+ try { await this.update(pending, true); }
497
+ catch (error) {
498
+ if (!(error instanceof DeliveryError) || !["Slack API rejected request: message_not_found", "Slack API rejected request: channel_not_found"].includes(error.message)) throw error;
499
+ }
500
+ this.pending.delete(token);
501
+ this.interactionReceipts.delete(token);
502
+ }
503
+
504
+ private async finish(pending: Pending, response: DialogResponse): Promise<void> {
505
+ // Claim locally before persistence/host I/O. An ambiguous callback cannot
506
+ // unlock the card for another answer; runtime remains native authority.
507
+ pending.active = false;
508
+ pending.modal = undefined;
509
+ try { await this.handlers!.answer(pending.approval.id, response, pending.approval.route); }
510
+ finally { await this.dismissApproval(pending.approval); }
511
+ }
512
+
513
+ private async openModal(pending: Pending, action: string, trigger: unknown): Promise<void> {
514
+ if (!string(trigger) || !trigger) throw new DeliveryError("Slack modal has no valid trigger", "rejected");
515
+ if (pending.modal) return; // Replayed button cannot replace a still-open modal.
516
+ const dialog = pending.dialog;
517
+ const ask = dialog.method === "ask";
518
+ const metadata = hash(JSON.stringify([pending.token, pending.messageId, pending.approval.route.channelId, action]));
519
+ const prefill = ask ? pending.customInput : dialog.method === "input" || dialog.method === "editor" ? dialog.prefill : undefined;
520
+ const placeholder = dialog.method === "input" || dialog.method === "editor" ? dialog.placeholder : undefined;
521
+ const title = ask ? "Other answer" : "OMP response"; // Full original title remains on the linked card.
522
+ const result = await this.api("views.open", { trigger_id: trigger, view: {
523
+ type: "modal", callback_id: this.control(pending, action), private_metadata: metadata, notify_on_close: true,
524
+ title: plain(title), submit: plain("Submit"), close: plain("Cancel"),
525
+ blocks: [{ type: "input", block_id: "response", optional: true, label: plain("Response (not secret)"), element: {
526
+ type: "plain_text_input", action_id: "value", multiline: dialog.method !== "input", max_length: 3000,
527
+ ...(prefill !== undefined ? { initial_value: prefill } : {}), ...(placeholder ? { placeholder: plain(placeholder) } : {}),
528
+ } }],
529
+ } });
530
+ if (!object(result.view) || !slackId(result.view.id)) throw new DeliveryError("Slack modal has no authoritative view receipt", "uncertain");
531
+ pending.modal = { id: result.view.id, metadata, action };
532
+ }
533
+
534
+ private selection(action: RecordValue, options: string[], multi: boolean): string[] {
535
+ const values = multi ? action.selected_options : action.selected_option === null ? [] : [action.selected_option];
536
+ if (!Array.isArray(values) || (!multi && values.length > 1)) throw new DeliveryError("Invalid Slack selection", "rejected");
537
+ const selected = values.map(value => {
538
+ if (!object(value) || !string(value.value) || !/^(0|[1-9][0-9]*)$/.test(value.value)) throw new DeliveryError("Invalid Slack option index", "rejected");
539
+ const label = options[Number(value.value)];
540
+ if (label === undefined) throw new DeliveryError("Slack selected option is not in the original dialog", "rejected");
541
+ return label;
542
+ });
543
+ if (new Set(selected).size !== selected.length) throw new DeliveryError("Duplicate Slack selected options", "rejected");
544
+ return selected;
545
+ }
546
+
547
+ private async queueInteraction(envelope: Envelope): Promise<void> {
548
+ if (!await this.ready) return; // Shutdown must leave unreconciled envelopes unacknowledged.
549
+ const body = envelope.body;
550
+ const view = object(body.view) ? body.view : {};
551
+ const actions = Array.isArray(body.actions) ? body.actions : [];
552
+ const action = object(actions[0]) ? actions[0] : {};
553
+ const modal = body.type === "view_submission" || body.type === "view_closed";
554
+ const control = modal ? view.callback_id : action.action_id;
555
+ const parsed = string(control) ? /^omp:([a-f0-9]{24}):([a-z]+(?:-[0-9]+)?)$/.exec(control) : null;
556
+ if (!parsed || !object(body.team) || body.team.id !== this.options.teamId || !object(body.user) || body.user.id !== this.options.ownerId ||
557
+ (body.user.team_id !== undefined && body.user.team_id !== this.options.teamId)) { await envelope.ack(); return; }
558
+ const token = parsed[1]!;
559
+ // Use server event identity, never a choice-value fingerprint: selecting A,
560
+ // then B, then A again are three different legitimate user interactions.
561
+ const identity = modal && slackId(view.id) ? `view:${body.type}:${view.id}` : timestamp(action.action_ts) ? `action:${control}:${action.action_ts}` :
562
+ string(envelope.envelope_id) && envelope.envelope_id ? `envelope:${envelope.envelope_id}` : null;
563
+ const previous = this.interactionQueues.get(token) ?? Promise.resolve();
564
+ // A failed UI refresh must not discard a later distinct selection or modal.
565
+ // Revalidate card, generation, and current question when its turn arrives.
566
+ const task: Promise<void> = previous.catch(() => {}).then(async () => {
567
+ const duplicate = identity ? this.interactionReceipts.get(token)?.get(identity) : undefined;
568
+ if (duplicate) { await duplicate; await envelope.ack(); return; }
569
+ await this.interact(envelope, () => {
570
+ if (!identity) return;
571
+ let receipts = this.interactionReceipts.get(token);
572
+ if (!receipts) { receipts = new Map(); this.interactionReceipts.set(token, receipts); }
573
+ receipts.set(identity, task);
574
+ });
575
+ });
576
+ this.interactionQueues.set(token, task);
577
+ try { await task; }
578
+ finally { if (this.interactionQueues.get(token) === task) this.interactionQueues.delete(token); }
579
+ }
580
+
581
+ private async interact(envelope: Envelope, claim: () => void): Promise<void> {
582
+ const body = envelope.body;
583
+ if (!object(body.team) || body.team.id !== this.options.teamId || !object(body.user) || body.user.id !== this.options.ownerId ||
584
+ (body.user.team_id !== undefined && body.user.team_id !== this.options.teamId) || !this.handlers) { await envelope.ack(); return; }
585
+ const modal = body.type === "view_submission" || body.type === "view_closed";
586
+ const view = object(body.view) ? body.view : {};
587
+ const actions = Array.isArray(body.actions) ? body.actions : [];
588
+ const action = object(actions[0]) ? actions[0] : {};
589
+ const control = modal ? view.callback_id : action.action_id;
590
+ const parsed = string(control) ? /^omp:([a-f0-9]{24}):([a-z]+(?:-[0-9]+)?)$/.exec(control) : null;
591
+ const pending = parsed ? this.pending.get(parsed[1]!) : undefined;
592
+ if (!parsed || !pending?.active || (!modal && (body.type !== "block_actions" || actions.length !== 1))) { await envelope.ack(); return; }
593
+ const actionName = parsed[2]!;
594
+ if (modal) {
595
+ if (!pending.modal || view.id !== pending.modal.id || view.private_metadata !== pending.modal.metadata || pending.modal.action !== actionName) { await envelope.ack(); return; }
596
+ } else {
597
+ const container = object(body.container) ? body.container : {};
598
+ const channel = object(body.channel) ? body.channel : {};
599
+ const message = object(body.message) ? body.message : {};
600
+ if (container.type !== "message" || container.channel_id !== pending.approval.route.channelId || container.message_ts !== pending.messageId || channel.id !== pending.approval.route.channelId || message.ts !== pending.messageId) { await envelope.ack(); return; }
601
+ try { this.assertCard(message, pending); }
602
+ catch { await envelope.ack(); return; }
603
+ const expectedType = actionName === "select" ? "static_select" : actionName.startsWith("choose-") && pending.dialog.method === "ask" && pending.dialog.questions[pending.question]?.multi ? "multi_static_select" : actionName.startsWith("choose-") ? "static_select" : "button";
604
+ if (action.type !== expectedType) { await envelope.ack(); return; }
605
+ }
606
+ this.assertRoute(pending.approval.route);
607
+ claim(); // Invalid/stale linkage must not poison a later genuine callback identity.
608
+ {
609
+ if (body.type === "view_closed") { pending.modal = undefined; await envelope.ack(); return; }
610
+ const dialog = pending.dialog;
611
+ if (!modal && ((actionName === "open" && (dialog.method === "input" || dialog.method === "editor")) || (dialog.method === "ask" && actionName === `other-${pending.question}`))) {
612
+ await envelope.ack();
613
+ await this.openModal(pending, dialog.method === "ask" ? `custom-${pending.question}` : "value", body.trigger_id);
614
+ return;
615
+ }
616
+ // Native admission is durable before ACK for all final answers. Duplicate
617
+ // deliveries wait behind the original operation and revalidate afterward.
618
+ if (!modal && actionName === "cancel") { await this.finish(pending, { cancelled: true }); await envelope.ack(); return; }
619
+ if (dialog.method === "confirm" && !modal && (actionName === "yes" || actionName === "no")) { await this.finish(pending, { confirmed: actionName === "yes" }); await envelope.ack(); return; }
620
+ if (dialog.method === "select" && !modal && actionName === "select") {
621
+ const selected = this.selection(action, dialog.options, false);
622
+ if (selected.length !== 1) throw new DeliveryError("Slack select requires one original option", "rejected");
623
+ await this.finish(pending, { value: selected[0]! }); await envelope.ack(); return;
624
+ }
625
+ let value: string | undefined;
626
+ if (modal) {
627
+ const state = object(view.state) ? view.state : {};
628
+ const values = object(state.values) ? state.values : {};
629
+ const response = object(values.response) ? values.response : {};
630
+ const input = object(response.value) ? response.value : {};
631
+ if (input.type !== "plain_text_input" || (input.value !== null && !string(input.value)) || (string(input.value) && input.value.length > 3000)) throw new DeliveryError("Malformed Slack modal input", "rejected");
632
+ value = string(input.value) ? input.value : "";
633
+ }
634
+ if ((dialog.method === "input" || dialog.method === "editor") && modal && actionName === "value") { await this.finish(pending, { value: value! }); await envelope.ack(); return; }
635
+ if (dialog.method === "ask") {
636
+ const question = dialog.questions[pending.question]!;
637
+ if (!modal && actionName === `choose-${pending.question}`) {
638
+ pending.selected = this.selection(action, question.options.map(option => option.label), !!question.multi);
639
+ if (!question.multi && pending.selected.length) pending.customInput = undefined;
640
+ } else if (modal && actionName === `custom-${pending.question}`) {
641
+ pending.customInput = value || undefined;
642
+ pending.modal = undefined;
643
+ if (!question.multi && pending.customInput !== undefined) pending.selected = [];
644
+ } else if (!modal && actionName === `next-${pending.question}`) {
645
+ pending.answers.push({ id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput !== undefined ? { customInput: pending.customInput } : {}) });
646
+ if (pending.question + 1 === dialog.questions.length) { await this.finish(pending, { answers: pending.answers }); await envelope.ack(); return; }
647
+ pending.question++;
648
+ pending.selected = [];
649
+ pending.customInput = undefined;
650
+ pending.modal = undefined;
651
+ } else { await envelope.ack(); return; }
652
+ await envelope.ack();
653
+ await this.update(pending);
654
+ return;
655
+ }
656
+ await envelope.ack();
657
+ }
658
+ }
659
+
660
+ /** History is queried only for runtime's stored routes and cursors. No workspace scans. */
661
+ async fetchAfter(route: Route, messageId: string): Promise<Inbound[]> {
662
+ if (!timestamp(messageId)) throw new DeliveryError("Slack catchup requires a stored exact message timestamp", "rejected");
663
+ await this.destination(route);
664
+ const messages: RecordValue[] = [];
665
+ let cursor: string | undefined;
666
+ let boundary = messageId;
667
+ let latest: string | undefined;
668
+ const seenCursors = new Set<string>();
669
+ for (;;) {
670
+ const result = await this.api(route.threadId ? "conversations.replies" : "conversations.history", {
671
+ channel: route.channelId, ...(route.threadId ? { ts: route.threadId } : {}),
672
+ oldest: boundary, ...(latest ? { latest } : {}), inclusive: false, limit: 100,
673
+ ...(cursor ? { cursor } : {}),
674
+ });
675
+ if (result.is_limited === true || !Array.isArray(result.messages)) throw new DeliveryError("Slack history is incomplete or retention-limited", "rejected");
676
+ const page = result.messages.filter(object);
677
+ if (page.length !== result.messages.length || page.some(message => !timestamp(message.ts))) throw new DeliveryError("Slack returned malformed history", "rejected");
678
+ messages.push(...page);
679
+ const metadata = object(result.response_metadata) ? result.response_metadata : {};
680
+ const next = string(metadata.next_cursor) ? metadata.next_cursor.trim() : "";
681
+ if (next) {
682
+ if (seenCursors.has(next)) throw new DeliveryError("Slack history pagination cursor did not advance", "rejected");
683
+ seenCursors.add(next); cursor = next; continue;
684
+ }
685
+ cursor = undefined;
686
+ if (result.has_more !== true) break;
687
+ // Slack also supports time pagination. Replies are oldest-first; channel
688
+ // history newest-first. Never use Number(timestamp) to choose boundaries.
689
+ if (!page.length) throw new DeliveryError("Slack history claimed more messages without an advancing page", "rejected");
690
+ const ordered = page.map(message => message.ts as string).sort(compare);
691
+ if (route.threadId) {
692
+ const nextBoundary = ordered[ordered.length - 1]!;
693
+ if (compare(nextBoundary, boundary) <= 0) throw new DeliveryError("Slack reply pagination did not advance", "rejected");
694
+ boundary = nextBoundary;
695
+ } else {
696
+ const nextLatest = ordered[0]!;
697
+ if ((latest && compare(nextLatest, latest) >= 0) || compare(nextLatest, messageId) <= 0) throw new DeliveryError("Slack history pagination did not advance", "rejected");
698
+ latest = nextLatest;
699
+ }
700
+ }
701
+ const inputs = new Map<string, Inbound & MessageReference>();
702
+ for (const message of messages) {
703
+ if (compare(message.ts as string, messageId) <= 0) continue;
704
+ const input = this.normalize(message, route);
705
+ if (input && physicalRouteKey(input.route) === physicalRouteKey(route)) inputs.set(input.id, input);
706
+ }
707
+ return [...inputs.values()].sort((left, right) => compare(left.messageId, right.messageId));
708
+ }
709
+
710
+ /** Slack roots in an authenticated channel or owner DM support thread_ts. */
711
+ async canCreateThread(route: Route): Promise<boolean> {
712
+ this.assertRoute(route);
713
+ if (route.threadId !== null) return false;
714
+ await this.destination(route);
715
+ return true;
716
+ }
717
+
718
+ async createThread(route: Route, title: string, sourceMessageId?: string): Promise<Route> {
719
+ await this.destination(route);
720
+ if (route.threadId) throw new DeliveryError("Slack cannot nest conversation threads", "rejected");
721
+ if (!title.trim() || title.length > TEXT_LIMIT) throw new DeliveryError("Slack thread title must contain 1–3000 characters", "rejected");
722
+ if (sourceMessageId) {
723
+ const source = await this.historyMessage(route, sourceMessageId);
724
+ if (source.type !== "message" || source.user !== this.options.ownerId || source.bot_id || source.app_id ||
725
+ (source.subtype !== undefined && source.subtype !== "file_share") ||
726
+ (source.thread_ts !== undefined && source.thread_ts !== source.ts) ||
727
+ (source.team !== undefined && source.team !== this.options.teamId) ||
728
+ (source.user_team !== undefined && source.user_team !== this.options.teamId) ||
729
+ (source.source_team !== undefined && source.source_team !== this.options.teamId)) throw new DeliveryError("Slack thread source is not an authorized owner root message", "rejected");
730
+ return { ...physicalRoute(route), threadId: sourceMessageId };
731
+ }
732
+ return { ...physicalRoute(route), threadId: await this.post(route, title) };
733
+ }
734
+
735
+ async openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
736
+ await this.destination(route);
737
+ if (typeof attachment.size !== "number" || !Number.isSafeInteger(attachment.size) || attachment.size < 0 ||
738
+ !/^F[A-Z0-9]+$/.test(attachment.id) || attachment.url !== `slack-file:${attachment.id}`) throw new DeliveryError("Slack attachment reference is not an authorized file ID", "rejected");
739
+ const result = await this.api("files.info", { file: attachment.id });
740
+ const file = result.file;
741
+ if (!object(file) || file.id !== attachment.id || file.user !== this.options.ownerId || file.mode !== "hosted" || file.is_external !== false || file.file_access === "check_file_info" ||
742
+ (file.team_id !== undefined && file.team_id !== this.options.teamId)) throw new DeliveryError("Slack file is not an owned hosted workspace attachment", "rejected");
743
+ const shares = object(file.shares) ? file.shares : {};
744
+ const allowedShares = [shares.public, shares.private].filter(object).flatMap(group => Array.isArray(group[route.channelId]) ? group[route.channelId] as unknown[] : []);
745
+ if (!allowedShares.some(share => object(share) && share.team_id === this.options.teamId && timestamp(share.ts) &&
746
+ (route.threadId ? share.thread_ts === route.threadId || share.ts === route.threadId : share.thread_ts === undefined || share.thread_ts === share.ts))) throw new DeliveryError("Slack file has no authoritative share in the original destination", "rejected");
747
+ const value = file.url_private_download ?? file.url_private;
748
+ let url: URL;
749
+ try { url = new URL(string(value) ? value : ""); } catch { throw new DeliveryError("Slack file has no valid private download URL", "rejected"); }
750
+ const path = `/files-pri/${this.options.teamId}-${attachment.id}/`;
751
+ if (url.protocol !== "https:" || url.hostname !== "files.slack.com" || url.username || url.password || (url.port && url.port !== "443") || !url.pathname.startsWith(path) || url.hash || /%(?:2f|5c|2e)/i.test(url.pathname)) throw new DeliveryError("Slack private file URL is not on the allowed workspace/file path", "rejected");
752
+ try { return await this.http(url, { signal, redirect: "error", headers: { Authorization: `Bearer ${this.options.botToken}` } }); }
753
+ catch { throw new DeliveryError("Slack private attachment download failed", "rejected"); }
754
+ }
755
+
756
+ async stop(): Promise<void> {
757
+ this.connected = false;
758
+ this.stopSignal.resolve();
759
+ this.socket.off("slack_event", this.onEnvelope);
760
+ this.socket.off("ws_message", this.onWireMessage);
761
+ this.socket.off("connecting", this.onConnecting);
762
+ this.socket.off("reconnecting", this.onConnecting);
763
+ this.socket.off("disconnected", this.onConnecting);
764
+ this.socket.off("connected", this.onConnected);
765
+ this.socket.off("error", this.onSocketError);
766
+ await this.intake;
767
+ await Promise.all(this.interactions);
768
+ this.interactionQueues.clear();
769
+ this.interactionReceipts.clear();
770
+ for (const pending of this.pending.values()) pending.active = false;
771
+ this.pending.clear();
772
+ this.handlers = null;
773
+ this.accountId = this.botUserId = this.botId = this.appId = this.socketAppId = null;
774
+ try { await this.socket.disconnect(); } catch { this.onSocketError(); }
775
+ }
776
+ }