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
@@ -70,25 +70,35 @@ function duplicatesStanding(verdict: ReviewVerdict, effective: EffectiveVerdict)
70
70
  return verdict === 'APPROVE' ? effective === 'APPROVED' : effective === 'CHANGES_REQUESTED'
71
71
  }
72
72
 
73
+ // Whether the duplicate-review cooldown may fire for this GitHub state. Only the
74
+ // AMBIGUOUS states qualify: a bare NONE (read lag) or the SAME standing verdict
75
+ // (post-indexing fan-out). A DISMISSED or the opposite decisive verdict is a real
76
+ // supersession that legitimizes a fresh same-verdict review, so the cooldown is
77
+ // skipped — preserving the 35287f99 invariant against stranding a re-verdict.
78
+ function cooldownApplies(verdict: ReviewVerdict, effective: EffectiveVerdict): boolean {
79
+ return effective === 'NONE' || duplicatesStanding(verdict, effective)
80
+ }
81
+
73
82
  // How long a reservation may sit before it is treated as abandoned. A normal
74
83
  // `gh` review submit completes in seconds; this only guards against a tool.after
75
84
  // that never fires (crash mid-command), so it must outlast a slow command yet
76
85
  // never strand a PR for long.
77
86
  const LEASE_TTL_MS = 5 * 60_000
78
87
 
79
- // How long a just-landed verdict is trusted to explain a GitHub `NONE` as
80
- // read-after-write lag rather than a genuine absence. GitHub's `/pulls/<n>/reviews`
81
- // list lags a write by up to ~10s, so a second engagement turn firing in that
82
- // window reads NONE and would land a duplicate. Observed duplicates were ~10-18s
83
- // apart originally; a later fan-out incident spread FOUR sequential APPROVEs over
84
- // ~15s (one channel session per inline review thread), each ~3-7s after the last —
85
- // well inside the read lag yet beyond a single turn. 120s gives margin for that
86
- // thread fan-out plus slow API indexing without turning the shield into a human-
87
- // facing rate limit (a legitimate re-verdict after a new push carries a new head
88
- // SHA and bypasses this entirely; staying under ~5min avoids blocking genuine
89
- // re-reviews). This window only shadows a raw NONE on the SAME verdict (+ same or
90
- // uncertain head) — a DISMISSED/CHANGES_REQUESTED/flipped-verdict all bypass it.
91
- const RECENT_LANDED_TTL_MS = 120_000
88
+ // How long a just-landed verdict suppresses a redundant same-verdict re-submit on
89
+ // the same head — a duplicate-review cooldown. It started as a narrow lag shield
90
+ // for GitHub's ~10-18s read-after-write lag (the original ~10-18s-apart duplicates
91
+ // on PR #691), but the PR #1042 thread fan-out spread same-commit APPROVEs over ~2
92
+ // minutes — each one AFTER GitHub had already indexed the prior, so the
93
+ // standing-verdict read no longer returned a bare NONE for a lag-only shield to
94
+ // catch, yet the redundant verdict still landed. So the window now also fires when
95
+ // GitHub reports the standing verdict, and is widened to 5 minutes to cover slow
96
+ // sequential fan-out. It only ever shadows the SAME verdict on the SAME (or
97
+ // uncertain) head: a DISMISSED, the opposite decisive verdict, a flipped verdict,
98
+ // and a new-push head all bypass it, so a genuine re-review is never stranded. 5min
99
+ // stays well under the lease TTL and short enough that a deliberate human-driven
100
+ // re-approval of the identical commit is the only thing it can delay.
101
+ const RECENT_LANDED_TTL_MS = 5 * 60_000
92
102
 
93
103
  type Reservation = {
94
104
  key: string
@@ -204,11 +214,23 @@ export function createApproveIdempotencyGuard(deps: {
204
214
  return { block: true, reason: duplicateReason(args.verdict) }
205
215
  }
206
216
 
207
- // Layer 3: only a raw NONE from a successful read is ambiguous — it can mean
208
- // "no review" or "our just-landed review not yet indexed". A recent same
209
- // verdict on the same head resolves it to lag and blocks the duplicate. Any
210
- // non-NONE state already decided above, so this never overrides a supersession.
211
- if (remote.ok && remote.effective === 'NONE' && recentlyLandedSame(key, args.verdict, headSha, now)) {
217
+ // Layer 3 — duplicate-review cooldown. A recently-landed SAME verdict on the
218
+ // SAME (or uncertain) head blocks a redundant re-submit for the window. It
219
+ // fires on a bare NONE (read-after-write lag, the original shield) AND on the
220
+ // now-indexed SAME standing verdict (the PR #1042 fan-out, where siblings fired
221
+ // minutes apart after indexing) — `duplicatesStanding` above already returned
222
+ // here for that case, so reaching this line on a same-standing-verdict means
223
+ // only that the lease-released duplicate is being re-tried; either way the
224
+ // cooldown holds. It must NOT fire on a DISMISSED or the opposite decisive
225
+ // verdict: those are genuine supersessions, so the cooldown is gated to the
226
+ // ambiguous states (NONE, or the same standing verdict) and skipped for any
227
+ // decisive state that contradicts a redundant re-submit. A read error skips it
228
+ // (fails open) so a transient failure cannot strand a re-verdict.
229
+ if (
230
+ remote.ok &&
231
+ cooldownApplies(args.verdict, remote.effective) &&
232
+ recentlyLandedSame(key, args.verdict, headSha, now)
233
+ ) {
212
234
  releaseReservation(args.callId, reservation)
213
235
  return { block: true, reason: duplicateReason(args.verdict) }
214
236
  }
@@ -0,0 +1,52 @@
1
+ import type { DiscordClient, DiscordUser } from 'agent-messenger/discord'
2
+
3
+ const DEFAULT_TTL_MS = 60 * 60 * 1000
4
+
5
+ export type DiscordAuthorResolverOptions = {
6
+ client: Pick<DiscordClient, 'getUser'>
7
+ now?: () => number
8
+ ttlMs?: number
9
+ }
10
+
11
+ export type DiscordAuthorResolver = {
12
+ resolve: (userId: string) => Promise<string>
13
+ }
14
+
15
+ type CacheEntry = { name: string; expiresAt: number }
16
+
17
+ export function createDiscordAuthorResolver(options: DiscordAuthorResolverOptions): DiscordAuthorResolver {
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
+ function pickDisplayName(user: DiscordUser): string | null {
47
+ const candidates = [user.global_name, user.username]
48
+ for (const c of candidates) {
49
+ if (typeof c === 'string' && c !== '') return c
50
+ }
51
+ return null
52
+ }
@@ -696,7 +696,7 @@ export function createOutboundCallback(deps: {
696
696
  Object.keys(sendOptions).length > 0 ? sendOptions : undefined,
697
697
  )
698
698
  logger.info(`[discord-bot] sent id=${sent.id} ${tag}`)
699
- return { ok: true }
699
+ return { ok: true, messageId: sent.id, messageIds: [sent.id] }
700
700
  } catch (err) {
701
701
  const message = err instanceof Error ? err.message : String(err)
702
702
  logger.error(`[discord-bot] sendMessage failed: ${message}`)
@@ -0,0 +1,44 @@
1
+ import type { DiscordClient } from 'agent-messenger/discord'
2
+
3
+ import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
4
+
5
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
6
+
7
+ export type DiscordChannelResolverOptions = {
8
+ client: Pick<DiscordClient, 'getChannel'>
9
+ now?: () => number
10
+ ttlMs?: number
11
+ }
12
+
13
+ type CacheEntry<T> = { value: T; expiresAt: number }
14
+
15
+ export function createDiscordChannelResolver(options: DiscordChannelResolverOptions): ChannelNameResolver {
16
+ const now = options.now ?? Date.now
17
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
18
+ const chatCache = new Map<string, CacheEntry<string>>()
19
+
20
+ const fetchCached = async <T>(
21
+ cache: Map<string, CacheEntry<T>>,
22
+ key: string,
23
+ fetcher: () => Promise<T | null>,
24
+ ): Promise<T | null> => {
25
+ const cached = cache.get(key)
26
+ if (cached && cached.expiresAt > now()) return cached.value
27
+ const value = await fetcher()
28
+ if (value !== null) cache.set(key, { value, expiresAt: now() + ttlMs })
29
+ return value
30
+ }
31
+
32
+ return async (key: ChannelKey): Promise<ResolvedChannelNames> => {
33
+ if (key.workspace === '@dm') return {}
34
+ const chatName = await fetchCached(chatCache, key.chat, async () => {
35
+ try {
36
+ const channel = await options.client.getChannel(key.chat)
37
+ return channel.name || null
38
+ } catch {
39
+ return null
40
+ }
41
+ })
42
+ return chatName !== null ? { chatName } : {}
43
+ }
44
+ }
@@ -0,0 +1,121 @@
1
+ import type { DiscordGatewayMessageCreateEvent } from 'agent-messenger/discord'
2
+
3
+ import { matchesAnyAlias } from '@/channels/engagement'
4
+ import type { ChannelAdapterConfig } from '@/channels/schema'
5
+ import type { InboundAttachment, InboundMessage } from '@/channels/types'
6
+
7
+ import { encodeDiscordReactionRef } from './discord-reactions'
8
+
9
+ export type DiscordInboundMessageEvent = DiscordGatewayMessageCreateEvent
10
+
11
+ // WORKAROUND: the USER-token SDK type omits `author.bot` and
12
+ // `message_reference`, but the listener spreads the raw Discord payload
13
+ // (`{ ...d }`), so both fields exist at runtime. Narrow locally instead of
14
+ // augmenting the SDK type globally — do not "simplify" this away.
15
+ export type RawDiscordMessageCreateEvent = DiscordGatewayMessageCreateEvent & {
16
+ author: { bot?: boolean }
17
+ message_reference?: { message_id?: string; channel_id?: string; guild_id?: string }
18
+ }
19
+
20
+ export type InboundDropReason = 'self_author' | 'no_user' | 'empty_content' | 'pre_connect'
21
+
22
+ export type InboundClassification =
23
+ | { kind: 'drop'; reason: InboundDropReason }
24
+ | { kind: 'route'; payload: InboundMessage }
25
+
26
+ export type DiscordInboundContext = {
27
+ selfUserId: string | null
28
+ selfAliases?: readonly string[]
29
+ }
30
+
31
+ export function classifyInbound(
32
+ event: DiscordInboundMessageEvent,
33
+ _config: ChannelAdapterConfig,
34
+ context: DiscordInboundContext,
35
+ ): InboundClassification {
36
+ if (context.selfUserId !== null && event.author.id === context.selfUserId)
37
+ return { kind: 'drop', reason: 'self_author' }
38
+ if (event.author.id === '') return { kind: 'drop', reason: 'no_user' }
39
+ const { text, attachments } = splitInbound(event)
40
+ if (text === '') return { kind: 'drop', reason: 'empty_content' }
41
+ if (context.selfUserId === null) return { kind: 'drop', reason: 'pre_connect' }
42
+
43
+ const isDm = event.guild_id === undefined
44
+ const workspace = isDm ? '@dm' : (event.guild_id ?? '')
45
+ const hasGroupMention = GROUP_MENTION_PATTERN.test(event.content)
46
+ const isBotMention =
47
+ hasGroupMention ||
48
+ event.content.includes(`<@${context.selfUserId}>`) ||
49
+ event.content.includes(`<@!${context.selfUserId}>`)
50
+ const aliasMatched = !isBotMention && matchesAnyAlias(event.content, context.selfAliases ?? [])
51
+ const mentionedUsers = event.mentions ?? []
52
+ const mentionsOthers = mentionedUsers.length > 0 && !mentionedUsers.some((user) => user.id === context.selfUserId)
53
+
54
+ const raw = event as RawDiscordMessageCreateEvent
55
+ const replyToParentId = raw.message_reference?.message_id
56
+ const replyToBotMessageId =
57
+ replyToParentId !== undefined && isReplyToSelf(raw, context.selfUserId) ? replyToParentId : null
58
+ const replyToOtherMessageId = replyToParentId !== undefined && replyToBotMessageId === null ? replyToParentId : null
59
+
60
+ return {
61
+ kind: 'route',
62
+ payload: {
63
+ adapter: 'discord',
64
+ workspace,
65
+ chat: event.channel_id,
66
+ thread: null,
67
+ text,
68
+ ...(attachments.length > 0 ? { attachments } : {}),
69
+ externalMessageId: event.id,
70
+ reactionRef: encodeDiscordReactionRef({ channel: event.channel_id, message: event.id }),
71
+ authorId: event.author.id,
72
+ authorName: event.author.username,
73
+ authorIsBot: raw.author.bot === true,
74
+ isBotMention: isBotMention || aliasMatched,
75
+ replyToBotMessageId,
76
+ mentionsOthers,
77
+ replyToOtherMessageId,
78
+ isDm,
79
+ ts: parseDiscordTimestamp(event.timestamp),
80
+ },
81
+ }
82
+ }
83
+
84
+ // `message_reference` carries only the parent id, not its author, so we infer
85
+ // "this reply targets us" from the auto-mention Discord injects into the
86
+ // reply's `mentions` array (same trick as the bot adapter). Named "...Self"
87
+ // because the user-token identity is a Discord user; the payload field stays
88
+ // `replyToBotMessageId` to match the InboundMessage contract.
89
+ function isReplyToSelf(event: RawDiscordMessageCreateEvent, selfUserId: string): boolean {
90
+ return (event.mentions ?? []).some((m) => m.id === selfUserId)
91
+ }
92
+
93
+ const GROUP_MENTION_PATTERN = /@(?:everyone|here)/
94
+
95
+ type SplitInbound = { text: string; attachments: InboundAttachment[] }
96
+
97
+ function splitInbound(event: DiscordInboundMessageEvent): SplitInbound {
98
+ const attachments = (event.attachments ?? []).map((attachment, index) => ({
99
+ id: index + 1,
100
+ kind: 'file' as const,
101
+ ref: attachment.url,
102
+ filename: attachment.filename,
103
+ ...(attachment.content_type !== undefined ? { mimetype: attachment.content_type } : {}),
104
+ }))
105
+ if (attachments.length === 0) return { text: event.content, attachments: [] }
106
+ const summary = attachments.map(renderPlaceholder).join('\n')
107
+ const text = event.content === '' ? summary : `${event.content}\n${summary}`
108
+ return { text, attachments }
109
+ }
110
+
111
+ function renderPlaceholder(attachment: InboundAttachment): string {
112
+ const parts: string[] = [`Discord attachment #${attachment.id}: ${attachment.kind}`]
113
+ if (attachment.mimetype !== undefined) parts.push(attachment.mimetype)
114
+ if (attachment.filename !== undefined) parts.push(`name=${attachment.filename}`)
115
+ return `[${parts.join(' ')}]`
116
+ }
117
+
118
+ function parseDiscordTimestamp(timestamp: string): number {
119
+ const millis = Date.parse(timestamp)
120
+ return Number.isFinite(millis) ? millis : 0
121
+ }
@@ -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
+ }