@openclaw/slack 2026.5.12-beta.7

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 (88) hide show
  1. package/dist/account-inspect-D7AZNs8C.js +77 -0
  2. package/dist/account-inspect-api.js +10 -0
  3. package/dist/accounts-ClAPP5ry.js +139 -0
  4. package/dist/accounts.runtime-DDVcLJUI.js +2 -0
  5. package/dist/action-runtime-e2UhRsNx.js +350 -0
  6. package/dist/action-runtime.runtime-BFcqMbOm.js +2 -0
  7. package/dist/actions-CYLFK-Zy.js +292 -0
  8. package/dist/actions.runtime-CO3OaTLb.js +2 -0
  9. package/dist/allow-list-BPnnlRPL.js +82 -0
  10. package/dist/api.js +21 -0
  11. package/dist/approval-handler.runtime-CmeRr9qA.js +256 -0
  12. package/dist/blocks-input-CwTFVImV.js +29 -0
  13. package/dist/blocks-render-BIDw-Pom.js +161 -0
  14. package/dist/channel-DRjHBTDB.js +1020 -0
  15. package/dist/channel-api-B_nZwosg.js +20 -0
  16. package/dist/channel-config-api.js +2 -0
  17. package/dist/channel-entry.js +22 -0
  18. package/dist/channel-plugin-api.js +2 -0
  19. package/dist/channel.setup-Cayn7afd.js +73 -0
  20. package/dist/client-CPe4GmDR.js +103 -0
  21. package/dist/config-api-B_jq4NJW.js +2 -0
  22. package/dist/config-schema-D9B5LB_L.js +167 -0
  23. package/dist/configured-state.js +11 -0
  24. package/dist/contract-api.js +5 -0
  25. package/dist/directory-config-B3JiHeB7.js +54 -0
  26. package/dist/directory-contract-api.js +2 -0
  27. package/dist/directory-live-Bf16GwDh.js +133 -0
  28. package/dist/doctor-contract-KUjHnkQm.js +147 -0
  29. package/dist/doctor-contract-api.js +2 -0
  30. package/dist/errors-BYFHR24f.js +109 -0
  31. package/dist/exec-approvals-7xUNgLi9.js +58 -0
  32. package/dist/group-policy-CyLUK6My.js +41 -0
  33. package/dist/http-routes-api.js +2 -0
  34. package/dist/inbound-contract-test-api.js +3 -0
  35. package/dist/index.js +33 -0
  36. package/dist/interactive-replies-api.js +2 -0
  37. package/dist/interactive-replies-qAIfuBor.js +173 -0
  38. package/dist/magic-string.es-BMaGRRZ1.js +1011 -0
  39. package/dist/media-D1XCd1uP.js +469 -0
  40. package/dist/message-tool-api-6lowf9zE.js +104 -0
  41. package/dist/message-tool-api.js +2 -0
  42. package/dist/monitor-a97o17G6.js +13 -0
  43. package/dist/mrkdwn-Cax-eSfK.js +6 -0
  44. package/dist/outbound-adapter-B_5sEhCg.js +174 -0
  45. package/dist/outbound-payload-test-api.js +2 -0
  46. package/dist/outbound-payload.test-harness-CVCamg1x.js +13558 -0
  47. package/dist/pipeline.runtime-DT0hLnq2.js +1379 -0
  48. package/dist/plugin-routes-DtTPmga1.js +20 -0
  49. package/dist/prepare-D3YqV8jB.js +1482 -0
  50. package/dist/prepare.test-helpers-DVcjRhfG.js +49 -0
  51. package/dist/probe-3eZf1FjI.js +42 -0
  52. package/dist/provider-D7uAN3Fq.js +3235 -0
  53. package/dist/registry-CeaoNfoP.js +39 -0
  54. package/dist/replies-Xe_jMR6o.js +139 -0
  55. package/dist/reply-blocks-Z5l6_R6H.js +14 -0
  56. package/dist/resolve-allowlist-common-Bk3clYPK.js +43 -0
  57. package/dist/resolve-channels-BRYqyNVJ.js +81 -0
  58. package/dist/resolve-users-Bd_SdP8j.js +113 -0
  59. package/dist/rolldown-runtime-CiIaOW0V.js +13 -0
  60. package/dist/room-context-0vovmZPU.js +787 -0
  61. package/dist/runtime-Bo-KHM-F.js +8 -0
  62. package/dist/runtime-api-Dd1xIV5v.js +9 -0
  63. package/dist/runtime-api.js +14 -0
  64. package/dist/runtime-setter-api.js +2 -0
  65. package/dist/scopes-CDevO8jg.js +74 -0
  66. package/dist/secret-contract-Bo6lbSkh.js +141 -0
  67. package/dist/secret-contract-api.js +2 -0
  68. package/dist/security-audit-BtHGnD3d.js +51 -0
  69. package/dist/security-contract-api.js +2 -0
  70. package/dist/send-D_A9kL-C.js +721 -0
  71. package/dist/send.runtime-BRE_ncCU.js +2 -0
  72. package/dist/send.runtime-_l76lUuL.js +2 -0
  73. package/dist/setup-core-B9NetDkM.js +320 -0
  74. package/dist/setup-entry.js +15 -0
  75. package/dist/setup-plugin-api.js +2 -0
  76. package/dist/setup-surface-D88QBVOW.js +128 -0
  77. package/dist/shared-D8U42xFL.js +208 -0
  78. package/dist/slash-commands.runtime-22kgyst2.js +19 -0
  79. package/dist/slash-dispatch.runtime-BJgT0jwV.js +32 -0
  80. package/dist/slash-plugin-commands.runtime-CF-n3MeP.js +2 -0
  81. package/dist/slash-skill-commands.runtime-BMs0VjTe.js +7 -0
  82. package/dist/streaming-compat-RkZgTmQ2.js +43 -0
  83. package/dist/target-parsing-CQmv-iSm.js +55 -0
  84. package/dist/targets-B1tYCAr6.js +2 -0
  85. package/dist/test-api.js +8 -0
  86. package/dist/thread-ts-C2x7c5PP.js +24 -0
  87. package/openclaw.plugin.json +2405 -0
  88. package/package.json +84 -0
@@ -0,0 +1,1379 @@
1
+ import { i as truncateSlackText, r as SLACK_TEXT_LIMIT } from "./thread-ts-C2x7c5PP.js";
2
+ import { n as isSlackInteractiveRepliesEnabled, t as compileSlackInteractiveReplies } from "./interactive-replies-qAIfuBor.js";
3
+ import { i as normalizeSlackAllowOwnerEntry } from "./allow-list-BPnnlRPL.js";
4
+ import "./blocks-input-CwTFVImV.js";
5
+ import { n as resolveSlackNativeStreaming, r as resolveSlackStreamingMode, t as mapStreamingModeToSlackLegacyDraftStreamMode } from "./streaming-compat-RkZgTmQ2.js";
6
+ import { a as recordSlackThreadParticipation, s as normalizeSlackOutboundText, t as sendMessageSlack } from "./send-D_A9kL-C.js";
7
+ import { f as removeSlackReaction, h as buildSlackEditTextPayload, l as reactSlackMessage, r as editSlackMessage, t as deleteSlackMessage } from "./actions-CYLFK-Zy.js";
8
+ import { t as formatSlackError } from "./errors-BYFHR24f.js";
9
+ import { T as updateLastRoute, a as recordInboundSession, w as resolveStorePath } from "./room-context-0vovmZPU.js";
10
+ import { t as escapeSlackMrkdwn } from "./mrkdwn-Cax-eSfK.js";
11
+ import { n as resolveSlackThreadTargets, t as prepareSlackMessage } from "./prepare-D3YqV8jB.js";
12
+ import { a as resolveDeliveredSlackReplyThreadTs, i as readSlackReplyBlocks, n as deliverReplies, o as resolveSlackThreadTs, t as createSlackReplyDeliveryPlan } from "./replies-Xe_jMR6o.js";
13
+ import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/string-coerce-runtime";
14
+ import { resolveInboundLastRouteSessionKey } from "openclaw/plugin-sdk/routing";
15
+ import { createChannelMessageReplyPipeline, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, resolveChannelMessageSourceReplyDeliveryMode } from "openclaw/plugin-sdk/channel-message";
16
+ import { buildChannelProgressDraftLine, buildChannelProgressDraftLineForEntry, createChannelProgressDraftGate, formatChannelProgressDraftText, isChannelProgressDraftWorkToolName, resolveChannelProgressDraftLabel, resolveChannelProgressDraftMaxLines, resolveChannelProgressDraftRender, resolveChannelStreamingBlockEnabled, resolveChannelStreamingNativeTransport, resolveChannelStreamingPreviewToolProgress, resolveChannelStreamingSuppressDefaultToolProgressMessages } from "openclaw/plugin-sdk/channel-streaming";
17
+ import { danger, logVerbose, shouldLogVerbose, sleep } from "openclaw/plugin-sdk/runtime-env";
18
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
19
+ import { resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
20
+ import { clearHistoryEntriesIfEnabled } from "openclaw/plugin-sdk/reply-history";
21
+ import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
22
+ import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
23
+ import { DEFAULT_TIMING, createStatusReactionController, logAckFailure, logTypingFailure, removeAckReactionAfterReply } from "openclaw/plugin-sdk/channel-feedback";
24
+ import { hasVisibleInboundReplyDispatch, runInboundReplyTurn } from "openclaw/plugin-sdk/inbound-reply-dispatch";
25
+ import { resolveAgentOutboundIdentity } from "openclaw/plugin-sdk/outbound-runtime";
26
+ import { createDraftStreamLoop } from "openclaw/plugin-sdk/channel-lifecycle";
27
+ import { createReplyDispatcherWithTyping, dispatchInboundMessage, settleReplyDispatcher } from "openclaw/plugin-sdk/reply-runtime";
28
+ //#region extensions/slack/src/draft-stream.ts
29
+ const DEFAULT_THROTTLE_MS = 1e3;
30
+ function createSlackDraftStream(params) {
31
+ const maxChars = Math.min(params.maxChars ?? 8e3, SLACK_TEXT_LIMIT);
32
+ const throttleMs = Math.max(250, params.throttleMs ?? DEFAULT_THROTTLE_MS);
33
+ const send = params.send ?? sendMessageSlack;
34
+ const edit = params.edit ?? editSlackMessage;
35
+ const remove = params.remove ?? deleteSlackMessage;
36
+ let streamMessageId;
37
+ let streamChannelId;
38
+ let lastSentKey = "";
39
+ let pendingUpdate;
40
+ let stopped = false;
41
+ const normalizeUpdate = (update) => typeof update === "string" ? { text: update } : update;
42
+ const sendOrEditStreamMessage = async (text) => {
43
+ if (stopped) return;
44
+ const trimmed = text.trimEnd();
45
+ if (!trimmed) return;
46
+ if (trimmed.length > maxChars) {
47
+ stopped = true;
48
+ params.warn?.(`slack stream preview stopped (text length ${trimmed.length} > ${maxChars})`);
49
+ return;
50
+ }
51
+ const update = normalizeUpdate(pendingUpdate ?? text);
52
+ const blocks = update.text === text ? update.blocks : void 0;
53
+ const sentKey = `${trimmed}\n${blocks ? JSON.stringify(blocks) : ""}`;
54
+ if (sentKey === lastSentKey) return;
55
+ lastSentKey = sentKey;
56
+ try {
57
+ if (streamChannelId && streamMessageId) {
58
+ await edit(streamChannelId, streamMessageId, trimmed, {
59
+ cfg: params.cfg,
60
+ token: params.token,
61
+ accountId: params.accountId,
62
+ ...blocks ? { blocks } : {}
63
+ });
64
+ return;
65
+ }
66
+ const sent = await send(params.target, trimmed, {
67
+ cfg: params.cfg,
68
+ token: params.token,
69
+ accountId: params.accountId,
70
+ threadTs: params.resolveThreadTs?.(),
71
+ identity: params.identity,
72
+ ...blocks ? { blocks } : {}
73
+ });
74
+ streamChannelId = sent.channelId || streamChannelId;
75
+ streamMessageId = sent.messageId || streamMessageId;
76
+ if (!streamChannelId || !streamMessageId) {
77
+ stopped = true;
78
+ params.warn?.("slack stream preview stopped (missing identifiers from sendMessage)");
79
+ return;
80
+ }
81
+ params.onMessageSent?.();
82
+ } catch (err) {
83
+ stopped = true;
84
+ params.warn?.(`slack stream preview failed: ${formatSlackError(err)}`);
85
+ }
86
+ };
87
+ const loop = createDraftStreamLoop({
88
+ throttleMs,
89
+ isStopped: () => stopped,
90
+ sendOrEditStreamMessage
91
+ });
92
+ const stop = () => {
93
+ stopped = true;
94
+ loop.stop();
95
+ };
96
+ const discardPending = async () => {
97
+ stop();
98
+ await loop.waitForInFlight();
99
+ };
100
+ const clear = async () => {
101
+ await discardPending();
102
+ const channelId = streamChannelId;
103
+ const messageId = streamMessageId;
104
+ streamChannelId = void 0;
105
+ streamMessageId = void 0;
106
+ lastSentKey = "";
107
+ pendingUpdate = void 0;
108
+ if (!channelId || !messageId) return;
109
+ try {
110
+ await remove(channelId, messageId, {
111
+ token: params.token,
112
+ accountId: params.accountId
113
+ });
114
+ } catch (err) {
115
+ params.warn?.(`slack stream preview cleanup failed: ${formatSlackError(err)}`);
116
+ }
117
+ };
118
+ const forceNewMessage = () => {
119
+ streamMessageId = void 0;
120
+ streamChannelId = void 0;
121
+ lastSentKey = "";
122
+ pendingUpdate = void 0;
123
+ loop.resetPending();
124
+ };
125
+ params.log?.(`slack stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
126
+ return {
127
+ update: (update) => {
128
+ const normalized = normalizeUpdate(update);
129
+ pendingUpdate = update;
130
+ loop.update(normalized.text);
131
+ },
132
+ flush: loop.flush,
133
+ clear,
134
+ discardPending,
135
+ seal: discardPending,
136
+ stop,
137
+ forceNewMessage,
138
+ messageId: () => streamMessageId,
139
+ channelId: () => streamChannelId
140
+ };
141
+ }
142
+ //#endregion
143
+ //#region extensions/slack/src/progress-blocks.ts
144
+ const SLACK_PROGRESS_FIELD_MAX = 1800;
145
+ const SLACK_PROGRESS_DETAIL_MAX_CHARS = 48;
146
+ function field(text) {
147
+ return {
148
+ type: "mrkdwn",
149
+ text: truncateSlackText(text, SLACK_PROGRESS_FIELD_MAX)
150
+ };
151
+ }
152
+ function lineTitle(line) {
153
+ return `${line.icon ?? "•"} *${escapeSlackMrkdwn(line.label)}*`;
154
+ }
155
+ function compactDetail(value) {
156
+ const normalized = value.replace(/\s+/g, " ").trim();
157
+ const chars = Array.from(normalized);
158
+ if (chars.length <= SLACK_PROGRESS_DETAIL_MAX_CHARS) return normalized;
159
+ const keepStart = Math.ceil((SLACK_PROGRESS_DETAIL_MAX_CHARS - 1) * .45);
160
+ const keepEnd = SLACK_PROGRESS_DETAIL_MAX_CHARS - keepStart - 1;
161
+ return `${chars.slice(0, keepStart).join("").trimEnd()}…${chars.slice(-keepEnd).join("").trimStart()}`;
162
+ }
163
+ function lineDetail(line) {
164
+ const parts = [line.detail, line.status && !line.detail?.includes(line.status) ? line.status : void 0].map((part) => part?.trim()).filter((part) => Boolean(part));
165
+ return parts.length ? escapeSlackMrkdwn(compactDetail(parts.join(" · "))) : " ";
166
+ }
167
+ function buildSlackProgressDraftBlocks(params) {
168
+ const label = params.label?.trim();
169
+ const blocks = [...label ? [{
170
+ type: "section",
171
+ text: field(`*${escapeSlackMrkdwn(label)}*`)
172
+ }] : [], ...params.lines.map((line) => ({
173
+ type: "section",
174
+ fields: [field(lineTitle(line)), field(lineDetail(line))]
175
+ }))].slice(-50);
176
+ return blocks.length ? blocks : void 0;
177
+ }
178
+ //#endregion
179
+ //#region extensions/slack/src/stream-mode.ts
180
+ function resolveSlackStreamingConfig(params) {
181
+ const mode = resolveSlackStreamingMode(params);
182
+ return {
183
+ mode,
184
+ nativeStreaming: resolveSlackNativeStreaming(params),
185
+ draftMode: mapStreamingModeToSlackLegacyDraftStreamMode(mode)
186
+ };
187
+ }
188
+ function applyAppendOnlyStreamUpdate(params) {
189
+ const incoming = params.incoming.trimEnd();
190
+ if (!incoming) return {
191
+ rendered: params.rendered,
192
+ source: params.source,
193
+ changed: false
194
+ };
195
+ if (!params.rendered) return {
196
+ rendered: incoming,
197
+ source: incoming,
198
+ changed: true
199
+ };
200
+ if (incoming === params.source) return {
201
+ rendered: params.rendered,
202
+ source: params.source,
203
+ changed: false
204
+ };
205
+ if (incoming.startsWith(params.source) || incoming.startsWith(params.rendered)) return {
206
+ rendered: incoming,
207
+ source: incoming,
208
+ changed: incoming !== params.rendered
209
+ };
210
+ if (params.source.startsWith(incoming)) return {
211
+ rendered: params.rendered,
212
+ source: params.source,
213
+ changed: false
214
+ };
215
+ const separator = params.rendered.endsWith("\n") ? "" : "\n";
216
+ return {
217
+ rendered: `${params.rendered}${separator}${incoming}`,
218
+ source: incoming,
219
+ changed: true
220
+ };
221
+ }
222
+ //#endregion
223
+ //#region extensions/slack/src/streaming.ts
224
+ /**
225
+ * Thrown when Slack rejects a stream flush/finalize with a recipient-resolution
226
+ * error (see {@link BENIGN_SLACK_FINALIZE_ERROR_CODES}) while text is still
227
+ * only buffered locally by the Slack SDK. Carries the pending text so the
228
+ * caller can deliver it via the normal Slack reply path.
229
+ */
230
+ var SlackStreamNotDeliveredError = class extends Error {
231
+ constructor(pendingText, slackCode) {
232
+ super(`slack-stream: finalize failed with ${slackCode} before any text reached Slack (${pendingText.length} chars pending)`);
233
+ this.name = "SlackStreamNotDeliveredError";
234
+ this.pendingText = pendingText;
235
+ this.slackCode = slackCode;
236
+ }
237
+ };
238
+ /**
239
+ * Start a new Slack text stream.
240
+ *
241
+ * Returns a {@link SlackStreamSession} that should be passed to
242
+ * {@link appendSlackStream} and {@link stopSlackStream}.
243
+ *
244
+ * The first chunk of text can optionally be included via `text`.
245
+ */
246
+ async function startSlackStream(params) {
247
+ const { client, channel, threadTs, text, teamId, userId } = params;
248
+ logVerbose(`slack-stream: starting stream in ${channel} thread=${threadTs}${teamId ? ` team=${teamId}` : ""}${userId ? ` user=${userId}` : ""}`);
249
+ const streamer = client.chatStream({
250
+ channel,
251
+ thread_ts: threadTs,
252
+ ...teamId ? { recipient_team_id: teamId } : {},
253
+ ...userId ? { recipient_user_id: userId } : {}
254
+ });
255
+ const session = {
256
+ streamer,
257
+ channel,
258
+ threadTs,
259
+ stopped: false,
260
+ delivered: false,
261
+ pendingText: ""
262
+ };
263
+ if (text) {
264
+ session.pendingText += text;
265
+ try {
266
+ const result = await streamer.append({ markdown_text: text });
267
+ if (result) {
268
+ session.delivered = true;
269
+ session.pendingText = "";
270
+ }
271
+ logVerbose(`slack-stream: appended initial text (${text.length} chars, ${result ? "flushed" : "buffered"})`);
272
+ } catch (err) {
273
+ if (isBenignSlackFinalizeError(err) && session.pendingText) throw new SlackStreamNotDeliveredError(session.pendingText, extractSlackErrorCode(err) ?? "unknown");
274
+ throw err;
275
+ }
276
+ }
277
+ return session;
278
+ }
279
+ /**
280
+ * Append markdown text to an active Slack stream.
281
+ */
282
+ async function appendSlackStream(params) {
283
+ const { session, text } = params;
284
+ if (session.stopped) {
285
+ logVerbose("slack-stream: attempted to append to a stopped stream, ignoring");
286
+ return;
287
+ }
288
+ if (!text) return;
289
+ session.pendingText += text;
290
+ try {
291
+ const result = await session.streamer.append({ markdown_text: text });
292
+ if (result) {
293
+ session.delivered = true;
294
+ session.pendingText = "";
295
+ }
296
+ logVerbose(`slack-stream: appended ${text.length} chars (${result ? "flushed" : "buffered"})`);
297
+ } catch (err) {
298
+ if (isBenignSlackFinalizeError(err) && session.pendingText) throw new SlackStreamNotDeliveredError(session.pendingText, extractSlackErrorCode(err) ?? "unknown");
299
+ throw err;
300
+ }
301
+ }
302
+ /**
303
+ * Stop (finalize) a Slack stream.
304
+ *
305
+ * After calling this the stream message becomes a normal Slack message.
306
+ * Optionally include final text to append before stopping.
307
+ *
308
+ * If Slack's `chat.stopStream` responds with a known benign finalize error
309
+ * (see {@link BENIGN_SLACK_FINALIZE_ERROR_CODES}) AND any prior `append`
310
+ * has already landed on Slack, the error is swallowed and the session is
311
+ * marked stopped - the already-delivered text stays visible.
312
+ *
313
+ * If the same benign error fires while text is still only buffered locally
314
+ * (e.g. short replies that never exceeded the SDK's buffer_size), this
315
+ * function throws a {@link SlackStreamNotDeliveredError} carrying that pending
316
+ * text so the caller can deliver it through the normal Slack reply path.
317
+ *
318
+ * All other errors propagate unchanged.
319
+ */
320
+ async function stopSlackStream(params) {
321
+ const { session, text } = params;
322
+ if (session.stopped) {
323
+ logVerbose("slack-stream: stream already stopped, ignoring duplicate stop");
324
+ return;
325
+ }
326
+ session.stopped = true;
327
+ if (text) session.pendingText += text;
328
+ logVerbose(`slack-stream: stopping stream in ${session.channel} thread=${session.threadTs}${text ? ` (final text: ${text.length} chars)` : ""}`);
329
+ try {
330
+ await session.streamer.stop(text ? { markdown_text: text } : void 0);
331
+ session.delivered = true;
332
+ session.pendingText = "";
333
+ } catch (err) {
334
+ if (isBenignSlackFinalizeError(err)) {
335
+ const code = extractSlackErrorCode(err) ?? "unknown";
336
+ if (session.pendingText) throw new SlackStreamNotDeliveredError(session.pendingText, code);
337
+ if (session.delivered) {
338
+ logVerbose(`slack-stream: finalize rejected by Slack (${code}); prior appends delivered, treating stream as stopped`);
339
+ return;
340
+ }
341
+ }
342
+ throw err;
343
+ }
344
+ logVerbose("slack-stream: stream stopped");
345
+ }
346
+ /**
347
+ * Slack API error codes that indicate `chat.stopStream` (or the
348
+ * `chat.startStream` call the SDK issues inside `stop()` when the buffer
349
+ * never flushed) cannot finalize the stream for the current recipient or
350
+ * team. Either the caller falls back to a normal message (see
351
+ * {@link SlackStreamNotDeliveredError}) or, if prior appends already
352
+ * delivered text, the error is logged verbosely and swallowed.
353
+ */
354
+ const BENIGN_SLACK_FINALIZE_ERROR_CODES = new Set([
355
+ "user_not_found",
356
+ "team_not_found",
357
+ "missing_recipient_user_id"
358
+ ]);
359
+ function isBenignSlackFinalizeError(err) {
360
+ const code = extractSlackErrorCode(err);
361
+ return code !== void 0 && BENIGN_SLACK_FINALIZE_ERROR_CODES.has(code);
362
+ }
363
+ function extractSlackErrorCode(err) {
364
+ if (!err || typeof err !== "object") return;
365
+ const record = err;
366
+ if (record.data && typeof record.data === "object") {
367
+ const inner = record.data.error;
368
+ if (typeof inner === "string") return inner;
369
+ }
370
+ return (typeof record.message === "string" ? record.message : "").match(/An API error occurred:\s*([a-z_][a-z0-9_]*)/i)?.[1];
371
+ }
372
+ function markSlackStreamFallbackDelivered(session) {
373
+ const hadNativeDelivery = session.delivered;
374
+ session.pendingText = "";
375
+ session.delivered = true;
376
+ if (!hadNativeDelivery) session.stopped = true;
377
+ }
378
+ //#endregion
379
+ //#region extensions/slack/src/monitor/message-handler/preview-finalize.ts
380
+ function buildExpectedSlackEditText(params) {
381
+ return buildSlackEditTextPayload(params.text, params.blocks);
382
+ }
383
+ function blocksMatch(expected, actual) {
384
+ if (!expected?.length) return !actual?.length;
385
+ if (!actual?.length) return false;
386
+ return JSON.stringify(expected) === JSON.stringify(actual);
387
+ }
388
+ async function readSlackMessageAfterEditError(params) {
389
+ if (params.threadTs) return ((await params.client.conversations.replies({
390
+ token: params.token,
391
+ channel: params.channelId,
392
+ ts: params.threadTs,
393
+ latest: params.messageId,
394
+ inclusive: true,
395
+ limit: 100
396
+ })).messages ?? []).find((message) => message?.ts === params.messageId) ?? null;
397
+ const message = (await params.client.conversations.history({
398
+ token: params.token,
399
+ channel: params.channelId,
400
+ latest: params.messageId,
401
+ oldest: params.messageId,
402
+ inclusive: true,
403
+ limit: 1
404
+ })).messages?.[0];
405
+ if (!message?.ts || message.ts !== params.messageId) return null;
406
+ return message;
407
+ }
408
+ async function didSlackPreviewEditApplyAfterError(params) {
409
+ const readback = await readSlackMessageAfterEditError(params);
410
+ if (!readback) return false;
411
+ const expectedText = buildExpectedSlackEditText({
412
+ text: params.text,
413
+ blocks: params.blocks
414
+ });
415
+ const actualText = normalizeSlackOutboundText((readback.text ?? "").trim());
416
+ if (params.blocks?.length) return actualText === expectedText && blocksMatch(params.blocks, readback.blocks);
417
+ return actualText === expectedText;
418
+ }
419
+ async function finalizeSlackPreviewEdit(params) {
420
+ try {
421
+ await editSlackMessage(params.channelId, params.messageId, params.text, {
422
+ token: params.token,
423
+ accountId: params.accountId,
424
+ client: params.client,
425
+ ...params.blocks?.length ? { blocks: params.blocks } : {}
426
+ });
427
+ return;
428
+ } catch (err) {
429
+ try {
430
+ if (await didSlackPreviewEditApplyAfterError({
431
+ client: params.client,
432
+ token: params.token,
433
+ channelId: params.channelId,
434
+ messageId: params.messageId,
435
+ text: params.text,
436
+ blocks: params.blocks,
437
+ threadTs: params.threadTs
438
+ })) {
439
+ logVerbose(`slack: preview final edit response failed but readback matched message ${params.channelId}/${params.messageId}; suppressing duplicate fallback send`);
440
+ return;
441
+ }
442
+ } catch (readbackErr) {
443
+ logVerbose(`slack: preview final edit readback failed (${String(readbackErr)})`);
444
+ }
445
+ throw err;
446
+ }
447
+ }
448
+ //#endregion
449
+ //#region extensions/slack/src/monitor/message-handler/dispatch.ts
450
+ const UNICODE_TO_SLACK = {
451
+ "👀": "eyes",
452
+ "🤔": "thinking_face",
453
+ "🔥": "fire",
454
+ "👨‍💻": "male-technologist",
455
+ "👨💻": "male-technologist",
456
+ "👩‍💻": "female-technologist",
457
+ "⚡": "zap",
458
+ "🌐": "globe_with_meridians",
459
+ "✅": "white_check_mark",
460
+ "👍": "thumbsup",
461
+ "❌": "x",
462
+ "😱": "scream",
463
+ "🥱": "yawning_face",
464
+ "😨": "fearful",
465
+ "⏳": "hourglass_flowing_sand",
466
+ "⚠️": "warning",
467
+ "✍": "writing_hand",
468
+ "🧠": "brain",
469
+ "🛠️": "hammer_and_wrench",
470
+ "💻": "computer"
471
+ };
472
+ function toSlackEmojiName(emoji) {
473
+ let trimmed = emoji.trim();
474
+ while (trimmed.startsWith(":")) trimmed = trimmed.slice(1);
475
+ while (trimmed.endsWith(":")) trimmed = trimmed.slice(0, -1);
476
+ return UNICODE_TO_SLACK[trimmed] ?? trimmed;
477
+ }
478
+ function isSlackStreamingEnabled(params) {
479
+ if (params.mode !== "partial") return false;
480
+ return params.nativeStreaming;
481
+ }
482
+ function shouldEnableSlackPreviewStreaming(params) {
483
+ return params.mode !== "off";
484
+ }
485
+ function shouldInitializeSlackDraftStream(params) {
486
+ return params.previewStreamingEnabled && !params.useStreaming;
487
+ }
488
+ function resolveSlackDisableBlockStreaming(params) {
489
+ if (params.useStreaming || params.shouldUseDraftStream) return true;
490
+ return typeof params.blockStreamingEnabled === "boolean" ? !params.blockStreamingEnabled : void 0;
491
+ }
492
+ function resolveSlackStreamingThreadHint(params) {
493
+ return resolveSlackThreadTs({
494
+ replyToMode: params.replyToMode,
495
+ incomingThreadTs: params.incomingThreadTs,
496
+ messageTs: params.messageTs,
497
+ hasReplied: false,
498
+ isThreadReply: params.isThreadReply
499
+ });
500
+ }
501
+ const SLACK_STREAM_RECIPIENT_TEAM_CACHE_MAX = 2e3;
502
+ const slackStreamRecipientTeamCache = /* @__PURE__ */ new Map();
503
+ function buildSlackTurnDeliveryKey(params) {
504
+ const reply = resolveSendableOutboundReplyParts(params.payload, { text: params.textOverride });
505
+ const slackBlocks = readSlackReplyBlocks(params.payload);
506
+ if (!reply.hasContent && !slackBlocks?.length) return null;
507
+ return JSON.stringify({
508
+ kind: params.kind,
509
+ threadTs: params.threadTs ?? "",
510
+ replyToId: params.payload.replyToId ?? null,
511
+ text: reply.trimmedText,
512
+ mediaUrls: reply.mediaUrls,
513
+ blocks: slackBlocks ?? null
514
+ });
515
+ }
516
+ function readSlackStreamRecipientTeamCache(params) {
517
+ if (!params.fallbackTeamId || !params.userId) return;
518
+ const cacheKey = `${params.fallbackTeamId}:${params.userId}`;
519
+ const cached = slackStreamRecipientTeamCache.get(cacheKey);
520
+ if (!cached) return;
521
+ slackStreamRecipientTeamCache.delete(cacheKey);
522
+ slackStreamRecipientTeamCache.set(cacheKey, cached);
523
+ return cached;
524
+ }
525
+ function rememberSlackStreamRecipientTeam(params) {
526
+ if (!params.fallbackTeamId || !params.userId) return;
527
+ const cacheKey = `${params.fallbackTeamId}:${params.userId}`;
528
+ if (slackStreamRecipientTeamCache.has(cacheKey)) slackStreamRecipientTeamCache.delete(cacheKey);
529
+ slackStreamRecipientTeamCache.set(cacheKey, params.teamId);
530
+ if (slackStreamRecipientTeamCache.size > SLACK_STREAM_RECIPIENT_TEAM_CACHE_MAX) {
531
+ const oldest = slackStreamRecipientTeamCache.keys().next().value;
532
+ if (oldest) slackStreamRecipientTeamCache.delete(oldest);
533
+ }
534
+ }
535
+ function createSlackTurnDeliveryTracker() {
536
+ const deliveredKeys = /* @__PURE__ */ new Set();
537
+ return {
538
+ hasDelivered(params) {
539
+ const key = buildSlackTurnDeliveryKey(params);
540
+ return key ? deliveredKeys.has(key) : false;
541
+ },
542
+ markDelivered(params) {
543
+ const key = buildSlackTurnDeliveryKey(params);
544
+ if (key) deliveredKeys.add(key);
545
+ }
546
+ };
547
+ }
548
+ function shouldUseStreaming(params) {
549
+ if (!params.streamingEnabled) return false;
550
+ if (!params.threadTs) {
551
+ logVerbose("slack-stream: streaming disabled — no reply thread target available");
552
+ return false;
553
+ }
554
+ return true;
555
+ }
556
+ async function resolveSlackStreamRecipientTeamId(params) {
557
+ const cachedTeamId = readSlackStreamRecipientTeamCache(params);
558
+ if (cachedTeamId) return cachedTeamId;
559
+ if (params.userId) try {
560
+ const info = await params.client.users.info({
561
+ token: params.token,
562
+ user: params.userId
563
+ });
564
+ const teamId = info.user?.team_id ?? info.user?.profile?.team;
565
+ if (teamId) {
566
+ rememberSlackStreamRecipientTeam({
567
+ ...params,
568
+ teamId
569
+ });
570
+ return teamId;
571
+ }
572
+ } catch (err) {
573
+ logVerbose(`slack-stream: users.info team lookup failed (${formatErrorMessage(err)})`);
574
+ }
575
+ return params.fallbackTeamId;
576
+ }
577
+ async function dispatchPreparedSlackMessage(prepared) {
578
+ const { ctx, account, message, route } = prepared;
579
+ const cfg = ctx.cfg;
580
+ const runtime = ctx.runtime;
581
+ const outboundIdentity = resolveAgentOutboundIdentity(cfg, route.agentId);
582
+ const slackIdentity = outboundIdentity ? {
583
+ username: outboundIdentity.name,
584
+ iconUrl: outboundIdentity.avatarUrl,
585
+ iconEmoji: outboundIdentity.emoji
586
+ } : void 0;
587
+ if (prepared.isDirectMessage) {
588
+ const sessionCfg = cfg.session;
589
+ const storePath = resolveStorePath(sessionCfg?.store, { agentId: route.agentId });
590
+ const pinnedMainDmOwner = resolvePinnedMainDmOwnerFromAllowlist({
591
+ dmScope: cfg.session?.dmScope,
592
+ allowFrom: ctx.allowFrom,
593
+ normalizeEntry: normalizeSlackAllowOwnerEntry
594
+ });
595
+ const senderRecipient = normalizeOptionalLowercaseString(message.user);
596
+ if (pinnedMainDmOwner && senderRecipient && normalizeOptionalLowercaseString(pinnedMainDmOwner) !== senderRecipient) logVerbose(`slack: skip main-session last route for ${senderRecipient} (pinned owner ${pinnedMainDmOwner})`);
597
+ else await updateLastRoute({
598
+ storePath,
599
+ sessionKey: resolveInboundLastRouteSessionKey({
600
+ route,
601
+ sessionKey: prepared.ctxPayload.SessionKey ?? route.sessionKey
602
+ }),
603
+ deliveryContext: {
604
+ channel: "slack",
605
+ to: `user:${message.user}`,
606
+ accountId: route.accountId,
607
+ threadId: prepared.ctxPayload.MessageThreadId
608
+ },
609
+ ctx: prepared.ctxPayload
610
+ });
611
+ }
612
+ const { statusThreadTs, isThreadReply } = resolveSlackThreadTargets({
613
+ message,
614
+ replyToMode: prepared.replyToMode
615
+ });
616
+ const sourceReplyDeliveryMode = resolveChannelMessageSourceReplyDeliveryMode({
617
+ cfg,
618
+ ctx: prepared.ctxPayload
619
+ });
620
+ const sourceRepliesAreToolOnly = sourceReplyDeliveryMode === "message_tool_only";
621
+ const reactionMessageTs = prepared.ackReactionMessageTs;
622
+ const messageTs = message.ts ?? message.event_ts;
623
+ const incomingThreadTs = message.thread_ts;
624
+ let didSetStatus = false;
625
+ const statusReactionsEnabled = Boolean(prepared.ackReactionPromise) && Boolean(reactionMessageTs) && cfg.messages?.statusReactions?.enabled !== false;
626
+ const slackStatusAdapter = {
627
+ setReaction: async (emoji) => {
628
+ await reactSlackMessage(message.channel, reactionMessageTs ?? "", toSlackEmojiName(emoji), {
629
+ token: ctx.botToken,
630
+ client: ctx.app.client
631
+ }).catch((err) => {
632
+ if (formatErrorMessage(err).includes("already_reacted")) return;
633
+ throw err;
634
+ });
635
+ },
636
+ removeReaction: async (emoji) => {
637
+ await removeSlackReaction(message.channel, reactionMessageTs ?? "", toSlackEmojiName(emoji), {
638
+ token: ctx.botToken,
639
+ client: ctx.app.client
640
+ }).catch((err) => {
641
+ if (formatErrorMessage(err).includes("no_reaction")) return;
642
+ throw err;
643
+ });
644
+ }
645
+ };
646
+ const statusReactionTiming = {
647
+ ...DEFAULT_TIMING,
648
+ ...cfg.messages?.statusReactions?.timing
649
+ };
650
+ const statusReactions = createStatusReactionController({
651
+ enabled: statusReactionsEnabled,
652
+ adapter: slackStatusAdapter,
653
+ initialEmoji: prepared.ackReactionValue || "eyes",
654
+ emojis: cfg.messages?.statusReactions?.emojis,
655
+ timing: cfg.messages?.statusReactions?.timing,
656
+ onError: (err) => {
657
+ logAckFailure({
658
+ log: logVerbose,
659
+ channel: "slack",
660
+ target: `${message.channel}/${message.ts}`,
661
+ error: err
662
+ });
663
+ }
664
+ });
665
+ if (statusReactionsEnabled) statusReactions.setQueued();
666
+ const hasRepliedRef = { value: false };
667
+ const replyPlan = createSlackReplyDeliveryPlan({
668
+ replyToMode: prepared.replyToMode,
669
+ incomingThreadTs,
670
+ messageTs,
671
+ hasRepliedRef,
672
+ isThreadReply
673
+ });
674
+ const typingTarget = statusThreadTs ? `${message.channel}/${statusThreadTs}` : message.channel;
675
+ const typingReaction = ctx.typingReaction;
676
+ const { onModelSelected, ...replyPipeline } = createChannelMessageReplyPipeline({
677
+ cfg,
678
+ agentId: route.agentId,
679
+ channel: "slack",
680
+ accountId: route.accountId,
681
+ transformReplyPayload: (payload) => isSlackInteractiveRepliesEnabled({
682
+ cfg,
683
+ accountId: route.accountId
684
+ }) ? compileSlackInteractiveReplies(payload) : payload,
685
+ typing: {
686
+ start: async () => {
687
+ didSetStatus = true;
688
+ await ctx.setSlackThreadStatus({
689
+ channelId: message.channel,
690
+ threadTs: statusThreadTs,
691
+ status: "is typing..."
692
+ });
693
+ if (typingReaction && message.ts) await reactSlackMessage(message.channel, message.ts, typingReaction, {
694
+ token: ctx.botToken,
695
+ client: ctx.app.client
696
+ }).catch(() => {});
697
+ },
698
+ stop: async () => {
699
+ if (!didSetStatus) return;
700
+ didSetStatus = false;
701
+ await ctx.setSlackThreadStatus({
702
+ channelId: message.channel,
703
+ threadTs: statusThreadTs,
704
+ status: ""
705
+ });
706
+ if (typingReaction && message.ts) await removeSlackReaction(message.channel, message.ts, typingReaction, {
707
+ token: ctx.botToken,
708
+ client: ctx.app.client
709
+ }).catch(() => {});
710
+ },
711
+ onStartError: (err) => {
712
+ logTypingFailure({
713
+ log: (message) => runtime.error?.(danger(message)),
714
+ channel: "slack",
715
+ action: "start",
716
+ target: typingTarget,
717
+ error: err
718
+ });
719
+ },
720
+ onStopError: (err) => {
721
+ logTypingFailure({
722
+ log: (message) => runtime.error?.(danger(message)),
723
+ channel: "slack",
724
+ action: "stop",
725
+ target: typingTarget,
726
+ error: err
727
+ });
728
+ }
729
+ }
730
+ });
731
+ const slackStreaming = resolveSlackStreamingConfig({
732
+ streaming: account.config.streaming,
733
+ nativeStreaming: resolveChannelStreamingNativeTransport(account.config)
734
+ });
735
+ const streamThreadHint = resolveSlackStreamingThreadHint({
736
+ replyToMode: prepared.replyToMode,
737
+ incomingThreadTs,
738
+ messageTs,
739
+ isThreadReply
740
+ });
741
+ const previewStreamingEnabled = !sourceRepliesAreToolOnly && shouldEnableSlackPreviewStreaming({ mode: slackStreaming.mode });
742
+ const useStreaming = shouldUseStreaming({
743
+ streamingEnabled: !sourceRepliesAreToolOnly && isSlackStreamingEnabled({
744
+ mode: slackStreaming.mode,
745
+ nativeStreaming: slackStreaming.nativeStreaming
746
+ }),
747
+ threadTs: streamThreadHint
748
+ });
749
+ const shouldUseDraftStream = shouldInitializeSlackDraftStream({
750
+ previewStreamingEnabled,
751
+ useStreaming
752
+ });
753
+ const blockStreamingEnabled = resolveChannelStreamingBlockEnabled(account.config);
754
+ const disableBlockStreaming = sourceRepliesAreToolOnly ? true : resolveSlackDisableBlockStreaming({
755
+ useStreaming,
756
+ shouldUseDraftStream,
757
+ blockStreamingEnabled
758
+ });
759
+ let streamSession = null;
760
+ let streamFailed = false;
761
+ let usedReplyThreadTs;
762
+ let usedBlockReplyThreadTs;
763
+ let observedReplyDelivery = false;
764
+ const deliveryTracker = createSlackTurnDeliveryTracker();
765
+ const resolveDeliveryThreadTs = (params) => {
766
+ const plannedThreadTs = params.forcedThreadTs ? void 0 : replyPlan.nextThreadTs();
767
+ return params.forcedThreadTs ?? plannedThreadTs ?? (params.kind === "block" ? usedBlockReplyThreadTs : void 0);
768
+ };
769
+ const rememberDeliveredThreadTs = (kind, deliveredThreadTs) => {
770
+ if (!deliveredThreadTs) return;
771
+ usedReplyThreadTs ??= deliveredThreadTs;
772
+ if (kind === "block") usedBlockReplyThreadTs = deliveredThreadTs;
773
+ };
774
+ const deliverPendingStreamFallback = async (session, err) => {
775
+ const fallbackText = err.pendingText.trim();
776
+ if (!fallbackText) return false;
777
+ try {
778
+ await deliverReplies({
779
+ cfg: ctx.cfg,
780
+ replies: [{ text: fallbackText }],
781
+ target: prepared.replyTarget,
782
+ token: ctx.botToken,
783
+ accountId: account.accountId,
784
+ runtime,
785
+ textLimit: ctx.textLimit,
786
+ replyThreadTs: session.threadTs,
787
+ replyToMode: prepared.replyToMode,
788
+ ...slackIdentity ? { identity: slackIdentity } : {}
789
+ });
790
+ markSlackStreamFallbackDelivered(session);
791
+ observedReplyDelivery = true;
792
+ usedReplyThreadTs ??= session.threadTs;
793
+ logVerbose(`slack-stream: streamed delivery failed (${err.slackCode}); delivered ${fallbackText.length} chars via deliverReplies fallback`);
794
+ return true;
795
+ } catch (postErr) {
796
+ runtime.error?.(danger(`slack-stream: fallback deliverReplies failed after ${err.slackCode}: ${formatErrorMessage(postErr)}`));
797
+ return false;
798
+ }
799
+ };
800
+ const deliverNormally = async (params) => {
801
+ const replyThreadTs = resolveDeliveryThreadTs(params);
802
+ if (deliveryTracker.hasDelivered({
803
+ kind: params.kind,
804
+ payload: params.payload,
805
+ threadTs: replyThreadTs
806
+ })) {
807
+ logVerbose("slack: suppressed duplicate normal delivery within the same turn");
808
+ return;
809
+ }
810
+ await deliverReplies({
811
+ cfg: ctx.cfg,
812
+ replies: [params.payload],
813
+ target: prepared.replyTarget,
814
+ token: ctx.botToken,
815
+ accountId: account.accountId,
816
+ runtime,
817
+ textLimit: ctx.textLimit,
818
+ replyThreadTs,
819
+ replyToMode: prepared.replyToMode,
820
+ ...slackIdentity ? { identity: slackIdentity } : {}
821
+ });
822
+ observedReplyDelivery = true;
823
+ const deliveredThreadTs = resolveDeliveredSlackReplyThreadTs({
824
+ replyToMode: prepared.replyToMode,
825
+ payloadReplyToId: params.payload.replyToId,
826
+ replyThreadTs
827
+ });
828
+ rememberDeliveredThreadTs(params.kind, deliveredThreadTs);
829
+ replyPlan.markSent();
830
+ deliveryTracker.markDelivered({
831
+ kind: params.kind,
832
+ payload: params.payload,
833
+ threadTs: replyThreadTs
834
+ });
835
+ };
836
+ const deliverBufferedStreamFallback = async (params) => {
837
+ if (!await deliverPendingStreamFallback(params.session, params.err)) return false;
838
+ replyPlan.markSent();
839
+ deliveryTracker.markDelivered({
840
+ kind: params.kind,
841
+ payload: params.payload,
842
+ threadTs: params.session.threadTs,
843
+ textOverride: params.textOverride
844
+ });
845
+ rememberDeliveredThreadTs(params.kind, params.session.threadTs);
846
+ return true;
847
+ };
848
+ const deliverWithStreaming = async (params) => {
849
+ if (params.payload.isReasoning === true) return;
850
+ const reply = resolveSendableOutboundReplyParts(params.payload);
851
+ if (streamFailed || reply.hasMedia || readSlackReplyBlocks(params.payload)?.length || !reply.hasText) {
852
+ await deliverNormally({
853
+ payload: params.payload,
854
+ kind: params.kind,
855
+ forcedThreadTs: streamSession?.threadTs
856
+ });
857
+ return;
858
+ }
859
+ const text = reply.trimmedText;
860
+ let plannedThreadTs;
861
+ try {
862
+ if (!streamSession) {
863
+ const streamThreadTs = replyPlan.nextThreadTs();
864
+ plannedThreadTs = streamThreadTs;
865
+ if (!streamThreadTs) {
866
+ logVerbose("slack-stream: no reply thread target for stream start, falling back to normal delivery");
867
+ streamFailed = true;
868
+ await deliverNormally({
869
+ payload: params.payload,
870
+ kind: params.kind
871
+ });
872
+ return;
873
+ }
874
+ if (deliveryTracker.hasDelivered({
875
+ kind: params.kind,
876
+ payload: params.payload,
877
+ threadTs: streamThreadTs,
878
+ textOverride: text
879
+ })) {
880
+ logVerbose("slack-stream: suppressed duplicate stream start payload");
881
+ return;
882
+ }
883
+ streamSession = await startSlackStream({
884
+ client: ctx.app.client,
885
+ channel: message.channel,
886
+ threadTs: streamThreadTs,
887
+ text,
888
+ teamId: await resolveSlackStreamRecipientTeamId({
889
+ client: ctx.app.client,
890
+ token: ctx.botToken,
891
+ userId: message.user,
892
+ fallbackTeamId: ctx.teamId
893
+ }),
894
+ userId: message.user
895
+ });
896
+ if (streamSession.delivered) observedReplyDelivery = true;
897
+ rememberDeliveredThreadTs(params.kind, streamThreadTs);
898
+ replyPlan.markSent();
899
+ deliveryTracker.markDelivered({
900
+ kind: params.kind,
901
+ payload: params.payload,
902
+ threadTs: streamThreadTs,
903
+ textOverride: text
904
+ });
905
+ return;
906
+ }
907
+ if (deliveryTracker.hasDelivered({
908
+ kind: params.kind,
909
+ payload: params.payload,
910
+ threadTs: streamSession.threadTs,
911
+ textOverride: text
912
+ })) {
913
+ logVerbose("slack-stream: suppressed duplicate append payload");
914
+ return;
915
+ }
916
+ await appendSlackStream({
917
+ session: streamSession,
918
+ text: "\n" + text
919
+ });
920
+ if (streamSession.delivered) observedReplyDelivery = true;
921
+ deliveryTracker.markDelivered({
922
+ kind: params.kind,
923
+ payload: params.payload,
924
+ threadTs: streamSession.threadTs,
925
+ textOverride: text
926
+ });
927
+ } catch (err) {
928
+ if (err instanceof SlackStreamNotDeliveredError) {
929
+ streamFailed = true;
930
+ if (streamSession) {
931
+ if (await deliverBufferedStreamFallback({
932
+ session: streamSession,
933
+ err,
934
+ payload: params.payload,
935
+ kind: params.kind,
936
+ textOverride: text
937
+ })) return;
938
+ throw err;
939
+ }
940
+ await deliverNormally({
941
+ payload: params.payload,
942
+ kind: params.kind,
943
+ forcedThreadTs: plannedThreadTs
944
+ });
945
+ return;
946
+ }
947
+ runtime.error?.(danger(`slack-stream: streaming API call failed: ${formatSlackError(err)}, falling back`));
948
+ streamFailed = true;
949
+ if (streamSession && streamSession.pendingText) {
950
+ const bufferedFallbackErr = new SlackStreamNotDeliveredError(streamSession.pendingText, "unknown");
951
+ if (await deliverBufferedStreamFallback({
952
+ session: streamSession,
953
+ err: bufferedFallbackErr,
954
+ payload: params.payload,
955
+ kind: params.kind,
956
+ textOverride: text
957
+ })) return;
958
+ }
959
+ await deliverNormally({
960
+ payload: params.payload,
961
+ kind: params.kind,
962
+ forcedThreadTs: streamSession?.threadTs ?? plannedThreadTs
963
+ });
964
+ }
965
+ };
966
+ const { dispatcher, replyOptions, markDispatchIdle } = createReplyDispatcherWithTyping({
967
+ ...replyPipeline,
968
+ humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
969
+ deliver: async (payload, info) => {
970
+ if (useStreaming) {
971
+ await deliverWithStreaming({
972
+ payload,
973
+ kind: info.kind
974
+ });
975
+ return;
976
+ }
977
+ const reply = resolveSendableOutboundReplyParts(payload);
978
+ const slackBlocks = readSlackReplyBlocks(payload);
979
+ const trimmedFinalText = reply.trimmedText;
980
+ if ((await deliverWithFinalizableLivePreviewAdapter({
981
+ kind: info.kind,
982
+ payload,
983
+ adapter: defineFinalizableLivePreviewAdapter({
984
+ draft: draftStream ? {
985
+ flush: draftStream.flush,
986
+ clear: draftStream.clear,
987
+ discardPending: draftStream.discardPending,
988
+ seal: draftStream.seal,
989
+ id: () => {
990
+ const channelId = draftStream.channelId();
991
+ const messageId = draftStream.messageId();
992
+ return channelId && messageId ? {
993
+ channelId,
994
+ messageId
995
+ } : void 0;
996
+ }
997
+ } : void 0,
998
+ buildFinalEdit: () => {
999
+ if (!previewStreamingEnabled || reply.hasMedia || payload.isError || trimmedFinalText.length === 0 && !slackBlocks?.length) return;
1000
+ return {
1001
+ text: normalizeSlackOutboundText(trimmedFinalText),
1002
+ blocks: slackBlocks,
1003
+ threadTs: usedReplyThreadTs ?? statusThreadTs
1004
+ };
1005
+ },
1006
+ editFinal: async (preview, edit) => {
1007
+ if (deliveryTracker.hasDelivered({
1008
+ kind: info.kind,
1009
+ payload,
1010
+ threadTs: edit.threadTs
1011
+ })) return;
1012
+ await finalizeSlackPreviewEdit({
1013
+ client: ctx.app.client,
1014
+ token: ctx.botToken,
1015
+ accountId: account.accountId,
1016
+ channelId: preview.channelId,
1017
+ messageId: preview.messageId,
1018
+ text: edit.text,
1019
+ ...edit.blocks?.length ? { blocks: edit.blocks } : {},
1020
+ threadTs: edit.threadTs
1021
+ });
1022
+ },
1023
+ onPreviewFinalized: (_preview) => {
1024
+ const finalThreadTs = usedReplyThreadTs ?? statusThreadTs;
1025
+ observedReplyDelivery = true;
1026
+ replyPlan.markSent();
1027
+ deliveryTracker.markDelivered({
1028
+ kind: info.kind,
1029
+ payload,
1030
+ threadTs: finalThreadTs
1031
+ });
1032
+ },
1033
+ logPreviewEditFailure: (err) => {
1034
+ logVerbose(`slack: preview final edit failed; falling back to standard send (${formatSlackError(err)})`);
1035
+ }
1036
+ }),
1037
+ deliverNormally: async () => {
1038
+ await deliverNormally({
1039
+ payload,
1040
+ kind: info.kind
1041
+ });
1042
+ }
1043
+ })).kind === "preview-finalized") return;
1044
+ },
1045
+ onError: (err, info) => {
1046
+ runtime.error?.(danger(`slack ${info.kind} reply failed: ${formatSlackError(err)}`));
1047
+ replyPipeline.typingCallbacks?.onIdle?.();
1048
+ }
1049
+ });
1050
+ const draftStream = shouldUseDraftStream ? createSlackDraftStream({
1051
+ target: prepared.replyTarget,
1052
+ cfg,
1053
+ token: ctx.botToken,
1054
+ accountId: account.accountId,
1055
+ identity: slackIdentity,
1056
+ maxChars: Math.min(ctx.textLimit, SLACK_TEXT_LIMIT),
1057
+ resolveThreadTs: () => {
1058
+ const ts = replyPlan.peekThreadTs();
1059
+ if (ts) usedReplyThreadTs ??= ts;
1060
+ return ts;
1061
+ },
1062
+ log: logVerbose,
1063
+ warn: logVerbose
1064
+ }) : void 0;
1065
+ let hasStreamedMessage = false;
1066
+ const streamMode = slackStreaming.draftMode;
1067
+ const previewToolProgressEnabled = Boolean(draftStream) && resolveChannelStreamingPreviewToolProgress(account.config);
1068
+ const suppressDefaultToolProgressMessages = resolveChannelStreamingSuppressDefaultToolProgressMessages(account.config, {
1069
+ draftStreamActive: Boolean(draftStream),
1070
+ previewToolProgressEnabled,
1071
+ previewStreamingEnabled
1072
+ });
1073
+ let previewToolProgressSuppressed = false;
1074
+ let previewToolProgressLines = [];
1075
+ let appendRenderedText = "";
1076
+ let appendSourceText = "";
1077
+ let statusUpdateCount = 0;
1078
+ const progressSeed = `${account.accountId}:${message.channel}`;
1079
+ const useRichProgressDraft = streamMode === "status_final" && resolveChannelProgressDraftRender(account.config) === "rich";
1080
+ const renderProgressDraft = () => {
1081
+ if (!draftStream || streamMode !== "status_final") return;
1082
+ const previewText = formatChannelProgressDraftText({
1083
+ entry: account.config,
1084
+ lines: previewToolProgressLines,
1085
+ seed: progressSeed,
1086
+ formatLine: escapeSlackMrkdwn
1087
+ });
1088
+ if (!previewText) return;
1089
+ draftStream.update(useRichProgressDraft ? {
1090
+ text: previewText,
1091
+ blocks: buildSlackProgressDraftBlocks({
1092
+ label: resolveChannelProgressDraftLabel({
1093
+ entry: account.config,
1094
+ seed: progressSeed
1095
+ }),
1096
+ lines: previewToolProgressLines
1097
+ })
1098
+ } : previewText);
1099
+ hasStreamedMessage = true;
1100
+ };
1101
+ const progressDraftGate = createChannelProgressDraftGate({ onStart: renderProgressDraft });
1102
+ const pushPreviewToolProgress = async (line, options) => {
1103
+ if (!draftStream) return;
1104
+ if (options?.toolName !== void 0 && !isChannelProgressDraftWorkToolName(options.toolName)) return;
1105
+ const normalized = line?.text.replace(/\s+/g, " ").trim();
1106
+ if (!line || !normalized) {
1107
+ if (streamMode !== "status_final") return;
1108
+ const alreadyStarted = progressDraftGate.hasStarted;
1109
+ await progressDraftGate.noteWork();
1110
+ if (alreadyStarted && progressDraftGate.hasStarted) renderProgressDraft();
1111
+ return;
1112
+ }
1113
+ if (streamMode !== "status_final") {
1114
+ if (!previewToolProgressEnabled || previewToolProgressSuppressed) return;
1115
+ if (previewToolProgressLines.at(-1)?.text === normalized) return;
1116
+ previewToolProgressLines = [...previewToolProgressLines, line].slice(-resolveChannelProgressDraftMaxLines(account.config));
1117
+ draftStream.update(formatChannelProgressDraftText({
1118
+ entry: account.config,
1119
+ lines: previewToolProgressLines,
1120
+ seed: progressSeed,
1121
+ formatLine: escapeSlackMrkdwn
1122
+ }));
1123
+ hasStreamedMessage = true;
1124
+ return;
1125
+ }
1126
+ if (previewToolProgressEnabled && !previewToolProgressSuppressed) {
1127
+ if (previewToolProgressLines.at(-1)?.text !== normalized) previewToolProgressLines = [...previewToolProgressLines, line].slice(-resolveChannelProgressDraftMaxLines(account.config));
1128
+ }
1129
+ const alreadyStarted = progressDraftGate.hasStarted;
1130
+ await progressDraftGate.noteWork();
1131
+ if (alreadyStarted && progressDraftGate.hasStarted) renderProgressDraft();
1132
+ };
1133
+ const updateDraftFromPartial = (text) => {
1134
+ const trimmed = text?.trimEnd();
1135
+ if (!trimmed) return;
1136
+ if (streamMode === "append") {
1137
+ previewToolProgressSuppressed = true;
1138
+ previewToolProgressLines = [];
1139
+ const next = applyAppendOnlyStreamUpdate({
1140
+ incoming: trimmed,
1141
+ rendered: appendRenderedText,
1142
+ source: appendSourceText
1143
+ });
1144
+ appendRenderedText = next.rendered;
1145
+ appendSourceText = next.source;
1146
+ if (!next.changed) return;
1147
+ draftStream?.update(next.rendered);
1148
+ hasStreamedMessage = true;
1149
+ return;
1150
+ }
1151
+ if (streamMode === "status_final") {
1152
+ if (!progressDraftGate.hasStarted) return;
1153
+ statusUpdateCount += 1;
1154
+ if (statusUpdateCount > 1 && statusUpdateCount % 4 !== 0) return;
1155
+ renderProgressDraft();
1156
+ return;
1157
+ }
1158
+ previewToolProgressSuppressed = true;
1159
+ previewToolProgressLines = [];
1160
+ draftStream?.update(trimmed);
1161
+ hasStreamedMessage = true;
1162
+ };
1163
+ const onDraftBoundary = !shouldUseDraftStream ? void 0 : async () => {
1164
+ if (hasStreamedMessage) {
1165
+ draftStream?.forceNewMessage();
1166
+ hasStreamedMessage = false;
1167
+ appendRenderedText = "";
1168
+ appendSourceText = "";
1169
+ statusUpdateCount = 0;
1170
+ }
1171
+ previewToolProgressSuppressed = false;
1172
+ previewToolProgressLines = [];
1173
+ };
1174
+ let dispatchError;
1175
+ let queuedFinal = false;
1176
+ let counts = {};
1177
+ let dispatchSettledBeforeStart = false;
1178
+ try {
1179
+ const turnResult = await runInboundReplyTurn({
1180
+ channel: "slack",
1181
+ accountId: route.accountId,
1182
+ raw: prepared.message,
1183
+ adapter: {
1184
+ ingest: () => ({
1185
+ id: prepared.message.ts ?? `${prepared.ctxPayload.From}:${Date.now()}`,
1186
+ timestamp: prepared.message.ts ? Number(prepared.message.ts) * 1e3 : void 0,
1187
+ rawText: prepared.ctxPayload.RawBody ?? "",
1188
+ textForAgent: prepared.ctxPayload.BodyForAgent,
1189
+ textForCommands: prepared.ctxPayload.CommandBody,
1190
+ raw: prepared.message
1191
+ }),
1192
+ resolveTurn: () => ({
1193
+ channel: "slack",
1194
+ accountId: route.accountId,
1195
+ routeSessionKey: route.sessionKey,
1196
+ storePath: prepared.turn.storePath,
1197
+ ctxPayload: prepared.ctxPayload,
1198
+ recordInboundSession,
1199
+ record: prepared.turn.record,
1200
+ onPreDispatchFailure: async () => {
1201
+ dispatchSettledBeforeStart = true;
1202
+ await settleReplyDispatcher({
1203
+ dispatcher,
1204
+ onSettled: () => markDispatchIdle()
1205
+ });
1206
+ },
1207
+ runDispatch: () => dispatchInboundMessage({
1208
+ ctx: prepared.ctxPayload,
1209
+ cfg,
1210
+ dispatcher,
1211
+ replyOptions: {
1212
+ ...replyOptions,
1213
+ skillFilter: prepared.channelConfig?.skills,
1214
+ sourceReplyDeliveryMode,
1215
+ hasRepliedRef,
1216
+ disableBlockStreaming,
1217
+ onModelSelected,
1218
+ suppressDefaultToolProgressMessages: suppressDefaultToolProgressMessages ? true : void 0,
1219
+ onPartialReply: useStreaming ? void 0 : !previewStreamingEnabled ? void 0 : async (payload) => {
1220
+ updateDraftFromPartial(payload.text);
1221
+ },
1222
+ onAssistantMessageStart: onDraftBoundary,
1223
+ onReasoningEnd: onDraftBoundary,
1224
+ onReasoningStream: statusReactionsEnabled ? async () => {
1225
+ await statusReactions.setThinking();
1226
+ } : void 0,
1227
+ onToolStart: async (payload) => {
1228
+ if (statusReactionsEnabled) await statusReactions.setTool(payload.name);
1229
+ await pushPreviewToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
1230
+ event: "tool",
1231
+ name: payload.name,
1232
+ phase: payload.phase,
1233
+ args: payload.args
1234
+ }, payload.detailMode ? { detailMode: payload.detailMode } : void 0), { toolName: payload.name });
1235
+ },
1236
+ onItemEvent: async (payload) => {
1237
+ await pushPreviewToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
1238
+ event: "item",
1239
+ itemKind: payload.kind,
1240
+ title: payload.title,
1241
+ name: payload.name,
1242
+ phase: payload.phase,
1243
+ status: payload.status,
1244
+ summary: payload.summary,
1245
+ progressText: payload.progressText,
1246
+ meta: payload.meta
1247
+ }));
1248
+ },
1249
+ onPlanUpdate: async (payload) => {
1250
+ if (payload.phase !== "update") return;
1251
+ await pushPreviewToolProgress(buildChannelProgressDraftLine({
1252
+ event: "plan",
1253
+ phase: payload.phase,
1254
+ title: payload.title,
1255
+ explanation: payload.explanation,
1256
+ steps: payload.steps
1257
+ }));
1258
+ },
1259
+ onApprovalEvent: async (payload) => {
1260
+ if (payload.phase !== "requested") return;
1261
+ await pushPreviewToolProgress(buildChannelProgressDraftLine({
1262
+ event: "approval",
1263
+ phase: payload.phase,
1264
+ title: payload.title,
1265
+ command: payload.command,
1266
+ reason: payload.reason,
1267
+ message: payload.message
1268
+ }));
1269
+ },
1270
+ onCommandOutput: async (payload) => {
1271
+ if (payload.phase !== "end") return;
1272
+ await pushPreviewToolProgress(buildChannelProgressDraftLine({
1273
+ event: "command-output",
1274
+ phase: payload.phase,
1275
+ title: payload.title,
1276
+ name: payload.name,
1277
+ status: payload.status,
1278
+ exitCode: payload.exitCode
1279
+ }));
1280
+ },
1281
+ onPatchSummary: async (payload) => {
1282
+ if (payload.phase !== "end") return;
1283
+ await pushPreviewToolProgress(buildChannelProgressDraftLine({
1284
+ event: "patch",
1285
+ phase: payload.phase,
1286
+ title: payload.title,
1287
+ name: payload.name,
1288
+ added: payload.added,
1289
+ modified: payload.modified,
1290
+ deleted: payload.deleted,
1291
+ summary: payload.summary
1292
+ }));
1293
+ }
1294
+ }
1295
+ })
1296
+ })
1297
+ }
1298
+ });
1299
+ if (!turnResult.dispatched) return;
1300
+ const result = turnResult.dispatchResult;
1301
+ queuedFinal = result.queuedFinal;
1302
+ counts = result.counts;
1303
+ } catch (err) {
1304
+ dispatchError = err;
1305
+ } finally {
1306
+ progressDraftGate.cancel();
1307
+ await draftStream?.discardPending();
1308
+ if (!dispatchSettledBeforeStart) markDispatchIdle();
1309
+ }
1310
+ let streamFallbackDelivered = false;
1311
+ const finalStream = streamSession;
1312
+ if (finalStream && !finalStream.stopped) try {
1313
+ await stopSlackStream({ session: finalStream });
1314
+ } catch (err) {
1315
+ if (err instanceof SlackStreamNotDeliveredError) streamFallbackDelivered = await deliverPendingStreamFallback(finalStream, err);
1316
+ else runtime.error?.(danger(`slack-stream: failed to stop stream: ${formatSlackError(err)}`));
1317
+ }
1318
+ const anyReplyDelivered = hasVisibleInboundReplyDispatch({
1319
+ queuedFinal,
1320
+ counts
1321
+ }, {
1322
+ observedReplyDelivery,
1323
+ fallbackDelivered: streamFallbackDelivered
1324
+ });
1325
+ if (statusReactionsEnabled) if (dispatchError) {
1326
+ await statusReactions.setError();
1327
+ if (ctx.removeAckAfterReply) (async () => {
1328
+ await sleep(statusReactionTiming.errorHoldMs);
1329
+ if (anyReplyDelivered) await statusReactions.clear();
1330
+ })();
1331
+ } else if (anyReplyDelivered) {
1332
+ await statusReactions.setDone();
1333
+ if (ctx.removeAckAfterReply) (async () => {
1334
+ await sleep(statusReactionTiming.doneHoldMs);
1335
+ await statusReactions.clear();
1336
+ })();
1337
+ else statusReactions.restoreInitial();
1338
+ } else await statusReactions.restoreInitial();
1339
+ if (dispatchError) throw dispatchError;
1340
+ const participationThreadTs = usedReplyThreadTs ?? statusThreadTs;
1341
+ if (anyReplyDelivered && participationThreadTs) recordSlackThreadParticipation(account.accountId, message.channel, participationThreadTs, { agentId: route.agentId });
1342
+ if (!anyReplyDelivered) {
1343
+ await draftStream?.clear();
1344
+ if (prepared.isRoomish && prepared.requireMention) clearHistoryEntriesIfEnabled({
1345
+ historyMap: ctx.channelHistories,
1346
+ historyKey: prepared.historyKey,
1347
+ limit: ctx.historyLimit
1348
+ });
1349
+ return;
1350
+ }
1351
+ if (shouldLogVerbose()) {
1352
+ const finalCount = counts.final;
1353
+ logVerbose(`slack: delivered ${finalCount} reply${finalCount === 1 ? "" : "ies"} to ${prepared.replyTarget}`);
1354
+ }
1355
+ if (!statusReactionsEnabled) removeAckReactionAfterReply({
1356
+ removeAfterReply: ctx.removeAckAfterReply && anyReplyDelivered,
1357
+ ackReactionPromise: prepared.ackReactionPromise,
1358
+ ackReactionValue: prepared.ackReactionValue,
1359
+ remove: () => removeSlackReaction(message.channel, prepared.ackReactionMessageTs ?? "", prepared.ackReactionValue, {
1360
+ token: ctx.botToken,
1361
+ client: ctx.app.client
1362
+ }),
1363
+ onError: (err) => {
1364
+ logAckFailure({
1365
+ log: logVerbose,
1366
+ channel: "slack",
1367
+ target: `${message.channel}/${message.ts}`,
1368
+ error: err
1369
+ });
1370
+ }
1371
+ });
1372
+ if (prepared.isRoomish && prepared.requireMention) clearHistoryEntriesIfEnabled({
1373
+ historyMap: ctx.channelHistories,
1374
+ historyKey: prepared.historyKey,
1375
+ limit: ctx.historyLimit
1376
+ });
1377
+ }
1378
+ //#endregion
1379
+ export { dispatchPreparedSlackMessage, prepareSlackMessage };