@desplega.ai/slack-mock 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/web-api.ts ADDED
@@ -0,0 +1,694 @@
1
+ // Slack Web API method handlers. Each receives the parsed args and returns the
2
+ // `ok: true` body; they throw SlackApiError for `ok: false` responses.
3
+
4
+ import { type Args, bool, num, str } from "./body.ts";
5
+ import { nextTs, nowUnix, slackId } from "./ids.ts";
6
+ import type { SocketModeHub } from "./socket-mode.ts";
7
+ import { SlackApiError, type Store, wireFile, wireMessage } from "./store.ts";
8
+ import type { SlackChannel, SlackFile, SlackMessage } from "./types.ts";
9
+
10
+ export interface Actor {
11
+ userId: string;
12
+ isBot: boolean;
13
+ }
14
+
15
+ export interface ApiContext {
16
+ store: Store;
17
+ hub: SocketModeHub;
18
+ baseUrl: string;
19
+ wsUrl: string;
20
+ actor: Actor;
21
+ /** Trigger ids issued with interactive payloads, with their expiry. */
22
+ triggerIds: Map<string, number>;
23
+ /** Files created by files.getUploadURLExternal that still await bytes. */
24
+ pendingUploads: Map<string, { name: string; length: number; alt_text?: string; user: string }>;
25
+ }
26
+
27
+ export type Handler = (ctx: ApiContext, args: Args) => Record<string, unknown>;
28
+
29
+ function required(args: Args, key: string): string {
30
+ const v = str(args, key);
31
+ if (!v)
32
+ throw new SlackApiError("invalid_arguments", {
33
+ response_metadata: { messages: [`[ERROR] missing required field: ${key}`] },
34
+ });
35
+ return v;
36
+ }
37
+
38
+ /** Resolve `channel` args that may be an id, a #name or a user id (opens a DM). */
39
+ function resolveChannel(store: Store, raw: string): SlackChannel {
40
+ if (raw.startsWith("#")) {
41
+ const c = store.channelByName(raw);
42
+ if (!c) throw new SlackApiError("channel_not_found");
43
+ return c;
44
+ }
45
+ if (raw.startsWith("U") || raw.startsWith("W")) return store.openDm(raw);
46
+ return store.channel(raw);
47
+ }
48
+
49
+ function requireMember(channel: SlackChannel, actor: Actor): void {
50
+ if (!channel.members.includes(actor.userId)) throw new SlackApiError("not_in_channel");
51
+ }
52
+
53
+ function botFields(ctx: ApiContext): Partial<SlackMessage> {
54
+ if (!ctx.actor.isBot) return {};
55
+ return {
56
+ bot_id: ctx.store.bot.botId,
57
+ app_id: ctx.store.app.id,
58
+ bot_profile: {
59
+ id: ctx.store.bot.botId,
60
+ name: ctx.store.app.name,
61
+ app_id: ctx.store.app.id,
62
+ team_id: ctx.store.team.id,
63
+ deleted: false,
64
+ },
65
+ };
66
+ }
67
+
68
+ function messageContent(
69
+ args: Args,
70
+ ): Pick<SlackMessage, "text" | "blocks" | "attachments" | "metadata"> {
71
+ const text = str(args, "text") ?? "";
72
+ const blocks = Array.isArray(args.blocks) ? (args.blocks as unknown[]) : undefined;
73
+ const attachments = Array.isArray(args.attachments) ? (args.attachments as unknown[]) : undefined;
74
+ if (!text && !blocks?.length && !attachments?.length) throw new SlackApiError("no_text");
75
+ if (blocks && blocks.length > 50)
76
+ throw new SlackApiError("invalid_blocks", {
77
+ response_metadata: { messages: ["[ERROR] must have at most 50 blocks"] },
78
+ });
79
+ const metadata =
80
+ args.metadata && typeof args.metadata === "object"
81
+ ? (args.metadata as SlackMessage["metadata"])
82
+ : undefined;
83
+ return { text, blocks, attachments, metadata };
84
+ }
85
+
86
+ function channelInfo(store: Store, c: SlackChannel, actor: Actor): Record<string, unknown> {
87
+ const { members, ...rest } = c;
88
+ return {
89
+ ...rest,
90
+ is_member: members.includes(actor.userId),
91
+ num_members: members.length,
92
+ context_team_id: store.team.id,
93
+ shared_team_ids: [store.team.id],
94
+ is_org_shared: false,
95
+ is_shared: false,
96
+ is_ext_shared: false,
97
+ is_pending_ext_shared: false,
98
+ unlinked: 0,
99
+ name_normalized: c.name,
100
+ updated: c.created * 1000,
101
+ };
102
+ }
103
+
104
+ export const handlers: Record<string, Handler> = {
105
+ "auth.test": ({ store, actor }) => {
106
+ const user = store.user(actor.userId);
107
+ return {
108
+ url: `https://${store.team.domain}.slack.com/`,
109
+ team: store.team.name,
110
+ user: user.name,
111
+ team_id: store.team.id,
112
+ user_id: user.id,
113
+ ...(actor.isBot ? { bot_id: store.bot.botId } : {}),
114
+ is_enterprise_install: false,
115
+ };
116
+ },
117
+
118
+ "apps.connections.open": ({ hub, wsUrl, store }) => ({
119
+ url: `${wsUrl}/link/?ticket=${hub.issueTicket()}&app_id=${store.app.id}`,
120
+ }),
121
+
122
+ "bots.info": ({ store }) => ({
123
+ bot: {
124
+ id: store.bot.botId,
125
+ deleted: false,
126
+ name: store.app.name,
127
+ updated: nowUnix(),
128
+ app_id: store.app.id,
129
+ user_id: store.bot.userId,
130
+ icons: {},
131
+ },
132
+ }),
133
+
134
+ "team.info": ({ store }) => ({
135
+ team: {
136
+ id: store.team.id,
137
+ name: store.team.name,
138
+ domain: store.team.domain,
139
+ email_domain: "",
140
+ icon: {},
141
+ is_verified: false,
142
+ },
143
+ }),
144
+
145
+ // ------------------------------------------------------------------ chat
146
+
147
+ "chat.postMessage": (ctx, args) => {
148
+ const channel = resolveChannel(ctx.store, required(args, "channel"));
149
+ requireMember(channel, ctx.actor);
150
+ const threadTs = str(args, "thread_ts");
151
+ const message = ctx.store.addMessage({
152
+ channel: channel.id,
153
+ user: ctx.actor.userId,
154
+ ...messageContent(args),
155
+ ...(threadTs ? { thread_ts: threadTs } : {}),
156
+ ...(bool(args, "reply_broadcast") && threadTs ? { subtype: "thread_broadcast" } : {}),
157
+ ...(str(args, "username") ? { username: str(args, "username") } : {}),
158
+ ...(str(args, "icon_emoji") || str(args, "icon_url")
159
+ ? {
160
+ icons: {
161
+ ...(str(args, "icon_emoji") ? { emoji: str(args, "icon_emoji")! } : {}),
162
+ ...(str(args, "icon_url") ? { image_64: str(args, "icon_url")! } : {}),
163
+ },
164
+ }
165
+ : {}),
166
+ ...botFields(ctx),
167
+ });
168
+ return { channel: channel.id, ts: message.ts, message: wireMessage(message) };
169
+ },
170
+
171
+ "chat.postEphemeral": (ctx, args) => {
172
+ const channel = resolveChannel(ctx.store, required(args, "channel"));
173
+ const user = required(args, "user");
174
+ ctx.store.user(user);
175
+ const threadTs = str(args, "thread_ts");
176
+ const message = ctx.store.addMessage({
177
+ channel: channel.id,
178
+ user: ctx.actor.userId,
179
+ ephemeral_user: user,
180
+ ...messageContent(args),
181
+ ...(threadTs ? { thread_ts: threadTs } : {}),
182
+ ...botFields(ctx),
183
+ });
184
+ return { message_ts: message.ts };
185
+ },
186
+
187
+ "chat.update": (ctx, args) => {
188
+ const channel = resolveChannel(ctx.store, required(args, "channel"));
189
+ const ts = required(args, "ts");
190
+ const existing = ctx.store.message(channel.id, ts);
191
+ if (existing.user !== ctx.actor.userId && !ctx.actor.isBot)
192
+ throw new SlackApiError("cant_update_message");
193
+ const patch: Partial<SlackMessage> = {};
194
+ if (args.text !== undefined) patch.text = str(args, "text") ?? "";
195
+ if (args.blocks !== undefined)
196
+ patch.blocks = Array.isArray(args.blocks) ? (args.blocks as unknown[]) : undefined;
197
+ if (args.attachments !== undefined)
198
+ patch.attachments = Array.isArray(args.attachments)
199
+ ? (args.attachments as unknown[])
200
+ : undefined;
201
+ if (args.metadata !== undefined) patch.metadata = args.metadata as SlackMessage["metadata"];
202
+ if (
203
+ patch.text === "" &&
204
+ !patch.blocks?.length &&
205
+ !patch.attachments?.length &&
206
+ !existing.blocks?.length
207
+ )
208
+ throw new SlackApiError("no_text");
209
+ const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId);
210
+ return { channel: channel.id, ts, text: message.text, message: wireMessage(message) };
211
+ },
212
+
213
+ "chat.delete": (ctx, args) => {
214
+ const channel = resolveChannel(ctx.store, required(args, "channel"));
215
+ const ts = required(args, "ts");
216
+ ctx.store.deleteMessage(channel.id, ts);
217
+ return { channel: channel.id, ts };
218
+ },
219
+
220
+ // ------------------------------------------------- chat streaming (markdown)
221
+
222
+ "chat.startStream": (ctx, args) => {
223
+ const channel = resolveChannel(ctx.store, required(args, "channel"));
224
+ requireMember(channel, ctx.actor);
225
+ const threadTs = str(args, "thread_ts");
226
+ const message = ctx.store.addMessage({
227
+ channel: channel.id,
228
+ user: ctx.actor.userId,
229
+ text: streamText(args),
230
+ streaming_state: "in_progress",
231
+ ...(threadTs ? { thread_ts: threadTs } : {}),
232
+ ...(str(args, "username") ? { username: str(args, "username") } : {}),
233
+ ...(str(args, "icon_emoji") ? { icons: { emoji: str(args, "icon_emoji")! } } : {}),
234
+ ...botFields(ctx),
235
+ });
236
+ return { channel: channel.id, ts: message.ts };
237
+ },
238
+
239
+ "chat.appendStream": (ctx, args) => {
240
+ const channel = resolveChannel(ctx.store, required(args, "channel"));
241
+ const ts = required(args, "ts");
242
+ const existing = ctx.store.message(channel.id, ts);
243
+ if (existing.streaming_state !== "in_progress")
244
+ throw new SlackApiError("message_not_in_streaming_state");
245
+ const message = ctx.store.updateMessage(
246
+ channel.id,
247
+ ts,
248
+ { text: existing.text + streamText(args) },
249
+ ctx.actor.userId,
250
+ );
251
+ return { channel: channel.id, ts: message.ts };
252
+ },
253
+
254
+ "chat.stopStream": (ctx, args) => {
255
+ const channel = resolveChannel(ctx.store, required(args, "channel"));
256
+ const ts = required(args, "ts");
257
+ const existing = ctx.store.message(channel.id, ts);
258
+ if (existing.streaming_state !== "in_progress")
259
+ throw new SlackApiError("message_not_in_streaming_state");
260
+ const patch: Partial<SlackMessage> = {
261
+ streaming_state: "completed",
262
+ text: existing.text + streamText(args),
263
+ };
264
+ if (Array.isArray(args.blocks)) patch.blocks = args.blocks as unknown[];
265
+ const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId);
266
+ return { channel: channel.id, ts, message: wireMessage(message) };
267
+ },
268
+
269
+ "chat.getPermalink": (ctx, args) => {
270
+ const channel = resolveChannel(ctx.store, required(args, "channel"));
271
+ const ts = required(args, "message_ts");
272
+ ctx.store.message(channel.id, ts);
273
+ return {
274
+ channel: channel.id,
275
+ permalink: `${ctx.baseUrl}/archives/${channel.id}/p${ts.replace(".", "")}`,
276
+ };
277
+ },
278
+
279
+ // --------------------------------------------------------- conversations
280
+
281
+ "conversations.list": (ctx, args) => {
282
+ const types = new Set((str(args, "types") ?? "public_channel").split(",").map((t) => t.trim()));
283
+ const excludeArchived = bool(args, "exclude_archived") ?? false;
284
+ const all = [...ctx.store.channels.values()].filter((c) => {
285
+ if (excludeArchived && c.is_archived) return false;
286
+ if (c.is_im) return types.has("im");
287
+ if (c.is_mpim) return types.has("mpim");
288
+ if (c.is_private) return types.has("private_channel");
289
+ return types.has("public_channel");
290
+ });
291
+ const limit = num(args, "limit", 100);
292
+ const start = cursorOffset(str(args, "cursor"));
293
+ const slice = all.slice(start, start + limit);
294
+ const hasMore = start + limit < all.length;
295
+ return {
296
+ channels: slice.map((c) => channelInfo(ctx.store, c, ctx.actor)),
297
+ response_metadata: { next_cursor: hasMore ? cursorFor(start + limit) : "" },
298
+ };
299
+ },
300
+
301
+ "conversations.info": (ctx, args) => {
302
+ const channel = ctx.store.channel(required(args, "channel"));
303
+ return { channel: channelInfo(ctx.store, channel, ctx.actor) };
304
+ },
305
+
306
+ "conversations.create": (ctx, args) => {
307
+ const name = required(args, "name");
308
+ if (!/^[a-z0-9_-]{1,80}$/.test(name)) throw new SlackApiError("invalid_name_specials");
309
+ const channel = ctx.store.addChannel({
310
+ name,
311
+ is_private: bool(args, "is_private") ?? false,
312
+ creator: ctx.actor.userId,
313
+ });
314
+ return { channel: channelInfo(ctx.store, channel, ctx.actor) };
315
+ },
316
+
317
+ "conversations.join": (ctx, args) => {
318
+ const channel = ctx.store.channel(required(args, "channel"));
319
+ if (channel.is_private) throw new SlackApiError("method_not_supported_for_channel_type");
320
+ const { alreadyMember } = ctx.store.join(channel.id, ctx.actor.userId);
321
+ return {
322
+ channel: channelInfo(ctx.store, channel, ctx.actor),
323
+ ...(alreadyMember
324
+ ? { warning: "already_in_channel", response_metadata: { warnings: ["already_in_channel"] } }
325
+ : {}),
326
+ };
327
+ },
328
+
329
+ "conversations.invite": (ctx, args) => {
330
+ const channel = ctx.store.channel(required(args, "channel"));
331
+ const users = required(args, "users")
332
+ .split(",")
333
+ .map((u) => u.trim())
334
+ .filter(Boolean);
335
+ const errors: Array<Record<string, unknown>> = [];
336
+ for (const u of users) {
337
+ if (!ctx.store.users.has(u)) {
338
+ errors.push({ user: u, ok: false, error: "user_not_found" });
339
+ continue;
340
+ }
341
+ const { alreadyMember } = ctx.store.join(channel.id, u, ctx.actor.userId);
342
+ if (alreadyMember) errors.push({ user: u, ok: false, error: "already_in_channel" });
343
+ }
344
+ if (errors.length === users.length)
345
+ throw new SlackApiError(String(errors[0]!.error), { errors });
346
+ return {
347
+ channel: channelInfo(ctx.store, channel, ctx.actor),
348
+ ...(errors.length ? { errors } : {}),
349
+ };
350
+ },
351
+
352
+ "conversations.archive": (ctx, args) => {
353
+ ctx.store.archive(required(args, "channel"));
354
+ return {};
355
+ },
356
+
357
+ "conversations.members": (ctx, args) => {
358
+ const channel = ctx.store.channel(required(args, "channel"));
359
+ return { members: channel.members, response_metadata: { next_cursor: "" } };
360
+ },
361
+
362
+ "conversations.open": (ctx, args) => {
363
+ const users = (str(args, "users") ?? "")
364
+ .split(",")
365
+ .map((u) => u.trim())
366
+ .filter(Boolean);
367
+ if (users.length !== 1) throw new SlackApiError("users_list_not_supplied");
368
+ const dm = ctx.store.openDm(users[0]!);
369
+ return { channel: { id: dm.id, is_im: true, user: dm.user, created: dm.created } };
370
+ },
371
+
372
+ "conversations.history": (ctx, args) => {
373
+ const channel = ctx.store.channel(required(args, "channel"));
374
+ requireMember(channel, ctx.actor);
375
+ const p = ctx.store.history(channel.id, {
376
+ oldest: str(args, "oldest"),
377
+ latest: str(args, "latest"),
378
+ inclusive: bool(args, "inclusive"),
379
+ limit: num(args, "limit", 100),
380
+ cursor: str(args, "cursor"),
381
+ });
382
+ return {
383
+ messages: p.items.map((m) => historyMessage(m, bool(args, "include_all_metadata"))),
384
+ has_more: p.has_more,
385
+ pin_count: 0,
386
+ response_metadata: { next_cursor: p.next_cursor },
387
+ };
388
+ },
389
+
390
+ "conversations.replies": (ctx, args) => {
391
+ const channel = ctx.store.channel(required(args, "channel"));
392
+ requireMember(channel, ctx.actor);
393
+ const ts = required(args, "ts");
394
+ if (!ctx.store.findMessage(channel.id, ts)) throw new SlackApiError("thread_not_found");
395
+ const p = ctx.store.replies(channel.id, ts, {
396
+ oldest: str(args, "oldest"),
397
+ latest: str(args, "latest"),
398
+ inclusive: bool(args, "inclusive"),
399
+ limit: num(args, "limit", 1000),
400
+ cursor: str(args, "cursor"),
401
+ });
402
+ return {
403
+ messages: p.items.map((m) => historyMessage(m, bool(args, "include_all_metadata"))),
404
+ has_more: p.has_more,
405
+ response_metadata: { next_cursor: p.next_cursor },
406
+ };
407
+ },
408
+
409
+ // ----------------------------------------------------------------- users
410
+
411
+ "users.info": (ctx, args) => ({ user: ctx.store.user(required(args, "user")) }),
412
+
413
+ "users.list": (ctx) => ({
414
+ members: [...ctx.store.users.values()],
415
+ response_metadata: { next_cursor: "" },
416
+ }),
417
+
418
+ "users.lookupByEmail": (ctx, args) => {
419
+ const user = ctx.store.userByEmail(required(args, "email"));
420
+ if (!user) throw new SlackApiError("users_not_found");
421
+ return { user };
422
+ },
423
+
424
+ "users.conversations": (ctx, args) => {
425
+ const user = str(args, "user") ?? ctx.actor.userId;
426
+ const channels = [...ctx.store.channels.values()].filter(
427
+ (c) => c.members.includes(user) && !c.is_im,
428
+ );
429
+ return {
430
+ channels: channels.map((c) => channelInfo(ctx.store, c, ctx.actor)),
431
+ response_metadata: { next_cursor: "" },
432
+ };
433
+ },
434
+
435
+ // ------------------------------------------------------------- reactions
436
+
437
+ "reactions.add": (ctx, args) => {
438
+ const channel = ctx.store.channel(required(args, "channel"));
439
+ ctx.store.addReaction(
440
+ channel.id,
441
+ required(args, "timestamp"),
442
+ required(args, "name"),
443
+ ctx.actor.userId,
444
+ );
445
+ return {};
446
+ },
447
+
448
+ "reactions.remove": (ctx, args) => {
449
+ const channel = ctx.store.channel(required(args, "channel"));
450
+ ctx.store.removeReaction(
451
+ channel.id,
452
+ required(args, "timestamp"),
453
+ required(args, "name"),
454
+ ctx.actor.userId,
455
+ );
456
+ return {};
457
+ },
458
+
459
+ "reactions.get": (ctx, args) => {
460
+ const channel = ctx.store.channel(required(args, "channel"));
461
+ const message = ctx.store.message(channel.id, required(args, "timestamp"));
462
+ return { type: "message", channel: channel.id, message: wireMessage(message) };
463
+ },
464
+
465
+ // ----------------------------------------------------------------- files
466
+
467
+ "files.info": (ctx, args) => {
468
+ const file = ctx.store.file(required(args, "file"));
469
+ return { file: wireFile(file), comments: [], response_metadata: { next_cursor: "" } };
470
+ },
471
+
472
+ "files.getUploadURLExternal": (ctx, args) => {
473
+ const filename = required(args, "filename");
474
+ const length = num(args, "length", -1);
475
+ if (length < 0)
476
+ throw new SlackApiError("invalid_arguments", {
477
+ response_metadata: { messages: ["[ERROR] missing required field: length"] },
478
+ });
479
+ const id = slackId("F");
480
+ ctx.pendingUploads.set(id, {
481
+ name: filename,
482
+ length,
483
+ alt_text: str(args, "alt_text"),
484
+ user: ctx.actor.userId,
485
+ });
486
+ return { upload_url: `${ctx.baseUrl}/upload/v1/${id}`, file_id: id };
487
+ },
488
+
489
+ "files.completeUploadExternal": (ctx, args) => {
490
+ const list = Array.isArray(args.files)
491
+ ? (args.files as Array<{ id: string; title?: string }>)
492
+ : [];
493
+ if (list.length === 0)
494
+ throw new SlackApiError("invalid_arguments", {
495
+ response_metadata: { messages: ["[ERROR] missing required field: files"] },
496
+ });
497
+ const files: SlackFile[] = list.map(({ id, title }) => {
498
+ const f = ctx.store.file(id);
499
+ if (title) f.title = title;
500
+ return f;
501
+ });
502
+ const channelId = str(args, "channel_id");
503
+ if (channelId) {
504
+ const channel = ctx.store.channel(channelId);
505
+ requireMember(channel, ctx.actor);
506
+ for (const f of files) if (!f.channels.includes(channel.id)) f.channels.push(channel.id);
507
+ const threadTs = str(args, "thread_ts");
508
+ ctx.store.addMessage({
509
+ channel: channel.id,
510
+ user: ctx.actor.userId,
511
+ subtype: "file_share",
512
+ text: str(args, "initial_comment") ?? "",
513
+ files,
514
+ ...(threadTs ? { thread_ts: threadTs } : {}),
515
+ ...botFields(ctx),
516
+ });
517
+ }
518
+ return { files: files.map(wireFile) };
519
+ },
520
+
521
+ "files.delete": (ctx, args) => {
522
+ ctx.store.file(required(args, "file"));
523
+ ctx.store.files.delete(required(args, "file"));
524
+ return {};
525
+ },
526
+
527
+ // ----------------------------------------------------------------- views
528
+
529
+ "views.open": (ctx, args) => {
530
+ const triggerId = required(args, "trigger_id");
531
+ const expires = ctx.triggerIds.get(triggerId);
532
+ if (expires === undefined) throw new SlackApiError("invalid_trigger_id");
533
+ ctx.triggerIds.delete(triggerId);
534
+ if (Date.now() > expires) throw new SlackApiError("expired_trigger_id");
535
+ const view = viewArg(args);
536
+ if (view.type !== "modal")
537
+ throw new SlackApiError("invalid_arguments", {
538
+ response_metadata: { messages: ["[ERROR] view type must be modal"] },
539
+ });
540
+ const stored = ctx.store.openView({
541
+ type: "modal",
542
+ callback_id: str(view, "callback_id"),
543
+ private_metadata: str(view, "private_metadata") ?? "",
544
+ title: view.title,
545
+ submit: view.submit,
546
+ close: view.close,
547
+ blocks: Array.isArray(view.blocks) ? view.blocks : [],
548
+ external_id: str(view, "external_id"),
549
+ opened_by: "",
550
+ trigger_id: triggerId,
551
+ state: { values: {} },
552
+ clear_on_close: bool(view, "clear_on_close") ?? false,
553
+ notify_on_close: bool(view, "notify_on_close") ?? false,
554
+ });
555
+ return { view: publicView(stored) };
556
+ },
557
+
558
+ "views.update": (ctx, args) => {
559
+ const id = required(args, "view_id");
560
+ const existing = ctx.store.views.get(id);
561
+ if (!existing) throw new SlackApiError("not_found");
562
+ const view = viewArg(args);
563
+ Object.assign(existing, {
564
+ callback_id: str(view, "callback_id") ?? existing.callback_id,
565
+ private_metadata: str(view, "private_metadata") ?? existing.private_metadata,
566
+ title: view.title ?? existing.title,
567
+ submit: view.submit ?? existing.submit,
568
+ close: view.close ?? existing.close,
569
+ blocks: Array.isArray(view.blocks) ? view.blocks : existing.blocks,
570
+ hash: `${nowUnix()}.${slackId("", 6).toLowerCase()}`,
571
+ });
572
+ ctx.store.onChangeEmit({ kind: "view.update", view: existing });
573
+ return { view: publicView(existing) };
574
+ },
575
+
576
+ "views.push": (ctx, args) => handlers["views.open"]!(ctx, args),
577
+
578
+ // ------------------------------------------------------------- assistant
579
+
580
+ "assistant.threads.setStatus": (ctx, args) => {
581
+ const channel = ctx.store.channel(required(args, "channel_id"));
582
+ const threadTs = required(args, "thread_ts");
583
+ const t = ctx.store.assistantThread(channel.id, threadTs);
584
+ t.status = str(args, "status") ?? "";
585
+ ctx.store.onChangeEmit({
586
+ kind: "assistant.status",
587
+ channel: channel.id,
588
+ thread_ts: threadTs,
589
+ status: t.status,
590
+ });
591
+ return {};
592
+ },
593
+
594
+ "assistant.threads.setTitle": (ctx, args) => {
595
+ const channel = ctx.store.channel(required(args, "channel_id"));
596
+ const threadTs = required(args, "thread_ts");
597
+ const t = ctx.store.assistantThread(channel.id, threadTs);
598
+ t.title = required(args, "title");
599
+ ctx.store.onChangeEmit({
600
+ kind: "assistant.title",
601
+ channel: channel.id,
602
+ thread_ts: threadTs,
603
+ title: t.title,
604
+ });
605
+ return {};
606
+ },
607
+
608
+ "assistant.threads.setSuggestedPrompts": (ctx, args) => {
609
+ const channel = ctx.store.channel(required(args, "channel_id"));
610
+ const threadTs = required(args, "thread_ts");
611
+ const t = ctx.store.assistantThread(channel.id, threadTs);
612
+ t.prompts = Array.isArray(args.prompts) ? (args.prompts as unknown[]) : [];
613
+ t.promptsTitle = str(args, "title");
614
+ ctx.store.onChangeEmit({
615
+ kind: "assistant.prompts",
616
+ channel: channel.id,
617
+ thread_ts: threadTs,
618
+ prompts: t.prompts,
619
+ title: t.promptsTitle,
620
+ });
621
+ return {};
622
+ },
623
+
624
+ // ------------------------------------------------------------------ pins
625
+
626
+ "pins.add": (ctx, args) => {
627
+ const channel = ctx.store.channel(required(args, "channel"));
628
+ ctx.store.message(channel.id, required(args, "timestamp"));
629
+ return {};
630
+ },
631
+ };
632
+
633
+ /** Text for a streaming call: markdown_text or the joined `chunks`. */
634
+ function streamText(args: Args): string {
635
+ const md = str(args, "markdown_text");
636
+ if (md) return md;
637
+ const chunks = Array.isArray(args.chunks) ? (args.chunks as Array<Record<string, unknown>>) : [];
638
+ return chunks
639
+ .map((c) =>
640
+ typeof c.text === "string"
641
+ ? c.text
642
+ : typeof c.markdown_text === "string"
643
+ ? c.markdown_text
644
+ : "",
645
+ )
646
+ .join("");
647
+ }
648
+
649
+ /** Slack only returns message metadata from history/replies when include_all_metadata is set. */
650
+ function historyMessage(
651
+ m: SlackMessage,
652
+ includeMetadata: boolean | undefined,
653
+ ): Record<string, unknown> {
654
+ const wire = wireMessage(m);
655
+ if (!includeMetadata) delete wire.metadata;
656
+ return wire;
657
+ }
658
+
659
+ function viewArg(args: Args): Record<string, unknown> {
660
+ const v = args.view;
661
+ if (typeof v === "string") {
662
+ try {
663
+ return JSON.parse(v);
664
+ } catch {
665
+ throw new SlackApiError("invalid_arguments", {
666
+ response_metadata: { messages: ["[ERROR] view must be valid JSON"] },
667
+ });
668
+ }
669
+ }
670
+ if (v && typeof v === "object") return v as Record<string, unknown>;
671
+ throw new SlackApiError("invalid_arguments", {
672
+ response_metadata: { messages: ["[ERROR] missing required field: view"] },
673
+ });
674
+ }
675
+
676
+ function publicView(view: import("./types.ts").SlackView): Record<string, unknown> {
677
+ const { opened_by: _o, trigger_id: _t, ...rest } = view;
678
+ return rest;
679
+ }
680
+
681
+ function cursorOffset(cursor: string | undefined): number {
682
+ if (!cursor) return 0;
683
+ return (
684
+ Number.parseInt(Buffer.from(cursor, "base64").toString("utf8").replace("offset:", ""), 10) || 0
685
+ );
686
+ }
687
+
688
+ function cursorFor(offset: number): string {
689
+ return Buffer.from(`offset:${offset}`).toString("base64");
690
+ }
691
+
692
+ export function newTriggerId(): string {
693
+ return `${nowUnix()}${Math.floor(Math.random() * 1e6)}.${slackId("", 10).toLowerCase()}.${nextTs().replace(".", "")}`;
694
+ }