typeclaw 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +3 -2
  2. package/auth.schema.json +57 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +57 -0
  5. package/src/agent/index.ts +10 -6
  6. package/src/agent/multimodal/look-at.ts +87 -0
  7. package/src/agent/session-origin.ts +1 -0
  8. package/src/agent/tools/channel-history-render.ts +21 -0
  9. package/src/agent/tools/channel-history.ts +2 -17
  10. package/src/agent/tools/channel-read.ts +206 -0
  11. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +26 -2
  12. package/src/bundled-plugins/github-cli-auth/index.ts +25 -6
  13. package/src/bundled-plugins/memory/index.ts +10 -11
  14. package/src/bundled-plugins/memory/vector/hybrid.ts +73 -6
  15. package/src/bundled-plugins/memory/vector/index-on-write.ts +25 -20
  16. package/src/bundled-plugins/memory/vector/passages.ts +2 -24
  17. package/src/bundled-plugins/memory/vector/reference-index-on-write.ts +28 -23
  18. package/src/bundled-plugins/memory/vector/store.ts +2 -0
  19. package/src/bundled-plugins/memory/vector/truncation.ts +28 -0
  20. package/src/bundled-plugins/planner/planner.ts +4 -2
  21. package/src/bundled-plugins/reviewer/reviewer.ts +9 -1
  22. package/src/bundled-plugins/tool-result-cap/README.md +10 -1
  23. package/src/bundled-plugins/tool-result-cap/cap-result.ts +8 -0
  24. package/src/channels/adapters/discord-bot.ts +112 -0
  25. package/src/channels/adapters/instagram-channel-resolver.ts +113 -0
  26. package/src/channels/adapters/instagram-classify.ts +69 -0
  27. package/src/channels/adapters/instagram-format.ts +8 -0
  28. package/src/channels/adapters/instagram.ts +346 -0
  29. package/src/channels/adapters/kakaotalk-classify.ts +31 -6
  30. package/src/channels/adapters/kakaotalk.ts +1 -1
  31. package/src/channels/adapters/slack-bot.ts +147 -0
  32. package/src/channels/manager.ts +60 -2
  33. package/src/channels/router.ts +64 -0
  34. package/src/channels/schema.ts +5 -0
  35. package/src/channels/types.ts +46 -0
  36. package/src/cli/channel.ts +76 -1
  37. package/src/cli/init.ts +1 -0
  38. package/src/cli/status.ts +37 -14
  39. package/src/config/channels-mutation.ts +2 -1
  40. package/src/doctor/channel-checks.ts +28 -0
  41. package/src/hostd/daemon.ts +59 -19
  42. package/src/hostd/kakao-renewal-manager.ts +35 -10
  43. package/src/hostd/protocol.ts +2 -0
  44. package/src/hostd/tailscale.ts +41 -5
  45. package/src/hostd/webex-renewal-manager.ts +13 -4
  46. package/src/init/index.ts +50 -1
  47. package/src/init/instagram-auth.ts +134 -0
  48. package/src/init/run-owner-claim.ts +1 -0
  49. package/src/permissions/match-rule.ts +1 -1
  50. package/src/permissions/resolve.ts +1 -0
  51. package/src/plugin/index.ts +1 -0
  52. package/src/plugin/manager.ts +14 -0
  53. package/src/plugin/registry.ts +12 -0
  54. package/src/plugin/types.ts +4 -0
  55. package/src/role-claim/match-rule.ts +2 -1
  56. package/src/run/index.ts +46 -20
  57. package/src/secrets/instagram-store.ts +112 -0
  58. package/src/secrets/schema.ts +18 -0
  59. package/src/skills/typeclaw-channel-instagram/SKILL.md +30 -0
  60. package/src/test-helpers/rm-temp-dir.ts +24 -0
  61. package/typeclaw.schema.json +161 -1
@@ -0,0 +1,346 @@
1
+ import * as instagramModule from 'agent-messenger/instagram'
2
+ import {
3
+ InstagramClient as RealInstagramClient,
4
+ InstagramCredentialManager,
5
+ InstagramListener as RealInstagramListener,
6
+ } from 'agent-messenger/instagram'
7
+ import type { InstagramChatSummary, InstagramMessageSummary } from 'agent-messenger/instagram'
8
+
9
+ import type { ChannelRouter } from '@/channels/router'
10
+ import type { ChannelAdapterConfig } from '@/channels/schema'
11
+ import type {
12
+ ChannelHistoryMessage,
13
+ FetchHistoryArgs,
14
+ FetchHistoryResult,
15
+ HistoryCallback,
16
+ OutboundCallback,
17
+ OutboundMessage,
18
+ ResolvedChannelNames,
19
+ SendResult,
20
+ } from '@/channels/types'
21
+
22
+ import { describeError } from './describe-error'
23
+ import { createInstagramChannelResolver } from './instagram-channel-resolver'
24
+ import { classifyInbound } from './instagram-classify'
25
+ import { toInstagramPlainText } from './instagram-format'
26
+
27
+ export interface InstagramClientShape {
28
+ login(credentials?: { username: string; password: string }, accountId?: string): Promise<this>
29
+ getProfile(): Promise<{ user_id: string; username: string; full_name: string | null; profile_pic_url: string | null }>
30
+ listChats(limit?: number): Promise<InstagramChatSummary[]>
31
+ getMessages(threadId: string, limit?: number): Promise<InstagramMessageSummary[]>
32
+ sendMessage(threadId: string, text: string): Promise<InstagramMessageSummary>
33
+ getUserId(): string | null
34
+ fetchIrisBootstrap?: () => Promise<unknown>
35
+ getSessionState?: () => unknown
36
+ }
37
+
38
+ export type ConnectedPayload = { userId: string; transport?: 'realtime' | 'polling' }
39
+
40
+ export interface InstagramListenerShape {
41
+ start(): Promise<void> | void
42
+ stop(): void
43
+ on(event: 'connected', handler: (payload: ConnectedPayload) => void): this
44
+ on(event: 'message', handler: (message: InstagramMessageSummary) => void): this
45
+ on(event: 'error', handler: (error: Error) => void): this
46
+ on(event: 'disconnected', handler: () => void): this
47
+ off(event: 'connected', handler: (payload: ConnectedPayload) => void): this
48
+ off(event: 'message', handler: (message: InstagramMessageSummary) => void): this
49
+ off(event: 'error', handler: (error: Error) => void): this
50
+ off(event: 'disconnected', handler: () => void): this
51
+ }
52
+
53
+ const InstagramClient = RealInstagramClient as unknown as new (
54
+ credManager?: InstagramCredentialManager,
55
+ ) => InstagramClientShape
56
+
57
+ export type InstagramListenerCtor = new (
58
+ client: InstagramClientShape,
59
+ options?: {
60
+ pollInterval?: number
61
+ realtimeRetryBaseMs?: number
62
+ realtimeRetryMaxMs?: number
63
+ disableRealtime?: boolean
64
+ connackTimeoutMs?: number
65
+ },
66
+ ) => InstagramListenerShape
67
+
68
+ export function resolveInstagramListenerCtor(): { ctor: InstagramListenerCtor; transport: 'hybrid' | 'polling' } {
69
+ const maybeHybrid = (instagramModule as Record<string, unknown>).InstagramHybridListener
70
+ if (typeof maybeHybrid === 'function')
71
+ return { ctor: maybeHybrid as unknown as InstagramListenerCtor, transport: 'hybrid' }
72
+ return { ctor: RealInstagramListener as unknown as InstagramListenerCtor, transport: 'polling' }
73
+ }
74
+
75
+ export type InstagramCredentialStore = {
76
+ getAccount(id?: string): Promise<{ account_id: string } | null>
77
+ }
78
+
79
+ export type InstagramAdapterLogger = {
80
+ info: (msg: string) => void
81
+ warn: (msg: string) => void
82
+ error: (msg: string) => void
83
+ }
84
+
85
+ const consoleLogger: InstagramAdapterLogger = {
86
+ info: (m) => console.log(m),
87
+ warn: (m) => console.warn(m),
88
+ error: (m) => console.error(m),
89
+ }
90
+
91
+ export type InstagramAdapterOptions = {
92
+ router: ChannelRouter
93
+ configRef: () => ChannelAdapterConfig
94
+ logger?: InstagramAdapterLogger
95
+ selfAliasesRef?: () => readonly string[]
96
+ credentialsStore?: InstagramCredentialStore
97
+ client?: InstagramClientShape
98
+ clientFactory?: (credManager?: InstagramCredentialManager) => InstagramClientShape
99
+ listenerCtorResolver?: () => { ctor: InstagramListenerCtor; transport: 'hybrid' | 'polling' }
100
+ now?: () => number
101
+ }
102
+
103
+ export type InstagramAdapter = {
104
+ start: () => Promise<void>
105
+ stop: () => Promise<void>
106
+ isConnected: () => boolean
107
+ }
108
+
109
+ export const INSTAGRAM_HISTORY_LIMIT_MAX = 200
110
+
111
+ export function createOutboundCallback(deps: {
112
+ client: Pick<InstagramClientShape, 'sendMessage'>
113
+ logger: InstagramAdapterLogger
114
+ formatChannelTag: (workspace: string, chat: string) => Promise<string>
115
+ }): OutboundCallback {
116
+ const { client, logger, formatChannelTag } = deps
117
+ return async (msg: OutboundMessage): Promise<SendResult> => {
118
+ if (msg.adapter !== 'instagram') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
119
+ if (msg.attachments !== undefined && msg.attachments.length > 0) {
120
+ return { ok: false, error: 'instagram adapter does not support outbound attachments' }
121
+ }
122
+ const text = toInstagramPlainText(msg.text ?? '')
123
+ if (text === '') return { ok: false, error: 'message has no text' }
124
+ const tag = await formatChannelTag(msg.workspace, msg.chat)
125
+ logger.info(`[instagram] outbound ${tag} text_len=${text.length}`)
126
+ try {
127
+ const result = await client.sendMessage(msg.chat, text)
128
+ logger.info(`[instagram] sent message_id=${result.id} ${tag}`)
129
+ return { ok: true, messageId: result.id, messageIds: [result.id] }
130
+ } catch (err) {
131
+ const message = describeError(err)
132
+ logger.error(`[instagram] sendMessage failed: ${message}`)
133
+ return { ok: false, error: message }
134
+ }
135
+ }
136
+ }
137
+
138
+ export function createInstagramHistoryCallback(deps: {
139
+ client: Pick<InstagramClientShape, 'getMessages'>
140
+ logger: InstagramAdapterLogger
141
+ selfUserIdRef: () => string | null
142
+ }): HistoryCallback {
143
+ const { client, logger, selfUserIdRef } = deps
144
+ return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
145
+ const limit = clampLimit(args.limit, INSTAGRAM_HISTORY_LIMIT_MAX)
146
+ try {
147
+ const messages = await client.getMessages(args.chat, limit)
148
+ const selfId = selfUserIdRef()
149
+ const mapped: ChannelHistoryMessage[] = messages.map((m) => {
150
+ const parsed = Date.parse(m.timestamp)
151
+ return {
152
+ externalMessageId: m.id,
153
+ authorId: m.from,
154
+ authorName: m.from_name ?? m.from,
155
+ text: m.text ?? '',
156
+ ts: Number.isNaN(parsed) ? 0 : parsed,
157
+ isBot: selfId !== null && (m.from === selfId || m.is_outgoing),
158
+ replyToBotMessageId: null,
159
+ }
160
+ })
161
+ return { ok: true, messages: mapped }
162
+ } catch (err) {
163
+ const message = describeError(err)
164
+ logger.warn(`[instagram] history fetch failed: ${message}`)
165
+ return { ok: false, error: message }
166
+ }
167
+ }
168
+ }
169
+
170
+ export function createInstagramAdapter(options: InstagramAdapterOptions): InstagramAdapter {
171
+ const logger = options.logger ?? consoleLogger
172
+ const buildClient = options.clientFactory ?? ((cm?: InstagramCredentialManager) => new InstagramClient(cm))
173
+ const client = options.client ?? buildClient(new InstagramCredentialManager())
174
+ let listener: InstagramListenerShape | null = null
175
+ let selfUserId: string | null = null
176
+ let connected = false
177
+ let started = false
178
+ let inflightInbounds = 0
179
+ let stopWaiters: Array<() => void> = []
180
+
181
+ const channelResolver = createInstagramChannelResolver({ client, logger })
182
+
183
+ const formatChannelTag = async (workspace: string, chat: string): Promise<string> => {
184
+ const names = await channelResolver
185
+ .resolve({ adapter: 'instagram', workspace, chat, thread: null })
186
+ .catch(() => ({}) as ResolvedChannelNames)
187
+ return `bucket=${workspace} chat=${formatLabel(names.chatName, chat)}`
188
+ }
189
+
190
+ const historyCallback = createInstagramHistoryCallback({ client, logger, selfUserIdRef: () => selfUserId })
191
+ const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
192
+
193
+ const processInbound = async (message: InstagramMessageSummary): Promise<void> => {
194
+ inflightInbounds++
195
+ try {
196
+ if (channelResolver.lookupChat(message.thread_id) === null) {
197
+ await channelResolver.refresh()
198
+ if (channelResolver.lookupChat(message.thread_id) === null) {
199
+ channelResolver.ingestProvisional(message.thread_id)
200
+ logger.warn(
201
+ `[instagram] provisional chat=${message.thread_id} message_id=${message.id} bucket=@instagram-group reason=not_in_listChats`,
202
+ )
203
+ }
204
+ }
205
+
206
+ const bucket = channelResolver.lookupChat(message.thread_id)?.workspace ?? '@instagram-group'
207
+ const inboundTag = await formatChannelTag(bucket, message.thread_id)
208
+ logger.info(
209
+ `[instagram] inbound message_id=${message.id} author=${message.from} ${inboundTag} type=${message.type} text_len=${(message.text ?? '').length}`,
210
+ )
211
+
212
+ const verdict = classifyInbound(message, options.configRef(), {
213
+ selfUserId,
214
+ lookupChat: (id) => channelResolver.lookupChat(id),
215
+ ...(options.selfAliasesRef ? { selfAliases: options.selfAliasesRef() } : {}),
216
+ })
217
+ if (verdict.kind === 'drop') {
218
+ logger.info(`[instagram] dropped message_id=${message.id} reason=${verdict.reason}`)
219
+ return
220
+ }
221
+
222
+ logger.info(
223
+ `[instagram] routed message_id=${message.id} ${inboundTag} mention=${verdict.payload.isBotMention} dm=${verdict.payload.isDm}`,
224
+ )
225
+ await options.router.route(verdict.payload)
226
+ } catch (err) {
227
+ logger.error(`[instagram] handleInbound failed: ${describeError(err)}`)
228
+ } finally {
229
+ inflightInbounds--
230
+ if (inflightInbounds === 0 && stopWaiters.length > 0) {
231
+ const waiters = stopWaiters
232
+ stopWaiters = []
233
+ for (const w of waiters) w()
234
+ }
235
+ }
236
+ }
237
+
238
+ return {
239
+ async start(): Promise<void> {
240
+ if (started) return
241
+ started = true
242
+
243
+ try {
244
+ const credentialStore = options.credentialsStore ?? null
245
+ if (credentialStore !== null) {
246
+ const account = await credentialStore.getAccount()
247
+ if (account === null) {
248
+ throw new Error(
249
+ 'no Instagram account in secrets.json#channels.instagram (run typeclaw channel add instagram)',
250
+ )
251
+ }
252
+ await client.login(undefined, account.account_id)
253
+ } else {
254
+ await client.login()
255
+ }
256
+ } catch (err) {
257
+ started = false
258
+ logger.error(`[instagram] login failed: ${describeError(err)}`)
259
+ throw err
260
+ }
261
+
262
+ try {
263
+ const profile = await client.getProfile()
264
+ selfUserId = profile.user_id
265
+ logger.info(`[instagram] authenticated as ${profile.username} (${profile.user_id})`)
266
+ } catch (err) {
267
+ started = false
268
+ logger.error(`[instagram] getProfile failed: ${describeError(err)}`)
269
+ throw err
270
+ }
271
+
272
+ try {
273
+ await channelResolver.refresh()
274
+ } catch (err) {
275
+ logger.warn(`[instagram] initial chat list fetch failed: ${describeError(err)}`)
276
+ }
277
+
278
+ const resolved = (options.listenerCtorResolver ?? resolveInstagramListenerCtor)()
279
+ listener = new resolved.ctor(client, { pollInterval: 5_000 })
280
+ logger.info(`[instagram] listener transport=${resolved.transport}`)
281
+ listener.on('connected', ({ userId, transport = 'polling' }) => {
282
+ connected = true
283
+ logger.info(`[instagram] connected (user_id=${userId}, transport=${transport})`)
284
+ })
285
+ listener.on('disconnected', () => {
286
+ connected = false
287
+ logger.warn('[instagram] disconnected; SDK will reconnect with backoff')
288
+ })
289
+ listener.on('error', (err) => {
290
+ logger.error(`[instagram] listener error: ${describeError(err)}`)
291
+ })
292
+ listener.on('message', (message) => {
293
+ void processInbound(message)
294
+ })
295
+
296
+ try {
297
+ await listener.start()
298
+ } catch (err) {
299
+ try {
300
+ listener.stop()
301
+ } catch {
302
+ // best-effort cleanup; the start failure is what we surface
303
+ }
304
+ listener = null
305
+ started = false
306
+ logger.error(`[instagram] listener start failed: ${describeError(err)}`)
307
+ throw err
308
+ }
309
+
310
+ options.router.registerOutbound('instagram', outboundCallback)
311
+ options.router.registerChannelNameResolver('instagram', channelResolver.resolve)
312
+ options.router.registerHistory('instagram', historyCallback)
313
+ },
314
+
315
+ async stop(): Promise<void> {
316
+ if (!started) return
317
+ started = false
318
+ options.router.unregisterOutbound('instagram', outboundCallback)
319
+ options.router.unregisterChannelNameResolver('instagram', channelResolver.resolve)
320
+ options.router.unregisterHistory('instagram', historyCallback)
321
+ if (inflightInbounds > 0) {
322
+ await new Promise<void>((resolve) => {
323
+ stopWaiters.push(resolve)
324
+ })
325
+ }
326
+ listener?.stop()
327
+ listener = null
328
+ selfUserId = null
329
+ connected = false
330
+ },
331
+
332
+ isConnected(): boolean {
333
+ return connected && selfUserId !== null
334
+ },
335
+ }
336
+ }
337
+
338
+ function clampLimit(requested: number, max: number): number {
339
+ if (!Number.isFinite(requested) || requested <= 0) return max
340
+ return Math.min(Math.floor(requested), max)
341
+ }
342
+
343
+ function formatLabel(name: string | undefined, id: string): string {
344
+ if (name === undefined || name === '' || name === id) return id
345
+ return `${name}(${id})`
346
+ }
@@ -109,11 +109,10 @@ function parseReplyContext(event: KakaoTalkPushMessageEvent, selfUserId: string)
109
109
  if (event.message_type !== KAKAO_MESSAGE_TYPE.REPLY) return null
110
110
  if (event.attachment === null) return null
111
111
 
112
- const logId = stringField(event.attachment, 'src_logId')
113
- const sourceUserId = numericField(event.attachment, 'src_userId')
114
- if (logId === null || sourceUserId === null) return null
112
+ const logId = scalarIdField(event.attachment, 'src_logId')
113
+ const sourceAuthorId = decimalIdField(event.attachment, 'src_userId')
114
+ if (logId === null || sourceAuthorId === null) return null
115
115
 
116
- const sourceAuthorId = String(sourceUserId)
117
116
  const quotedText = stringField(event.attachment, 'src_message')
118
117
  return {
119
118
  logId,
@@ -150,7 +149,33 @@ function stringField(record: Record<string, unknown>, key: string): string | nul
150
149
  return typeof value === 'string' && value.length > 0 ? value : null
151
150
  }
152
151
 
153
- function numericField(record: Record<string, unknown>, key: string): number | null {
152
+ // LOCO reply attachments are unvalidated `JSON.parse` output: `src_userId` arrives
153
+ // as a string in production despite the SDK annotating it `number`, so a number-only
154
+ // reader dropped every reply-to-bot. `src_userId` gates the bot-vs-other identity
155
+ // check, so require digits and keep it as an opaque string — never `Number()` a
156
+ // 64-bit id (lossy past 2^53).
157
+ function decimalIdField(record: Record<string, unknown>, key: string): string | null {
154
158
  const value = record[key]
155
- return typeof value === 'number' && Number.isFinite(value) ? value : null
159
+ if (typeof value === 'string') {
160
+ const trimmed = value.trim()
161
+ return /^\d+$/.test(trimmed) ? trimmed : null
162
+ }
163
+ if (typeof value === 'number') {
164
+ return Number.isInteger(value) && value >= 0 ? String(value) : null
165
+ }
166
+ return null
167
+ }
168
+
169
+ // `src_logId` is an opaque message reference we only echo back, never compare for
170
+ // identity, so accept any non-empty scalar (string or integer) without digit-gating.
171
+ function scalarIdField(record: Record<string, unknown>, key: string): string | null {
172
+ const value = record[key]
173
+ if (typeof value === 'string') {
174
+ const trimmed = value.trim()
175
+ return trimmed.length > 0 ? trimmed : null
176
+ }
177
+ if (typeof value === 'number') {
178
+ return Number.isInteger(value) && value >= 0 ? String(value) : null
179
+ }
180
+ return null
156
181
  }
@@ -480,7 +480,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
480
480
  authorName: resolvedName ?? verdict.payload.authorId,
481
481
  }
482
482
  logger.info(
483
- `[kakaotalk] routed log_id=${event.log_id} ${inboundTag} mention=${enriched.isBotMention} dm=${enriched.isDm}`,
483
+ `[kakaotalk] routed log_id=${event.log_id} ${inboundTag} mention=${enriched.isBotMention} reply=${enriched.replyToBotMessageId !== null} dm=${enriched.isDm}`,
484
484
  )
485
485
  await options.router.route(enriched)
486
486
  } catch (err) {
@@ -18,11 +18,18 @@ import type { ChannelRouter } from '@/channels/router'
18
18
  import type { ChannelAdapterConfig } from '@/channels/schema'
19
19
  import type {
20
20
  ChannelHistoryMessage,
21
+ ChannelListEntry,
21
22
  ChannelSelfIdentityResolver,
22
23
  FetchAttachmentCallback,
23
24
  FetchHistoryArgs,
24
25
  FetchHistoryResult,
26
+ GetMessageArgs,
27
+ GetMessageResult,
25
28
  HistoryCallback,
29
+ ListCallback,
30
+ ListChannelsArgs,
31
+ ListChannelsResult,
32
+ MessageGetCallback,
26
33
  OutboundCallback,
27
34
  OutboundMessage,
28
35
  ResolvedChannelNames,
@@ -414,6 +421,21 @@ type SlackConversationInfoResponse = {
414
421
  channel?: { num_members?: number }
415
422
  }
416
423
 
424
+ type SlackConversationsListChannel = {
425
+ id?: string
426
+ name?: string
427
+ is_im?: boolean
428
+ is_mpim?: boolean
429
+ is_member?: boolean
430
+ }
431
+
432
+ type SlackConversationsListResponse = {
433
+ ok: boolean
434
+ error?: string
435
+ channels?: SlackConversationsListChannel[]
436
+ response_metadata?: { next_cursor?: string }
437
+ }
438
+
417
439
  type SlackConversationMembersResponse = {
418
440
  ok: boolean
419
441
  error?: string
@@ -729,6 +751,116 @@ export function createSlackHistoryCallback(deps: {
729
751
  }
730
752
  }
731
753
 
754
+ // Fetch one message by ts. Slack has no by-id endpoint, so we window
755
+ // conversations.history (channel root) or conversations.replies (thread) to a
756
+ // single ts via oldest=latest=messageId, inclusive=true, limit=1 — without the
757
+ // window, a long thread is cursor-paginated and a reply past the first page
758
+ // would be wrongly reported not-found. conversations.replies still needs `ts`
759
+ // set to the thread ROOT to identify the thread. Reuses mapSlackMessage so a
760
+ // single message renders identically to a history entry.
761
+ export function createSlackMessageGetCallback(deps: {
762
+ token: string
763
+ logger: SlackBotAdapterLogger
764
+ botUserIdRef: () => string | null
765
+ authorResolver?: SlackAuthorResolver
766
+ fetchImpl?: typeof fetch
767
+ }): MessageGetCallback {
768
+ const { token, logger, botUserIdRef, authorResolver } = deps
769
+ const fetchFn = deps.fetchImpl ?? fetch
770
+ return async (args: GetMessageArgs): Promise<GetMessageResult> => {
771
+ const body = new URLSearchParams()
772
+ body.set('channel', args.chat)
773
+ if (args.thread !== null) body.set('ts', args.thread)
774
+ body.set('oldest', args.messageId)
775
+ body.set('latest', args.messageId)
776
+ body.set('inclusive', 'true')
777
+ body.set('limit', '1')
778
+ const endpoint = args.thread === null ? 'conversations.history' : 'conversations.replies'
779
+
780
+ let raw: SlackHistoryResponse
781
+ try {
782
+ const response = await fetchFn(`${SLACK_API_BASE}/${endpoint}`, {
783
+ method: 'POST',
784
+ headers: {
785
+ Authorization: `Bearer ${token}`,
786
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
787
+ },
788
+ body: body.toString(),
789
+ })
790
+ raw = (await response.json()) as SlackHistoryResponse
791
+ } catch (err) {
792
+ const message = err instanceof Error ? err.message : String(err)
793
+ logger.warn(`[slack-bot] message get failed: ${message}`)
794
+ return { ok: false, error: message }
795
+ }
796
+
797
+ if (!raw.ok) return { ok: false, error: raw.error ?? 'unknown slack error' }
798
+
799
+ const botUserId = botUserIdRef()
800
+ const found = (raw.messages ?? []).find((m) => m.ts === args.messageId)
801
+ if (found === undefined) return { ok: false, error: 'message not found', code: 'not-found' }
802
+
803
+ const message = mapSlackMessage(found, botUserId)
804
+ if (authorResolver !== undefined && found.user !== undefined && found.user !== '') {
805
+ message.text = await addSlackMentionHints(message.text, authorResolver.resolve, { botUserId })
806
+ message.authorName = await authorResolver.resolve(found.user)
807
+ }
808
+ return { ok: true, message }
809
+ }
810
+ }
811
+
812
+ // List channels the bot can see via conversations.list. Maps Slack channel
813
+ // types to ChannelListEntry.kind; `is_member` from the API populates isMember.
814
+ export function createSlackListCallback(deps: {
815
+ token: string
816
+ logger: SlackBotAdapterLogger
817
+ fetchImpl?: typeof fetch
818
+ }): ListCallback {
819
+ const { token, logger } = deps
820
+ const fetchFn = deps.fetchImpl ?? fetch
821
+ return async (args: ListChannelsArgs): Promise<ListChannelsResult> => {
822
+ const body = new URLSearchParams()
823
+ body.set('limit', String(clampLimit(args.limit, 200)))
824
+ body.set('types', 'public_channel,private_channel,mpim,im')
825
+ if (args.cursor !== undefined && args.cursor !== '') body.set('cursor', args.cursor)
826
+
827
+ let raw: SlackConversationsListResponse
828
+ try {
829
+ const response = await fetchFn(`${SLACK_API_BASE}/conversations.list`, {
830
+ method: 'POST',
831
+ headers: {
832
+ Authorization: `Bearer ${token}`,
833
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
834
+ },
835
+ body: body.toString(),
836
+ })
837
+ raw = (await response.json()) as SlackConversationsListResponse
838
+ } catch (err) {
839
+ const message = err instanceof Error ? err.message : String(err)
840
+ logger.warn(`[slack-bot] channel list failed: ${message}`)
841
+ return { ok: false, error: message }
842
+ }
843
+
844
+ if (!raw.ok) return { ok: false, error: raw.error ?? 'unknown slack error' }
845
+
846
+ const entries = (raw.channels ?? []).map((c) => mapSlackChannelEntry(c))
847
+ const nextCursor = raw.response_metadata?.next_cursor
848
+ if (nextCursor !== undefined && nextCursor !== '') return { ok: true, entries, nextCursor }
849
+ return { ok: true, entries }
850
+ }
851
+ }
852
+
853
+ function mapSlackChannelEntry(c: SlackConversationsListChannel): ChannelListEntry {
854
+ const kind: ChannelListEntry['kind'] = c.is_im === true ? 'dm' : c.is_mpim === true ? 'group' : 'channel'
855
+ const name = c.name !== undefined && c.name !== '' ? `#${c.name}` : (c.id ?? 'unknown')
856
+ return {
857
+ chat: c.id ?? 'unknown',
858
+ name,
859
+ kind,
860
+ ...(c.is_member !== undefined ? { isMember: c.is_member } : {}),
861
+ }
862
+ }
863
+
732
864
  function mapSlackMessage(msg: SlackRawHistoryMessage, botUserId: string | null): ChannelHistoryMessage {
733
865
  const isBot =
734
866
  msg.subtype === 'bot_message' ||
@@ -1022,6 +1154,15 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1022
1154
  authorResolver,
1023
1155
  })
1024
1156
 
1157
+ const messageGetCallback = createSlackMessageGetCallback({
1158
+ token: options.token,
1159
+ logger,
1160
+ botUserIdRef: () => botUserId,
1161
+ authorResolver,
1162
+ })
1163
+
1164
+ const listCallback = createSlackListCallback({ token: options.token, logger })
1165
+
1025
1166
  const membershipResolver = createSlackMembershipResolver({
1026
1167
  token: options.token,
1027
1168
  logger,
@@ -1257,6 +1398,8 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1257
1398
  options.router.registerChannelNameResolver('slack-bot', channelResolver)
1258
1399
  options.router.registerSelfIdentity('slack-bot', selfIdentityResolver)
1259
1400
  options.router.registerHistory('slack-bot', historyCallback)
1401
+ options.router.registerMessageGet('slack-bot', messageGetCallback)
1402
+ options.router.registerList('slack-bot', listCallback)
1260
1403
  options.router.registerFetchAttachment('slack-bot', fetchAttachmentCallback)
1261
1404
  options.router.registerMembership('slack-bot', membershipResolver)
1262
1405
 
@@ -1275,6 +1418,8 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1275
1418
  options.router.unregisterChannelNameResolver('slack-bot', channelResolver)
1276
1419
  options.router.unregisterSelfIdentity('slack-bot', selfIdentityResolver)
1277
1420
  options.router.unregisterHistory('slack-bot', historyCallback)
1421
+ options.router.unregisterMessageGet('slack-bot', messageGetCallback)
1422
+ options.router.unregisterList('slack-bot', listCallback)
1278
1423
  options.router.unregisterFetchAttachment('slack-bot', fetchAttachmentCallback)
1279
1424
  options.router.unregisterMembership('slack-bot', membershipResolver)
1280
1425
  listener = null
@@ -1297,6 +1442,8 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1297
1442
  options.router.unregisterChannelNameResolver('slack-bot', channelResolver)
1298
1443
  options.router.unregisterSelfIdentity('slack-bot', selfIdentityResolver)
1299
1444
  options.router.unregisterHistory('slack-bot', historyCallback)
1445
+ options.router.unregisterMessageGet('slack-bot', messageGetCallback)
1446
+ options.router.unregisterList('slack-bot', listCallback)
1300
1447
  options.router.unregisterFetchAttachment('slack-bot', fetchAttachmentCallback)
1301
1448
  options.router.unregisterMembership('slack-bot', membershipResolver)
1302
1449
  if (inflightInbounds > 0) {