@geminixiang/mikan 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,28 @@ any release.
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.4.2] - 2026-06-11
13
+
14
+ ### Fixed
15
+
16
+ - Resolve custom providers through pi's model registry so conversation settings can select models from `models.json`.
17
+ - Resolve attached file paths from the sandbox runtime workspace so image sandboxes upload generated files from the correct host path.
18
+
19
+ ## [0.4.1] - 2026-06-08
20
+
21
+ ### Changed
22
+
23
+ - Update bundled pi packages to the 0.78.1 line.
24
+
25
+ ### Fixed
26
+
27
+ - Stream Slack responses with delta-only appends to avoid duplicated message segments and streaming state conflicts.
28
+ - Include Slack streaming recipient metadata so threaded streamed replies work in Slack E2E and production workspaces.
29
+
30
+ ### Tests
31
+
32
+ - Add Slack streaming E2E coverage for delta appends without duplicate text.
33
+
12
34
  ## [0.4.0] - 2026-06-07
13
35
 
14
36
  ### Added
@@ -16,6 +16,7 @@ export declare class SlackBot implements Bot {
16
16
  private store;
17
17
  private botUserId;
18
18
  private botId;
19
+ private teamId;
19
20
  private ownMentionRegex;
20
21
  private startupTs;
21
22
  private users;
@@ -46,7 +47,7 @@ export declare class SlackBot implements Bot {
46
47
  }): Promise<void>;
47
48
  openDirectMessage(userId: string): Promise<string>;
48
49
  updateMessage(channel: string, ts: string, text: string): Promise<void>;
49
- startMessageStream(channel: string, text: string, threadTs?: string): Promise<string>;
50
+ startMessageStream(channel: string, text: string, threadTs?: string, recipientUserId?: string): Promise<string>;
50
51
  appendMessageStream(channel: string, ts: string, text: string): Promise<void>;
51
52
  stopMessageStream(channel: string, ts: string): Promise<void>;
52
53
  deleteMessage(channel: string, ts: string): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"bot.d.ts","sourceRoot":"","sources":["../../../src/adapters/slack/bot.ts"],"names":[],"mappings":"AAMA,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IAAI,CAE9C;IAED,cAAc,CACZ,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,QAAQ,CAAC,EAAE,MAAM,EACjB,WAAW,CAAC,EAAE,MAAM,EAAE,GACrB,IAAI,CAKN;IAED,eAAe,IAAI,YAAY,CAe9B;IAMD;;;OAGG;IACH,YAAY,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CA0ErC;IAMD,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,yBAAyB;IAuBjC,OAAO,CAAC,aAAa;IA4JrB,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,UAAU;IAKlB,OAAO,CAAC,qBAAqB;IAkF7B,OAAO,CAAC,sBAAsB;YA0DhB,sBAAsB;YActB,oBAAoB;YAyCpB,sBAAsB;YAWtB,wBAAwB;YAWxB,sBAAsB;IAWpC,OAAO,CAAC,kBAAkB;IAuB1B,OAAO,CAAC,gBAAgB;IAyExB,OAAO,CAAC,kBAAkB;YAgKZ,kBAAkB;IA8EhC,OAAO,CAAC,mBAAmB;YAeb,iBAAiB;IA6C/B,OAAO,CAAC,sBAAsB;YA+EhB,cAAc;YA4Bd,qBAAqB;YAwCrB,qBAAqB;YAqBrB,eAAe;YA2Gf,mBAAmB;YAsCnB,UAAU;YAsBV,aAAa;CA6C5B","sourcesContent":["import { SocketModeClient } from \"@slack/socket-mode\";\nimport type { KnownBlock } from \"@slack/types\";\nimport { WebClient } from \"@slack/web-api\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { readFile } from \"fs/promises\";\nimport { basename, join } from \"path\";\nimport type {\n Bot,\n BotAdapters,\n BotEvent,\n BotHandler,\n ChatMessage,\n ChatResponseContext,\n ChatToolResult,\n ConversationKind,\n PlatformInfo,\n} from \"../../adapter.js\";\nimport { resolveConversationSettings } from \"../../config.js\";\nimport type { EventsWatcher } from \"../../events.js\";\nimport * as log from \"../../log.js\";\nimport type { Attachment, ChannelStore } from \"../../store.js\";\nimport type {\n SlackBlockAction,\n SlackBlockActionBody,\n SlackChannel,\n SlackEvent,\n SlackUser,\n} from \"./types.js\";\nimport { PRODUCT_NAME, formatForceStopped, formatNothingRunning } from \"../../platform-messages.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n ChannelQueue,\n resolveOnlyScopedStopTarget,\n resolveStopTarget,\n withRetry,\n} from \"../shared.js\";\nimport { processMessageIntake } from \"../intake.js\";\nimport { createSlackAdapters } from \"./context.js\";\nimport {\n hasMaterializedChatSession,\n registerThreadSession,\n} from \"../../sessions/chat-session-manager.js\";\nimport {\n isSlackThreadSessionKey,\n planSlackAdapterSession,\n planSlackEventAnchorRun,\n resolveSlackSessionKey,\n} from \"./session.js\";\nimport { reportUserFacingError } from \"../../observability/sentry.js\";\n\nconst SLACK_EVENT_ANCHOR_TEXT = \"Working on it...\";\n\n// Slack WebClient errors carry either `code: \"rate_limited\"` (retry-after) or\n// the legacy `data.error === \"rate_limited\"` / 429 status shape.\nfunction slackIsRateLimited(err: Error): boolean {\n if ((err as { code?: unknown }).code === \"rate_limited\") return true;\n const data = (err as { data?: { error?: string; response?: { status?: number } } }).data;\n return data?.error === \"rate_limited\" || data?.response?.status === 429;\n}\n\nconst slackRetry = <T>(fn: () => Promise<T>): Promise<T> =>\n withRetry(fn, { isRateLimited: slackIsRateLimited });\n\nfunction collectSlackText(value: unknown, parts: string[]): void {\n if (value === null || value === undefined) return;\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (trimmed) parts.push(trimmed);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) collectSlackText(item, parts);\n return;\n }\n if (typeof value !== \"object\") return;\n\n const obj = value as Record<string, unknown>;\n for (const key of [\"text\", \"fallback\", \"title\", \"value\"] as const) {\n collectSlackText(obj[key], parts);\n }\n collectSlackText(obj.fields, parts);\n collectSlackText(obj.elements, parts);\n collectSlackText(obj.blocks, parts);\n}\n\nfunction buildSlackAppMessageText(event: {\n text?: string;\n blocks?: unknown[];\n attachments?: unknown[];\n}): string {\n const parts: string[] = [];\n collectSlackText(event.text, parts);\n collectSlackText(event.blocks, parts);\n collectSlackText(event.attachments, parts);\n const deduped = parts.filter((part, index) => parts.indexOf(part) === index);\n return deduped.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Shared mrkdwn truncation helper\n// ---------------------------------------------------------------------------\n\nconst MRKDWN_CONTEXT_TEXT_LIMIT = 3000;\n\n/**\n * Build a Slack context block whose text is capped at the mrkdwn limit.\n * Used for muted diagnostics and ephemeral command responses.\n */\nexport function buildMrkdwnContextBlock(text: string): object {\n const blockText =\n text.length > MRKDWN_CONTEXT_TEXT_LIMIT\n ? text.substring(0, MRKDWN_CONTEXT_TEXT_LIMIT - 20) + \"\\n_(truncated)_\"\n : text;\n return { type: \"context\", elements: [{ type: \"mrkdwn\", text: blockText }] };\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type { SlackChannel, SlackEvent, SlackUser } from \"./types.js\";\n\n// ============================================================================\n// SlackBot\n// ============================================================================\n\nexport class SlackBot implements Bot {\n private socketClient: SocketModeClient;\n private webClient: WebClient;\n private handler: BotHandler;\n private workingDir: string;\n private store: ChannelStore;\n private botUserId: string | null = null;\n private botId: string | null = null;\n private ownMentionRegex: RegExp | null = null;\n private startupTs: string | null = null; // Messages older than this are just logged, not processed\n\n private users = new Map<string, SlackUser>();\n private channels = new Map<string, SlackChannel>();\n private queues = new Map<string, ChannelQueue>();\n private eventsWatcher: EventsWatcher | null = null;\n\n private createAdapters(event: SlackEvent): BotAdapters {\n return createSlackAdapters(event, this, {\n replyMode:\n resolveConversationSettings(join(this.workingDir, event.conversationId)).slack?.replyMode ??\n \"top-level\",\n });\n }\n\n constructor(\n handler: BotHandler,\n config: { appToken: string; botToken: string; workingDir: string; store: ChannelStore },\n ) {\n this.handler = handler;\n this.workingDir = config.workingDir;\n this.store = config.store;\n this.socketClient = new SocketModeClient({\n appToken: config.appToken,\n // Default 5s is too tight: brief event-loop stalls (e.g. backfill, sync fs)\n // cause false pong timeouts; 4 in a row makes Slack drop the socket.\n clientPingTimeout: 12_000,\n });\n this.webClient = new WebClient(config.botToken);\n }\n\n setEventsWatcher(watcher: EventsWatcher): void {\n this.eventsWatcher = watcher;\n }\n\n // ==========================================================================\n // Public API\n // ==========================================================================\n\n async start(): Promise<void> {\n const auth = await this.webClient.auth.test();\n this.botUserId = auth.user_id as string;\n this.botId = typeof auth.bot_id === \"string\" ? auth.bot_id : null;\n\n await Promise.all([this.fetchUsers(), this.fetchChannels()]);\n log.logInfo(`Loaded ${this.channels.size} channels, ${this.users.size} users`);\n\n // Record startup time before opening the socket. Slack may replay older events;\n // those should be logged but not processed. Backfill runs in the background up\n // to this timestamp so startup is not blocked by one history call per channel.\n this.startupTs = (Date.now() / 1000).toFixed(6);\n\n this.setupEventHandlers();\n await this.socketClient.start();\n\n log.logConnected(\"Slack\");\n\n void this.backfillAllChannels(this.startupTs).catch((error) => {\n log.logWarning(\"Slack backfill failed\", String(error));\n });\n }\n\n getUser(userId: string): SlackUser | undefined {\n return this.users.get(userId);\n }\n\n getChannel(channelId: string): SlackChannel | undefined {\n return this.channels.get(channelId);\n }\n\n getAllUsers(): SlackUser[] {\n return Array.from(this.users.values());\n }\n\n getAllChannels(): SlackChannel[] {\n return Array.from(this.channels.values());\n }\n\n private stripOwnMention(text: string | undefined): string {\n const source = text ?? \"\";\n if (!this.botUserId) return source.trim();\n if (!this.ownMentionRegex || !this.ownMentionRegex.source.includes(this.botUserId)) {\n this.ownMentionRegex = new RegExp(`<@${this.botUserId}>`, \"gi\");\n }\n return source.replace(this.ownMentionRegex, \"\").trim();\n }\n\n async postMessage(channel: string, text: string): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.chat.postMessage({ channel, text });\n return result.ts as string;\n });\n }\n\n async postEphemeral(\n channel: string,\n user: string,\n text: string,\n threadTs?: string,\n ): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.chat.postEphemeral({\n channel,\n user,\n text,\n ...(threadTs ? { thread_ts: threadTs } : {}),\n });\n });\n }\n\n async postEphemeralBlocks(\n channel: string,\n user: string,\n text: string,\n blocks: object[],\n threadTs?: string,\n ): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.chat.postEphemeral({\n channel,\n user,\n text,\n blocks: blocks as KnownBlock[],\n ...(threadTs ? { thread_ts: threadTs } : {}),\n });\n });\n }\n\n async postMessageBlocks(channel: string, text: string, blocks: object[]): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.chat.postMessage({\n channel,\n text,\n blocks: blocks as KnownBlock[],\n });\n return result.ts as string;\n });\n }\n\n async postPrivate(conversationId: string, userId: string, text: string): Promise<void> {\n await this.postEphemeral(conversationId, userId, text);\n }\n\n async postPrivateDiagnostic(\n conversationId: string,\n userId: string,\n text: string,\n options?: { style?: \"muted\" | \"error\" },\n ): Promise<void> {\n if (options?.style !== \"muted\") {\n await this.postEphemeral(\n conversationId,\n userId,\n options?.style === \"error\" ? `_${text}_` : text,\n );\n return;\n }\n await this.postEphemeralBlocks(conversationId, userId, text, [buildMrkdwnContextBlock(text)]);\n }\n\n async openDirectMessage(userId: string): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.conversations.open({ users: userId });\n const channelId = result.channel?.id;\n if (!channelId) {\n throw new Error(`Failed to open DM for user ${userId}`);\n }\n return channelId;\n });\n }\n\n async updateMessage(channel: string, ts: string, text: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.chat.update({ channel, ts, text });\n });\n }\n\n async startMessageStream(channel: string, text: string, threadTs?: string): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.apiCall(\"chat.startStream\", {\n channel,\n markdown_text: text,\n ...(threadTs ? { thread_ts: threadTs } : {}),\n });\n const ts = (result as { ts?: string }).ts;\n if (!ts) throw new Error(\"Slack chat.startStream did not return ts\");\n return ts;\n });\n }\n\n async appendMessageStream(channel: string, ts: string, text: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.apiCall(\"chat.appendStream\", {\n channel,\n ts,\n markdown_text: text,\n });\n });\n }\n\n async stopMessageStream(channel: string, ts: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.apiCall(\"chat.stopStream\", { channel, ts });\n });\n }\n\n async deleteMessage(channel: string, ts: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.chat.delete({ channel, ts });\n });\n }\n\n // ==========================================================================\n // Slack Assistant API (AI assistant experience)\n // ==========================================================================\n\n /** Set the status for an assistant thread (shows \"thinking\" state) */\n async setAssistantStatus(channel: string, threadTs: string, status: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.assistant.threads.setStatus({\n channel_id: channel,\n thread_ts: threadTs,\n status,\n });\n });\n }\n\n async postInThread(channel: string, threadTs: string, text: string): Promise<string> {\n return slackRetry(async () => {\n // Use Block Kit section for long messages to trigger Slack's \"Show more\" collapsing (~700 chars)\n const SECTION_TEXT_LIMIT = 3000;\n if (text.length > 500) {\n const blockText =\n text.length > SECTION_TEXT_LIMIT\n ? text.substring(0, SECTION_TEXT_LIMIT - 20) + \"\\n_(truncated)_\"\n : text;\n const result = await this.webClient.chat.postMessage({\n channel,\n thread_ts: threadTs,\n text, // full text as notification fallback\n blocks: [{ type: \"section\", text: { type: \"mrkdwn\", text: blockText } }],\n });\n return result.ts as string;\n }\n const result = await this.webClient.chat.postMessage({ channel, thread_ts: threadTs, text });\n return result.ts as string;\n });\n }\n\n async postInThreadBlocks(\n channel: string,\n threadTs: string,\n text: string,\n blocks: object[],\n ): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.chat.postMessage({\n channel,\n thread_ts: threadTs,\n text, // fallback for notifications\n blocks: blocks as KnownBlock[],\n });\n return result.ts as string;\n });\n }\n\n async postBlocks(channel: string, text: string, blocks: object[]): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.chat.postMessage({\n channel,\n text,\n blocks: blocks as KnownBlock[],\n });\n return result.ts as string;\n });\n }\n\n async uploadFile(\n channel: string,\n filePath: string,\n title?: string,\n threadTs?: string,\n ): Promise<void> {\n return slackRetry(async () => {\n const fileName = title || basename(filePath);\n const fileContent = readFileSync(filePath);\n await this.webClient.files.uploadV2({\n channel_id: channel,\n file: fileContent,\n filename: fileName,\n title: fileName,\n ...(threadTs ? { thread_ts: threadTs } : {}),\n } as Parameters<typeof this.webClient.files.uploadV2>[0]);\n });\n }\n\n logToFile(channel: string, entry: object): void {\n appendChannelLog(this.workingDir, channel, entry);\n }\n\n logBotResponse(\n channel: string,\n text: string,\n ts: string,\n threadTs?: string,\n slackBlocks?: object[],\n ): void {\n appendBotResponseLog(this.workingDir, channel, text, ts, threadTs, {\n platform: \"slack\",\n ...(slackBlocks ? { slackBlocks } : {}),\n });\n }\n\n getPlatformInfo(): PlatformInfo {\n return {\n name: \"slack\",\n formattingGuide:\n \"## Slack Formatting (mrkdwn, NOT Markdown)\\nBold: *text*, Italic: _text_, Code: `code`, Block: ```code```, Links: <url|text>\\nDo NOT use **double asterisks** or [markdown](links).\",\n channels: this.getAllChannels().map((c) => ({ id: c.id, name: c.name })),\n users: this.getAllUsers().map((u) => ({\n id: u.id,\n userName: u.userName,\n displayName: u.displayName,\n })),\n diagnostics: {\n showUsageSummary: true,\n },\n };\n }\n\n // ==========================================================================\n // Events Integration\n // ==========================================================================\n\n /**\n * Enqueue an event for processing. Always queues (no \"already working\" rejection).\n * Returns true if enqueued, false if queue is full (max 5).\n */\n enqueueEvent(event: BotEvent): boolean {\n const conversationId = event.conversationId;\n const queue = this.getQueue(conversationId);\n if (queue.size() >= 5) {\n log.logWarning(\n `Event queue full for ${conversationId}, discarding: ${event.text.substring(0, 50)}`,\n );\n return false;\n }\n log.logInfo(`Enqueueing event for ${conversationId}: ${event.text.substring(0, 50)}`);\n queue.enqueue(async () => {\n let anchorTs: string | undefined;\n if (!event.thread_ts) {\n try {\n anchorTs = await this.postMessage(conversationId, SLACK_EVENT_ANCHOR_TEXT);\n } catch (err) {\n log.logWarning(\n `Failed to post Slack event anchor for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n reportUserFacingError(err, {\n domain: \"events\",\n surface: \"event_delivery\",\n operation: \"slack_anchor_post\",\n severity: \"error\",\n platform: \"slack\",\n context: {\n conversationId,\n conversationKind: event.conversationKind,\n eventTs: event.ts,\n textLength: event.text.length,\n },\n });\n throw err;\n }\n }\n const eventPlan = planSlackEventAnchorRun(event, anchorTs);\n const eventForRun = eventPlan.event;\n if (eventPlan.initialMessageTs && eventForRun.sessionKey) {\n registerThreadSession({\n conversationDir: join(this.workingDir, conversationId),\n sessionKey: eventForRun.sessionKey,\n });\n }\n\n const runQueueKey = planSlackAdapterSession(eventForRun, {\n initialMessageTs: eventPlan.initialMessageTs,\n }).sessionKey;\n this.getQueue(runQueueKey).enqueue(async () => {\n const slackEvent: SlackEvent = {\n type: eventForRun.type as SlackEvent[\"type\"],\n conversationId,\n conversationKind: eventForRun.conversationKind,\n channel: conversationId,\n ts: eventForRun.ts,\n thread_ts: eventForRun.thread_ts,\n user: eventForRun.user,\n text: eventForRun.text,\n attachments: eventForRun.attachments?.map((attachment) => ({\n original: attachment.name,\n localPath: attachment.localPath,\n })),\n sessionKey: eventForRun.sessionKey,\n };\n const adapters = createSlackAdapters(slackEvent, this, {\n initialMessageTs: eventPlan.initialMessageTs,\n replyMode:\n resolveConversationSettings(join(this.workingDir, eventForRun.conversationId)).slack\n ?.replyMode ?? \"top-level\",\n });\n return this.handler.handleEvent(eventForRun, this, adapters);\n });\n });\n return true;\n }\n\n // ==========================================================================\n // Private - Event Handlers\n // ==========================================================================\n\n private getQueue(channelId: string): ChannelQueue {\n let queue = this.queues.get(channelId);\n if (!queue) {\n queue = new ChannelQueue(\"Slack\");\n this.queues.set(channelId, queue);\n }\n return queue;\n }\n\n private resolveQueueKey(conversationId: string, sessionKey: string): string {\n if (!isSlackThreadSessionKey(sessionKey)) return sessionKey;\n if (this.handler.isRunning(sessionKey)) return sessionKey;\n return this.hasKnownThreadSession(conversationId, sessionKey) ? sessionKey : conversationId;\n }\n\n private hasKnownThreadSession(conversationId: string, sessionKey: string): boolean {\n return hasMaterializedChatSession({\n conversationDir: join(this.workingDir, conversationId),\n sessionKey,\n });\n }\n\n private processSlackMessageIntake(options: {\n event: SlackEvent;\n attachmentsPromise: Promise<Attachment[]>;\n queueKey: string;\n isAutoReplyCandidate: boolean;\n onNotTriggered?: () => void;\n }): void {\n void processMessageIntake({\n eventBase: options.event as unknown as BotEvent,\n workingDir: this.workingDir,\n isAutoReplyCandidate: options.isAutoReplyCandidate,\n logEntryBase: {},\n processAttachments: () => options.attachmentsPromise,\n queueKey: options.queueKey,\n enqueue: (queueKey, work) => this.getQueue(queueKey).enqueue(work),\n handler: this.handler,\n bot: this,\n createAdapters: (event) => this.createAdapters(event as SlackEvent),\n onNotTriggered: options.onNotTriggered,\n deferAttachmentsUntilRun: true,\n });\n }\n\n private buildHomeView(): { type: \"home\"; blocks: KnownBlock[] } {\n const blocks: object[] = [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: `*${PRODUCT_NAME}*\\nStart a new task or check on running work.`,\n },\n accessory: {\n type: \"image\",\n image_url: \"https://media1.tenor.com/m/lfDATg4Bhc0AAAAC/happy-cat.gif\",\n alt_text: PRODUCT_NAME,\n },\n },\n ];\n\n // --- Running tasks ---\n const runningSessions = this.handler.getRunningSessions();\n\n blocks.push(\n { type: \"divider\" },\n {\n type: \"header\",\n text: {\n type: \"plain_text\",\n text: `Running Tasks (${runningSessions.length})`,\n emoji: true,\n },\n },\n );\n\n if (runningSessions.length === 0) {\n blocks.push({\n type: \"context\",\n elements: [{ type: \"mrkdwn\", text: \"_No tasks running right now._\" }],\n });\n } else {\n // Threshold for \"stuck\" detection (10 minutes)\n const STUCK_THRESHOLD_MS = 10 * 60 * 1000;\n\n for (const session of runningSessions) {\n const channelId = session.sessionKey.split(\":\")[0];\n const channel = this.channels.get(channelId);\n const channelName = channel ? `#${channel.name}` : channelId;\n const elapsed = Math.floor((Date.now() - session.startedAt) / 60000);\n const elapsedStr = elapsed < 1 ? \"<1 min\" : `${elapsed} min`;\n\n // Check if task might be stuck\n const lastActivity = session.lastActivityAt ? Date.now() - session.lastActivityAt : 0;\n const isStuck = lastActivity > STUCK_THRESHOLD_MS;\n const statusText = isStuck ? \"_stuck_\" : \"_running_\";\n\n // Build status line: channel · status · time · step\n let statusLine = `${statusText} · ${elapsedStr}`;\n if (session.currentTool) {\n statusLine += ` · ${session.currentTool}`;\n }\n if (isStuck && lastActivity > 0) {\n const inactiveMin = Math.floor(lastActivity / 60000);\n statusLine += ` · idle ${inactiveMin}m`;\n }\n\n // Use context block for gray small text (like \"No scheduled jobs.\")\n blocks.push({\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: `*${channelName}* · ${statusLine}`,\n },\n ],\n });\n\n // Add Force Stop button as separate element if stuck\n if (isStuck) {\n blocks.push({\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: \" \",\n },\n {\n type: \"button\",\n text: { type: \"plain_text\", text: \"Force Stop\", emoji: true },\n action_id: `force_stop_${session.sessionKey.replace(/:/g, \"_\")}`,\n style: \"danger\",\n },\n ],\n });\n }\n }\n }\n\n // --- Cron jobs ---\n const periodicEvents = this.eventsWatcher?.getPeriodicEvents() ?? [];\n\n blocks.push(\n { type: \"divider\" },\n {\n type: \"header\",\n text: {\n type: \"plain_text\",\n text: `Scheduled Jobs (${periodicEvents.length})`,\n emoji: true,\n },\n },\n );\n\n if (periodicEvents.length === 0) {\n blocks.push({\n type: \"context\",\n elements: [{ type: \"mrkdwn\", text: \"_No scheduled jobs._\" }],\n });\n } else {\n for (const ev of periodicEvents) {\n const channelLabel =\n ev.platform === \"slack\"\n ? (() => {\n const channel = this.channels.get(ev.conversationId);\n const channelName = channel ? `#${channel.name}` : ev.conversationId;\n return `${ev.platform}:${channelName}`;\n })()\n : `${ev.platform}:${ev.conversationId}`;\n const nextStr = ev.nextRun\n ? new Date(ev.nextRun).toLocaleString(\"en-US\", {\n month: \"short\",\n day: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n })\n : \"—\";\n blocks.push({\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: `*${ev.text}*\\n└ \\`${ev.schedule}\\` · ${channelLabel} · Next: ${nextStr}`,\n },\n });\n }\n }\n\n // --- Footer ---\n blocks.push(\n { type: \"divider\" },\n {\n type: \"context\",\n elements: [\n { type: \"mrkdwn\", text: \"💡 @mention in a channel or send a DM to start a new task\" },\n ],\n },\n );\n\n return { type: \"home\", blocks: blocks as KnownBlock[] };\n }\n\n private resolveStopTarget(channelId: string, threadTs?: string): string | null {\n const directTarget = resolveStopTarget({\n handler: this.handler,\n conversationId: channelId,\n sessionKey: resolveSlackSessionKey(channelId, threadTs),\n });\n if (directTarget) return directTarget;\n if (threadTs) return null;\n return resolveOnlyScopedStopTarget(this.handler, channelId);\n }\n\n private isStopText(text: string): boolean {\n const normalized = text.trim().toLowerCase();\n return normalized === \"stop\" || normalized === \"/stop\";\n }\n\n private createCommandAdapters(\n conversationId: string,\n userId: string,\n userName: string | undefined,\n text: string,\n ts: string,\n options: { ephemeralChannelId?: string; threadTs?: string } = {},\n ): BotAdapters {\n const message: ChatMessage = {\n id: ts,\n sessionKey: conversationId,\n conversationKind: options.ephemeralChannelId ? \"shared\" : \"direct\",\n userId,\n userName,\n text,\n attachments: [],\n };\n\n const respond = async (responseText: string) => {\n if (options.ephemeralChannelId) {\n await this.postEphemeral(\n options.ephemeralChannelId,\n userId,\n responseText,\n options.threadTs,\n );\n return;\n }\n const messageTs = await this.postMessage(conversationId, responseText);\n this.logBotResponse(conversationId, responseText, messageTs);\n };\n\n const respondMuted = async (responseText: string) => {\n const blocks = [buildMrkdwnContextBlock(responseText)];\n if (options.ephemeralChannelId) {\n await this.postEphemeralBlocks(\n options.ephemeralChannelId,\n userId,\n responseText,\n blocks,\n options.threadTs,\n );\n return;\n }\n const messageTs = await this.postMessageBlocks(conversationId, responseText, blocks);\n this.logBotResponse(conversationId, responseText, messageTs);\n };\n\n const responseCtx: ChatResponseContext = {\n respond,\n replaceResponse: respond,\n respondDiagnostic: async (\n responseText: string,\n responseOptions?: { style?: \"muted\" | \"error\" },\n ) => {\n if (responseOptions?.style === \"muted\") {\n await respondMuted(responseText);\n return;\n }\n await respond(responseOptions?.style === \"error\" ? `_${responseText}_` : responseText);\n },\n respondToolResult: async (result: ChatToolResult) => {\n const duration = (result.durationMs / 1000).toFixed(1);\n await respond(\n `${result.isError ? \"Error\" : \"Done\"} ${result.toolName} (${duration}s)\\n${result.result}`,\n );\n },\n setTyping: async () => {},\n setWorking: async () => {},\n uploadFile: async (filePath: string, title?: string) => {\n await this.uploadFile(conversationId, filePath, title);\n },\n deleteResponse: async () => {},\n };\n\n return {\n message,\n responseCtx,\n platform: this.getPlatformInfo(),\n };\n }\n\n private buildSlashCommandEvent(\n payload: {\n command: string;\n text?: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n thread_ts?: string;\n },\n options: { type?: BotEvent[\"type\"]; includeText?: boolean; thread?: boolean } = {},\n ): { event: BotEvent; adapters: BotAdapters } {\n const conversationId = payload.channel_id;\n const isDirectMessage = conversationId.startsWith(\"D\");\n const createdAt = new Date();\n const eventTs = (createdAt.getTime() / 1000).toFixed(6);\n const userName = payload.user_name ?? this.getUser(payload.user_id)?.userName;\n const commandSuffix = options.includeText ? payload.text?.trim() : undefined;\n const commandText = commandSuffix ? `${payload.command} ${commandSuffix}` : payload.command;\n const threadTs = options.thread ? payload.thread_ts : undefined;\n const sessionKey = options.thread\n ? resolveSlackSessionKey(conversationId, threadTs)\n : conversationId;\n\n this.logToFile(conversationId, {\n date: createdAt.toISOString(),\n ts: eventTs,\n user: payload.user_id,\n userName,\n text: commandText,\n attachments: [],\n isBot: false,\n ...(threadTs ? { threadTs } : {}),\n });\n\n const event: BotEvent = {\n type: options.type ?? (isDirectMessage ? \"dm\" : \"mention\"),\n conversationId,\n conversationKind: isDirectMessage ? \"direct\" : \"shared\",\n ts: eventTs,\n user: payload.user_id,\n text: commandText,\n attachments: [],\n ...(threadTs ? { thread_ts: threadTs } : {}),\n sessionKey,\n };\n\n const adapters = this.createCommandAdapters(\n conversationId,\n payload.user_id,\n userName,\n commandText,\n eventTs,\n isDirectMessage ? { threadTs } : { ephemeralChannelId: conversationId, threadTs },\n );\n\n return { event, adapters };\n }\n\n private async routeSlashLoginCommand(payload: {\n command: string;\n text?: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n }): Promise<void> {\n const { event, adapters } = this.buildSlashCommandEvent(payload, {\n type: payload.channel_id.startsWith(\"D\") ? \"dm\" : \"private_command\",\n includeText: true,\n });\n await this.handler.handleEvent(event, this, adapters);\n }\n\n private async routeSlashNewCommand(payload: {\n command: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n }): Promise<void> {\n const conversationId = payload.channel_id;\n if (!conversationId.startsWith(\"D\")) {\n await this.postEphemeral(\n conversationId,\n payload.user_id,\n `為了避免誤清除共享上下文,${payload.command} 目前只能在與 ${PRODUCT_NAME} 的私訊中使用。`,\n );\n return;\n }\n\n const createdAt = new Date();\n const eventTs = (createdAt.getTime() / 1000).toFixed(6);\n const userName = payload.user_name ?? this.getUser(payload.user_id)?.userName;\n\n this.logToFile(conversationId, {\n date: createdAt.toISOString(),\n ts: eventTs,\n user: payload.user_id,\n userName,\n text: payload.command,\n attachments: [],\n isBot: false,\n });\n\n const commandBot: Bot = {\n start: async () => {},\n postMessage: async (_channel: string, text: string) => this.postMessage(conversationId, text),\n updateMessage: async (channel: string, ts: string, text: string) =>\n this.updateMessage(channel, ts, text),\n enqueueEvent: (event: BotEvent) => this.enqueueEvent(event),\n getPlatformInfo: () => this.getPlatformInfo(),\n };\n await this.handler.handleNewCommand(conversationId, conversationId, commandBot);\n }\n\n private async routeSlashModelCommand(payload: {\n command: string;\n text?: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n }): Promise<void> {\n const { event, adapters } = this.buildSlashCommandEvent(payload, { includeText: true });\n await this.handler.handleEvent(event, this, adapters);\n }\n\n private async routeSlashSessionCommand(payload: {\n command: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n thread_ts?: string;\n }): Promise<void> {\n const { event, adapters } = this.buildSlashCommandEvent(payload, { thread: true });\n await this.handler.handleEvent(event, this, adapters);\n }\n\n private async routeSlashAdminCommand(payload: {\n command: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n thread_ts?: string;\n }): Promise<void> {\n const { event, adapters } = this.buildSlashCommandEvent(payload, { thread: true });\n await this.handler.handleEvent(event, this, adapters);\n }\n\n private setupEventHandlers(): void {\n this.socketClient.on(\"disconnect\", (err: unknown) => {\n log.logWarning(\"Slack socket disconnect\", err ? String(err) : \"\");\n });\n this.socketClient.on(\"error\", (err: unknown) => {\n log.logWarning(\"Slack socket error\", err ? String(err) : \"\");\n });\n this.socketClient.on(\"unable_to_socket_mode_start\", (err: unknown) => {\n log.logWarning(\"Slack socket unable_to_start\", err ? String(err) : \"\");\n });\n\n this.socketClient.on(\"app_mention\", (payload) => this.handleAppMention(payload));\n this.socketClient.on(\"message\", (payload) => this.handleMessageEvent(payload));\n this.socketClient.on(\"slash_commands\", (payload) => void this.handleSlashCommand(payload));\n this.socketClient.on(\"app_home_opened\", (payload) => this.handleAppHomeOpened(payload));\n this.socketClient.on(\"block_actions\", (payload) => void this.handleBlockAction(payload));\n this.socketClient.on(\n \"interactive\",\n (payload) =>\n void this.handleBlockAction(payload as { body: SlackBlockActionBody; ack: () => void }),\n );\n }\n\n private handleAppMention({ event, ack }: { event: unknown; ack: () => void }): void {\n const e = event as {\n text: string;\n channel: string;\n user: string;\n ts: string;\n thread_ts?: string;\n files?: Array<{ name: string; url_private_download?: string; url_private?: string }>;\n };\n\n // Skip DMs (handled by message event)\n if (e.channel.startsWith(\"D\")) {\n ack();\n return;\n }\n\n // Top-level mentions use a persistent channel session.\n // Thread replies get their own isolated session (channelId:thread_ts).\n const sessionKey = resolveSlackSessionKey(e.channel, e.thread_ts);\n\n const mentionText = this.stripOwnMention(e.text);\n const slackEvent: SlackEvent = {\n type: \"mention\",\n conversationId: e.channel,\n conversationKind: \"shared\",\n channel: e.channel,\n ts: e.ts,\n thread_ts: e.thread_ts,\n user: e.user,\n text: mentionText || \"Please respond to the recent conversation context.\",\n files: e.files,\n sessionKey,\n };\n\n const attachmentsPromise = this.logUserMessage(slackEvent);\n\n // Only trigger processing for messages AFTER startup (not replayed old messages)\n if (this.startupTs && e.ts < this.startupTs) {\n log.logInfo(\n `[${e.channel}] Logged old message (pre-startup), not triggering: ${slackEvent.text.substring(0, 30)}`,\n );\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n ack();\n return;\n }\n\n // Check for stop command - execute immediately, don't queue!\n if (this.isStopText(slackEvent.text)) {\n const stopTarget = this.resolveStopTarget(e.channel, e.thread_ts);\n if (stopTarget) {\n this.handler.handleStop(stopTarget, e.channel, this);\n } else {\n this.postMessage(e.channel, formatNothingRunning(\"slack\"));\n }\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n ack();\n return;\n }\n\n this.processSlackMessageIntake({\n event: slackEvent,\n attachmentsPromise,\n queueKey: this.resolveQueueKey(e.channel, sessionKey),\n isAutoReplyCandidate: false,\n });\n\n ack();\n }\n\n private handleMessageEvent({ event, ack }: { event: unknown; ack: () => void }): void {\n const e = event as {\n text?: string;\n channel: string;\n user?: string;\n ts: string;\n thread_ts?: string;\n channel_type?: string;\n subtype?: string;\n bot_id?: string;\n app_id?: string;\n username?: string;\n bot_profile?: { id?: string; app_id?: string; name?: string; real_name?: string };\n blocks?: unknown[];\n attachments?: unknown[];\n files?: Array<{ name: string; url_private_download?: string; url_private?: string }>;\n };\n\n const hasFiles = !!e.files && e.files.length > 0;\n const hasSlackContent = !!e.text || hasFiles || !!e.blocks?.length || !!e.attachments?.length;\n const isOwnBotMessage =\n (!!e.user && e.user === this.botUserId) || (!!this.botId && e.bot_id === this.botId);\n if (isOwnBotMessage) {\n ack();\n return;\n }\n\n const isExternalBotMessage = !!e.bot_id || e.subtype === \"bot_message\";\n if (isExternalBotMessage) {\n if (e.subtype !== undefined && e.subtype !== \"bot_message\" && e.subtype !== \"file_share\") {\n ack();\n return;\n }\n if (!hasSlackContent) {\n ack();\n return;\n }\n void this.logExternalBotMessage(e).catch((err) => {\n log.logWarning(\"Failed to log Slack bot message\", String(err));\n });\n ack();\n return;\n }\n\n if (!e.user) {\n ack();\n return;\n }\n if (e.subtype !== undefined && e.subtype !== \"file_share\") {\n ack();\n return;\n }\n if (!hasSlackContent) {\n ack();\n return;\n }\n\n const isDM = e.channel_type === \"im\";\n const conversationKind: ConversationKind = isDM ? \"direct\" : \"shared\";\n const isBotMention = e.text?.includes(`<@${this.botUserId}>`);\n\n // Skip channel @mentions - already handled by app_mention event\n if (!isDM && isBotMention) {\n ack();\n return;\n }\n\n const isThreadReply = !!e.thread_ts;\n const sessionKey = isDM ? resolveSlackSessionKey(e.channel, e.thread_ts) : undefined;\n\n const slackEvent: SlackEvent = {\n type: isDM ? \"dm\" : \"mention\",\n conversationId: e.channel,\n conversationKind,\n channel: e.channel,\n ts: e.ts,\n thread_ts: e.thread_ts,\n user: e.user,\n text: this.stripOwnMention(e.text),\n files: e.files,\n sessionKey,\n };\n\n const attachmentsPromise = this.logUserMessage(slackEvent);\n\n // Only trigger processing for messages AFTER startup (not replayed old messages)\n if (this.startupTs && e.ts < this.startupTs) {\n log.logInfo(\n `[${e.channel}] Skipping old message (pre-startup): ${slackEvent.text.substring(0, 30)}`,\n );\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n ack();\n return;\n }\n\n // Stop command for DM only (app_mention handles shared-channel \"@mikan stop\").\n if (isDM && this.isStopText(slackEvent.text)) {\n const stopTarget = this.resolveStopTarget(e.channel, e.thread_ts);\n if (stopTarget) {\n this.handler.handleStop(stopTarget, e.channel, this);\n } else {\n this.postMessage(e.channel, formatNothingRunning(\"slack\"));\n }\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n ack();\n return;\n }\n\n const enqueueTriggered = () => {\n const activeSessionKey =\n slackEvent.sessionKey ?? resolveSlackSessionKey(e.channel, e.thread_ts);\n // Auto-reply top-level channel messages start with no sessionKey because\n // they are only candidates until the policy allows them. Once triggered,\n // persist the resolved key on the event; otherwise the runtime fallback\n // treats the message ts as a thread session (`channel:ts`) instead of the\n // persistent top-level channel session.\n slackEvent.sessionKey = activeSessionKey;\n this.processSlackMessageIntake({\n event: slackEvent,\n attachmentsPromise,\n queueKey: this.resolveQueueKey(e.channel, activeSessionKey),\n isAutoReplyCandidate: false,\n });\n };\n\n const logOnly = () => {\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n };\n\n if (isDM) {\n enqueueTriggered();\n ack();\n return;\n }\n\n if (isThreadReply) {\n logOnly();\n ack();\n return;\n }\n\n const activeSessionKey = resolveSlackSessionKey(e.channel, e.thread_ts);\n slackEvent.sessionKey = activeSessionKey;\n this.processSlackMessageIntake({\n event: slackEvent,\n attachmentsPromise,\n queueKey: this.resolveQueueKey(e.channel, activeSessionKey),\n isAutoReplyCandidate: true,\n onNotTriggered: logOnly,\n });\n\n ack();\n }\n\n private async handleSlashCommand({\n body,\n ack,\n }: {\n body: unknown;\n ack: () => Promise<void>;\n }): Promise<void> {\n const payload = body as {\n command?: string;\n text?: string;\n channel_id?: string;\n user_id?: string;\n user_name?: string;\n thread_ts?: string;\n };\n\n await ack();\n\n if (!payload.command || !payload.channel_id || !payload.user_id) {\n return;\n }\n\n const { command, text, channel_id, user_id, user_name, thread_ts } = payload;\n\n let handlerPromise: Promise<void> | null = null;\n if (command === \"/pi-login\") {\n handlerPromise = this.routeSlashLoginCommand({\n command,\n text,\n channel_id,\n user_id,\n user_name,\n });\n } else if (command === \"/pi-new\") {\n handlerPromise = this.routeSlashNewCommand({ command, channel_id, user_id, user_name });\n } else if (command === \"/pi-session\") {\n handlerPromise = this.routeSlashSessionCommand({\n command,\n channel_id,\n user_id,\n user_name,\n thread_ts,\n });\n } else if (command === \"/pi-model\") {\n handlerPromise = this.routeSlashModelCommand({\n command,\n text,\n channel_id,\n user_id,\n user_name,\n });\n } else if (command === \"/pi-sandbox\" || command === \"/pi-auto-reply\") {\n handlerPromise = this.routeSlashModelCommand({\n command,\n text,\n channel_id,\n user_id,\n user_name,\n });\n } else if (command === \"/pi-admin\") {\n handlerPromise = this.routeSlashAdminCommand({\n command,\n channel_id,\n user_id,\n user_name,\n thread_ts,\n });\n }\n\n if (!handlerPromise) {\n return;\n }\n\n handlerPromise.catch((err) => {\n log.logWarning(\"Slack slash command error\", err instanceof Error ? err.message : String(err));\n });\n }\n\n private handleAppHomeOpened({ event, ack }: { event: unknown; ack: () => void }): void {\n const e = event as { user: string; tab: string };\n ack();\n if (e.tab !== \"home\") return;\n\n this.webClient.views\n .publish({\n user_id: e.user,\n view: this.buildHomeView(),\n })\n .catch((err) => {\n log.logWarning(`Failed to publish App Home view`, String(err));\n });\n }\n\n private async handleBlockAction({\n body,\n ack,\n }: {\n body: SlackBlockActionBody;\n ack: () => void;\n }): Promise<void> {\n const action = body.actions?.[0];\n if (!action) {\n ack();\n return;\n }\n\n if (!action.action_id?.startsWith(\"force_stop_\")) {\n ack();\n this.handleSlackInteraction(body, action);\n return;\n }\n\n ack();\n const sessionKey = action.action_id.replace(\"force_stop_\", \"\").replace(/_/g, \":\");\n const userId = body.user?.id;\n const channelId = body.container?.channel_id || sessionKey.split(\":\")[0];\n\n log.logInfo(`[Force Stop] User ${userId} requested force stop for ${sessionKey}`);\n\n // Use handler's forceStop method\n this.handler.forceStop(sessionKey);\n\n // Notify in channel\n await this.postMessage(channelId, formatForceStopped(\"slack\", userId ?? \"unknown\"));\n\n // Refresh home tab\n if (userId) {\n this.webClient.views\n .publish({\n user_id: userId,\n view: this.buildHomeView(),\n })\n .catch((err) => {\n log.logWarning(`Failed to refresh App Home view`, String(err));\n });\n }\n }\n\n private handleSlackInteraction(body: SlackBlockActionBody, action: SlackBlockAction): void {\n const container = body.container ?? {};\n const channelId = container.channel_id;\n const userId = body.user?.id;\n if (!channelId || !userId) return;\n\n const selectedOption = action.selected_option;\n const selectedOptions = Array.isArray(action.selected_options)\n ? action.selected_options\n : undefined;\n const selectedText = selectedOption?.text?.text ?? selectedOption?.value;\n const selectedTexts = selectedOptions?.map((option) => option.text?.text ?? option.value);\n const valueText = selectedTexts?.length\n ? selectedTexts.join(\", \")\n : (selectedText ?? action.value ?? action.action_id);\n const text = `[Slack action] ${action.action_id}: ${valueText}`;\n const ts = `action:${Date.now()}`;\n const threadTs = container.thread_ts;\n const sessionKey = resolveSlackSessionKey(channelId, threadTs);\n\n this.logToFile(channelId, {\n date: new Date().toISOString(),\n ts,\n ...(threadTs ? { threadTs } : {}),\n user: userId,\n userName: body.user?.username ?? body.user?.name,\n text,\n attachments: [],\n isBot: false,\n platform: \"slack\",\n slackInteraction: {\n type: \"block_actions\",\n actionId: action.action_id,\n blockId: action.block_id,\n actionType: action.type,\n value: action.value,\n selectedOption: selectedOption\n ? { text: selectedOption.text?.text, value: selectedOption.value }\n : undefined,\n selectedOptions: selectedOptions?.map((option) => ({\n text: option.text?.text,\n value: option.value,\n })),\n messageTs: container.message_ts,\n },\n });\n\n const event: BotEvent = {\n type: \"slack_action\",\n conversationId: channelId,\n conversationKind: channelId.startsWith(\"D\") ? \"direct\" : \"shared\",\n ts,\n user: userId,\n text,\n attachments: [],\n ...(threadTs ? { thread_ts: threadTs } : {}),\n sessionKey,\n };\n\n this.getQueue(this.resolveQueueKey(channelId, sessionKey)).enqueue(async () => {\n const slackEvent: SlackEvent = {\n type: event.conversationKind === \"direct\" ? \"dm\" : \"mention\",\n conversationId: channelId,\n conversationKind: event.conversationKind,\n channel: channelId,\n ts,\n thread_ts: threadTs,\n user: userId,\n text,\n attachments: [],\n sessionKey,\n };\n return this.handler.handleEvent(event, this, this.createAdapters(slackEvent));\n });\n }\n\n /**\n * Log a user message to log.jsonl after attachments are ready.\n */\n private async logUserMessage(event: SlackEvent): Promise<Attachment[]> {\n const user = this.users.get(event.user);\n let attachments: Attachment[] = [];\n let attachmentError: unknown;\n if (event.files) {\n try {\n attachments = await this.store.processAttachments(event.channel, event.files, event.ts);\n } catch (err) {\n attachmentError = err;\n }\n }\n // Always write the text log, even if attachment processing failed — we want\n // a record of the user message regardless of file-handling errors.\n this.logToFile(event.channel, {\n date: new Date(parseFloat(event.ts) * 1000).toISOString(),\n ts: event.ts,\n threadTs: event.thread_ts,\n user: event.user,\n userName: user?.userName,\n displayName: user?.displayName,\n text: event.text,\n attachments,\n isBot: false,\n });\n if (attachmentError) throw attachmentError;\n return attachments;\n }\n\n private async logExternalBotMessage(event: {\n channel: string;\n ts: string;\n thread_ts?: string;\n text?: string;\n subtype?: string;\n bot_id?: string;\n app_id?: string;\n username?: string;\n bot_profile?: { app_id?: string; name?: string; real_name?: string };\n blocks?: unknown[];\n attachments?: unknown[];\n files?: Array<{ name: string; url_private_download?: string; url_private?: string }>;\n }): Promise<Attachment[]> {\n const attachments = event.files\n ? await this.store.processAttachments(event.channel, event.files, event.ts)\n : [];\n const botName =\n event.username ?? event.bot_profile?.name ?? event.bot_profile?.real_name ?? event.bot_id;\n this.logToFile(event.channel, {\n date: new Date(parseFloat(event.ts) * 1000).toISOString(),\n ts: event.ts,\n threadTs: event.thread_ts,\n user: event.bot_id ? `bot:${event.bot_id}` : \"external-bot\",\n userName: botName,\n displayName: botName,\n text: buildSlackAppMessageText(event),\n attachments,\n isBot: true,\n botId: event.bot_id,\n appId: event.app_id ?? event.bot_profile?.app_id,\n subtype: event.subtype,\n });\n return attachments;\n }\n\n // ==========================================================================\n // Private - Backfill\n // ==========================================================================\n\n private async getExistingTimestamps(channelId: string): Promise<Set<string>> {\n const logPath = join(this.workingDir, channelId, \"log.jsonl\");\n const timestamps = new Set<string>();\n if (!existsSync(logPath)) return timestamps;\n\n const content = await readFile(logPath, \"utf-8\");\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n for (let i = 0; i < lines.length; i++) {\n try {\n const entry = JSON.parse(lines[i]);\n if (entry.ts) timestamps.add(entry.ts);\n } catch (err) {\n log.logWarning(\n `Skipping malformed log entry at ${logPath}:${i + 1}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n return timestamps;\n }\n\n private async backfillChannel(channelId: string, upperBoundTs?: string): Promise<number> {\n const existingTs = await this.getExistingTimestamps(channelId);\n\n // Find the biggest ts in log.jsonl\n let lastLoggedTs: string | undefined;\n for (const ts of existingTs) {\n if (!lastLoggedTs || parseFloat(ts) > parseFloat(lastLoggedTs)) lastLoggedTs = ts;\n }\n\n type Message = {\n user?: string;\n bot_id?: string;\n app_id?: string;\n username?: string;\n bot_profile?: { app_id?: string; name?: string; real_name?: string };\n blocks?: unknown[];\n attachments?: unknown[];\n text?: string;\n ts?: string;\n thread_ts?: string;\n subtype?: string;\n files?: Array<{ name: string }>;\n };\n const allMessages: Message[] = [];\n\n let cursor: string | undefined;\n let pageCount = 0;\n const maxPages = 3;\n\n do {\n const result = await this.webClient.conversations.history({\n channel: channelId,\n oldest: lastLoggedTs, // Only fetch messages newer than what we have\n latest: upperBoundTs, // Do not race live socket events after startup\n inclusive: false,\n limit: 1000,\n cursor,\n });\n if (result.messages) {\n allMessages.push(...(result.messages as Message[]));\n }\n cursor = result.response_metadata?.next_cursor;\n pageCount++;\n } while (cursor && pageCount < maxPages);\n\n // Filter: include mikan's messages, external app/bot messages, and user messages.\n const relevantMessages = allMessages.filter((msg) => {\n if (!msg.ts || existingTs.has(msg.ts)) return false; // Skip duplicates\n if (msg.user === this.botUserId) return true;\n const isExternalBotMessage = !!msg.bot_id || msg.subtype === \"bot_message\";\n if (isExternalBotMessage) {\n if (this.botId && msg.bot_id === this.botId) return false;\n if (\n msg.subtype !== undefined &&\n msg.subtype !== \"bot_message\" &&\n msg.subtype !== \"file_share\"\n ) {\n return false;\n }\n return (\n !!msg.text ||\n !!(msg.files && msg.files.length > 0) ||\n !!msg.blocks?.length ||\n !!msg.attachments?.length\n );\n }\n if (msg.subtype !== undefined && msg.subtype !== \"file_share\") return false;\n if (!msg.user) return false;\n if (!msg.text && (!msg.files || msg.files.length === 0)) return false;\n return true;\n });\n\n // Reverse to chronological order\n relevantMessages.reverse();\n\n // Log each message to log.jsonl\n for (const msg of relevantMessages) {\n const isMikanMessage = msg.user === this.botUserId;\n const isExternalBotMessage =\n !isMikanMessage && (!!msg.bot_id || msg.subtype === \"bot_message\");\n if (isExternalBotMessage) {\n await this.logExternalBotMessage({ ...msg, channel: channelId, ts: msg.ts! });\n continue;\n }\n\n const user = this.users.get(msg.user!);\n const text = this.stripOwnMention(msg.text);\n const attachments = msg.files\n ? await this.store.processAttachments(channelId, msg.files, msg.ts!)\n : [];\n\n this.logToFile(channelId, {\n date: new Date(parseFloat(msg.ts!) * 1000).toISOString(),\n ts: msg.ts!,\n threadTs: msg.thread_ts,\n user: isMikanMessage ? \"bot\" : msg.user!,\n userName: isMikanMessage ? undefined : user?.userName,\n displayName: isMikanMessage ? undefined : user?.displayName,\n text,\n attachments,\n isBot: isMikanMessage,\n });\n }\n\n return relevantMessages.length;\n }\n\n private async backfillAllChannels(upperBoundTs?: string): Promise<void> {\n const startTime = Date.now();\n\n // Only backfill channels that already have a log.jsonl (mikan has interacted with them before)\n const channelsToBackfill: Array<[string, SlackChannel]> = [];\n for (const [channelId, channel] of this.channels) {\n const logPath = join(this.workingDir, channelId, \"log.jsonl\");\n if (existsSync(logPath)) {\n channelsToBackfill.push([channelId, channel]);\n }\n }\n\n log.logBackfillStart(channelsToBackfill.length);\n\n let totalMessages = 0;\n for (const [channelId, channel] of channelsToBackfill) {\n try {\n const count = await this.backfillChannel(channelId, upperBoundTs);\n if (count > 0) log.logBackfillChannel(channel.name, count);\n totalMessages += count;\n } catch (error) {\n log.logWarning(`Failed to backfill #${channel.name}`, String(error));\n }\n\n // Add delay between channels to avoid hitting Slack rate limits\n if (channelId !== channelsToBackfill[channelsToBackfill.length - 1][0]) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n }\n\n const durationMs = Date.now() - startTime;\n log.logBackfillComplete(totalMessages, durationMs);\n }\n\n // ==========================================================================\n // Private - Fetch Users/Channels\n // ==========================================================================\n\n private async fetchUsers(): Promise<void> {\n let cursor: string | undefined;\n do {\n const result = await this.webClient.users.list({ limit: 200, cursor });\n const members = result.members as\n | Array<{ id?: string; name?: string; real_name?: string; deleted?: boolean }>\n | undefined;\n if (members) {\n for (const u of members) {\n if (u.id && u.name && !u.deleted) {\n this.users.set(u.id, {\n id: u.id,\n userName: u.name,\n displayName: u.real_name || u.name,\n });\n }\n }\n }\n cursor = result.response_metadata?.next_cursor;\n } while (cursor);\n }\n\n private async fetchChannels(): Promise<void> {\n // Fetch public/private channels\n let cursor: string | undefined;\n do {\n const result = await this.webClient.conversations.list({\n types: \"public_channel,private_channel\",\n exclude_archived: true,\n limit: 200,\n cursor,\n });\n const channels = result.channels as\n | Array<{ id?: string; name?: string; is_member?: boolean }>\n | undefined;\n if (channels) {\n for (const c of channels) {\n if (c.id && c.name && c.is_member) {\n this.channels.set(c.id, { id: c.id, name: c.name });\n }\n }\n }\n cursor = result.response_metadata?.next_cursor;\n } while (cursor);\n\n // Also fetch DM channels (IMs)\n cursor = undefined;\n do {\n const result = await this.webClient.conversations.list({\n types: \"im\",\n limit: 200,\n cursor,\n });\n const ims = result.channels as Array<{ id?: string; user?: string }> | undefined;\n if (ims) {\n for (const im of ims) {\n if (im.id) {\n // Use user's name as channel name for DMs\n const user = im.user ? this.users.get(im.user) : undefined;\n const name = user ? `DM:${user.userName}` : `DM:${im.id}`;\n this.channels.set(im.id, { id: im.id, name });\n }\n }\n }\n cursor = result.response_metadata?.next_cursor;\n } while (cursor);\n }\n}\n"]}
1
+ {"version":3,"file":"bot.d.ts","sourceRoot":"","sources":["../../../src/adapters/slack/bot.ts"],"names":[],"mappings":"A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AED,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAE9C;IAED,cAAc,CACZ,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,QAAQ,CAAC,EAAE,MAAM,EACjB,WAAW,CAAC,EAAE,MAAM,EAAE,GACrB,IAAI,CAKN;IAED,eAAe,IAAI,YAAY,CAe9B;IAMD;;;OAGG;IACH,YAAY,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CA0ErC;IAMD,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,yBAAyB;IAuBjC,OAAO,CAAC,aAAa;IA4JrB,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,UAAU;IAKlB,OAAO,CAAC,qBAAqB;IAkF7B,OAAO,CAAC,sBAAsB;YA0DhB,sBAAsB;YActB,oBAAoB;YAyCpB,sBAAsB;YAWtB,wBAAwB;YAWxB,sBAAsB;IAWpC,OAAO,CAAC,kBAAkB;IAuB1B,OAAO,CAAC,gBAAgB;IAyExB,OAAO,CAAC,kBAAkB;YAgKZ,kBAAkB;IA8EhC,OAAO,CAAC,mBAAmB;YAeb,iBAAiB;IA6C/B,OAAO,CAAC,sBAAsB;YA+EhB,cAAc;YA4Bd,qBAAqB;YAwCrB,qBAAqB;YAqBrB,eAAe;YA2Gf,mBAAmB;YAsCnB,UAAU;YAsBV,aAAa;CA6C5B","sourcesContent":["import { SocketModeClient } from \"@slack/socket-mode\";\nimport type { KnownBlock } from \"@slack/types\";\nimport { WebClient } from \"@slack/web-api\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { readFile } from \"fs/promises\";\nimport { basename, join } from \"path\";\nimport type {\n Bot,\n BotAdapters,\n BotEvent,\n BotHandler,\n ChatMessage,\n ChatResponseContext,\n ChatToolResult,\n ConversationKind,\n PlatformInfo,\n} from \"../../adapter.js\";\nimport { resolveConversationSettings } from \"../../config.js\";\nimport type { EventsWatcher } from \"../../events.js\";\nimport * as log from \"../../log.js\";\nimport type { Attachment, ChannelStore } from \"../../store.js\";\nimport type {\n SlackBlockAction,\n SlackBlockActionBody,\n SlackChannel,\n SlackEvent,\n SlackUser,\n} from \"./types.js\";\nimport { PRODUCT_NAME, formatForceStopped, formatNothingRunning } from \"../../platform-messages.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n ChannelQueue,\n resolveOnlyScopedStopTarget,\n resolveStopTarget,\n withRetry,\n} from \"../shared.js\";\nimport { processMessageIntake } from \"../intake.js\";\nimport { createSlackAdapters } from \"./context.js\";\nimport {\n hasMaterializedChatSession,\n registerThreadSession,\n} from \"../../sessions/chat-session-manager.js\";\nimport {\n isSlackThreadSessionKey,\n planSlackAdapterSession,\n planSlackEventAnchorRun,\n resolveSlackSessionKey,\n} from \"./session.js\";\nimport { reportUserFacingError } from \"../../observability/sentry.js\";\n\nconst SLACK_EVENT_ANCHOR_TEXT = \"Working on it...\";\n\n// Slack WebClient errors carry either `code: \"rate_limited\"` (retry-after) or\n// the legacy `data.error === \"rate_limited\"` / 429 status shape.\nfunction slackIsRateLimited(err: Error): boolean {\n if ((err as { code?: unknown }).code === \"rate_limited\") return true;\n const data = (err as { data?: { error?: string; response?: { status?: number } } }).data;\n return data?.error === \"rate_limited\" || data?.response?.status === 429;\n}\n\nconst slackRetry = <T>(fn: () => Promise<T>): Promise<T> =>\n withRetry(fn, { isRateLimited: slackIsRateLimited });\n\nfunction collectSlackText(value: unknown, parts: string[]): void {\n if (value === null || value === undefined) return;\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (trimmed) parts.push(trimmed);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) collectSlackText(item, parts);\n return;\n }\n if (typeof value !== \"object\") return;\n\n const obj = value as Record<string, unknown>;\n for (const key of [\"text\", \"fallback\", \"title\", \"value\"] as const) {\n collectSlackText(obj[key], parts);\n }\n collectSlackText(obj.fields, parts);\n collectSlackText(obj.elements, parts);\n collectSlackText(obj.blocks, parts);\n}\n\nfunction buildSlackAppMessageText(event: {\n text?: string;\n blocks?: unknown[];\n attachments?: unknown[];\n}): string {\n const parts: string[] = [];\n collectSlackText(event.text, parts);\n collectSlackText(event.blocks, parts);\n collectSlackText(event.attachments, parts);\n const deduped = parts.filter((part, index) => parts.indexOf(part) === index);\n return deduped.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Shared mrkdwn truncation helper\n// ---------------------------------------------------------------------------\n\nconst MRKDWN_CONTEXT_TEXT_LIMIT = 3000;\n\n/**\n * Build a Slack context block whose text is capped at the mrkdwn limit.\n * Used for muted diagnostics and ephemeral command responses.\n */\nexport function buildMrkdwnContextBlock(text: string): object {\n const blockText =\n text.length > MRKDWN_CONTEXT_TEXT_LIMIT\n ? text.substring(0, MRKDWN_CONTEXT_TEXT_LIMIT - 20) + \"\\n_(truncated)_\"\n : text;\n return { type: \"context\", elements: [{ type: \"mrkdwn\", text: blockText }] };\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type { SlackChannel, SlackEvent, SlackUser } from \"./types.js\";\n\n// ============================================================================\n// SlackBot\n// ============================================================================\n\nexport class SlackBot implements Bot {\n private socketClient: SocketModeClient;\n private webClient: WebClient;\n private handler: BotHandler;\n private workingDir: string;\n private store: ChannelStore;\n private botUserId: string | null = null;\n private botId: string | null = null;\n private teamId: string | null = null;\n private ownMentionRegex: RegExp | null = null;\n private startupTs: string | null = null; // Messages older than this are just logged, not processed\n\n private users = new Map<string, SlackUser>();\n private channels = new Map<string, SlackChannel>();\n private queues = new Map<string, ChannelQueue>();\n private eventsWatcher: EventsWatcher | null = null;\n\n private createAdapters(event: SlackEvent): BotAdapters {\n return createSlackAdapters(event, this, {\n replyMode:\n resolveConversationSettings(join(this.workingDir, event.conversationId)).slack?.replyMode ??\n \"top-level\",\n });\n }\n\n constructor(\n handler: BotHandler,\n config: { appToken: string; botToken: string; workingDir: string; store: ChannelStore },\n ) {\n this.handler = handler;\n this.workingDir = config.workingDir;\n this.store = config.store;\n this.socketClient = new SocketModeClient({\n appToken: config.appToken,\n // Default 5s is too tight: brief event-loop stalls (e.g. backfill, sync fs)\n // cause false pong timeouts; 4 in a row makes Slack drop the socket.\n clientPingTimeout: 12_000,\n });\n this.webClient = new WebClient(config.botToken);\n }\n\n setEventsWatcher(watcher: EventsWatcher): void {\n this.eventsWatcher = watcher;\n }\n\n // ==========================================================================\n // Public API\n // ==========================================================================\n\n async start(): Promise<void> {\n const auth = await this.webClient.auth.test();\n this.botUserId = auth.user_id as string;\n this.botId = typeof auth.bot_id === \"string\" ? auth.bot_id : null;\n this.teamId = typeof auth.team_id === \"string\" ? auth.team_id : null;\n\n await Promise.all([this.fetchUsers(), this.fetchChannels()]);\n log.logInfo(`Loaded ${this.channels.size} channels, ${this.users.size} users`);\n\n // Record startup time before opening the socket. Slack may replay older events;\n // those should be logged but not processed. Backfill runs in the background up\n // to this timestamp so startup is not blocked by one history call per channel.\n this.startupTs = (Date.now() / 1000).toFixed(6);\n\n this.setupEventHandlers();\n await this.socketClient.start();\n\n log.logConnected(\"Slack\");\n\n void this.backfillAllChannels(this.startupTs).catch((error) => {\n log.logWarning(\"Slack backfill failed\", String(error));\n });\n }\n\n getUser(userId: string): SlackUser | undefined {\n return this.users.get(userId);\n }\n\n getChannel(channelId: string): SlackChannel | undefined {\n return this.channels.get(channelId);\n }\n\n getAllUsers(): SlackUser[] {\n return Array.from(this.users.values());\n }\n\n getAllChannels(): SlackChannel[] {\n return Array.from(this.channels.values());\n }\n\n private stripOwnMention(text: string | undefined): string {\n const source = text ?? \"\";\n if (!this.botUserId) return source.trim();\n if (!this.ownMentionRegex || !this.ownMentionRegex.source.includes(this.botUserId)) {\n this.ownMentionRegex = new RegExp(`<@${this.botUserId}>`, \"gi\");\n }\n return source.replace(this.ownMentionRegex, \"\").trim();\n }\n\n async postMessage(channel: string, text: string): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.chat.postMessage({ channel, text });\n return result.ts as string;\n });\n }\n\n async postEphemeral(\n channel: string,\n user: string,\n text: string,\n threadTs?: string,\n ): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.chat.postEphemeral({\n channel,\n user,\n text,\n ...(threadTs ? { thread_ts: threadTs } : {}),\n });\n });\n }\n\n async postEphemeralBlocks(\n channel: string,\n user: string,\n text: string,\n blocks: object[],\n threadTs?: string,\n ): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.chat.postEphemeral({\n channel,\n user,\n text,\n blocks: blocks as KnownBlock[],\n ...(threadTs ? { thread_ts: threadTs } : {}),\n });\n });\n }\n\n async postMessageBlocks(channel: string, text: string, blocks: object[]): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.chat.postMessage({\n channel,\n text,\n blocks: blocks as KnownBlock[],\n });\n return result.ts as string;\n });\n }\n\n async postPrivate(conversationId: string, userId: string, text: string): Promise<void> {\n await this.postEphemeral(conversationId, userId, text);\n }\n\n async postPrivateDiagnostic(\n conversationId: string,\n userId: string,\n text: string,\n options?: { style?: \"muted\" | \"error\" },\n ): Promise<void> {\n if (options?.style !== \"muted\") {\n await this.postEphemeral(\n conversationId,\n userId,\n options?.style === \"error\" ? `_${text}_` : text,\n );\n return;\n }\n await this.postEphemeralBlocks(conversationId, userId, text, [buildMrkdwnContextBlock(text)]);\n }\n\n async openDirectMessage(userId: string): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.conversations.open({ users: userId });\n const channelId = result.channel?.id;\n if (!channelId) {\n throw new Error(`Failed to open DM for user ${userId}`);\n }\n return channelId;\n });\n }\n\n async updateMessage(channel: string, ts: string, text: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.chat.update({ channel, ts, text });\n });\n }\n\n async startMessageStream(\n channel: string,\n text: string,\n threadTs?: string,\n recipientUserId?: string,\n ): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.apiCall(\"chat.startStream\", {\n channel,\n markdown_text: text,\n ...(threadTs ? { thread_ts: threadTs } : {}),\n ...(this.teamId ? { recipient_team_id: this.teamId } : {}),\n ...(recipientUserId ? { recipient_user_id: recipientUserId } : {}),\n });\n const ts = (result as { ts?: string }).ts;\n if (!ts) throw new Error(\"Slack chat.startStream did not return ts\");\n return ts;\n });\n }\n\n async appendMessageStream(channel: string, ts: string, text: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.apiCall(\"chat.appendStream\", {\n channel,\n ts,\n markdown_text: text,\n });\n });\n }\n\n async stopMessageStream(channel: string, ts: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.apiCall(\"chat.stopStream\", { channel, ts });\n });\n }\n\n async deleteMessage(channel: string, ts: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.chat.delete({ channel, ts });\n });\n }\n\n // ==========================================================================\n // Slack Assistant API (AI assistant experience)\n // ==========================================================================\n\n /** Set the status for an assistant thread (shows \"thinking\" state) */\n async setAssistantStatus(channel: string, threadTs: string, status: string): Promise<void> {\n return slackRetry(async () => {\n await this.webClient.assistant.threads.setStatus({\n channel_id: channel,\n thread_ts: threadTs,\n status,\n });\n });\n }\n\n async postInThread(channel: string, threadTs: string, text: string): Promise<string> {\n return slackRetry(async () => {\n // Use Block Kit section for long messages to trigger Slack's \"Show more\" collapsing (~700 chars)\n const SECTION_TEXT_LIMIT = 3000;\n if (text.length > 500) {\n const blockText =\n text.length > SECTION_TEXT_LIMIT\n ? text.substring(0, SECTION_TEXT_LIMIT - 20) + \"\\n_(truncated)_\"\n : text;\n const result = await this.webClient.chat.postMessage({\n channel,\n thread_ts: threadTs,\n text, // full text as notification fallback\n blocks: [{ type: \"section\", text: { type: \"mrkdwn\", text: blockText } }],\n });\n return result.ts as string;\n }\n const result = await this.webClient.chat.postMessage({ channel, thread_ts: threadTs, text });\n return result.ts as string;\n });\n }\n\n async postInThreadBlocks(\n channel: string,\n threadTs: string,\n text: string,\n blocks: object[],\n ): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.chat.postMessage({\n channel,\n thread_ts: threadTs,\n text, // fallback for notifications\n blocks: blocks as KnownBlock[],\n });\n return result.ts as string;\n });\n }\n\n async postBlocks(channel: string, text: string, blocks: object[]): Promise<string> {\n return slackRetry(async () => {\n const result = await this.webClient.chat.postMessage({\n channel,\n text,\n blocks: blocks as KnownBlock[],\n });\n return result.ts as string;\n });\n }\n\n async uploadFile(\n channel: string,\n filePath: string,\n title?: string,\n threadTs?: string,\n ): Promise<void> {\n return slackRetry(async () => {\n const fileName = title || basename(filePath);\n const fileContent = readFileSync(filePath);\n await this.webClient.files.uploadV2({\n channel_id: channel,\n file: fileContent,\n filename: fileName,\n title: fileName,\n ...(threadTs ? { thread_ts: threadTs } : {}),\n } as Parameters<typeof this.webClient.files.uploadV2>[0]);\n });\n }\n\n logToFile(channel: string, entry: object): void {\n appendChannelLog(this.workingDir, channel, entry);\n }\n\n logBotResponse(\n channel: string,\n text: string,\n ts: string,\n threadTs?: string,\n slackBlocks?: object[],\n ): void {\n appendBotResponseLog(this.workingDir, channel, text, ts, threadTs, {\n platform: \"slack\",\n ...(slackBlocks ? { slackBlocks } : {}),\n });\n }\n\n getPlatformInfo(): PlatformInfo {\n return {\n name: \"slack\",\n formattingGuide:\n \"## Slack Formatting (mrkdwn, NOT Markdown)\\nBold: *text*, Italic: _text_, Code: `code`, Block: ```code```, Links: <url|text>\\nDo NOT use **double asterisks** or [markdown](links).\",\n channels: this.getAllChannels().map((c) => ({ id: c.id, name: c.name })),\n users: this.getAllUsers().map((u) => ({\n id: u.id,\n userName: u.userName,\n displayName: u.displayName,\n })),\n diagnostics: {\n showUsageSummary: true,\n },\n };\n }\n\n // ==========================================================================\n // Events Integration\n // ==========================================================================\n\n /**\n * Enqueue an event for processing. Always queues (no \"already working\" rejection).\n * Returns true if enqueued, false if queue is full (max 5).\n */\n enqueueEvent(event: BotEvent): boolean {\n const conversationId = event.conversationId;\n const queue = this.getQueue(conversationId);\n if (queue.size() >= 5) {\n log.logWarning(\n `Event queue full for ${conversationId}, discarding: ${event.text.substring(0, 50)}`,\n );\n return false;\n }\n log.logInfo(`Enqueueing event for ${conversationId}: ${event.text.substring(0, 50)}`);\n queue.enqueue(async () => {\n let anchorTs: string | undefined;\n if (!event.thread_ts) {\n try {\n anchorTs = await this.postMessage(conversationId, SLACK_EVENT_ANCHOR_TEXT);\n } catch (err) {\n log.logWarning(\n `Failed to post Slack event anchor for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n reportUserFacingError(err, {\n domain: \"events\",\n surface: \"event_delivery\",\n operation: \"slack_anchor_post\",\n severity: \"error\",\n platform: \"slack\",\n context: {\n conversationId,\n conversationKind: event.conversationKind,\n eventTs: event.ts,\n textLength: event.text.length,\n },\n });\n throw err;\n }\n }\n const eventPlan = planSlackEventAnchorRun(event, anchorTs);\n const eventForRun = eventPlan.event;\n if (eventPlan.initialMessageTs && eventForRun.sessionKey) {\n registerThreadSession({\n conversationDir: join(this.workingDir, conversationId),\n sessionKey: eventForRun.sessionKey,\n });\n }\n\n const runQueueKey = planSlackAdapterSession(eventForRun, {\n initialMessageTs: eventPlan.initialMessageTs,\n }).sessionKey;\n this.getQueue(runQueueKey).enqueue(async () => {\n const slackEvent: SlackEvent = {\n type: eventForRun.type as SlackEvent[\"type\"],\n conversationId,\n conversationKind: eventForRun.conversationKind,\n channel: conversationId,\n ts: eventForRun.ts,\n thread_ts: eventForRun.thread_ts,\n user: eventForRun.user,\n text: eventForRun.text,\n attachments: eventForRun.attachments?.map((attachment) => ({\n original: attachment.name,\n localPath: attachment.localPath,\n })),\n sessionKey: eventForRun.sessionKey,\n };\n const adapters = createSlackAdapters(slackEvent, this, {\n initialMessageTs: eventPlan.initialMessageTs,\n replyMode:\n resolveConversationSettings(join(this.workingDir, eventForRun.conversationId)).slack\n ?.replyMode ?? \"top-level\",\n });\n return this.handler.handleEvent(eventForRun, this, adapters);\n });\n });\n return true;\n }\n\n // ==========================================================================\n // Private - Event Handlers\n // ==========================================================================\n\n private getQueue(channelId: string): ChannelQueue {\n let queue = this.queues.get(channelId);\n if (!queue) {\n queue = new ChannelQueue(\"Slack\");\n this.queues.set(channelId, queue);\n }\n return queue;\n }\n\n private resolveQueueKey(conversationId: string, sessionKey: string): string {\n if (!isSlackThreadSessionKey(sessionKey)) return sessionKey;\n if (this.handler.isRunning(sessionKey)) return sessionKey;\n return this.hasKnownThreadSession(conversationId, sessionKey) ? sessionKey : conversationId;\n }\n\n private hasKnownThreadSession(conversationId: string, sessionKey: string): boolean {\n return hasMaterializedChatSession({\n conversationDir: join(this.workingDir, conversationId),\n sessionKey,\n });\n }\n\n private processSlackMessageIntake(options: {\n event: SlackEvent;\n attachmentsPromise: Promise<Attachment[]>;\n queueKey: string;\n isAutoReplyCandidate: boolean;\n onNotTriggered?: () => void;\n }): void {\n void processMessageIntake({\n eventBase: options.event as unknown as BotEvent,\n workingDir: this.workingDir,\n isAutoReplyCandidate: options.isAutoReplyCandidate,\n logEntryBase: {},\n processAttachments: () => options.attachmentsPromise,\n queueKey: options.queueKey,\n enqueue: (queueKey, work) => this.getQueue(queueKey).enqueue(work),\n handler: this.handler,\n bot: this,\n createAdapters: (event) => this.createAdapters(event as SlackEvent),\n onNotTriggered: options.onNotTriggered,\n deferAttachmentsUntilRun: true,\n });\n }\n\n private buildHomeView(): { type: \"home\"; blocks: KnownBlock[] } {\n const blocks: object[] = [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: `*${PRODUCT_NAME}*\\nStart a new task or check on running work.`,\n },\n accessory: {\n type: \"image\",\n image_url: \"https://media1.tenor.com/m/lfDATg4Bhc0AAAAC/happy-cat.gif\",\n alt_text: PRODUCT_NAME,\n },\n },\n ];\n\n // --- Running tasks ---\n const runningSessions = this.handler.getRunningSessions();\n\n blocks.push(\n { type: \"divider\" },\n {\n type: \"header\",\n text: {\n type: \"plain_text\",\n text: `Running Tasks (${runningSessions.length})`,\n emoji: true,\n },\n },\n );\n\n if (runningSessions.length === 0) {\n blocks.push({\n type: \"context\",\n elements: [{ type: \"mrkdwn\", text: \"_No tasks running right now._\" }],\n });\n } else {\n // Threshold for \"stuck\" detection (10 minutes)\n const STUCK_THRESHOLD_MS = 10 * 60 * 1000;\n\n for (const session of runningSessions) {\n const channelId = session.sessionKey.split(\":\")[0];\n const channel = this.channels.get(channelId);\n const channelName = channel ? `#${channel.name}` : channelId;\n const elapsed = Math.floor((Date.now() - session.startedAt) / 60000);\n const elapsedStr = elapsed < 1 ? \"<1 min\" : `${elapsed} min`;\n\n // Check if task might be stuck\n const lastActivity = session.lastActivityAt ? Date.now() - session.lastActivityAt : 0;\n const isStuck = lastActivity > STUCK_THRESHOLD_MS;\n const statusText = isStuck ? \"_stuck_\" : \"_running_\";\n\n // Build status line: channel · status · time · step\n let statusLine = `${statusText} · ${elapsedStr}`;\n if (session.currentTool) {\n statusLine += ` · ${session.currentTool}`;\n }\n if (isStuck && lastActivity > 0) {\n const inactiveMin = Math.floor(lastActivity / 60000);\n statusLine += ` · idle ${inactiveMin}m`;\n }\n\n // Use context block for gray small text (like \"No scheduled jobs.\")\n blocks.push({\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: `*${channelName}* · ${statusLine}`,\n },\n ],\n });\n\n // Add Force Stop button as separate element if stuck\n if (isStuck) {\n blocks.push({\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: \" \",\n },\n {\n type: \"button\",\n text: { type: \"plain_text\", text: \"Force Stop\", emoji: true },\n action_id: `force_stop_${session.sessionKey.replace(/:/g, \"_\")}`,\n style: \"danger\",\n },\n ],\n });\n }\n }\n }\n\n // --- Cron jobs ---\n const periodicEvents = this.eventsWatcher?.getPeriodicEvents() ?? [];\n\n blocks.push(\n { type: \"divider\" },\n {\n type: \"header\",\n text: {\n type: \"plain_text\",\n text: `Scheduled Jobs (${periodicEvents.length})`,\n emoji: true,\n },\n },\n );\n\n if (periodicEvents.length === 0) {\n blocks.push({\n type: \"context\",\n elements: [{ type: \"mrkdwn\", text: \"_No scheduled jobs._\" }],\n });\n } else {\n for (const ev of periodicEvents) {\n const channelLabel =\n ev.platform === \"slack\"\n ? (() => {\n const channel = this.channels.get(ev.conversationId);\n const channelName = channel ? `#${channel.name}` : ev.conversationId;\n return `${ev.platform}:${channelName}`;\n })()\n : `${ev.platform}:${ev.conversationId}`;\n const nextStr = ev.nextRun\n ? new Date(ev.nextRun).toLocaleString(\"en-US\", {\n month: \"short\",\n day: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n })\n : \"—\";\n blocks.push({\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: `*${ev.text}*\\n└ \\`${ev.schedule}\\` · ${channelLabel} · Next: ${nextStr}`,\n },\n });\n }\n }\n\n // --- Footer ---\n blocks.push(\n { type: \"divider\" },\n {\n type: \"context\",\n elements: [\n { type: \"mrkdwn\", text: \"💡 @mention in a channel or send a DM to start a new task\" },\n ],\n },\n );\n\n return { type: \"home\", blocks: blocks as KnownBlock[] };\n }\n\n private resolveStopTarget(channelId: string, threadTs?: string): string | null {\n const directTarget = resolveStopTarget({\n handler: this.handler,\n conversationId: channelId,\n sessionKey: resolveSlackSessionKey(channelId, threadTs),\n });\n if (directTarget) return directTarget;\n if (threadTs) return null;\n return resolveOnlyScopedStopTarget(this.handler, channelId);\n }\n\n private isStopText(text: string): boolean {\n const normalized = text.trim().toLowerCase();\n return normalized === \"stop\" || normalized === \"/stop\";\n }\n\n private createCommandAdapters(\n conversationId: string,\n userId: string,\n userName: string | undefined,\n text: string,\n ts: string,\n options: { ephemeralChannelId?: string; threadTs?: string } = {},\n ): BotAdapters {\n const message: ChatMessage = {\n id: ts,\n sessionKey: conversationId,\n conversationKind: options.ephemeralChannelId ? \"shared\" : \"direct\",\n userId,\n userName,\n text,\n attachments: [],\n };\n\n const respond = async (responseText: string) => {\n if (options.ephemeralChannelId) {\n await this.postEphemeral(\n options.ephemeralChannelId,\n userId,\n responseText,\n options.threadTs,\n );\n return;\n }\n const messageTs = await this.postMessage(conversationId, responseText);\n this.logBotResponse(conversationId, responseText, messageTs);\n };\n\n const respondMuted = async (responseText: string) => {\n const blocks = [buildMrkdwnContextBlock(responseText)];\n if (options.ephemeralChannelId) {\n await this.postEphemeralBlocks(\n options.ephemeralChannelId,\n userId,\n responseText,\n blocks,\n options.threadTs,\n );\n return;\n }\n const messageTs = await this.postMessageBlocks(conversationId, responseText, blocks);\n this.logBotResponse(conversationId, responseText, messageTs);\n };\n\n const responseCtx: ChatResponseContext = {\n respond,\n replaceResponse: respond,\n respondDiagnostic: async (\n responseText: string,\n responseOptions?: { style?: \"muted\" | \"error\" },\n ) => {\n if (responseOptions?.style === \"muted\") {\n await respondMuted(responseText);\n return;\n }\n await respond(responseOptions?.style === \"error\" ? `_${responseText}_` : responseText);\n },\n respondToolResult: async (result: ChatToolResult) => {\n const duration = (result.durationMs / 1000).toFixed(1);\n await respond(\n `${result.isError ? \"Error\" : \"Done\"} ${result.toolName} (${duration}s)\\n${result.result}`,\n );\n },\n setTyping: async () => {},\n setWorking: async () => {},\n uploadFile: async (filePath: string, title?: string) => {\n await this.uploadFile(conversationId, filePath, title);\n },\n deleteResponse: async () => {},\n };\n\n return {\n message,\n responseCtx,\n platform: this.getPlatformInfo(),\n };\n }\n\n private buildSlashCommandEvent(\n payload: {\n command: string;\n text?: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n thread_ts?: string;\n },\n options: { type?: BotEvent[\"type\"]; includeText?: boolean; thread?: boolean } = {},\n ): { event: BotEvent; adapters: BotAdapters } {\n const conversationId = payload.channel_id;\n const isDirectMessage = conversationId.startsWith(\"D\");\n const createdAt = new Date();\n const eventTs = (createdAt.getTime() / 1000).toFixed(6);\n const userName = payload.user_name ?? this.getUser(payload.user_id)?.userName;\n const commandSuffix = options.includeText ? payload.text?.trim() : undefined;\n const commandText = commandSuffix ? `${payload.command} ${commandSuffix}` : payload.command;\n const threadTs = options.thread ? payload.thread_ts : undefined;\n const sessionKey = options.thread\n ? resolveSlackSessionKey(conversationId, threadTs)\n : conversationId;\n\n this.logToFile(conversationId, {\n date: createdAt.toISOString(),\n ts: eventTs,\n user: payload.user_id,\n userName,\n text: commandText,\n attachments: [],\n isBot: false,\n ...(threadTs ? { threadTs } : {}),\n });\n\n const event: BotEvent = {\n type: options.type ?? (isDirectMessage ? \"dm\" : \"mention\"),\n conversationId,\n conversationKind: isDirectMessage ? \"direct\" : \"shared\",\n ts: eventTs,\n user: payload.user_id,\n text: commandText,\n attachments: [],\n ...(threadTs ? { thread_ts: threadTs } : {}),\n sessionKey,\n };\n\n const adapters = this.createCommandAdapters(\n conversationId,\n payload.user_id,\n userName,\n commandText,\n eventTs,\n isDirectMessage ? { threadTs } : { ephemeralChannelId: conversationId, threadTs },\n );\n\n return { event, adapters };\n }\n\n private async routeSlashLoginCommand(payload: {\n command: string;\n text?: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n }): Promise<void> {\n const { event, adapters } = this.buildSlashCommandEvent(payload, {\n type: payload.channel_id.startsWith(\"D\") ? \"dm\" : \"private_command\",\n includeText: true,\n });\n await this.handler.handleEvent(event, this, adapters);\n }\n\n private async routeSlashNewCommand(payload: {\n command: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n }): Promise<void> {\n const conversationId = payload.channel_id;\n if (!conversationId.startsWith(\"D\")) {\n await this.postEphemeral(\n conversationId,\n payload.user_id,\n `為了避免誤清除共享上下文,${payload.command} 目前只能在與 ${PRODUCT_NAME} 的私訊中使用。`,\n );\n return;\n }\n\n const createdAt = new Date();\n const eventTs = (createdAt.getTime() / 1000).toFixed(6);\n const userName = payload.user_name ?? this.getUser(payload.user_id)?.userName;\n\n this.logToFile(conversationId, {\n date: createdAt.toISOString(),\n ts: eventTs,\n user: payload.user_id,\n userName,\n text: payload.command,\n attachments: [],\n isBot: false,\n });\n\n const commandBot: Bot = {\n start: async () => {},\n postMessage: async (_channel: string, text: string) => this.postMessage(conversationId, text),\n updateMessage: async (channel: string, ts: string, text: string) =>\n this.updateMessage(channel, ts, text),\n enqueueEvent: (event: BotEvent) => this.enqueueEvent(event),\n getPlatformInfo: () => this.getPlatformInfo(),\n };\n await this.handler.handleNewCommand(conversationId, conversationId, commandBot);\n }\n\n private async routeSlashModelCommand(payload: {\n command: string;\n text?: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n }): Promise<void> {\n const { event, adapters } = this.buildSlashCommandEvent(payload, { includeText: true });\n await this.handler.handleEvent(event, this, adapters);\n }\n\n private async routeSlashSessionCommand(payload: {\n command: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n thread_ts?: string;\n }): Promise<void> {\n const { event, adapters } = this.buildSlashCommandEvent(payload, { thread: true });\n await this.handler.handleEvent(event, this, adapters);\n }\n\n private async routeSlashAdminCommand(payload: {\n command: string;\n channel_id: string;\n user_id: string;\n user_name?: string;\n thread_ts?: string;\n }): Promise<void> {\n const { event, adapters } = this.buildSlashCommandEvent(payload, { thread: true });\n await this.handler.handleEvent(event, this, adapters);\n }\n\n private setupEventHandlers(): void {\n this.socketClient.on(\"disconnect\", (err: unknown) => {\n log.logWarning(\"Slack socket disconnect\", err ? String(err) : \"\");\n });\n this.socketClient.on(\"error\", (err: unknown) => {\n log.logWarning(\"Slack socket error\", err ? String(err) : \"\");\n });\n this.socketClient.on(\"unable_to_socket_mode_start\", (err: unknown) => {\n log.logWarning(\"Slack socket unable_to_start\", err ? String(err) : \"\");\n });\n\n this.socketClient.on(\"app_mention\", (payload) => this.handleAppMention(payload));\n this.socketClient.on(\"message\", (payload) => this.handleMessageEvent(payload));\n this.socketClient.on(\"slash_commands\", (payload) => void this.handleSlashCommand(payload));\n this.socketClient.on(\"app_home_opened\", (payload) => this.handleAppHomeOpened(payload));\n this.socketClient.on(\"block_actions\", (payload) => void this.handleBlockAction(payload));\n this.socketClient.on(\n \"interactive\",\n (payload) =>\n void this.handleBlockAction(payload as { body: SlackBlockActionBody; ack: () => void }),\n );\n }\n\n private handleAppMention({ event, ack }: { event: unknown; ack: () => void }): void {\n const e = event as {\n text: string;\n channel: string;\n user: string;\n ts: string;\n thread_ts?: string;\n files?: Array<{ name: string; url_private_download?: string; url_private?: string }>;\n };\n\n // Skip DMs (handled by message event)\n if (e.channel.startsWith(\"D\")) {\n ack();\n return;\n }\n\n // Top-level mentions use a persistent channel session.\n // Thread replies get their own isolated session (channelId:thread_ts).\n const sessionKey = resolveSlackSessionKey(e.channel, e.thread_ts);\n\n const mentionText = this.stripOwnMention(e.text);\n const slackEvent: SlackEvent = {\n type: \"mention\",\n conversationId: e.channel,\n conversationKind: \"shared\",\n channel: e.channel,\n ts: e.ts,\n thread_ts: e.thread_ts,\n user: e.user,\n text: mentionText || \"Please respond to the recent conversation context.\",\n files: e.files,\n sessionKey,\n };\n\n const attachmentsPromise = this.logUserMessage(slackEvent);\n\n // Only trigger processing for messages AFTER startup (not replayed old messages)\n if (this.startupTs && e.ts < this.startupTs) {\n log.logInfo(\n `[${e.channel}] Logged old message (pre-startup), not triggering: ${slackEvent.text.substring(0, 30)}`,\n );\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n ack();\n return;\n }\n\n // Check for stop command - execute immediately, don't queue!\n if (this.isStopText(slackEvent.text)) {\n const stopTarget = this.resolveStopTarget(e.channel, e.thread_ts);\n if (stopTarget) {\n this.handler.handleStop(stopTarget, e.channel, this);\n } else {\n this.postMessage(e.channel, formatNothingRunning(\"slack\"));\n }\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n ack();\n return;\n }\n\n this.processSlackMessageIntake({\n event: slackEvent,\n attachmentsPromise,\n queueKey: this.resolveQueueKey(e.channel, sessionKey),\n isAutoReplyCandidate: false,\n });\n\n ack();\n }\n\n private handleMessageEvent({ event, ack }: { event: unknown; ack: () => void }): void {\n const e = event as {\n text?: string;\n channel: string;\n user?: string;\n ts: string;\n thread_ts?: string;\n channel_type?: string;\n subtype?: string;\n bot_id?: string;\n app_id?: string;\n username?: string;\n bot_profile?: { id?: string; app_id?: string; name?: string; real_name?: string };\n blocks?: unknown[];\n attachments?: unknown[];\n files?: Array<{ name: string; url_private_download?: string; url_private?: string }>;\n };\n\n const hasFiles = !!e.files && e.files.length > 0;\n const hasSlackContent = !!e.text || hasFiles || !!e.blocks?.length || !!e.attachments?.length;\n const isOwnBotMessage =\n (!!e.user && e.user === this.botUserId) || (!!this.botId && e.bot_id === this.botId);\n if (isOwnBotMessage) {\n ack();\n return;\n }\n\n const isExternalBotMessage = !!e.bot_id || e.subtype === \"bot_message\";\n if (isExternalBotMessage) {\n if (e.subtype !== undefined && e.subtype !== \"bot_message\" && e.subtype !== \"file_share\") {\n ack();\n return;\n }\n if (!hasSlackContent) {\n ack();\n return;\n }\n void this.logExternalBotMessage(e).catch((err) => {\n log.logWarning(\"Failed to log Slack bot message\", String(err));\n });\n ack();\n return;\n }\n\n if (!e.user) {\n ack();\n return;\n }\n if (e.subtype !== undefined && e.subtype !== \"file_share\") {\n ack();\n return;\n }\n if (!hasSlackContent) {\n ack();\n return;\n }\n\n const isDM = e.channel_type === \"im\";\n const conversationKind: ConversationKind = isDM ? \"direct\" : \"shared\";\n const isBotMention = e.text?.includes(`<@${this.botUserId}>`);\n\n // Skip channel @mentions - already handled by app_mention event\n if (!isDM && isBotMention) {\n ack();\n return;\n }\n\n const isThreadReply = !!e.thread_ts;\n const sessionKey = isDM ? resolveSlackSessionKey(e.channel, e.thread_ts) : undefined;\n\n const slackEvent: SlackEvent = {\n type: isDM ? \"dm\" : \"mention\",\n conversationId: e.channel,\n conversationKind,\n channel: e.channel,\n ts: e.ts,\n thread_ts: e.thread_ts,\n user: e.user,\n text: this.stripOwnMention(e.text),\n files: e.files,\n sessionKey,\n };\n\n const attachmentsPromise = this.logUserMessage(slackEvent);\n\n // Only trigger processing for messages AFTER startup (not replayed old messages)\n if (this.startupTs && e.ts < this.startupTs) {\n log.logInfo(\n `[${e.channel}] Skipping old message (pre-startup): ${slackEvent.text.substring(0, 30)}`,\n );\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n ack();\n return;\n }\n\n // Stop command for DM only (app_mention handles shared-channel \"@mikan stop\").\n if (isDM && this.isStopText(slackEvent.text)) {\n const stopTarget = this.resolveStopTarget(e.channel, e.thread_ts);\n if (stopTarget) {\n this.handler.handleStop(stopTarget, e.channel, this);\n } else {\n this.postMessage(e.channel, formatNothingRunning(\"slack\"));\n }\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n ack();\n return;\n }\n\n const enqueueTriggered = () => {\n const activeSessionKey =\n slackEvent.sessionKey ?? resolveSlackSessionKey(e.channel, e.thread_ts);\n // Auto-reply top-level channel messages start with no sessionKey because\n // they are only candidates until the policy allows them. Once triggered,\n // persist the resolved key on the event; otherwise the runtime fallback\n // treats the message ts as a thread session (`channel:ts`) instead of the\n // persistent top-level channel session.\n slackEvent.sessionKey = activeSessionKey;\n this.processSlackMessageIntake({\n event: slackEvent,\n attachmentsPromise,\n queueKey: this.resolveQueueKey(e.channel, activeSessionKey),\n isAutoReplyCandidate: false,\n });\n };\n\n const logOnly = () => {\n void attachmentsPromise.catch((err) => {\n log.logWarning(\"Failed to log Slack message\", String(err));\n });\n };\n\n if (isDM) {\n enqueueTriggered();\n ack();\n return;\n }\n\n if (isThreadReply) {\n logOnly();\n ack();\n return;\n }\n\n const activeSessionKey = resolveSlackSessionKey(e.channel, e.thread_ts);\n slackEvent.sessionKey = activeSessionKey;\n this.processSlackMessageIntake({\n event: slackEvent,\n attachmentsPromise,\n queueKey: this.resolveQueueKey(e.channel, activeSessionKey),\n isAutoReplyCandidate: true,\n onNotTriggered: logOnly,\n });\n\n ack();\n }\n\n private async handleSlashCommand({\n body,\n ack,\n }: {\n body: unknown;\n ack: () => Promise<void>;\n }): Promise<void> {\n const payload = body as {\n command?: string;\n text?: string;\n channel_id?: string;\n user_id?: string;\n user_name?: string;\n thread_ts?: string;\n };\n\n await ack();\n\n if (!payload.command || !payload.channel_id || !payload.user_id) {\n return;\n }\n\n const { command, text, channel_id, user_id, user_name, thread_ts } = payload;\n\n let handlerPromise: Promise<void> | null = null;\n if (command === \"/pi-login\") {\n handlerPromise = this.routeSlashLoginCommand({\n command,\n text,\n channel_id,\n user_id,\n user_name,\n });\n } else if (command === \"/pi-new\") {\n handlerPromise = this.routeSlashNewCommand({ command, channel_id, user_id, user_name });\n } else if (command === \"/pi-session\") {\n handlerPromise = this.routeSlashSessionCommand({\n command,\n channel_id,\n user_id,\n user_name,\n thread_ts,\n });\n } else if (command === \"/pi-model\") {\n handlerPromise = this.routeSlashModelCommand({\n command,\n text,\n channel_id,\n user_id,\n user_name,\n });\n } else if (command === \"/pi-sandbox\" || command === \"/pi-auto-reply\") {\n handlerPromise = this.routeSlashModelCommand({\n command,\n text,\n channel_id,\n user_id,\n user_name,\n });\n } else if (command === \"/pi-admin\") {\n handlerPromise = this.routeSlashAdminCommand({\n command,\n channel_id,\n user_id,\n user_name,\n thread_ts,\n });\n }\n\n if (!handlerPromise) {\n return;\n }\n\n handlerPromise.catch((err) => {\n log.logWarning(\"Slack slash command error\", err instanceof Error ? err.message : String(err));\n });\n }\n\n private handleAppHomeOpened({ event, ack }: { event: unknown; ack: () => void }): void {\n const e = event as { user: string; tab: string };\n ack();\n if (e.tab !== \"home\") return;\n\n this.webClient.views\n .publish({\n user_id: e.user,\n view: this.buildHomeView(),\n })\n .catch((err) => {\n log.logWarning(`Failed to publish App Home view`, String(err));\n });\n }\n\n private async handleBlockAction({\n body,\n ack,\n }: {\n body: SlackBlockActionBody;\n ack: () => void;\n }): Promise<void> {\n const action = body.actions?.[0];\n if (!action) {\n ack();\n return;\n }\n\n if (!action.action_id?.startsWith(\"force_stop_\")) {\n ack();\n this.handleSlackInteraction(body, action);\n return;\n }\n\n ack();\n const sessionKey = action.action_id.replace(\"force_stop_\", \"\").replace(/_/g, \":\");\n const userId = body.user?.id;\n const channelId = body.container?.channel_id || sessionKey.split(\":\")[0];\n\n log.logInfo(`[Force Stop] User ${userId} requested force stop for ${sessionKey}`);\n\n // Use handler's forceStop method\n this.handler.forceStop(sessionKey);\n\n // Notify in channel\n await this.postMessage(channelId, formatForceStopped(\"slack\", userId ?? \"unknown\"));\n\n // Refresh home tab\n if (userId) {\n this.webClient.views\n .publish({\n user_id: userId,\n view: this.buildHomeView(),\n })\n .catch((err) => {\n log.logWarning(`Failed to refresh App Home view`, String(err));\n });\n }\n }\n\n private handleSlackInteraction(body: SlackBlockActionBody, action: SlackBlockAction): void {\n const container = body.container ?? {};\n const channelId = container.channel_id;\n const userId = body.user?.id;\n if (!channelId || !userId) return;\n\n const selectedOption = action.selected_option;\n const selectedOptions = Array.isArray(action.selected_options)\n ? action.selected_options\n : undefined;\n const selectedText = selectedOption?.text?.text ?? selectedOption?.value;\n const selectedTexts = selectedOptions?.map((option) => option.text?.text ?? option.value);\n const valueText = selectedTexts?.length\n ? selectedTexts.join(\", \")\n : (selectedText ?? action.value ?? action.action_id);\n const text = `[Slack action] ${action.action_id}: ${valueText}`;\n const ts = `action:${Date.now()}`;\n const threadTs = container.thread_ts;\n const sessionKey = resolveSlackSessionKey(channelId, threadTs);\n\n this.logToFile(channelId, {\n date: new Date().toISOString(),\n ts,\n ...(threadTs ? { threadTs } : {}),\n user: userId,\n userName: body.user?.username ?? body.user?.name,\n text,\n attachments: [],\n isBot: false,\n platform: \"slack\",\n slackInteraction: {\n type: \"block_actions\",\n actionId: action.action_id,\n blockId: action.block_id,\n actionType: action.type,\n value: action.value,\n selectedOption: selectedOption\n ? { text: selectedOption.text?.text, value: selectedOption.value }\n : undefined,\n selectedOptions: selectedOptions?.map((option) => ({\n text: option.text?.text,\n value: option.value,\n })),\n messageTs: container.message_ts,\n },\n });\n\n const event: BotEvent = {\n type: \"slack_action\",\n conversationId: channelId,\n conversationKind: channelId.startsWith(\"D\") ? \"direct\" : \"shared\",\n ts,\n user: userId,\n text,\n attachments: [],\n ...(threadTs ? { thread_ts: threadTs } : {}),\n sessionKey,\n };\n\n this.getQueue(this.resolveQueueKey(channelId, sessionKey)).enqueue(async () => {\n const slackEvent: SlackEvent = {\n type: event.conversationKind === \"direct\" ? \"dm\" : \"mention\",\n conversationId: channelId,\n conversationKind: event.conversationKind,\n channel: channelId,\n ts,\n thread_ts: threadTs,\n user: userId,\n text,\n attachments: [],\n sessionKey,\n };\n return this.handler.handleEvent(event, this, this.createAdapters(slackEvent));\n });\n }\n\n /**\n * Log a user message to log.jsonl after attachments are ready.\n */\n private async logUserMessage(event: SlackEvent): Promise<Attachment[]> {\n const user = this.users.get(event.user);\n let attachments: Attachment[] = [];\n let attachmentError: unknown;\n if (event.files) {\n try {\n attachments = await this.store.processAttachments(event.channel, event.files, event.ts);\n } catch (err) {\n attachmentError = err;\n }\n }\n // Always write the text log, even if attachment processing failed — we want\n // a record of the user message regardless of file-handling errors.\n this.logToFile(event.channel, {\n date: new Date(parseFloat(event.ts) * 1000).toISOString(),\n ts: event.ts,\n threadTs: event.thread_ts,\n user: event.user,\n userName: user?.userName,\n displayName: user?.displayName,\n text: event.text,\n attachments,\n isBot: false,\n });\n if (attachmentError) throw attachmentError;\n return attachments;\n }\n\n private async logExternalBotMessage(event: {\n channel: string;\n ts: string;\n thread_ts?: string;\n text?: string;\n subtype?: string;\n bot_id?: string;\n app_id?: string;\n username?: string;\n bot_profile?: { app_id?: string; name?: string; real_name?: string };\n blocks?: unknown[];\n attachments?: unknown[];\n files?: Array<{ name: string; url_private_download?: string; url_private?: string }>;\n }): Promise<Attachment[]> {\n const attachments = event.files\n ? await this.store.processAttachments(event.channel, event.files, event.ts)\n : [];\n const botName =\n event.username ?? event.bot_profile?.name ?? event.bot_profile?.real_name ?? event.bot_id;\n this.logToFile(event.channel, {\n date: new Date(parseFloat(event.ts) * 1000).toISOString(),\n ts: event.ts,\n threadTs: event.thread_ts,\n user: event.bot_id ? `bot:${event.bot_id}` : \"external-bot\",\n userName: botName,\n displayName: botName,\n text: buildSlackAppMessageText(event),\n attachments,\n isBot: true,\n botId: event.bot_id,\n appId: event.app_id ?? event.bot_profile?.app_id,\n subtype: event.subtype,\n });\n return attachments;\n }\n\n // ==========================================================================\n // Private - Backfill\n // ==========================================================================\n\n private async getExistingTimestamps(channelId: string): Promise<Set<string>> {\n const logPath = join(this.workingDir, channelId, \"log.jsonl\");\n const timestamps = new Set<string>();\n if (!existsSync(logPath)) return timestamps;\n\n const content = await readFile(logPath, \"utf-8\");\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n for (let i = 0; i < lines.length; i++) {\n try {\n const entry = JSON.parse(lines[i]);\n if (entry.ts) timestamps.add(entry.ts);\n } catch (err) {\n log.logWarning(\n `Skipping malformed log entry at ${logPath}:${i + 1}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n return timestamps;\n }\n\n private async backfillChannel(channelId: string, upperBoundTs?: string): Promise<number> {\n const existingTs = await this.getExistingTimestamps(channelId);\n\n // Find the biggest ts in log.jsonl\n let lastLoggedTs: string | undefined;\n for (const ts of existingTs) {\n if (!lastLoggedTs || parseFloat(ts) > parseFloat(lastLoggedTs)) lastLoggedTs = ts;\n }\n\n type Message = {\n user?: string;\n bot_id?: string;\n app_id?: string;\n username?: string;\n bot_profile?: { app_id?: string; name?: string; real_name?: string };\n blocks?: unknown[];\n attachments?: unknown[];\n text?: string;\n ts?: string;\n thread_ts?: string;\n subtype?: string;\n files?: Array<{ name: string }>;\n };\n const allMessages: Message[] = [];\n\n let cursor: string | undefined;\n let pageCount = 0;\n const maxPages = 3;\n\n do {\n const result = await this.webClient.conversations.history({\n channel: channelId,\n oldest: lastLoggedTs, // Only fetch messages newer than what we have\n latest: upperBoundTs, // Do not race live socket events after startup\n inclusive: false,\n limit: 1000,\n cursor,\n });\n if (result.messages) {\n allMessages.push(...(result.messages as Message[]));\n }\n cursor = result.response_metadata?.next_cursor;\n pageCount++;\n } while (cursor && pageCount < maxPages);\n\n // Filter: include mikan's messages, external app/bot messages, and user messages.\n const relevantMessages = allMessages.filter((msg) => {\n if (!msg.ts || existingTs.has(msg.ts)) return false; // Skip duplicates\n if (msg.user === this.botUserId) return true;\n const isExternalBotMessage = !!msg.bot_id || msg.subtype === \"bot_message\";\n if (isExternalBotMessage) {\n if (this.botId && msg.bot_id === this.botId) return false;\n if (\n msg.subtype !== undefined &&\n msg.subtype !== \"bot_message\" &&\n msg.subtype !== \"file_share\"\n ) {\n return false;\n }\n return (\n !!msg.text ||\n !!(msg.files && msg.files.length > 0) ||\n !!msg.blocks?.length ||\n !!msg.attachments?.length\n );\n }\n if (msg.subtype !== undefined && msg.subtype !== \"file_share\") return false;\n if (!msg.user) return false;\n if (!msg.text && (!msg.files || msg.files.length === 0)) return false;\n return true;\n });\n\n // Reverse to chronological order\n relevantMessages.reverse();\n\n // Log each message to log.jsonl\n for (const msg of relevantMessages) {\n const isMikanMessage = msg.user === this.botUserId;\n const isExternalBotMessage =\n !isMikanMessage && (!!msg.bot_id || msg.subtype === \"bot_message\");\n if (isExternalBotMessage) {\n await this.logExternalBotMessage({ ...msg, channel: channelId, ts: msg.ts! });\n continue;\n }\n\n const user = this.users.get(msg.user!);\n const text = this.stripOwnMention(msg.text);\n const attachments = msg.files\n ? await this.store.processAttachments(channelId, msg.files, msg.ts!)\n : [];\n\n this.logToFile(channelId, {\n date: new Date(parseFloat(msg.ts!) * 1000).toISOString(),\n ts: msg.ts!,\n threadTs: msg.thread_ts,\n user: isMikanMessage ? \"bot\" : msg.user!,\n userName: isMikanMessage ? undefined : user?.userName,\n displayName: isMikanMessage ? undefined : user?.displayName,\n text,\n attachments,\n isBot: isMikanMessage,\n });\n }\n\n return relevantMessages.length;\n }\n\n private async backfillAllChannels(upperBoundTs?: string): Promise<void> {\n const startTime = Date.now();\n\n // Only backfill channels that already have a log.jsonl (mikan has interacted with them before)\n const channelsToBackfill: Array<[string, SlackChannel]> = [];\n for (const [channelId, channel] of this.channels) {\n const logPath = join(this.workingDir, channelId, \"log.jsonl\");\n if (existsSync(logPath)) {\n channelsToBackfill.push([channelId, channel]);\n }\n }\n\n log.logBackfillStart(channelsToBackfill.length);\n\n let totalMessages = 0;\n for (const [channelId, channel] of channelsToBackfill) {\n try {\n const count = await this.backfillChannel(channelId, upperBoundTs);\n if (count > 0) log.logBackfillChannel(channel.name, count);\n totalMessages += count;\n } catch (error) {\n log.logWarning(`Failed to backfill #${channel.name}`, String(error));\n }\n\n // Add delay between channels to avoid hitting Slack rate limits\n if (channelId !== channelsToBackfill[channelsToBackfill.length - 1][0]) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n }\n\n const durationMs = Date.now() - startTime;\n log.logBackfillComplete(totalMessages, durationMs);\n }\n\n // ==========================================================================\n // Private - Fetch Users/Channels\n // ==========================================================================\n\n private async fetchUsers(): Promise<void> {\n let cursor: string | undefined;\n do {\n const result = await this.webClient.users.list({ limit: 200, cursor });\n const members = result.members as\n | Array<{ id?: string; name?: string; real_name?: string; deleted?: boolean }>\n | undefined;\n if (members) {\n for (const u of members) {\n if (u.id && u.name && !u.deleted) {\n this.users.set(u.id, {\n id: u.id,\n userName: u.name,\n displayName: u.real_name || u.name,\n });\n }\n }\n }\n cursor = result.response_metadata?.next_cursor;\n } while (cursor);\n }\n\n private async fetchChannels(): Promise<void> {\n // Fetch public/private channels\n let cursor: string | undefined;\n do {\n const result = await this.webClient.conversations.list({\n types: \"public_channel,private_channel\",\n exclude_archived: true,\n limit: 200,\n cursor,\n });\n const channels = result.channels as\n | Array<{ id?: string; name?: string; is_member?: boolean }>\n | undefined;\n if (channels) {\n for (const c of channels) {\n if (c.id && c.name && c.is_member) {\n this.channels.set(c.id, { id: c.id, name: c.name });\n }\n }\n }\n cursor = result.response_metadata?.next_cursor;\n } while (cursor);\n\n // Also fetch DM channels (IMs)\n cursor = undefined;\n do {\n const result = await this.webClient.conversations.list({\n types: \"im\",\n limit: 200,\n cursor,\n });\n const ims = result.channels as Array<{ id?: string; user?: string }> | undefined;\n if (ims) {\n for (const im of ims) {\n if (im.id) {\n // Use user's name as channel name for DMs\n const user = im.user ? this.users.get(im.user) : undefined;\n const name = user ? `DM:${user.userName}` : `DM:${im.id}`;\n this.channels.set(im.id, { id: im.id, name });\n }\n }\n }\n cursor = result.response_metadata?.next_cursor;\n } while (cursor);\n }\n}\n"]}
@@ -81,6 +81,7 @@ export class SlackBot {
81
81
  constructor(handler, config) {
82
82
  this.botUserId = null;
83
83
  this.botId = null;
84
+ this.teamId = null;
84
85
  this.ownMentionRegex = null;
85
86
  this.startupTs = null; // Messages older than this are just logged, not processed
86
87
  this.users = new Map();
@@ -108,6 +109,7 @@ export class SlackBot {
108
109
  const auth = await this.webClient.auth.test();
109
110
  this.botUserId = auth.user_id;
110
111
  this.botId = typeof auth.bot_id === "string" ? auth.bot_id : null;
112
+ this.teamId = typeof auth.team_id === "string" ? auth.team_id : null;
111
113
  await Promise.all([this.fetchUsers(), this.fetchChannels()]);
112
114
  log.logInfo(`Loaded ${this.channels.size} channels, ${this.users.size} users`);
113
115
  // Record startup time before opening the socket. Slack may replay older events;
@@ -204,12 +206,14 @@ export class SlackBot {
204
206
  await this.webClient.chat.update({ channel, ts, text });
205
207
  });
206
208
  }
207
- async startMessageStream(channel, text, threadTs) {
209
+ async startMessageStream(channel, text, threadTs, recipientUserId) {
208
210
  return slackRetry(async () => {
209
211
  const result = await this.webClient.apiCall("chat.startStream", {
210
212
  channel,
211
213
  markdown_text: text,
212
214
  ...(threadTs ? { thread_ts: threadTs } : {}),
215
+ ...(this.teamId ? { recipient_team_id: this.teamId } : {}),
216
+ ...(recipientUserId ? { recipient_user_id: recipientUserId } : {}),
213
217
  });
214
218
  const ts = result.ts;
215
219
  if (!ts)