typeclaw 0.48.13 → 0.49.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 (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -1,4 +1,5 @@
1
1
  import { readFile } from 'node:fs/promises'
2
+ import { basename } from 'node:path'
2
3
 
3
4
  import { DiscordBotClient, DiscordBotListener, type DiscordBotListenerOptions } from 'agent-messenger/discordbot'
4
5
  import {
@@ -65,6 +66,7 @@ import {
65
66
  createDiscordRemoveReactionCallback,
66
67
  encodeDiscordReactionRef,
67
68
  } from './discord-bot-reactions'
69
+ import { createDiscordOwnReactionCallbacks } from './discord-bot-reactions'
68
70
  import { enrichDiscordMessageReferences } from './discord-bot-reference'
69
71
  import {
70
72
  ackInteraction,
@@ -74,6 +76,8 @@ import {
74
76
  } from './discord-bot-slash-commands'
75
77
  import { createDiscordThreadRoomResolver } from './discord-bot-thread-room'
76
78
  import { addDiscordMentionHints, type DiscordMentionUser } from './mention-hints'
79
+ import { withOutboundAccount } from './outbound-account'
80
+ import { createBotRecoveryCallbacks, sendBotRecovery } from './recovery-correlation'
77
81
 
78
82
  // One declared slash command per logical agent gesture. /stop maps to the
79
83
  // existing channel-command of the same name in the router. Adding new
@@ -748,15 +752,22 @@ function clampLimit(requested: number, max: number): number {
748
752
  return Math.min(Math.floor(requested), max)
749
753
  }
750
754
 
751
- // Discord-side asymmetry: agent-messenger's upstream `uploadFile` posts the
752
- // file to `POST /channels/{id}/messages` as a multipart-only request. It does
753
- // not accept a `content` body or a `thread_id`. So when the agent wants to
754
- // send "text + file together in a thread", we cannot do it in one round-trip
755
- // the way Slack can. Compromise that preserves observable intent without
756
- // patching upstream:
757
- // 1. Upload each attachment individually via uploadFile(chat, path).
758
- // Files land in channel root even when the session is in a thread —
759
- // logged as a warning so it shows up in operator triage.
755
+ // Every file goes through a raw multipart create-message (uploadDiscordFile)
756
+ // rather than agent-messenger's `uploadFile`. The SDK sends only the
757
+ // `files[0]` part and relies on Discord parsing the filename out of the
758
+ // Content-Disposition header; Discord's attachment pipeline does not reliably
759
+ // recover non-ASCII filenames from that header and falls back to the part
760
+ // index, so files land as `0`, `1`, ... in the chat. Declaring the filename in
761
+ // `payload_json.attachments` (the documented shape, matching what discord.js
762
+ // sends) is unambiguous UTF-8 JSON. It is also the only way to honor the
763
+ // OutboundAttachment `filename` override and to attach a `message_reference`.
764
+ //
765
+ // Discord-side asymmetry: a file upload here does not accept a `thread_id`, so
766
+ // "text + file together in a thread" cannot happen in one round-trip the way
767
+ // Slack can. Compromise that preserves observable intent:
768
+ // 1. Upload each attachment individually. Files land in channel root even
769
+ // when the session is in a thread — logged as a warning so it shows up in
770
+ // operator triage.
760
771
  // 2. After uploads, if `text` was provided, send it via sendMessage with
761
772
  // thread_id when applicable. Text DOES get the thread, file does not.
762
773
  // Failure semantics: if any upload fails, we abort and return ok:false with
@@ -764,29 +775,29 @@ function clampLimit(requested: number, max: number): number {
764
775
  // part of the message). The text post is best-effort and only attempted
765
776
  // after every upload succeeds.
766
777
  //
767
- // Native reply on an attachment-only send: the SDK's `uploadFile` cannot carry
768
- // a `message_reference`, so a reply-arrow on a pure-attachment reply is
769
- // impossible through it. When `msg.replyTo` is set AND there is no text send to
770
- // carry the reference, the FIRST file upload goes through a raw multipart POST
771
- // with a `payload_json.message_reference` instead (uploadFirstFileWithReply) so
772
- // the file message itself is the native reply. Only the first file carries it —
773
- // otherwise Discord renders one reply-arrow per attachment. Remaining files, and
774
- // every upload on a send that also has text (the text send carries the
775
- // reference), stay on the SDK path.
778
+ // Native reply on an attachment-only send: when `msg.replyTo` is set AND there
779
+ // is no text send to carry the reference, the FIRST file upload carries
780
+ // `payload_json.message_reference` so the file message itself is the native
781
+ // reply. Only the first file carries it — otherwise Discord renders one
782
+ // reply-arrow per attachment. On a send that also has text, the text send
783
+ // carries the reference instead.
776
784
  export function createOutboundCallback(deps: {
777
- client: Pick<DiscordBotClient, 'sendMessage' | 'uploadFile'>
785
+ client: Pick<DiscordBotClient, 'sendMessage'>
778
786
  logger: DiscordBotAdapterLogger
779
787
  formatChannelTag: (workspace: string, chat: string) => Promise<string>
780
788
  token: string
781
789
  resolvePath?: (path: string) => string
782
790
  fetchImpl?: typeof fetch
791
+ sleep?: (ms: number) => Promise<void>
783
792
  }): OutboundCallback {
784
793
  const { client, logger, formatChannelTag, token, resolvePath } = deps
785
794
  const fetchImpl = deps.fetchImpl ?? fetch
795
+ const sleep = deps.sleep ?? ((ms: number) => Bun.sleep(ms))
786
796
  return async (msg: OutboundMessage): Promise<SendResult> => {
787
797
  if (msg.adapter !== 'discord-bot') {
788
798
  return { ok: false, error: `unknown adapter: ${msg.adapter}` }
789
799
  }
800
+ if (msg.sendOptions?.accounting === 'recovery') return sendBotRecovery('discord-bot', token, msg, fetchImpl)
790
801
  const text = convertDiscordTables(msg.text ?? '')
791
802
  const attachments = msg.attachments ?? []
792
803
  if (text === '' && attachments.length === 0) {
@@ -804,23 +815,22 @@ export function createOutboundCallback(deps: {
804
815
 
805
816
  for (const [index, attachment] of attachments.entries()) {
806
817
  const path = resolvePath ? resolvePath(attachment.path) : attachment.path
807
- const referenceThisFile = index === 0 ? replyOnFirstFile : undefined
818
+ const filename = attachment.filename ?? basenameOf(attachment.path)
808
819
  try {
809
- const file =
810
- referenceThisFile !== undefined
811
- ? await uploadFirstFileWithReply({
812
- channelId: msg.chat,
813
- path,
814
- replyToId: referenceThisFile,
815
- token,
816
- fetchImpl,
817
- })
818
- : await client.uploadFile(msg.chat, path)
820
+ const file = await uploadDiscordFile({
821
+ channelId: msg.chat,
822
+ path,
823
+ filename,
824
+ replyToId: index === 0 ? replyOnFirstFile : undefined,
825
+ token,
826
+ fetchImpl,
827
+ sleep,
828
+ })
819
829
  logger.info(`[discord-bot] uploaded id=${file.id} filename=${file.filename} size=${file.size} ${tag}`)
820
830
  if (msg.thread) {
821
831
  logger.warn(
822
832
  `[discord-bot] uploaded file landed in channel root, not thread ${msg.thread}: ` +
823
- 'agent-messenger uploadFile does not accept thread_id',
833
+ 'file uploads do not accept thread_id',
824
834
  )
825
835
  }
826
836
  } catch (err) {
@@ -862,41 +872,64 @@ type DiscordCreateMessageWithAttachments = {
862
872
  attachments?: DiscordFile[]
863
873
  }
864
874
 
865
- // Raw multipart create-message so a pure-attachment reply carries a native
866
- // `message_reference`. Mirrors the SDK's `uploadFile` wire shape (`files[0]`)
867
- // and adds a `payload_json` field — Discord merges JSON body fields from
868
- // `payload_json` with the multipart file parts, which is the only documented
869
- // way to attach `message_reference` to a file upload. Returns the created
870
- // message's first attachment as a `DiscordFile`, matching `client.uploadFile`
871
- // so the caller's logging/typing is identical on both paths.
872
- async function uploadFirstFileWithReply(args: {
875
+ const UPLOAD_MAX_ATTEMPTS = 3
876
+
877
+ function basenameOf(path: string): string {
878
+ return basename(path) || 'file'
879
+ }
880
+
881
+ async function uploadDiscordFile(args: {
873
882
  channelId: string
874
883
  path: string
875
- replyToId: string
884
+ filename: string
885
+ replyToId: string | undefined
876
886
  token: string
877
887
  fetchImpl: typeof fetch
888
+ sleep: (ms: number) => Promise<void>
878
889
  }): Promise<DiscordFile> {
879
890
  const fileBuffer = await readFile(args.path)
880
- const filename = args.path.split('/').pop() ?? 'file'
881
- const form = new FormData()
882
- form.append('payload_json', JSON.stringify({ message_reference: { message_id: args.replyToId } }))
883
- form.append('files[0]', new Blob([new Uint8Array(fileBuffer)]), filename)
884
-
885
- const response = await args.fetchImpl(`${DISCORD_API_BASE}/channels/${args.channelId}/messages`, {
886
- method: 'POST',
887
- headers: { Authorization: `Bot ${args.token}` },
888
- body: form,
889
- })
890
- if (!response.ok) {
891
- const body = await response.text().catch(() => '')
892
- throw new Error(`http ${response.status}${body ? `: ${body.slice(0, 200)}` : ''}`)
891
+ const payload = {
892
+ attachments: [{ id: 0, filename: args.filename }],
893
+ ...(args.replyToId !== undefined ? { message_reference: { message_id: args.replyToId } } : {}),
893
894
  }
894
- const message = (await response.json()) as DiscordCreateMessageWithAttachments
895
- const first = message.attachments?.[0]
896
- if (first === undefined) {
897
- throw new Error('upload succeeded but no attachments returned')
895
+ for (let attempt = 1; ; attempt++) {
896
+ // FormData bodies are single-use streams, so rebuild per attempt.
897
+ const form = new FormData()
898
+ form.append('payload_json', JSON.stringify(payload))
899
+ form.append('files[0]', new Blob([new Uint8Array(fileBuffer)]), args.filename)
900
+ const response = await args.fetchImpl(`${DISCORD_API_BASE}/channels/${args.channelId}/messages`, {
901
+ method: 'POST',
902
+ headers: { Authorization: `Bot ${args.token}` },
903
+ body: form,
904
+ })
905
+ // The SDK upload path this replaced retried rate limits; keep that so a
906
+ // burst of attachments doesn't fail the whole send on the first 429.
907
+ if (response.status === 429 && attempt < UPLOAD_MAX_ATTEMPTS) {
908
+ await args.sleep(retryAfterMs(response))
909
+ continue
910
+ }
911
+ if (!response.ok) {
912
+ const body = await response.text().catch(() => '')
913
+ throw new Error(`http ${response.status}${body ? `: ${body.slice(0, 200)}` : ''}`)
914
+ }
915
+ const message = (await response.json()) as DiscordCreateMessageWithAttachments
916
+ const first = message.attachments?.[0]
917
+ if (first === undefined) {
918
+ throw new Error('upload succeeded but no attachments returned')
919
+ }
920
+ return first
898
921
  }
899
- return first
922
+ }
923
+
924
+ function retryAfterMs(response: Response): number {
925
+ // Number(null) and Number('') are 0, so a missing header must be caught
926
+ // before conversion or it becomes a zero-delay retry.
927
+ const header = response.headers.get('retry-after')?.trim() ?? ''
928
+ const seconds = header === '' ? Number.NaN : Number(header)
929
+ if (!Number.isFinite(seconds) || seconds < 0) return 1_000
930
+ // Honor the full cooldown, as the SDK's own rate-limit handling does: a
931
+ // capped wait retries before the bucket resets and burns the attempts.
932
+ return seconds * 1_000
900
933
  }
901
934
 
902
935
  // Discord CDN URLs (`cdn.discordapp.com/attachments/...`) are signed and
@@ -1046,6 +1079,9 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1046
1079
  options.createListener ?? ((client, listenerOptions) => new DiscordBotListener(client, listenerOptions))
1047
1080
  const client = createClient()
1048
1081
  const fetchImpl = options.fetchImpl ?? fetch
1082
+ const recoveryCallbacks = createBotRecoveryCallbacks('discord-bot', options.token, fetchImpl, () =>
1083
+ botUserId !== null ? `discord-bot:${botUserId}` : undefined,
1084
+ )
1049
1085
  let listener: DiscordBotListener | null = null
1050
1086
  let botUserId: string | null = null
1051
1087
  let connected = false
@@ -1094,18 +1130,22 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1094
1130
  historyCallback,
1095
1131
  })
1096
1132
 
1097
- const outboundCallback = createOutboundCallback({
1098
- client,
1099
- logger,
1100
- formatChannelTag,
1101
- token: options.token,
1102
- fetchImpl,
1103
- })
1133
+ const outboundCallback = withOutboundAccount(
1134
+ createOutboundCallback({
1135
+ client,
1136
+ logger,
1137
+ formatChannelTag,
1138
+ token: options.token,
1139
+ fetchImpl,
1140
+ }),
1141
+ (workspace) => recoveryCallbacks.cachedAccountIdentity?.(workspace),
1142
+ )
1104
1143
 
1105
1144
  const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger })
1106
1145
 
1107
1146
  const reactionCallback = createDiscordReactionCallback({ client })
1108
1147
  const removeReactionCallback = createDiscordRemoveReactionCallback({ client })
1148
+ const ownReaction = createDiscordOwnReactionCallbacks({ client, identity: async () => (await client.testAuth()).id })
1109
1149
  const editMessageCallback = createDiscordEditMessageCallback({ client })
1110
1150
 
1111
1151
  const interactionHandler = createInteractionHandler({
@@ -1131,6 +1171,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1131
1171
  }
1132
1172
 
1133
1173
  const handleMessageCreate = async (event: DiscordGatewayMessageCreateEvent): Promise<void> => {
1174
+ const inboundBotId = botUserId
1134
1175
  inflightInbounds++
1135
1176
  try {
1136
1177
  // One log line per gateway event is non-negotiable: it's the only way to
@@ -1142,7 +1183,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1142
1183
  `[discord-bot] inbound id=${event.id} author=${formatLabel(event.author.username, event.author.id)} ${inboundTag} content_len=${event.content.length}`,
1143
1184
  )
1144
1185
 
1145
- const verdict = classifyInbound(event, options.configRef(), botUserId)
1186
+ const verdict = classifyInbound(event, options.configRef(), inboundBotId)
1146
1187
  if (verdict.kind === 'drop') {
1147
1188
  logger.info(`[discord-bot] dropped id=${event.id} reason=${verdict.reason}${dropHint(verdict.reason)}`)
1148
1189
  return
@@ -1189,7 +1230,12 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1189
1230
  logger.info(
1190
1231
  `[discord-bot] routed id=${event.id} ${routedTag} mention=${payload.isBotMention} reply=${payload.replyToBotMessageId !== null}`,
1191
1232
  )
1192
- await options.router.route(payload)
1233
+ await options.router.route({
1234
+ ...payload,
1235
+ accountIdentity: inboundBotId === null ? undefined : `discord-bot:${inboundBotId}`,
1236
+ eventKind: 'message',
1237
+ revision: 'original',
1238
+ })
1193
1239
  } catch (err) {
1194
1240
  logger.error(`[discord-bot] handleInbound failed: ${describeError(err)}`)
1195
1241
  } finally {
@@ -1267,8 +1313,11 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1267
1313
  })
1268
1314
 
1269
1315
  options.router.registerOutbound('discord-bot', outboundCallback)
1316
+ options.router.registerRecoveryAdapter('discord-bot', recoveryCallbacks)
1270
1317
  options.router.registerReaction('discord-bot', reactionCallback)
1271
1318
  options.router.registerRemoveReaction('discord-bot', removeReactionCallback)
1319
+ options.router.registerPrepareOwnReaction('discord-bot', ownReaction.prepare)
1320
+ options.router.registerRemoveOwnReaction('discord-bot', ownReaction.remove)
1272
1321
  options.router.registerTyping('discord-bot', typingCallback)
1273
1322
  options.router.setTypingCapability('discord-bot', true)
1274
1323
  options.router.registerChannelNameResolver('discord-bot', channelResolver)
@@ -1288,8 +1337,11 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1288
1337
  // !started and would otherwise skip cleanup), mirroring the github
1289
1338
  // adapter's rollback path.
1290
1339
  options.router.unregisterOutbound('discord-bot', outboundCallback)
1340
+ options.router.unregisterRecoveryAdapter('discord-bot', recoveryCallbacks)
1291
1341
  options.router.unregisterReaction('discord-bot', reactionCallback)
1292
1342
  options.router.unregisterRemoveReaction('discord-bot', removeReactionCallback)
1343
+ options.router.unregisterPrepareOwnReaction('discord-bot', ownReaction.prepare)
1344
+ options.router.unregisterRemoveOwnReaction('discord-bot', ownReaction.remove)
1293
1345
  options.router.unregisterTyping('discord-bot', typingCallback)
1294
1346
  options.router.setTypingCapability('discord-bot', false)
1295
1347
  options.router.unregisterChannelNameResolver('discord-bot', channelResolver)
@@ -1356,11 +1408,14 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1356
1408
  options.router.unregisterOutbound('discord-bot', outboundCallback)
1357
1409
  options.router.unregisterReaction('discord-bot', reactionCallback)
1358
1410
  options.router.unregisterRemoveReaction('discord-bot', removeReactionCallback)
1411
+ options.router.unregisterPrepareOwnReaction('discord-bot', ownReaction.prepare)
1412
+ options.router.unregisterRemoveOwnReaction('discord-bot', ownReaction.remove)
1359
1413
  options.router.unregisterTyping('discord-bot', typingCallback)
1360
1414
  options.router.setTypingCapability('discord-bot', false)
1361
1415
  options.router.unregisterChannelNameResolver('discord-bot', channelResolver)
1362
1416
  options.router.unregisterSelfIdentity('discord-bot', selfIdentityResolver)
1363
1417
  options.router.unregisterHistory('discord-bot', historyCallback)
1418
+ options.router.unregisterRecoveryAdapter('discord-bot', recoveryCallbacks)
1364
1419
  options.router.unregisterMessageGet('discord-bot', messageGetCallback)
1365
1420
  options.router.unregisterList('discord-bot', listCallback)
1366
1421
  options.router.unregisterEditMessage('discord-bot', editMessageCallback)
@@ -9,6 +9,7 @@ import type {
9
9
  } from '@/channels/types'
10
10
 
11
11
  import { describeError } from '../describe-error'
12
+ import { createOwnReactionCallbacks } from './own-reactions'
12
13
 
13
14
  export type DiscordReactionTarget = { channel: string; message: string }
14
15
  export type DiscordReactionRemovalTarget = { channel: string; message: string; emoji: string }
@@ -62,6 +63,7 @@ const EMOJI_UNICODE: Record<string, string> = {
62
63
  raised_hands: '🙌',
63
64
  zipper_mouth_face: '🤐',
64
65
  hourglass_flowing_sand: '⏳',
66
+ warning: '⚠️',
65
67
  }
66
68
 
67
69
  function resolveEmoji(emoji: string): string | null {
@@ -135,3 +137,19 @@ function parseRecord(value: string): Record<string, unknown> | null {
135
137
  ? (parsed as Record<string, unknown>)
136
138
  : null
137
139
  }
140
+
141
+ export function createDiscordOwnReactionCallbacks(deps: {
142
+ client: Pick<DiscordClient, 'removeReaction'>
143
+ identity: () => string | null | Promise<string | null>
144
+ }) {
145
+ return createOwnReactionCallbacks({
146
+ adapter: 'discord',
147
+ identity: deps.identity,
148
+ decode: decodeDiscordReactionRef,
149
+ encode: encodeDiscordReactionRef,
150
+ emoji: (emoji) => resolveEmoji(emoji) ?? (Object.values(EMOJI_UNICODE).includes(emoji) ? emoji : null),
151
+ remove: (target, emoji) => deps.client.removeReaction(target.channel, target.message, emoji),
152
+ classify: classifyDiscordError,
153
+ absent: (error) => classifyDiscordError(error) === 'not-found',
154
+ })
155
+ }
@@ -1,6 +1,10 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { basename } from 'node:path'
3
+
1
4
  import {
2
5
  DiscordClient,
3
6
  DiscordListener,
7
+ type DiscordFile,
4
8
  type DiscordGatewayMessageCreateEvent,
5
9
  type DiscordMessage,
6
10
  } from 'agent-messenger/discord'
@@ -18,6 +22,7 @@ import type { MembershipResolver, MembershipResolverResult } from '@/channels/me
18
22
  import { deriveMembershipFromHistory } from '@/channels/membership-from-history'
19
23
  import type { ChannelRouter } from '@/channels/router'
20
24
  import type { ChannelAdapterConfig } from '@/channels/schema'
25
+ import { fallbackChannelAccountIdentity } from '@/channels/types'
21
26
  import type {
22
27
  ChannelHistoryMessage,
23
28
  ChannelSelfIdentityResolver,
@@ -44,6 +49,8 @@ import {
44
49
  } from './discord-classify'
45
50
  import { createDiscordUserEditMessageCallback } from './discord-edit'
46
51
  import { createDiscordReactionCallback, createDiscordRemoveReactionCallback } from './discord-reactions'
52
+ import { createDiscordOwnReactionCallbacks } from './discord-reactions'
53
+ import { withOutboundAccount } from './outbound-account'
47
54
 
48
55
  export type DiscordAdapterLogger = {
49
56
  info: (msg: string) => void
@@ -57,6 +64,8 @@ const consoleLogger: DiscordAdapterLogger = {
57
64
  error: (m) => console.error(m),
58
65
  }
59
66
 
67
+ const DISCORD_API_BASE = 'https://discord.com/api/v10'
68
+
60
69
  export type DiscordCredentialStore = {
61
70
  getAccount(id?: string): Promise<DiscordAccountRecord | null>
62
71
  }
@@ -81,10 +90,15 @@ export type DiscordAdapter = {
81
90
  }
82
91
 
83
92
  export function createDiscordOutboundCallback(deps: {
84
- client: Pick<DiscordClient, 'sendMessage' | 'uploadFile'>
93
+ client: Pick<DiscordClient, 'sendMessage'>
85
94
  logger: DiscordAdapterLogger
86
95
  formatChannelTag: (chat: string) => Promise<string>
96
+ tokenRef: () => string | null
97
+ fetchImpl?: typeof fetch
98
+ sleep?: (ms: number) => Promise<void>
87
99
  }): OutboundCallback {
100
+ const fetchImpl = deps.fetchImpl ?? fetch
101
+ const sleep = deps.sleep ?? ((ms: number) => Bun.sleep(ms))
88
102
  return async (msg: OutboundMessage): Promise<SendResult> => {
89
103
  if (msg.adapter !== 'discord') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
90
104
  const text = msg.text ?? ''
@@ -101,11 +115,20 @@ export function createDiscordOutboundCallback(deps: {
101
115
  const replyOption = (reference: string | undefined): { reply_to: string } | undefined =>
102
116
  reference !== undefined ? { reply_to: reference } : undefined
103
117
  try {
104
- // Attachments first, then text — Discord's upstream uploadFile takes no
105
- // content body, so a failed upload must not leave a text-only message
106
- // already posted (see OutboundMessage.attachments contract).
118
+ // Attachments first, then text, so a failed upload never leaves a
119
+ // text-only message already posted (see OutboundMessage.attachments).
107
120
  for (const [index, attachment] of attachments.entries()) {
108
- await deps.client.uploadFile(msg.chat, attachment.path, replyOption(index === 0 ? replyOnFirstFile : undefined))
121
+ const token = deps.tokenRef()
122
+ if (token === null) throw new Error('discord account is not logged in')
123
+ await uploadDiscordUserFile({
124
+ channelId: msg.chat,
125
+ path: attachment.path,
126
+ filename: attachment.filename ?? (basename(attachment.path) || 'file'),
127
+ replyToId: index === 0 ? replyOnFirstFile : undefined,
128
+ token,
129
+ fetchImpl,
130
+ sleep,
131
+ })
109
132
  }
110
133
  if (text !== '') {
111
134
  const chunks = chunkMarkdown(text, 2_000)
@@ -123,6 +146,69 @@ export function createDiscordOutboundCallback(deps: {
123
146
  }
124
147
  }
125
148
 
149
+ // Raw multipart create-message instead of the SDK's `uploadFile`. The SDK
150
+ // sends only a `files[0]` part and leaves Discord to recover the name from its
151
+ // Content-Disposition header; when Discord can't, the attachment is named by
152
+ // the part index and lands in chat as `0`, `1`, .... Declaring the filename in
153
+ // `payload_json.attachments` (Discord's documented upload shape) is
154
+ // unambiguous UTF-8 JSON, and is also what lets the OutboundAttachment
155
+ // `filename` override reach the chat.
156
+ //
157
+ // Bypassing the SDK also bypasses its per-bucket rate-limit pacing, so a 429
158
+ // is retried here after Discord's Retry-After delay instead of aborting the
159
+ // remaining attachments and text.
160
+ async function uploadDiscordUserFile(args: {
161
+ channelId: string
162
+ path: string
163
+ filename: string
164
+ replyToId: string | undefined
165
+ token: string
166
+ fetchImpl: typeof fetch
167
+ sleep: (ms: number) => Promise<void>
168
+ }): Promise<DiscordFile> {
169
+ const fileBuffer = await readFile(args.path)
170
+ const payload = {
171
+ attachments: [{ id: 0, filename: args.filename }],
172
+ ...(args.replyToId !== undefined ? { message_reference: { message_id: args.replyToId } } : {}),
173
+ }
174
+ for (let attempt = 1; ; attempt++) {
175
+ // FormData bodies are single-use streams, so rebuild per attempt.
176
+ const form = new FormData()
177
+ form.append('payload_json', JSON.stringify(payload))
178
+ form.append('files[0]', new Blob([new Uint8Array(fileBuffer)]), args.filename)
179
+ const response = await args.fetchImpl(`${DISCORD_API_BASE}/channels/${args.channelId}/messages`, {
180
+ method: 'POST',
181
+ headers: { Authorization: args.token },
182
+ body: form,
183
+ })
184
+ if (response.status === 429 && attempt < UPLOAD_MAX_ATTEMPTS) {
185
+ await args.sleep(retryAfterMs(response))
186
+ continue
187
+ }
188
+ if (!response.ok) {
189
+ const body = await response.text().catch(() => '')
190
+ throw new Error(`uploadFile failed: http ${response.status}${body ? `: ${body.slice(0, 200)}` : ''}`)
191
+ }
192
+ const message = (await response.json()) as { attachments?: DiscordFile[] }
193
+ const first = message.attachments?.[0]
194
+ if (first === undefined) throw new Error('uploadFile failed: upload succeeded but no attachments returned')
195
+ return first
196
+ }
197
+ }
198
+
199
+ const UPLOAD_MAX_ATTEMPTS = 3
200
+
201
+ function retryAfterMs(response: Response): number {
202
+ // Number(null) and Number('') are 0, so a missing header must be caught
203
+ // before conversion or it becomes a zero-delay retry.
204
+ const header = response.headers.get('retry-after')?.trim() ?? ''
205
+ const seconds = header === '' ? Number.NaN : Number(header)
206
+ if (!Number.isFinite(seconds) || seconds < 0) return 1_000
207
+ // Honor the full cooldown, as the SDK's own rate-limit handling does: a
208
+ // capped wait retries before the bucket resets and burns the attempts.
209
+ return seconds * 1_000
210
+ }
211
+
126
212
  export function createDiscordHistoryCallback(deps: {
127
213
  client: Pick<DiscordClient, 'getMessages'>
128
214
  logger: DiscordAdapterLogger
@@ -225,7 +311,16 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
225
311
  }
226
312
  const historyCallback = createDiscordHistoryCallback({ client, logger })
227
313
  const membershipResolver = createDiscordMembershipResolver({ historyCallback })
228
- const outboundCallback = createDiscordOutboundCallback({ client, logger, formatChannelTag })
314
+ const outboundCallback = withOutboundAccount(
315
+ createDiscordOutboundCallback({
316
+ client,
317
+ logger,
318
+ formatChannelTag,
319
+ tokenRef: () => token,
320
+ fetchImpl: options.fetchImpl,
321
+ }),
322
+ (workspace) => fallbackChannelAccountIdentity('discord', workspace, selfUserId),
323
+ )
229
324
  const fetchAttachmentCallback = createDiscordFetchAttachmentCallback({
230
325
  tokenRef: () => token,
231
326
  fetchImpl: options.fetchImpl,
@@ -233,13 +328,15 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
233
328
  })
234
329
  const reactionCallback = createDiscordReactionCallback({ client })
235
330
  const removeReactionCallback = createDiscordRemoveReactionCallback({ client })
331
+ const ownReaction = createDiscordOwnReactionCallbacks({ client, identity: async () => (await client.testAuth()).id })
236
332
  const editMessageCallback = createDiscordUserEditMessageCallback({ client })
237
333
 
238
334
  const handleMessage = async (event: DiscordGatewayMessageCreateEvent): Promise<void> => {
335
+ const inboundSelfId = selfUserId
239
336
  inflightInbounds++
240
337
  try {
241
338
  const verdict = classifyInbound(event, options.configRef(), {
242
- selfUserId,
339
+ selfUserId: inboundSelfId,
243
340
  selfAliases: options.selfAliasesRef?.() ?? [],
244
341
  })
245
342
  const tag =
@@ -266,7 +363,12 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
266
363
  ...(attachments.length > 0 ? { attachments } : {}),
267
364
  }
268
365
  logger.info(`[discord] routed id=${event.id} ${tag} mention=${payload.isBotMention}`)
269
- await options.router.route(payload)
366
+ await options.router.route({
367
+ ...payload,
368
+ accountIdentity: fallbackChannelAccountIdentity('discord', payload.workspace, inboundSelfId),
369
+ eventKind: 'message',
370
+ revision: 'original',
371
+ })
270
372
  } catch (err) {
271
373
  logger.error(`[discord] handleInbound failed: ${describeError(err)}`)
272
374
  } finally {
@@ -425,6 +527,8 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
425
527
  router.registerMembership('discord', membershipResolver)
426
528
  router.registerReaction('discord', reactionCallback)
427
529
  router.registerRemoveReaction('discord', removeReactionCallback)
530
+ router.registerPrepareOwnReaction('discord', ownReaction.prepare)
531
+ router.registerRemoveOwnReaction('discord', ownReaction.remove)
428
532
  router.registerEditMessage('discord', editMessageCallback)
429
533
  }
430
534
 
@@ -438,6 +542,8 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
438
542
  router.unregisterMembership('discord', membershipResolver)
439
543
  router.unregisterReaction('discord', reactionCallback)
440
544
  router.unregisterRemoveReaction('discord', removeReactionCallback)
545
+ router.unregisterPrepareOwnReaction('discord', ownReaction.prepare)
546
+ router.unregisterRemoveOwnReaction('discord', ownReaction.remove)
441
547
  router.unregisterEditMessage('discord', editMessageCallback)
442
548
  }
443
549
  }