typeclaw 0.39.2 → 0.39.3

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 (73) hide show
  1. package/auth.schema.json +110 -0
  2. package/package.json +2 -2
  3. package/secrets.schema.json +110 -0
  4. package/src/agent/index.ts +44 -19
  5. package/src/agent/plugin-tools.ts +12 -12
  6. package/src/agent/session-origin.ts +2 -0
  7. package/src/agent/todo/store.ts +21 -1
  8. package/src/agent/tools/channel-reply.ts +18 -5
  9. package/src/agent/tools/channel-send.ts +13 -2
  10. package/src/bundled-plugins/doc-render/render.ts +2 -2
  11. package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +40 -18
  12. package/src/channels/adapters/discord-author-resolver.ts +52 -0
  13. package/src/channels/adapters/discord-bot.ts +1 -1
  14. package/src/channels/adapters/discord-channel-resolver.ts +44 -0
  15. package/src/channels/adapters/discord-classify.ts +121 -0
  16. package/src/channels/adapters/discord-reactions.ts +138 -0
  17. package/src/channels/adapters/discord.ts +416 -0
  18. package/src/channels/adapters/github/outbound.ts +23 -4
  19. package/src/channels/adapters/kakaotalk.ts +8 -1
  20. package/src/channels/adapters/line.ts +1 -1
  21. package/src/channels/adapters/slack-author-resolver.ts +54 -0
  22. package/src/channels/adapters/slack-bot.ts +3 -1
  23. package/src/channels/adapters/slack-channel-resolver.ts +49 -0
  24. package/src/channels/adapters/slack-classify.ts +83 -0
  25. package/src/channels/adapters/slack-reactions.ts +126 -0
  26. package/src/channels/adapters/slack.ts +416 -0
  27. package/src/channels/adapters/telegram-bot.ts +2 -1
  28. package/src/channels/adapters/webex-bot.ts +5 -2
  29. package/src/channels/adapters/webex.ts +55 -2
  30. package/src/channels/github-review-turn-ledger.ts +32 -0
  31. package/src/channels/github-verdict-activity.ts +60 -0
  32. package/src/channels/index.ts +6 -0
  33. package/src/channels/manager.ts +130 -6
  34. package/src/channels/pr-verdict-activity-bridge.ts +43 -0
  35. package/src/channels/router.ts +161 -9
  36. package/src/channels/schema.ts +4 -0
  37. package/src/channels/types.ts +17 -1
  38. package/src/cli/builtins.ts +1 -0
  39. package/src/cli/channel.ts +170 -18
  40. package/src/cli/index.ts +11 -0
  41. package/src/cli/init.ts +2 -0
  42. package/src/cli/update-check.ts +14 -0
  43. package/src/cli/update-notify.ts +91 -0
  44. package/src/cli/update-suppression.ts +19 -0
  45. package/src/config/channels-mutation.ts +3 -1
  46. package/src/config/config.ts +51 -0
  47. package/src/config/index.ts +1 -0
  48. package/src/container/start.ts +30 -6
  49. package/src/doctor/channel-checks.ts +57 -3
  50. package/src/hostd/daemon.ts +22 -5
  51. package/src/hostd/index.ts +11 -1
  52. package/src/hostd/paths.ts +4 -0
  53. package/src/hostd/protocol.ts +15 -2
  54. package/src/init/cli-version.ts +1 -1
  55. package/src/init/discord-auth.ts +50 -0
  56. package/src/init/index.ts +94 -4
  57. package/src/init/reconcile-plugin-deps.ts +30 -5
  58. package/src/init/run-owner-claim.ts +2 -0
  59. package/src/init/slack-auth.ts +51 -0
  60. package/src/mcp/manager.ts +94 -7
  61. package/src/mcp/tools.ts +7 -4
  62. package/src/permissions/resolve.ts +2 -0
  63. package/src/role-claim/match-rule.ts +2 -0
  64. package/src/run/index.ts +74 -29
  65. package/src/secrets/discord-store.ts +96 -0
  66. package/src/secrets/schema.ts +34 -0
  67. package/src/secrets/slack-store.ts +96 -0
  68. package/src/server/command-runner.ts +21 -0
  69. package/src/skills/typeclaw-cron/SKILL.md +13 -2
  70. package/src/tui/format.ts +0 -19
  71. package/src/tui/index.ts +2 -8
  72. package/src/update/check.ts +192 -0
  73. package/typeclaw.schema.json +332 -0
@@ -0,0 +1,416 @@
1
+ import {
2
+ DiscordClient,
3
+ DiscordListener,
4
+ type DiscordGatewayMessageCreateEvent,
5
+ type DiscordMessage,
6
+ } from 'agent-messenger/discord'
7
+
8
+ import type { MembershipResolver, MembershipResolverResult } from '@/channels/membership'
9
+ import { deriveMembershipFromHistory } from '@/channels/membership-from-history'
10
+ import type { ChannelRouter } from '@/channels/router'
11
+ import type { ChannelAdapterConfig } from '@/channels/schema'
12
+ import type {
13
+ ChannelHistoryMessage,
14
+ ChannelSelfIdentityResolver,
15
+ FetchAttachmentCallback,
16
+ FetchHistoryArgs,
17
+ FetchHistoryResult,
18
+ HistoryCallback,
19
+ OutboundCallback,
20
+ OutboundMessage,
21
+ ResolvedChannelNames,
22
+ SendResult,
23
+ } from '@/channels/types'
24
+ import { chunkMarkdown } from '@/markdown'
25
+ import type { DiscordAccountRecord } from '@/secrets/schema'
26
+
27
+ import { createDiscordAuthorResolver } from './discord-author-resolver'
28
+ import { createDiscordChannelResolver } from './discord-channel-resolver'
29
+ import { classifyInbound, type InboundDropReason } from './discord-classify'
30
+ import { createDiscordReactionCallback, createDiscordRemoveReactionCallback } from './discord-reactions'
31
+
32
+ export type DiscordAdapterLogger = {
33
+ info: (msg: string) => void
34
+ warn: (msg: string) => void
35
+ error: (msg: string) => void
36
+ }
37
+
38
+ const consoleLogger: DiscordAdapterLogger = {
39
+ info: (m) => console.log(m),
40
+ warn: (m) => console.warn(m),
41
+ error: (m) => console.error(m),
42
+ }
43
+
44
+ export type DiscordCredentialStore = {
45
+ getAccount(id?: string): Promise<DiscordAccountRecord | null>
46
+ }
47
+
48
+ export type DiscordAdapterOptions = {
49
+ router: ChannelRouter
50
+ configRef: () => ChannelAdapterConfig
51
+ logger?: DiscordAdapterLogger
52
+ selfAliasesRef?: () => readonly string[]
53
+ credentialsStore?: DiscordCredentialStore
54
+ createClient?: () => DiscordClient
55
+ createListener?: (client: DiscordClient) => DiscordListener
56
+ fetchImpl?: typeof fetch
57
+ }
58
+
59
+ export type DiscordAdapter = {
60
+ start: () => Promise<void>
61
+ stop: () => Promise<void>
62
+ isConnected: () => boolean
63
+ }
64
+
65
+ export function createDiscordOutboundCallback(deps: {
66
+ client: Pick<DiscordClient, 'sendMessage' | 'uploadFile'>
67
+ logger: DiscordAdapterLogger
68
+ formatChannelTag: (chat: string) => Promise<string>
69
+ }): OutboundCallback {
70
+ return async (msg: OutboundMessage): Promise<SendResult> => {
71
+ if (msg.adapter !== 'discord') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
72
+ const text = msg.text ?? ''
73
+ const attachments = msg.attachments ?? []
74
+ if (text === '' && attachments.length === 0) return { ok: false, error: 'message has neither text nor attachments' }
75
+ const tag = await deps.formatChannelTag(msg.chat)
76
+ deps.logger.info(`[discord] outbound ${tag} text_len=${text.length} attachments=${attachments.length}`)
77
+ try {
78
+ // Attachments first, then text — Discord's upstream uploadFile takes no
79
+ // content body, so a failed upload must not leave a text-only message
80
+ // already posted (see OutboundMessage.attachments contract).
81
+ for (const attachment of attachments) await deps.client.uploadFile(msg.chat, attachment.path)
82
+ if (text !== '') {
83
+ for (const chunk of chunkMarkdown(text, 2_000)) await deps.client.sendMessage(msg.chat, chunk)
84
+ }
85
+ return { ok: true }
86
+ } catch (err) {
87
+ const message = describe(err)
88
+ deps.logger.error(`[discord] outbound failed: ${message}`)
89
+ return { ok: false, error: message }
90
+ }
91
+ }
92
+ }
93
+
94
+ export function createDiscordHistoryCallback(deps: {
95
+ client: Pick<DiscordClient, 'getMessages'>
96
+ logger: DiscordAdapterLogger
97
+ }): HistoryCallback {
98
+ return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
99
+ try {
100
+ const messages = await deps.client.getMessages(args.chat, clampLimit(args.limit, 100))
101
+ return { ok: true, messages: messages.map(mapDiscordHistoryMessage).reverse() }
102
+ } catch (err) {
103
+ const message = describe(err)
104
+ deps.logger.warn(`[discord] history fetch failed: ${message}`)
105
+ return { ok: false, error: message }
106
+ }
107
+ }
108
+ }
109
+
110
+ export function createDiscordMembershipResolver(deps: {
111
+ historyCallback: HistoryCallback
112
+ now?: () => number
113
+ }): MembershipResolver {
114
+ const now = deps.now ?? Date.now
115
+ return async (key): Promise<MembershipResolverResult> => {
116
+ if (key.adapter !== 'discord') return { kind: 'permanent' }
117
+ if (key.workspace === '@dm') return { humans: 1, bots: 1, fetchedAt: now(), truncated: false }
118
+ return await deriveMembershipFromHistory({
119
+ fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit }),
120
+ now,
121
+ })
122
+ }
123
+ }
124
+
125
+ export function createDiscordFetchAttachmentCallback(deps: {
126
+ tokenRef: () => string | null
127
+ fetchImpl?: typeof fetch
128
+ logger: DiscordAdapterLogger
129
+ }): FetchAttachmentCallback {
130
+ const fetchFn = deps.fetchImpl ?? fetch
131
+ return async ({ ref, filename }) => {
132
+ let url: URL
133
+ try {
134
+ url = new URL(ref)
135
+ } catch {
136
+ return { ok: false, error: `invalid Discord attachment URL: ${ref}` }
137
+ }
138
+ if (!DISCORD_ATTACHMENT_HOSTS.has(url.hostname)) {
139
+ return { ok: false, error: `not a Discord CDN URL: ${url.hostname}` }
140
+ }
141
+ try {
142
+ const token = deps.tokenRef()
143
+ const headers = token !== null ? { Authorization: token } : undefined
144
+ const res = await fetchFn(url.toString(), headers !== undefined ? { headers } : undefined)
145
+ if (!res.ok) {
146
+ const body = await res.text().catch(() => '')
147
+ const message = `discord cdn fetch ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`
148
+ deps.logger.error(`[discord] fetchAttachment failed for ${url.toString()}: ${message}`)
149
+ return { ok: false, error: message }
150
+ }
151
+ const buffer = Buffer.from(await res.arrayBuffer())
152
+ const inferredFilename = filename ?? url.pathname.split('/').pop() ?? 'attachment'
153
+ const contentType = res.headers.get('content-type') ?? undefined
154
+ return {
155
+ ok: true,
156
+ buffer,
157
+ filename: inferredFilename,
158
+ ...(contentType !== undefined ? { mimetype: contentType } : {}),
159
+ size: buffer.length,
160
+ }
161
+ } catch (err) {
162
+ const message = describe(err)
163
+ deps.logger.error(`[discord] fetchAttachment failed for ${url.toString()}: ${message}`)
164
+ return { ok: false, error: message }
165
+ }
166
+ }
167
+ }
168
+
169
+ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAdapter {
170
+ const logger = options.logger ?? consoleLogger
171
+ const createClient = options.createClient ?? (() => new DiscordClient())
172
+ const createListener = options.createListener ?? ((client) => new DiscordListener(client))
173
+ const client = createClient()
174
+ let listener: DiscordListener | null = null
175
+ let selfUserId: string | null = null
176
+ let selfName: string | null = null
177
+ let token: string | null = null
178
+ let connected = false
179
+ let started = false
180
+ let inflightInbounds = 0
181
+ let stopWaiters: Array<() => void> = []
182
+
183
+ const channelResolver = createDiscordChannelResolver({ client })
184
+ const authorResolver = createDiscordAuthorResolver({ client })
185
+ const selfIdentityResolver: ChannelSelfIdentityResolver = () =>
186
+ selfUserId !== null ? { id: selfUserId, username: selfName ?? selfUserId } : null
187
+ const formatChannelTag = async (chat: string): Promise<string> => {
188
+ const names = await channelResolver({ adapter: 'discord', workspace: '', chat, thread: null }).catch(
189
+ (): ResolvedChannelNames => ({}),
190
+ )
191
+ const label = names.chatName ?? null
192
+ return label === null || label === chat ? `channel=${chat}` : `channel=${label}(${chat})`
193
+ }
194
+ const historyCallback = createDiscordHistoryCallback({ client, logger })
195
+ const membershipResolver = createDiscordMembershipResolver({ historyCallback })
196
+ const outboundCallback = createDiscordOutboundCallback({ client, logger, formatChannelTag })
197
+ const fetchAttachmentCallback = createDiscordFetchAttachmentCallback({
198
+ tokenRef: () => token,
199
+ fetchImpl: options.fetchImpl,
200
+ logger,
201
+ })
202
+ const reactionCallback = createDiscordReactionCallback({ client })
203
+ const removeReactionCallback = createDiscordRemoveReactionCallback({ client })
204
+
205
+ const handleMessage = async (event: DiscordGatewayMessageCreateEvent): Promise<void> => {
206
+ inflightInbounds++
207
+ try {
208
+ const tag = await formatChannelTag(event.channel_id)
209
+ logger.info(
210
+ `[discord] inbound id=${event.id} author=${event.author.id || '(none)'} ${tag} text_len=${event.content.length}`,
211
+ )
212
+ const verdict = classifyInbound(event, options.configRef(), {
213
+ selfUserId,
214
+ selfAliases: options.selfAliasesRef?.() ?? [],
215
+ })
216
+ if (verdict.kind === 'drop') {
217
+ logger.info(`[discord] dropped id=${event.id} reason=${verdict.reason}${dropHint(verdict.reason)}`)
218
+ return
219
+ }
220
+ const attachments = (event.attachments ?? []).map((file, index) => ({
221
+ id: index + 1,
222
+ kind: 'file' as const,
223
+ ref: file.url,
224
+ filename: file.filename,
225
+ mimetype: file.content_type,
226
+ }))
227
+ const payload = {
228
+ ...verdict.payload,
229
+ authorName: await authorResolver.resolve(verdict.payload.authorId),
230
+ ...(attachments.length > 0 ? { attachments } : {}),
231
+ }
232
+ logger.info(`[discord] routed id=${event.id} ${tag} mention=${payload.isBotMention}`)
233
+ await options.router.route(payload)
234
+ } catch (err) {
235
+ logger.error(`[discord] handleInbound failed: ${describe(err)}`)
236
+ } finally {
237
+ inflightInbounds--
238
+ if (inflightInbounds === 0 && stopWaiters.length > 0) {
239
+ const waiters = stopWaiters
240
+ stopWaiters = []
241
+ for (const w of waiters) w()
242
+ }
243
+ }
244
+ }
245
+
246
+ return {
247
+ async start(): Promise<void> {
248
+ if (started) return
249
+ started = true
250
+ try {
251
+ const account = await (options.credentialsStore ?? null)?.getAccount()
252
+ if (account === null || account === undefined) {
253
+ throw new Error('no Discord account in secrets.json#channels.discord (run typeclaw init to authenticate)')
254
+ }
255
+ token = account.token
256
+ await client.login({ token: account.token })
257
+ const auth = await client.testAuth()
258
+ selfUserId = auth.id
259
+ selfName = auth.global_name ?? auth.username
260
+ logger.info(`[discord] authenticated as ${selfName} (${selfUserId})`)
261
+ } catch (err) {
262
+ started = false
263
+ selfUserId = null
264
+ token = null
265
+ logger.error(`[discord] login failed: ${describe(err)}`)
266
+ throw err
267
+ }
268
+
269
+ listener = createListener(client)
270
+ let listenerConnected = false
271
+ let listenerStartupError: Error | null = null
272
+ listener.on('connected', (info) => {
273
+ listenerConnected = true
274
+ connected = true
275
+ selfUserId = info.user.id
276
+ selfName = info.user.username
277
+ })
278
+ listener.on('disconnected', () => {
279
+ connected = false
280
+ logger.warn('[discord] disconnected')
281
+ })
282
+ listener.on('error', (err) => {
283
+ if (!listenerConnected && listenerStartupError === null) listenerStartupError = err
284
+ logger.error(`[discord] listener error: ${describe(err)}`)
285
+ })
286
+ listener.on('message_create', (event) => void handleMessage(event))
287
+ listener.on('message_reaction_add', (event) =>
288
+ logger.info(
289
+ `[discord] reaction_added channel=${event.channel_id} message=${event.message_id} emoji=${event.emoji.name}`,
290
+ ),
291
+ )
292
+ listener.on('message_reaction_remove', (event) =>
293
+ logger.info(
294
+ `[discord] reaction_removed channel=${event.channel_id} message=${event.message_id} emoji=${event.emoji.name}`,
295
+ ),
296
+ )
297
+
298
+ registerCallbacks(options.router)
299
+
300
+ const rollbackStart = (reason: string, cause: Error): never => {
301
+ unregisterCallbacks(options.router)
302
+ listener?.stop()
303
+ listener = null
304
+ selfUserId = null
305
+ token = null
306
+ connected = false
307
+ started = false
308
+ logger.error(`[discord] ${reason}: ${describe(cause)}`)
309
+ throw cause
310
+ }
311
+
312
+ try {
313
+ await listener.start()
314
+ } catch (err) {
315
+ rollbackStart('listener start threw', err instanceof Error ? err : new Error(String(err)))
316
+ }
317
+ if (!listenerConnected) {
318
+ rollbackStart(
319
+ 'listener start failed silently',
320
+ listenerStartupError ?? new Error('listener.start() returned without emitting connected'),
321
+ )
322
+ }
323
+ },
324
+
325
+ async stop(): Promise<void> {
326
+ if (!started) return
327
+ started = false
328
+ unregisterCallbacks(options.router)
329
+ listener?.stop()
330
+ listener = null
331
+ connected = false
332
+ if (inflightInbounds > 0) {
333
+ await new Promise<void>((resolve) => {
334
+ stopWaiters.push(resolve)
335
+ })
336
+ }
337
+ selfUserId = null
338
+ token = null
339
+ },
340
+
341
+ isConnected(): boolean {
342
+ return started && selfUserId !== null && connected
343
+ },
344
+ }
345
+
346
+ function registerCallbacks(router: ChannelRouter): void {
347
+ router.registerOutbound('discord', outboundCallback)
348
+ router.setTypingCapability('discord', false)
349
+ router.registerChannelNameResolver('discord', channelResolver)
350
+ router.registerSelfIdentity('discord', selfIdentityResolver)
351
+ router.registerHistory('discord', historyCallback)
352
+ router.registerFetchAttachment('discord', fetchAttachmentCallback)
353
+ router.registerMembership('discord', membershipResolver)
354
+ router.registerReaction('discord', reactionCallback)
355
+ router.registerRemoveReaction('discord', removeReactionCallback)
356
+ }
357
+
358
+ function unregisterCallbacks(router: ChannelRouter): void {
359
+ router.unregisterOutbound('discord', outboundCallback)
360
+ router.setTypingCapability('discord', false)
361
+ router.unregisterChannelNameResolver('discord', channelResolver)
362
+ router.unregisterSelfIdentity('discord', selfIdentityResolver)
363
+ router.unregisterHistory('discord', historyCallback)
364
+ router.unregisterFetchAttachment('discord', fetchAttachmentCallback)
365
+ router.unregisterMembership('discord', membershipResolver)
366
+ router.unregisterReaction('discord', reactionCallback)
367
+ router.unregisterRemoveReaction('discord', removeReactionCallback)
368
+ }
369
+ }
370
+
371
+ // WORKAROUND: the SDK's `DiscordMessage` type omits `author.bot`, but the REST
372
+ // API returns it and the client passes the body through unchanged, so it's
373
+ // present at runtime. `=== true` fails closed to human if absent. This flag
374
+ // feeds history-derived membership (deriveMembershipFromHistory), which
375
+ // otherwise miscounts peer bots as humans and inflates effectiveHumans.
376
+ type RawDiscordMessage = DiscordMessage & { author: { bot?: boolean } }
377
+
378
+ function mapDiscordHistoryMessage(msg: DiscordMessage): ChannelHistoryMessage {
379
+ const raw = msg as RawDiscordMessage
380
+ return {
381
+ externalMessageId: msg.id,
382
+ authorId: msg.author.id,
383
+ authorName: msg.author.username,
384
+ text: msg.content,
385
+ ts: parseDiscordTimestamp(msg.timestamp),
386
+ isBot: raw.author.bot === true,
387
+ replyToBotMessageId: null,
388
+ }
389
+ }
390
+
391
+ function parseDiscordTimestamp(timestamp: string): number {
392
+ const millis = Date.parse(timestamp)
393
+ return Number.isFinite(millis) ? millis : 0
394
+ }
395
+
396
+ const DISCORD_ATTACHMENT_HOSTS = new Set(['cdn.discordapp.com', 'media.discordapp.net'])
397
+
398
+ function clampLimit(requested: number, max: number): number {
399
+ if (!Number.isFinite(requested) || requested <= 0) return max
400
+ return Math.min(Math.floor(requested), max)
401
+ }
402
+
403
+ function describe(err: unknown): string {
404
+ return err instanceof Error ? err.message : String(err)
405
+ }
406
+
407
+ function dropHint(reason: InboundDropReason): string {
408
+ switch (reason) {
409
+ case 'empty_content':
410
+ return ' (message had no text)'
411
+ case 'pre_connect':
412
+ case 'self_author':
413
+ case 'no_user':
414
+ return ''
415
+ }
416
+ }
@@ -69,7 +69,10 @@ async function postDiscussionComment(options: {
69
69
  }): Promise<SendResult> {
70
70
  const discussionId = await fetchDiscussionId(options)
71
71
  if (!discussionId.ok) return discussionId
72
- const mutation = `mutation($discussionId:ID!,$body:String!){addDiscussionComment(input:{discussionId:$discussionId,body:$body}){comment{id}}}`
72
+ // databaseId (numeric REST id), NOT the GraphQL node id: the discussion_comment
73
+ // inbound classifier stamps externalMessageId from the webhook's numeric
74
+ // comment.id, so the outbound messageId must use the same shape to round-trip.
75
+ const mutation = `mutation($discussionId:ID!,$body:String!){addDiscussionComment(input:{discussionId:$discussionId,body:$body}){comment{databaseId}}}`
73
76
  return await postGraphql(
74
77
  options.fetchImpl,
75
78
  await options.token(),
@@ -82,6 +85,10 @@ async function postDiscussionComment(options: {
82
85
  )
83
86
  }
84
87
 
88
+ function withMessageId(id: string | undefined): SendResult {
89
+ return id !== undefined ? { ok: true, messageId: id, messageIds: [id] } : { ok: true }
90
+ }
91
+
85
92
  async function fetchDiscussionId(options: {
86
93
  token: () => Promise<string>
87
94
  authType: GithubAuthType
@@ -113,8 +120,16 @@ async function postGraphql(
113
120
  variables: Record<string, unknown>,
114
121
  guidance: { authType: GithubAuthType; endpointKind: OutboundEndpointKind },
115
122
  ): Promise<SendResult> {
116
- const result = await graphql(fetchImpl, token, query, variables, guidance)
117
- return result.ok ? { ok: true } : { ok: false, error: result.error }
123
+ const result = await graphql<{ addDiscussionComment?: { comment?: { databaseId?: number } | null } | null }>(
124
+ fetchImpl,
125
+ token,
126
+ query,
127
+ variables,
128
+ guidance,
129
+ )
130
+ if (!result.ok) return { ok: false, error: result.error }
131
+ const id = result.data.addDiscussionComment?.comment?.databaseId
132
+ return withMessageId(typeof id === 'number' ? String(id) : undefined)
118
133
  }
119
134
 
120
135
  async function graphql<T>(
@@ -162,7 +177,11 @@ async function postJson(
162
177
  headers: githubJsonHeaders(token),
163
178
  body: JSON.stringify(payload),
164
179
  })
165
- if (response.ok) return { ok: true }
180
+ if (response.ok) {
181
+ const created = (await response.json().catch(() => null)) as { id?: number | string } | null
182
+ const id = created?.id
183
+ return withMessageId(id !== undefined ? String(id) : undefined)
184
+ }
166
185
  const text = await response.text().catch(() => '')
167
186
  const baseError = `GitHub API ${response.status}${text !== '' ? `: ${text}` : ''}`
168
187
  const decorated = isOutboundPermissionDenial(response.status, text)
@@ -200,6 +200,7 @@ export function createOutboundCallback(deps: {
200
200
  const tag = await formatChannelTag(msg.workspace, msg.chat)
201
201
  logger.info(`[kakaotalk] outbound ${tag} text_len=${text.length} attachments=${attachments.length}`)
202
202
 
203
+ const logIds: string[] = []
203
204
  // KakaoTalk has no shared text-with-file send (Slack's initial_comment) — files first, then text.
204
205
  if (attachments.length > 0) {
205
206
  let items: AttachmentInput[]
@@ -224,6 +225,7 @@ export function createOutboundCallback(deps: {
224
225
  logger.error(`[kakaotalk] sendAttachment status_code=${result.status_code} ${tag}`)
225
226
  return { ok: false, error: `kakaotalk attachment send failed with status ${result.status_code}` }
226
227
  }
228
+ logIds.push(result.log_id)
227
229
  logger.info(`[kakaotalk] uploaded log_id=${result.log_id} attachments=${items.length} ${tag}`)
228
230
  } catch (err) {
229
231
  const message = describe(err)
@@ -257,6 +259,7 @@ export function createOutboundCallback(deps: {
257
259
  logger.error(`[kakaotalk] sendMessage status_code=${result.status_code} ${tag}`)
258
260
  return { ok: false, error: `kakaotalk send failed with status ${result.status_code}` }
259
261
  }
262
+ logIds.push(result.log_id)
260
263
  logger.info(`[kakaotalk] sent log_id=${result.log_id} ${tag}`)
261
264
  } catch (err) {
262
265
  const message = describe(err)
@@ -265,7 +268,11 @@ export function createOutboundCallback(deps: {
265
268
  }
266
269
  }
267
270
 
268
- return { ok: true }
271
+ // The text send is the message an agent replies to, so when both an
272
+ // attachment and text went out the text log_id (last in `logIds`) is the
273
+ // anchor; attachment-only sends fall back to the attachment log_id.
274
+ const anchor = logIds.length > 0 ? logIds[logIds.length - 1] : undefined
275
+ return { ok: true, messageId: anchor, messageIds: logIds }
269
276
  }
270
277
  }
271
278
 
@@ -126,12 +126,12 @@ export function createOutboundCallback(deps: {
126
126
  return { ok: false, error: 'line send failed' }
127
127
  }
128
128
  logger.info(`[line] sent message_id=${result.message_id} ${tag}`)
129
+ return { ok: true, messageId: result.message_id, messageIds: [result.message_id] }
129
130
  } catch (err) {
130
131
  const message = describe(err)
131
132
  logger.error(`[line] sendMessage failed: ${message}`)
132
133
  return { ok: false, error: message }
133
134
  }
134
- return { ok: true }
135
135
  }
136
136
  }
137
137
 
@@ -0,0 +1,54 @@
1
+ import type { SlackClient, SlackUser } from 'agent-messenger/slack'
2
+
3
+ const DEFAULT_TTL_MS = 60 * 60 * 1000
4
+
5
+ export type SlackAuthorResolverOptions = {
6
+ client: Pick<SlackClient, 'getUser'>
7
+ now?: () => number
8
+ ttlMs?: number
9
+ }
10
+
11
+ export type SlackAuthorResolver = {
12
+ resolve: (userId: string) => Promise<string>
13
+ }
14
+
15
+ type CacheEntry = { name: string; expiresAt: number }
16
+
17
+ export function createSlackAuthorResolver(options: SlackAuthorResolverOptions): SlackAuthorResolver {
18
+ const now = options.now ?? Date.now
19
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
20
+ const cache = new Map<string, CacheEntry>()
21
+ const inflight = new Map<string, Promise<string>>()
22
+
23
+ const resolve = async (userId: string): Promise<string> => {
24
+ const cached = cache.get(userId)
25
+ if (cached && cached.expiresAt > now()) return cached.name
26
+ const existing = inflight.get(userId)
27
+ if (existing) return existing
28
+ const promise = options.client
29
+ .getUser(userId)
30
+ .then((user) => pickDisplayName(user) ?? userId)
31
+ .catch(() => userId)
32
+ .then((name) => {
33
+ if (name !== userId) cache.set(userId, { name, expiresAt: now() + ttlMs })
34
+ return name
35
+ })
36
+ .finally(() => {
37
+ inflight.delete(userId)
38
+ })
39
+ inflight.set(userId, promise)
40
+ return promise
41
+ }
42
+
43
+ return { resolve }
44
+ }
45
+
46
+ // Identity fields only. `profile.status_text` is presence text ("In a meeting"),
47
+ // not a name, so it must never stand in for the author's display name.
48
+ function pickDisplayName(user: SlackUser): string | null {
49
+ const candidates = [user.real_name, user.name]
50
+ for (const c of candidates) {
51
+ if (typeof c === 'string' && c !== '') return c
52
+ }
53
+ return null
54
+ }
@@ -845,12 +845,14 @@ export function createOutboundCallback(deps: {
845
845
  const chunks = chunkMarkdown(text, SLACK_MARKDOWN_BLOCK_LIMIT)
846
846
  const explicitThread = msg.thread !== undefined && msg.thread !== null ? msg.thread : null
847
847
  let threadTs: string | null = explicitThread
848
+ const sentTs: string[] = []
848
849
  try {
849
850
  for (let i = 0; i < chunks.length; i++) {
850
851
  const chunk = chunks[i]!
851
852
  const options: { thread_ts?: string; blocks?: unknown[] } = { blocks: [buildMarkdownBlock(chunk)] }
852
853
  if (threadTs !== null) options.thread_ts = threadTs
853
854
  const sent = await client.postMessage(msg.chat, chunk, options)
855
+ sentTs.push(sent.ts)
854
856
  logger.info(
855
857
  `[slack-bot] sent ts=${sent.ts} ${tag} chunk=${i + 1}/${chunks.length} blocks=markdown len=${chunk.length}`,
856
858
  )
@@ -860,7 +862,7 @@ export function createOutboundCallback(deps: {
860
862
  if (threadTs === null && chunks.length > 1) threadTs = sent.ts
861
863
  }
862
864
  if (typingTracker) await typingTracker.clearAfterSend(msg.chat, msg.typingThread ?? msg.thread)
863
- return { ok: true }
865
+ return { ok: true, messageId: sentTs[0], messageIds: sentTs }
864
866
  } catch (err) {
865
867
  const message = err instanceof Error ? err.message : String(err)
866
868
  logger.error(`[slack-bot] postMessage failed: ${message}`)
@@ -0,0 +1,49 @@
1
+ import type { SlackClient } from 'agent-messenger/slack'
2
+
3
+ import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
4
+
5
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
6
+
7
+ export type SlackChannelResolverOptions = {
8
+ client: Pick<SlackClient, 'getChannel'>
9
+ teamNameRef?: () => string | null
10
+ now?: () => number
11
+ ttlMs?: number
12
+ }
13
+
14
+ type CacheEntry<T> = { value: T; expiresAt: number }
15
+
16
+ export function createSlackChannelResolver(options: SlackChannelResolverOptions): ChannelNameResolver {
17
+ const now = options.now ?? Date.now
18
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
19
+ const chatCache = new Map<string, CacheEntry<string>>()
20
+
21
+ const fetchCached = async <T>(
22
+ cache: Map<string, CacheEntry<T>>,
23
+ key: string,
24
+ fetcher: () => Promise<T | null>,
25
+ ): Promise<T | null> => {
26
+ const cached = cache.get(key)
27
+ if (cached && cached.expiresAt > now()) return cached.value
28
+ const value = await fetcher()
29
+ if (value !== null) cache.set(key, { value, expiresAt: now() + ttlMs })
30
+ return value
31
+ }
32
+
33
+ return async (key: ChannelKey): Promise<ResolvedChannelNames> => {
34
+ if (key.workspace === '@dm') return {}
35
+ const chatName = await fetchCached(chatCache, key.chat, async () => {
36
+ try {
37
+ const channel = await options.client.getChannel(key.chat)
38
+ return channel.name || null
39
+ } catch {
40
+ return null
41
+ }
42
+ })
43
+ const workspaceName = options.teamNameRef?.() ?? null
44
+ const result: ResolvedChannelNames = {}
45
+ if (chatName !== null) result.chatName = chatName
46
+ if (workspaceName !== null) result.workspaceName = workspaceName
47
+ return result
48
+ }
49
+ }