typeclaw 0.39.2 → 0.39.4

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 (102) 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 +39 -18
  5. package/src/agent/model-fallback.ts +13 -4
  6. package/src/agent/plugin-tools.ts +12 -12
  7. package/src/agent/provider-error.ts +36 -1
  8. package/src/agent/session-origin.ts +2 -0
  9. package/src/agent/subagents.ts +29 -2
  10. package/src/agent/throttle-circuit.ts +50 -0
  11. package/src/agent/todo/store.ts +21 -1
  12. package/src/agent/tools/channel-reply.ts +18 -5
  13. package/src/agent/tools/channel-send.ts +13 -2
  14. package/src/agent/turn-runner.ts +162 -0
  15. package/src/bundled-plugins/doc-render/render.ts +2 -2
  16. package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +40 -18
  17. package/src/bundled-plugins/memory/README.md +12 -12
  18. package/src/bundled-plugins/memory/append-tool.ts +58 -6
  19. package/src/bundled-plugins/memory/dreaming.ts +1 -1
  20. package/src/bundled-plugins/memory/fragment-parser.ts +10 -3
  21. package/src/bundled-plugins/memory/load-memory.ts +28 -2
  22. package/src/bundled-plugins/memory/memory-logger.ts +14 -2
  23. package/src/bundled-plugins/memory/search-tool.ts +50 -7
  24. package/src/bundled-plugins/memory/stream-events.ts +23 -0
  25. package/src/bundled-plugins/memory/vector/hybrid.ts +9 -2
  26. package/src/bundled-plugins/security/index.ts +24 -1
  27. package/src/bundled-plugins/security/policies/cron-promotion.ts +94 -62
  28. package/src/bundled-plugins/security/policies/plugin-addition.ts +2 -4
  29. package/src/bundled-plugins/security/policies/role-promotion.ts +2 -4
  30. package/src/channels/adapters/discord-author-resolver.ts +52 -0
  31. package/src/channels/adapters/discord-bot.ts +1 -1
  32. package/src/channels/adapters/discord-channel-resolver.ts +44 -0
  33. package/src/channels/adapters/discord-classify.ts +121 -0
  34. package/src/channels/adapters/discord-reactions.ts +138 -0
  35. package/src/channels/adapters/discord.ts +416 -0
  36. package/src/channels/adapters/github/outbound.ts +23 -4
  37. package/src/channels/adapters/kakaotalk.ts +8 -1
  38. package/src/channels/adapters/line.ts +1 -1
  39. package/src/channels/adapters/slack-author-resolver.ts +54 -0
  40. package/src/channels/adapters/slack-bot.ts +3 -1
  41. package/src/channels/adapters/slack-channel-resolver.ts +49 -0
  42. package/src/channels/adapters/slack-classify.ts +83 -0
  43. package/src/channels/adapters/slack-reactions.ts +126 -0
  44. package/src/channels/adapters/slack.ts +416 -0
  45. package/src/channels/adapters/telegram-bot.ts +2 -1
  46. package/src/channels/adapters/webex-bot.ts +31 -27
  47. package/src/channels/adapters/webex-prefetch-limiter.ts +120 -0
  48. package/src/channels/adapters/webex.ts +81 -31
  49. package/src/channels/github-review-turn-ledger.ts +32 -0
  50. package/src/channels/github-verdict-activity.ts +60 -0
  51. package/src/channels/index.ts +6 -0
  52. package/src/channels/manager.ts +168 -37
  53. package/src/channels/pr-verdict-activity-bridge.ts +43 -0
  54. package/src/channels/router.ts +295 -13
  55. package/src/channels/schema.ts +4 -0
  56. package/src/channels/types.ts +25 -2
  57. package/src/cli/builtins.ts +6 -31
  58. package/src/cli/channel.ts +170 -18
  59. package/src/cli/command-meta.ts +93 -0
  60. package/src/cli/help.ts +24 -0
  61. package/src/cli/index.ts +45 -10
  62. package/src/cli/init.ts +2 -0
  63. package/src/cli/update-check.ts +14 -0
  64. package/src/cli/update-notify.ts +91 -0
  65. package/src/cli/update-suppression.ts +19 -0
  66. package/src/config/channels-mutation.ts +3 -1
  67. package/src/config/config.ts +78 -1
  68. package/src/config/index.ts +1 -0
  69. package/src/container/start.ts +52 -8
  70. package/src/doctor/channel-checks.ts +57 -3
  71. package/src/hostd/daemon.ts +77 -31
  72. package/src/hostd/index.ts +11 -1
  73. package/src/hostd/paths.ts +4 -0
  74. package/src/hostd/protocol.ts +15 -2
  75. package/src/hostd/spawn.ts +53 -19
  76. package/src/init/cli-version.ts +1 -1
  77. package/src/init/discord-auth.ts +50 -0
  78. package/src/init/index.ts +94 -4
  79. package/src/init/reconcile-plugin-deps.ts +30 -5
  80. package/src/init/run-owner-claim.ts +2 -0
  81. package/src/init/slack-auth.ts +51 -0
  82. package/src/mcp/manager.ts +94 -7
  83. package/src/mcp/tools.ts +7 -4
  84. package/src/permissions/permissions.ts +12 -0
  85. package/src/permissions/resolve.ts +2 -0
  86. package/src/role-claim/match-rule.ts +2 -0
  87. package/src/run/codex-fetch-observer.ts +11 -6
  88. package/src/run/index.ts +74 -29
  89. package/src/secrets/discord-store.ts +96 -0
  90. package/src/secrets/oauth-xai.ts +2 -2
  91. package/src/secrets/schema.ts +34 -0
  92. package/src/secrets/slack-store.ts +96 -0
  93. package/src/server/command-runner.ts +21 -0
  94. package/src/server/index.ts +27 -2
  95. package/src/skills/typeclaw-channels/SKILL.md +1 -1
  96. package/src/skills/typeclaw-config/SKILL.md +1 -0
  97. package/src/skills/typeclaw-cron/SKILL.md +20 -4
  98. package/src/skills/typeclaw-permissions/SKILL.md +18 -6
  99. package/src/tui/format.ts +0 -19
  100. package/src/tui/index.ts +2 -8
  101. package/src/update/check.ts +192 -0
  102. package/typeclaw.schema.json +332 -0
@@ -0,0 +1,138 @@
1
+ import type { DiscordClient } from 'agent-messenger/discord'
2
+
3
+ import type {
4
+ ReactionCallback,
5
+ ReactionErrorCode,
6
+ ReactionRef,
7
+ ReactionResult,
8
+ RemoveReactionCallback,
9
+ } from '@/channels/types'
10
+
11
+ export type DiscordReactionTarget = { channel: string; message: string }
12
+ export type DiscordReactionRemovalTarget = { channel: string; message: string; emoji: string }
13
+
14
+ export function encodeDiscordReactionRef(target: DiscordReactionTarget): ReactionRef {
15
+ return { adapter: 'discord', value: JSON.stringify(target) }
16
+ }
17
+
18
+ export function decodeDiscordReactionRef(ref: ReactionRef): DiscordReactionTarget | null {
19
+ if (ref.adapter !== 'discord') return null
20
+ const parsed = parseRecord(ref.value)
21
+ if (parsed === null || parsed.op !== undefined) return null
22
+ const channel = typeof parsed.channel === 'string' ? parsed.channel : null
23
+ const message = typeof parsed.message === 'string' ? parsed.message : null
24
+ if (channel === null || message === null) return null
25
+ return { channel, message }
26
+ }
27
+
28
+ export function encodeDiscordRemovalRef(target: DiscordReactionRemovalTarget): ReactionRef {
29
+ return { adapter: 'discord', value: JSON.stringify({ op: 'remove', ...target }) }
30
+ }
31
+
32
+ export function decodeDiscordRemovalRef(ref: ReactionRef): DiscordReactionRemovalTarget | null {
33
+ if (ref.adapter !== 'discord') return null
34
+ const parsed = parseRecord(ref.value)
35
+ if (parsed === null || parsed.op !== 'remove') return null
36
+ const channel = typeof parsed.channel === 'string' ? parsed.channel : null
37
+ const message = typeof parsed.message === 'string' ? parsed.message : null
38
+ const emoji = typeof parsed.emoji === 'string' ? parsed.emoji : null
39
+ if (channel === null || message === null || emoji === null) return null
40
+ return { channel, message, emoji }
41
+ }
42
+
43
+ const EMOJI_UNICODE: Record<string, string> = {
44
+ eyes: '👀',
45
+ '+1': '👍',
46
+ thumbsup: '👍',
47
+ '-1': '👎',
48
+ thumbsdown: '👎',
49
+ laugh: '😄',
50
+ hooray: '🎉',
51
+ tada: '🎉',
52
+ confused: '😕',
53
+ heart: '❤️',
54
+ rocket: '🚀',
55
+ white_check_mark: '✅',
56
+ 'white-check-mark': '✅',
57
+ check: '✅',
58
+ fire: '🔥',
59
+ eye: '👁️',
60
+ raised_hands: '🙌',
61
+ zipper_mouth_face: '🤐',
62
+ }
63
+
64
+ function resolveEmoji(emoji: string): string | null {
65
+ const name = emoji.replace(/^:|:$/g, '')
66
+ return EMOJI_UNICODE[name] ?? null
67
+ }
68
+
69
+ export function createDiscordReactionCallback(deps: { client: Pick<DiscordClient, 'addReaction'> }): ReactionCallback {
70
+ return async (req): Promise<ReactionResult> => {
71
+ if (req.adapter !== 'discord') return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'unsupported' }
72
+ const unicode = resolveEmoji(req.emoji)
73
+ if (unicode === null) {
74
+ return { ok: false, error: `discord does not support reaction "${req.emoji}"`, code: 'unsupported' }
75
+ }
76
+ const target = decodeDiscordReactionRef(req.reactionRef)
77
+ if (target === null) return { ok: false, error: 'unparseable discord reaction ref', code: 'unsupported' }
78
+ try {
79
+ await deps.client.addReaction(target.channel, target.message, unicode)
80
+ } catch (err) {
81
+ return { ok: false, error: describe(err), code: classifyDiscordError(err) }
82
+ }
83
+ return { ok: true, reactionRef: encodeDiscordRemovalRef({ ...target, emoji: unicode }) }
84
+ }
85
+ }
86
+
87
+ export function createDiscordRemoveReactionCallback(deps: {
88
+ client: Pick<DiscordClient, 'removeReaction'>
89
+ }): RemoveReactionCallback {
90
+ return async (req): Promise<ReactionResult> => {
91
+ if (req.adapter !== 'discord') return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'unsupported' }
92
+ const target = decodeDiscordRemovalRef(req.reactionRef)
93
+ if (target === null) return { ok: false, error: 'unparseable discord reaction removal ref', code: 'unsupported' }
94
+ try {
95
+ await deps.client.removeReaction(target.channel, target.message, target.emoji)
96
+ } catch (err) {
97
+ return { ok: false, error: describe(err), code: classifyDiscordError(err) }
98
+ }
99
+ return { ok: true }
100
+ }
101
+ }
102
+
103
+ function classifyDiscordError(err: unknown): ReactionErrorCode {
104
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code: unknown }).code) : ''
105
+ switch (code) {
106
+ case '10003':
107
+ case '10008':
108
+ case 'http_404':
109
+ return 'not-found'
110
+ case '50001':
111
+ case '50013':
112
+ case 'http_403':
113
+ case 'http_401':
114
+ return 'permission-denied'
115
+ case '10014':
116
+ return 'unsupported'
117
+ case 'http_429':
118
+ return 'rate-limited'
119
+ default:
120
+ return 'transient'
121
+ }
122
+ }
123
+
124
+ function parseRecord(value: string): Record<string, unknown> | null {
125
+ let parsed: unknown
126
+ try {
127
+ parsed = JSON.parse(value)
128
+ } catch {
129
+ return null
130
+ }
131
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
132
+ ? (parsed as Record<string, unknown>)
133
+ : null
134
+ }
135
+
136
+ function describe(err: unknown): string {
137
+ return err instanceof Error ? err.message : String(err)
138
+ }
@@ -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