typeclaw 0.45.1 → 0.46.1

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 (163) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +161 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +207 -0
  11. package/src/agent/plugin-tools.ts +377 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1310 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +163 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +30 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/README.md +23 -10
  32. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  33. package/src/bundled-plugins/backup/index.ts +85 -44
  34. package/src/bundled-plugins/backup/runner.ts +85 -1
  35. package/src/bundled-plugins/doc-render/render.ts +93 -12
  36. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  37. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  38. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  39. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  40. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  41. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  42. package/src/bundled-plugins/github-cli-auth/index.ts +207 -132
  43. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  44. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  45. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  46. package/src/bundled-plugins/memory/README.md +32 -11
  47. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  48. package/src/bundled-plugins/memory/citations.ts +22 -9
  49. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  50. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  51. package/src/bundled-plugins/memory/index.ts +0 -4
  52. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  53. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  54. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  55. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  56. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  57. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  58. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  59. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  60. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  61. package/src/bundled-plugins/researcher/write-report.ts +8 -5
  62. package/src/bundled-plugins/reviewer/index.ts +2 -2
  63. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  64. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  65. package/src/bundled-plugins/scout/scout.ts +8 -0
  66. package/src/bundled-plugins/security/index.ts +4 -4
  67. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  68. package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
  69. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  70. package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
  71. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  72. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  73. package/src/channels/adapters/discord-bot.ts +66 -6
  74. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  75. package/src/channels/adapters/discord-id.ts +4 -0
  76. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  77. package/src/channels/adapters/discord.ts +57 -7
  78. package/src/channels/adapters/github/auth-app.ts +41 -12
  79. package/src/channels/adapters/github/inbound.ts +11 -0
  80. package/src/channels/adapters/github/index.ts +71 -65
  81. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  82. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  83. package/src/channels/adapters/github/review-submitter.ts +302 -0
  84. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  85. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  86. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  87. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  88. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  89. package/src/channels/adapters/slack-bot.ts +26 -10
  90. package/src/channels/adapters/slack-classify.ts +21 -2
  91. package/src/channels/adapters/slack-format.ts +245 -0
  92. package/src/channels/adapters/slack.ts +59 -7
  93. package/src/channels/adapters/telegram-bot.ts +18 -5
  94. package/src/channels/adapters/webex-bot.ts +8 -3
  95. package/src/channels/adapters/webex.ts +8 -3
  96. package/src/channels/fetch-attachment.ts +43 -0
  97. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  98. package/src/channels/github-token-bridge.ts +12 -6
  99. package/src/channels/manager.ts +9 -0
  100. package/src/channels/router.ts +248 -6
  101. package/src/channels/types.ts +28 -1
  102. package/src/cli/channel.ts +1 -1
  103. package/src/cli/init.ts +1 -1
  104. package/src/cli/model.ts +57 -7
  105. package/src/compose/stop.ts +17 -5
  106. package/src/config/config.ts +6 -6
  107. package/src/config/models-mutation.ts +13 -1
  108. package/src/config/providers.ts +176 -0
  109. package/src/container/docker-app.ts +42 -13
  110. package/src/container/start.ts +62 -10
  111. package/src/cron/bridge.ts +9 -2
  112. package/src/doctor/checks.ts +8 -3
  113. package/src/doctor/commit.ts +2 -1
  114. package/src/doctor/file-ownership.ts +52 -0
  115. package/src/dreams/git.ts +2 -1
  116. package/src/git/bound-gc-config.ts +82 -0
  117. package/src/git/hookless.ts +5 -0
  118. package/src/git/reconcile-ignored.ts +18 -5
  119. package/src/git/system-commit.ts +12 -6
  120. package/src/hostd/spawn.ts +133 -47
  121. package/src/init/dockerfile.ts +99 -5
  122. package/src/init/index.ts +17 -5
  123. package/src/init/models-dev.ts +4 -0
  124. package/src/init/validate-api-key.ts +2 -0
  125. package/src/inspect/replay.ts +21 -9
  126. package/src/inspect/session-list.ts +71 -33
  127. package/src/mcp/tools.ts +17 -3
  128. package/src/network/internal-destinations.ts +267 -0
  129. package/src/permissions/builtins.ts +3 -1
  130. package/src/plugin/context.ts +2 -0
  131. package/src/plugin/index.ts +1 -0
  132. package/src/plugin/manager.ts +4 -0
  133. package/src/plugin/types.ts +22 -0
  134. package/src/run/index.ts +40 -0
  135. package/src/run/llm-fetch-observer.ts +41 -4
  136. package/src/sandbox/build.ts +37 -15
  137. package/src/sandbox/canonical-secrets.ts +18 -0
  138. package/src/sandbox/env-exposure.ts +83 -0
  139. package/src/sandbox/errors.ts +13 -6
  140. package/src/sandbox/hidden-paths.ts +102 -44
  141. package/src/sandbox/index.ts +22 -4
  142. package/src/sandbox/package-install.ts +3 -27
  143. package/src/sandbox/policy.ts +16 -28
  144. package/src/sandbox/privileged-runtime.ts +256 -0
  145. package/src/sandbox/session-tmp.ts +8 -2
  146. package/src/sandbox/writable-zones.ts +204 -140
  147. package/src/secrets/index.ts +8 -0
  148. package/src/secrets/refresh-provider-oauth.ts +128 -0
  149. package/src/server/command-runner.ts +48 -4
  150. package/src/server/index.ts +4 -0
  151. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  152. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  153. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  154. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  155. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  156. package/src/skills/typeclaw-config/SKILL.md +27 -11
  157. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  158. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  159. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  160. package/src/skills/typeclaw-permissions/SKILL.md +36 -19
  161. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  162. package/src/usage/scan.ts +11 -2
  163. package/typeclaw.schema.json +25 -0
@@ -5,6 +5,7 @@ import {
5
5
  type SlackSocketModeSlashCommandArgs,
6
6
  } from 'agent-messenger/slackbot'
7
7
 
8
+ import { DEFAULT_ATTACHMENT_MAX_BYTES, enforceAttachmentMetadataSize } from '@/channels/fetch-attachment'
8
9
  import {
9
10
  MEMBERSHIP_CACHE_TRANSIENT_TTL_MS,
10
11
  MEMBERSHIP_CACHE_TTL_MS,
@@ -41,6 +42,7 @@ import { chunkMarkdown } from '@/markdown'
41
42
 
42
43
  import { describeError } from './describe-error'
43
44
  import { addSlackMentionHints } from './mention-hints'
45
+ import { downloadSlackAttachment, type SlackAttachmentFetch } from './slack-attachment-download'
44
46
  import { createSlackAuthorResolver, type SlackAuthorResolver } from './slack-bot-author-resolver'
45
47
  import { createSlackChannelResolver } from './slack-bot-channel-resolver'
46
48
  import {
@@ -65,6 +67,7 @@ import {
65
67
  type ThreadCommandInput,
66
68
  } from './slack-bot-slash-commands'
67
69
  import { slackTsToMillis } from './slack-bot-time'
70
+ import { toSlackMrkdwn } from './slack-format'
68
71
 
69
72
  // One slash command per logical agent gesture. Mirrors the discord-bot
70
73
  // SLASH_COMMANDS constant so the cross-platform set stays consistent — when
@@ -1025,7 +1028,11 @@ export function createOutboundCallback(deps: {
1025
1028
  const isFirst = index === 0
1026
1029
  const uploadOptions: { thread_ts?: string; initial_comment?: string } = {}
1027
1030
  if (threadTs !== undefined) uploadOptions.thread_ts = threadTs
1028
- if (isFirst && text !== '') uploadOptions.initial_comment = text
1031
+ // A file caption cannot carry a `markdown` block (files.uploadV2 has no
1032
+ // `blocks` param), so it is parsed as Slack mrkdwn. Convert the agent's
1033
+ // GFM (`**bold**`) to mrkdwn (`*bold*`) here — the text-only path above
1034
+ // relies on the native markdown block and needs no conversion.
1035
+ if (isFirst && text !== '') uploadOptions.initial_comment = toSlackMrkdwn(text)
1029
1036
  try {
1030
1037
  const file = await client.uploadFile(msg.chat, buffer, filename, uploadOptions)
1031
1038
  logger.info(`[slack-bot] uploaded id=${file.id} filename=${file.name} size=${file.size} ${tag}`)
@@ -1049,24 +1056,33 @@ export function createOutboundCallback(deps: {
1049
1056
  // (legacy persisted state may still carry the old prompt-visible `id=` shape,
1050
1057
  // which channel_fetch_attachment strips before reaching this callback).
1051
1058
  export function createFetchAttachmentCallback(deps: {
1052
- client: Pick<SlackBotClient, 'downloadFile'>
1059
+ client: Pick<SlackBotClient, 'getFileInfo'>
1060
+ token: string
1061
+ fetchImpl?: SlackAttachmentFetch
1053
1062
  logger: SlackBotAdapterLogger
1054
1063
  }): FetchAttachmentCallback {
1055
1064
  const { client, logger } = deps
1056
- return async ({ ref, filename }) => {
1065
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
1057
1066
  const fileId = ref.trim()
1058
1067
  if (!/^F[A-Z0-9]+$/.test(fileId)) {
1059
1068
  return { ok: false, error: `invalid Slack file id: ${ref}` }
1060
1069
  }
1061
1070
  try {
1062
- const { buffer, file } = await client.downloadFile(fileId)
1063
- logger.info(`[slack-bot] downloaded id=${file.id} name=${file.name} size=${file.size}`)
1071
+ const metadata = await client.getFileInfo(fileId)
1072
+ enforceAttachmentMetadataSize(metadata.size, maxBytes)
1073
+ const { buffer } = await downloadSlackAttachment({
1074
+ metadata,
1075
+ token: deps.token,
1076
+ maxBytes,
1077
+ fetchImpl: deps.fetchImpl,
1078
+ })
1079
+ logger.info(`[slack-bot] downloaded id=${fileId} name=${metadata.name} size=${buffer.length}`)
1064
1080
  return {
1065
1081
  ok: true,
1066
1082
  buffer,
1067
- filename: filename ?? file.name,
1068
- mimetype: file.mimetype,
1069
- size: file.size,
1083
+ filename: filename ?? metadata.name,
1084
+ mimetype: metadata.mimetype,
1085
+ size: buffer.length,
1070
1086
  }
1071
1087
  } catch (err) {
1072
1088
  const message = err instanceof Error ? err.message : String(err)
@@ -1184,11 +1200,11 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1184
1200
  typingTracker,
1185
1201
  })
1186
1202
 
1187
- const fetchAttachmentCallback = createFetchAttachmentCallback({ client, logger })
1203
+ const fetchAttachmentCallback = createFetchAttachmentCallback({ client, logger, token: options.token })
1188
1204
 
1189
1205
  const reactionCallback = createSlackReactionCallback({ client })
1190
1206
  const removeReactionCallback = createSlackRemoveReactionCallback({ client })
1191
- const editMessageCallback = createSlackEditMessageCallback({ client })
1207
+ const editMessageCallback = createSlackEditMessageCallback({ token: options.token, fetchImpl })
1192
1208
 
1193
1209
  const dedupe = createSlackDedupe()
1194
1210
 
@@ -7,7 +7,12 @@ import type { InboundMessage } from '@/channels/types'
7
7
  import { slackTsToMillis } from './slack-bot-time'
8
8
  import { encodeSlackReactionRef } from './slack-reactions'
9
9
 
10
- export type SlackInboundMessageEvent = SlackRTMMessageEvent
10
+ export type SlackInboundMessageEvent = SlackRTMMessageEvent & {
11
+ channel_type?: string
12
+ is_mpim?: boolean
13
+ }
14
+
15
+ export type SlackConversationType = 'im' | 'mpim' | 'channel'
11
16
 
12
17
  export type InboundDropReason = 'self_author' | 'no_user' | 'slack_system_message' | 'empty_text' | 'pre_connect'
13
18
 
@@ -19,6 +24,7 @@ export type SlackInboundContext = {
19
24
  teamId: string
20
25
  selfUserId: string | null
21
26
  selfAliases?: readonly string[]
27
+ conversationType?: SlackConversationType
22
28
  }
23
29
 
24
30
  export function classifyInbound(
@@ -33,7 +39,8 @@ export function classifyInbound(
33
39
  if (context.selfUserId === null) return { kind: 'drop', reason: 'pre_connect' }
34
40
 
35
41
  const rawText = event.text ?? ''
36
- const isDm = event.channel.startsWith('D')
42
+ const conversationType = classifyConversation(event, context.conversationType)
43
+ const isDm = conversationType === 'im'
37
44
  const workspace = isDm ? '@dm' : context.teamId
38
45
  const hasGroupMention = GROUP_MENTION_PATTERN.test(rawText)
39
46
  const isBotMention = hasGroupMention || rawText.includes(`<@${context.selfUserId}>`)
@@ -68,6 +75,18 @@ export function classifyInbound(
68
75
  }
69
76
  }
70
77
 
78
+ function classifyConversation(
79
+ event: SlackInboundMessageEvent,
80
+ resolvedType: SlackConversationType | undefined,
81
+ ): SlackConversationType {
82
+ if (event.channel_type === 'im' || event.channel_type === 'mpim' || event.channel_type === 'channel') {
83
+ return event.channel_type
84
+ }
85
+ if (event.is_mpim === true) return 'mpim'
86
+ if (resolvedType !== undefined) return resolvedType
87
+ return event.channel.startsWith('D') ? 'im' : 'channel'
88
+ }
89
+
71
90
  export function isRouteableSlackMessageSubtype(subtype: string | undefined): boolean {
72
91
  return subtype === undefined || subtype === 'me_message'
73
92
  }
@@ -0,0 +1,245 @@
1
+ // Convert the model's common-Markdown (GFM) output to Slack mrkdwn.
2
+ //
3
+ // Why this exists: the agent writes GitHub-Flavored Markdown the way a
4
+ // human types it (`**bold**`, `## heading`, `[text](url)`, tables). For a
5
+ // normal chat post the slack-bot adapter wraps that GFM in a Slack
6
+ // `markdown` block and Slack renders it natively — so no conversion is
7
+ // needed there. But two outbound fields cannot carry a `markdown` block:
8
+ // a file upload's `initial_comment` (files.uploadV2 has no `blocks`
9
+ // param). That field is parsed as Slack *mrkdwn*, where bold is a SINGLE
10
+ // `*`, so raw GFM `**bold**` renders as literal double asterisks. This
11
+ // converter bridges GFM -> mrkdwn for exactly those constrained fields.
12
+ //
13
+ // Slack mrkdwn is forgiving (unlike Telegram MarkdownV2, there is no
14
+ // escaping that can crash the parser), so this is a best-effort semantic
15
+ // translation, not a safety escape. Constructs mrkdwn cannot represent
16
+ // (headings, tables) degrade to the closest readable form.
17
+ //
18
+ // Slack mrkdwn spec (https://docs.slack.dev/messaging/formatting-message-text):
19
+ // - bold: *text*
20
+ // - italic: _text_
21
+ // - strike: ~text~
22
+ // - link: <url|label>
23
+ // - code: `code`, ```block```
24
+ // - quote: > line
25
+ // No native heading or table syntax exists.
26
+
27
+ export function toSlackMrkdwn(input: string): string {
28
+ if (input === '') return ''
29
+ const lines = input.split('\n')
30
+ const out: string[] = []
31
+ let i = 0
32
+ while (i < lines.length) {
33
+ const line = lines[i]!
34
+
35
+ if (isFenceOpen(line)) {
36
+ // Emit the fence and its body verbatim — a `*` inside a code block is
37
+ // literal, never italic. Scan to the closing fence (or EOF).
38
+ out.push(line)
39
+ i++
40
+ while (i < lines.length && !isFenceClose(lines[i]!)) {
41
+ out.push(lines[i]!)
42
+ i++
43
+ }
44
+ if (i < lines.length) {
45
+ out.push(lines[i]!)
46
+ i++
47
+ }
48
+ continue
49
+ }
50
+
51
+ if (isTableSeparatorRow(line) && out.length > 0 && isTableRow(lines[i - 1])) {
52
+ // GFM alignment row (`| --- | :--: |`) has no mrkdwn equivalent; drop
53
+ // it. The header row above and the data rows below stay as plain
54
+ // pipe-separated text, which reads fine in monospace-free mrkdwn.
55
+ i++
56
+ continue
57
+ }
58
+
59
+ out.push(renderLine(line))
60
+ i++
61
+ }
62
+ return out.join('\n')
63
+ }
64
+
65
+ function isFenceOpen(line: string): boolean {
66
+ return /^\s*```/.test(line)
67
+ }
68
+
69
+ function isFenceClose(line: string): boolean {
70
+ return /^\s*```\s*$/.test(line)
71
+ }
72
+
73
+ function isTableRow(line: string | undefined): boolean {
74
+ if (line === undefined) return false
75
+ return /^\s*\|.*\|\s*$/.test(line)
76
+ }
77
+
78
+ function isTableSeparatorRow(line: string): boolean {
79
+ return /^\s*\|(\s*:?-+:?\s*\|)+\s*$/.test(line)
80
+ }
81
+
82
+ // A heading line (`#`..`######` then space) has no mrkdwn equivalent, so
83
+ // render its inline-converted text as a bold line. A `#` that is not at the
84
+ // line start (e.g. `issue #42`) is not a heading and falls through. Inner
85
+ // bold is flattened to plain (`flattenBold`) because mrkdwn has no
86
+ // bold-inside-bold — the whole heading line is already bold, so a nested
87
+ // `*..*` would just emit a stray unbalanced `*`. Flattening happens INSIDE
88
+ // the tokenizer so code spans stay protected: a global post-pass regex
89
+ // would corrupt a `*` that lives inside a heading's inline code.
90
+ const HEADING = /^(#{1,6})\s+(.*)$/
91
+
92
+ function renderLine(line: string): string {
93
+ const heading = HEADING.exec(line)
94
+ if (heading !== null) {
95
+ const body = renderInline(heading[2]!, { flattenBold: true })
96
+ return body === '' ? '' : `*${body}*`
97
+ }
98
+ return renderInline(line)
99
+ }
100
+
101
+ type InlineOptions = { flattenBold: boolean }
102
+
103
+ // Inline tokenizer. Recognizes, in priority order:
104
+ // 1. inline code: `code`
105
+ // 2. link: [label](url) -> <url|label>
106
+ // 3. bold: **text** / __text__ -> *text* (or plain when flattenBold)
107
+ // 4. strike: ~~text~~ -> ~text~
108
+ // 5. italic: *text* / _text_ -> _text_
109
+ //
110
+ // Italic is last so `**` is consumed as bold, not two italics. Everything
111
+ // unrecognized is emitted verbatim — Slack mrkdwn needs no escaping.
112
+ function renderInline(text: string, options: InlineOptions = { flattenBold: false }): string {
113
+ const out: string[] = []
114
+ let i = 0
115
+ while (i < text.length) {
116
+ const ch = text[i]!
117
+
118
+ if (ch === '`') {
119
+ const close = text.indexOf('`', i + 1)
120
+ if (close !== -1) {
121
+ out.push(text.slice(i, close + 1))
122
+ i = close + 1
123
+ continue
124
+ }
125
+ }
126
+
127
+ if (ch === '[') {
128
+ const link = parseLink(text, i)
129
+ if (link !== null) {
130
+ out.push(`<${link.url}|${renderInline(link.label, options)}>`)
131
+ i = link.end
132
+ continue
133
+ }
134
+ }
135
+
136
+ if (ch === '*' && text[i + 1] === '*') {
137
+ const close = findClose(text, i + 2, '**')
138
+ if (close > i + 2) {
139
+ const inner = renderInline(text.slice(i + 2, close), options)
140
+ out.push(options.flattenBold ? inner : `*${inner}*`)
141
+ i = close + 2
142
+ continue
143
+ }
144
+ }
145
+
146
+ // `__bold__` only when not adjacent to a word char on either side, so a
147
+ // snake_case identifier the model wrote (`my__var__name`) is left alone.
148
+ if (ch === '_' && text[i + 1] === '_' && !isWordChar(text[i - 1])) {
149
+ const close = findClose(text, i + 2, '__')
150
+ if (close > i + 2 && !isWordChar(text[close + 2])) {
151
+ const inner = renderInline(text.slice(i + 2, close), options)
152
+ out.push(options.flattenBold ? inner : `*${inner}*`)
153
+ i = close + 2
154
+ continue
155
+ }
156
+ }
157
+
158
+ if (ch === '~' && text[i + 1] === '~') {
159
+ const close = findClose(text, i + 2, '~~')
160
+ if (close > i + 2) {
161
+ out.push(`~${renderInline(text.slice(i + 2, close), options)}~`)
162
+ i = close + 2
163
+ continue
164
+ }
165
+ }
166
+
167
+ // Italic: word-boundary guard on both sides so `a*b*c` and identifiers
168
+ // don't italicize. The guards are ASCII word chars by design — they
169
+ // gate on the model's Latin identifier/math usage; CJK/Korean text has
170
+ // no such tokens, so bold/italic markers around Korean still convert.
171
+ if (ch === '*' && !isWordChar(text[i - 1])) {
172
+ const close = findInlineClose(text, i + 1, '*')
173
+ if (close !== -1 && !isWordChar(text[close + 1])) {
174
+ const inner = text.slice(i + 1, close)
175
+ if (inner !== '' && !/^\s|\s$/.test(inner)) {
176
+ out.push(`_${renderInline(inner, options)}_`)
177
+ i = close + 1
178
+ continue
179
+ }
180
+ }
181
+ }
182
+ if (ch === '_' && !isWordChar(text[i - 1])) {
183
+ const close = findInlineClose(text, i + 1, '_')
184
+ if (close !== -1 && !isWordChar(text[close + 1])) {
185
+ const inner = text.slice(i + 1, close)
186
+ if (inner !== '' && !/^\s|\s$/.test(inner)) {
187
+ out.push(`_${renderInline(inner, options)}_`)
188
+ i = close + 1
189
+ continue
190
+ }
191
+ }
192
+ }
193
+
194
+ out.push(ch)
195
+ i++
196
+ }
197
+ return out.join('')
198
+ }
199
+
200
+ function findClose(text: string, from: number, marker: string): number {
201
+ let i = from
202
+ while (i <= text.length - marker.length) {
203
+ if (text.slice(i, i + marker.length) === marker) return i
204
+ i++
205
+ }
206
+ return -1
207
+ }
208
+
209
+ function findInlineClose(text: string, from: number, marker: string): number {
210
+ let i = from
211
+ while (i < text.length) {
212
+ if (text[i] === '\n') return -1
213
+ if (text[i] === marker) return i
214
+ i++
215
+ }
216
+ return -1
217
+ }
218
+
219
+ function parseLink(text: string, start: number): { label: string; url: string; end: number } | null {
220
+ let i = start + 1
221
+ const labelStart = i
222
+ while (i < text.length) {
223
+ const c = text[i]!
224
+ if (c === ']') break
225
+ if (c === '\n') return null
226
+ i++
227
+ }
228
+ if (text[i] !== ']' || text[i + 1] !== '(') return null
229
+ const label = text.slice(labelStart, i)
230
+ const urlStart = i + 2
231
+ let j = urlStart
232
+ while (j < text.length) {
233
+ const c = text[j]!
234
+ if (c === ')') break
235
+ if (c === '(' || c === '\n') return null
236
+ j++
237
+ }
238
+ if (text[j] !== ')') return null
239
+ return { label, url: text.slice(urlStart, j), end: j + 1 }
240
+ }
241
+
242
+ function isWordChar(ch: string | undefined): boolean {
243
+ if (ch === undefined) return false
244
+ return /[A-Za-z0-9_]/.test(ch)
245
+ }
@@ -8,6 +8,7 @@ import {
8
8
  type SlackRTMReactionEvent,
9
9
  } from 'agent-messenger/slack'
10
10
 
11
+ import { DEFAULT_ATTACHMENT_MAX_BYTES, enforceAttachmentMetadataSize } from '@/channels/fetch-attachment'
11
12
  import {
12
13
  MEMBERSHIP_ENUMERATION_CAP,
13
14
  type MembershipResolver,
@@ -33,10 +34,11 @@ import { chunkMarkdown } from '@/markdown'
33
34
  import type { SlackAccountRecord } from '@/secrets/schema'
34
35
 
35
36
  import { describeError } from './describe-error'
37
+ import { downloadSlackAttachment, type SlackAttachmentFetch } from './slack-attachment-download'
36
38
  import { createSlackAuthorResolver } from './slack-author-resolver'
37
39
  import { slackTsToMillis } from './slack-bot-time'
38
40
  import { createSlackChannelResolver } from './slack-channel-resolver'
39
- import { classifyInbound, type InboundDropReason } from './slack-classify'
41
+ import { classifyInbound, type InboundDropReason, type SlackConversationType } from './slack-classify'
40
42
  import { createSlackUserEditMessageCallback } from './slack-edit'
41
43
  import { createSlackReactionCallback, createSlackRemoveReactionCallback } from './slack-reactions'
42
44
 
@@ -166,17 +168,31 @@ export function createSlackMembershipResolver(deps: {
166
168
  }
167
169
 
168
170
  export function createSlackFetchAttachmentCallback(deps: {
169
- client: Pick<SlackClient, 'downloadFile'>
171
+ client: Pick<SlackClient, 'getFileInfo'>
172
+ tokenRef: () => string | null
173
+ cookieRef?: () => string | null
174
+ fetchImpl?: SlackAttachmentFetch
170
175
  logger: SlackAdapterLogger
171
176
  }): FetchAttachmentCallback {
172
- return async ({ ref, filename }) => {
177
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
173
178
  try {
174
- const { buffer, file } = await deps.client.downloadFile(ref)
179
+ const metadata = await deps.client.getFileInfo(ref)
180
+ enforceAttachmentMetadataSize(metadata.size, maxBytes)
181
+ const token = deps.tokenRef()
182
+ if (token === null) throw new Error('Slack attachment credential is unavailable')
183
+ const cookie = deps.cookieRef?.() ?? undefined
184
+ const { buffer } = await downloadSlackAttachment({
185
+ metadata,
186
+ token,
187
+ ...(cookie === undefined ? {} : { cookie }),
188
+ maxBytes,
189
+ fetchImpl: deps.fetchImpl,
190
+ })
175
191
  return {
176
192
  ok: true,
177
193
  buffer,
178
- filename: filename ?? file.name ?? 'attachment',
179
- mimetype: file.mimetype,
194
+ filename: filename ?? metadata.name ?? 'attachment',
195
+ mimetype: metadata.mimetype,
180
196
  size: buffer.length,
181
197
  }
182
198
  } catch (err) {
@@ -197,10 +213,13 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
197
213
  let selfName: string | null = null
198
214
  let teamId = ''
199
215
  let teamName: string | null = null
216
+ let accountToken: string | null = null
217
+ let accountCookie: string | null = null
200
218
  let connected = false
201
219
  let started = false
202
220
  let inflightInbounds = 0
203
221
  let stopWaiters: Array<() => void> = []
222
+ const conversationTypes = new Map<string, SlackConversationType>()
204
223
 
205
224
  const channelResolver = createSlackChannelResolver({ client, teamNameRef: () => teamName })
206
225
  const authorResolver = createSlackAuthorResolver({ client })
@@ -221,11 +240,37 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
221
240
  selfUserIdRef: () => selfUserId,
222
241
  })
223
242
  const outboundCallback = createSlackOutboundCallback({ client, logger, formatChannelTag })
224
- const fetchAttachmentCallback = createSlackFetchAttachmentCallback({ client, logger })
243
+ const fetchAttachmentCallback = createSlackFetchAttachmentCallback({
244
+ client,
245
+ logger,
246
+ tokenRef: () => accountToken,
247
+ cookieRef: () => accountCookie,
248
+ })
225
249
  const reactionCallback = createSlackReactionCallback({ client })
226
250
  const removeReactionCallback = createSlackRemoveReactionCallback({ client })
227
251
  const editMessageCallback = createSlackUserEditMessageCallback({ client })
228
252
 
253
+ const resolveConversationType = async (event: SlackRTMMessageEvent): Promise<SlackConversationType | undefined> => {
254
+ if (!event.channel.startsWith('G')) return undefined
255
+ const cached = conversationTypes.get(event.channel)
256
+ if (cached !== undefined) return cached
257
+ return await client.listDMs().then(
258
+ (conversations) => {
259
+ const type: SlackConversationType = conversations.some(
260
+ (conversation) => conversation.id === event.channel && conversation.is_mpim,
261
+ )
262
+ ? 'mpim'
263
+ : 'channel'
264
+ conversationTypes.set(event.channel, type)
265
+ return type
266
+ },
267
+ (error: unknown) => {
268
+ logger.warn(`[slack] conversation metadata failed channel=${event.channel}: ${describeError(error)}`)
269
+ return 'channel'
270
+ },
271
+ )
272
+ }
273
+
229
274
  const handleMessage = async (event: SlackRTMMessageEvent): Promise<void> => {
230
275
  inflightInbounds++
231
276
  try {
@@ -237,6 +282,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
237
282
  teamId,
238
283
  selfUserId,
239
284
  selfAliases: options.selfAliasesRef?.() ?? [],
285
+ conversationType: await resolveConversationType(event),
240
286
  })
241
287
  if (verdict.kind === 'drop') {
242
288
  logger.info(`[slack] dropped id=${event.ts} reason=${verdict.reason}${dropHint(verdict.reason)}`)
@@ -271,6 +317,8 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
271
317
  throw new Error('no Slack account in secrets.json#channels.slack (run typeclaw init to authenticate)')
272
318
  }
273
319
  await client.login({ token: account.token, cookie: account.cookie })
320
+ accountToken = account.token
321
+ accountCookie = account.cookie
274
322
  const auth = await client.testAuth()
275
323
  selfUserId = auth.user_id
276
324
  selfName = auth.user ?? auth.user_id
@@ -280,6 +328,8 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
280
328
  } catch (err) {
281
329
  started = false
282
330
  selfUserId = null
331
+ accountToken = null
332
+ accountCookie = null
283
333
  teamId = ''
284
334
  logger.error(`[slack] login failed: ${describeError(err)}`)
285
335
  throw err
@@ -358,6 +408,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
358
408
  listener?.stop()
359
409
  listener = null
360
410
  selfUserId = null
411
+ accountToken = null
361
412
  connected = false
362
413
  started = false
363
414
  logger.error(`[slack] ${reason}: ${describeError(cause)}`)
@@ -376,6 +427,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
376
427
  async stop(): Promise<void> {
377
428
  if (!started) return
378
429
  started = false
430
+ accountToken = null
379
431
  options.router.unregisterOutbound('slack', outboundCallback)
380
432
  options.router.setTypingCapability('slack', false)
381
433
  options.router.unregisterChannelNameResolver('slack', channelResolver)
@@ -1,6 +1,12 @@
1
1
  import { TelegramBotClient, TelegramBotListener } from 'agent-messenger/telegrambot'
2
2
  import type { TelegramBotUser, TelegramMessage } from 'agent-messenger/telegrambot'
3
3
 
4
+ import { readResponseBodyBounded } from '@/agent/network/response-body'
5
+ import {
6
+ DEFAULT_ATTACHMENT_MAX_BYTES,
7
+ readAttachmentErrorSnippet,
8
+ readAttachmentResponse,
9
+ } from '@/channels/fetch-attachment'
4
10
  import type { MembershipResolver, MembershipResolverFailure, MembershipResolverResult } from '@/channels/membership'
5
11
  import type { ChannelRouter } from '@/channels/router'
6
12
  import type { ChannelAdapterConfig } from '@/channels/schema'
@@ -313,7 +319,7 @@ export function createFetchAttachmentCallback(deps: {
313
319
  }): FetchAttachmentCallback {
314
320
  const { token, logger } = deps
315
321
  const fetchImpl = deps.fetchImpl ?? fetch
316
- return async ({ ref, filename }) => {
322
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
317
323
  if (ref === '' || ref.includes('://')) {
318
324
  return { ok: false, error: `invalid Telegram file_id: ${ref}` }
319
325
  }
@@ -333,7 +339,8 @@ export function createFetchAttachmentCallback(deps: {
333
339
  }
334
340
  let meta: TelegramFileResponse
335
341
  try {
336
- meta = (await metaResponse.json()) as TelegramFileResponse
342
+ const bytes = await readResponseBodyBounded(metaResponse, 64 * 1024)
343
+ meta = JSON.parse(bytes.toString('utf8')) as TelegramFileResponse
337
344
  } catch (err) {
338
345
  return { ok: false, error: `getFile parse failed: ${describeError(err)}` }
339
346
  }
@@ -352,13 +359,19 @@ export function createFetchAttachmentCallback(deps: {
352
359
  return { ok: false, error: message }
353
360
  }
354
361
  if (!response.ok) {
355
- const body = await response.text().catch(() => '')
362
+ const body = await readAttachmentErrorSnippet(response)
356
363
  const message = `download ${response.status} ${response.statusText}${body !== '' ? `: ${body.slice(0, 200)}` : ''}`
357
364
  logger.error(`[telegram-bot] download failed for ${ref}: ${message}`)
358
365
  return { ok: false, error: message }
359
366
  }
360
- const arrayBuffer = await response.arrayBuffer()
361
- const buffer = Buffer.from(arrayBuffer)
367
+ let buffer: Buffer
368
+ try {
369
+ buffer = await readAttachmentResponse(response, maxBytes)
370
+ } catch (err) {
371
+ const message = describeError(err)
372
+ logger.error(`[telegram-bot] download failed for ${ref}: ${message}`)
373
+ return { ok: false, error: message }
374
+ }
362
375
  const inferredFilename = filename ?? filePath.split('/').pop() ?? 'attachment'
363
376
  const contentType = response.headers.get('content-type') ?? undefined
364
377
  logger.info(
@@ -7,6 +7,11 @@ import type {
7
7
  WebexPerson,
8
8
  } from 'agent-messenger/webexbot'
9
9
 
10
+ import {
11
+ DEFAULT_ATTACHMENT_MAX_BYTES,
12
+ readAttachmentErrorSnippet,
13
+ readAttachmentResponse,
14
+ } from '@/channels/fetch-attachment'
10
15
  import {
11
16
  MEMBERSHIP_ENUMERATION_CAP,
12
17
  type MembershipResolver,
@@ -236,7 +241,7 @@ export function createFetchAttachmentCallback(deps: {
236
241
  fetchImpl?: typeof fetch
237
242
  }): FetchAttachmentCallback {
238
243
  const fetchImpl = deps.fetchImpl ?? fetch
239
- return async ({ ref, filename }) => {
244
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
240
245
  let url: URL
241
246
  try {
242
247
  url = new URL(ref)
@@ -255,12 +260,12 @@ export function createFetchAttachmentCallback(deps: {
255
260
  try {
256
261
  const res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${deps.token}` } })
257
262
  if (!res.ok) {
258
- const body = await res.text().catch(() => '')
263
+ const body = await readAttachmentErrorSnippet(res)
259
264
  const message = `webex file fetch ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`
260
265
  deps.logger.error(`[webex-bot] fetchAttachment failed for ${url.toString()}: ${message}`)
261
266
  return { ok: false, error: message }
262
267
  }
263
- const buffer = Buffer.from(await res.arrayBuffer())
268
+ const buffer = await readAttachmentResponse(res, maxBytes)
264
269
  const inferredFilename = filename ?? url.pathname.split('/').pop() ?? 'attachment'
265
270
  const contentType = res.headers.get('content-type') ?? undefined
266
271
  return {
@@ -9,6 +9,11 @@ import type {
9
9
  WebexPerson,
10
10
  } from 'agent-messenger/webex'
11
11
 
12
+ import {
13
+ DEFAULT_ATTACHMENT_MAX_BYTES,
14
+ readAttachmentErrorSnippet,
15
+ readAttachmentResponse,
16
+ } from '@/channels/fetch-attachment'
12
17
  import {
13
18
  MEMBERSHIP_ENUMERATION_CAP,
14
19
  type MembershipResolver,
@@ -285,7 +290,7 @@ export function createFetchAttachmentCallback(deps: {
285
290
  fetchImpl?: typeof fetch
286
291
  }): FetchAttachmentCallback {
287
292
  const fetchImpl = deps.fetchImpl ?? fetch
288
- return async ({ ref, filename }) => {
293
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
289
294
  const token = deps.tokenRef()
290
295
  if (token === null) return { ok: false, error: 'webex account token is not available' }
291
296
  let url: URL
@@ -306,12 +311,12 @@ export function createFetchAttachmentCallback(deps: {
306
311
  try {
307
312
  const res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${token}` } })
308
313
  if (!res.ok) {
309
- const body = await res.text().catch(() => '')
314
+ const body = await readAttachmentErrorSnippet(res)
310
315
  const message = `webex file fetch ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`
311
316
  deps.logger.error(`[webex] fetchAttachment failed for ${url.toString()}: ${message}`)
312
317
  return { ok: false, error: message }
313
318
  }
314
- const buffer = Buffer.from(await res.arrayBuffer())
319
+ const buffer = await readAttachmentResponse(res, maxBytes)
315
320
  const inferredFilename = filename ?? url.pathname.split('/').pop() ?? 'attachment'
316
321
  const contentType = res.headers.get('content-type') ?? undefined
317
322
  return {