typeclaw 0.45.1 → 0.46.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 (142) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -1
  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 +151 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +198 -0
  11. package/src/agent/plugin-tools.ts +379 -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 +1050 -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 +143 -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 +27 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/index.ts +2 -1
  32. package/src/bundled-plugins/backup/runner.ts +2 -1
  33. package/src/bundled-plugins/doc-render/render.ts +93 -12
  34. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  35. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  36. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  37. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  38. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  39. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  40. package/src/bundled-plugins/memory/README.md +23 -11
  41. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  42. package/src/bundled-plugins/memory/citations.ts +22 -9
  43. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  44. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  45. package/src/bundled-plugins/memory/index.ts +0 -4
  46. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  47. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  48. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  49. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  50. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  51. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  52. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  53. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  54. package/src/bundled-plugins/reviewer/index.ts +2 -2
  55. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  56. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  57. package/src/bundled-plugins/scout/scout.ts +8 -0
  58. package/src/bundled-plugins/security/index.ts +4 -4
  59. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  60. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  61. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  62. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  63. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  64. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  65. package/src/channels/adapters/discord-bot.ts +66 -6
  66. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  67. package/src/channels/adapters/discord-id.ts +4 -0
  68. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  69. package/src/channels/adapters/discord.ts +57 -7
  70. package/src/channels/adapters/github/auth-app.ts +41 -12
  71. package/src/channels/adapters/github/index.ts +23 -11
  72. package/src/channels/adapters/github/review-submitter.ts +302 -0
  73. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  74. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  75. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  76. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  77. package/src/channels/adapters/slack-bot.ts +19 -8
  78. package/src/channels/adapters/slack-classify.ts +21 -2
  79. package/src/channels/adapters/slack.ts +59 -7
  80. package/src/channels/adapters/telegram-bot.ts +18 -5
  81. package/src/channels/adapters/webex-bot.ts +8 -3
  82. package/src/channels/adapters/webex.ts +8 -3
  83. package/src/channels/fetch-attachment.ts +43 -0
  84. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  85. package/src/channels/github-token-bridge.ts +10 -3
  86. package/src/channels/manager.ts +9 -0
  87. package/src/channels/router.ts +248 -6
  88. package/src/channels/types.ts +28 -1
  89. package/src/cli/channel.ts +1 -1
  90. package/src/cli/init.ts +1 -1
  91. package/src/cli/model.ts +57 -7
  92. package/src/compose/stop.ts +17 -5
  93. package/src/config/config.ts +6 -6
  94. package/src/config/models-mutation.ts +13 -1
  95. package/src/config/providers.ts +176 -0
  96. package/src/container/start.ts +49 -10
  97. package/src/doctor/checks.ts +3 -1
  98. package/src/doctor/commit.ts +2 -1
  99. package/src/doctor/file-ownership.ts +52 -0
  100. package/src/dreams/git.ts +2 -1
  101. package/src/git/hookless.ts +5 -0
  102. package/src/git/reconcile-ignored.ts +18 -5
  103. package/src/git/secret-history.ts +371 -0
  104. package/src/git/system-commit.ts +12 -6
  105. package/src/init/dockerfile.ts +86 -5
  106. package/src/init/index.ts +17 -5
  107. package/src/init/models-dev.ts +4 -0
  108. package/src/init/validate-api-key.ts +2 -0
  109. package/src/mcp/tools.ts +16 -3
  110. package/src/permissions/builtins.ts +3 -1
  111. package/src/plugin/context.ts +2 -0
  112. package/src/plugin/index.ts +1 -0
  113. package/src/plugin/manager.ts +4 -0
  114. package/src/plugin/types.ts +21 -0
  115. package/src/run/index.ts +40 -0
  116. package/src/run/llm-fetch-observer.ts +41 -4
  117. package/src/sandbox/build.ts +37 -15
  118. package/src/sandbox/canonical-secrets.ts +18 -0
  119. package/src/sandbox/env-exposure.ts +80 -0
  120. package/src/sandbox/errors.ts +13 -6
  121. package/src/sandbox/hidden-paths.ts +102 -44
  122. package/src/sandbox/index.ts +22 -4
  123. package/src/sandbox/package-install.ts +3 -27
  124. package/src/sandbox/policy.ts +11 -25
  125. package/src/sandbox/privileged-runtime.ts +255 -0
  126. package/src/sandbox/session-tmp.ts +8 -2
  127. package/src/sandbox/writable-zones.ts +204 -140
  128. package/src/secrets/index.ts +8 -0
  129. package/src/secrets/refresh-provider-oauth.ts +128 -0
  130. package/src/server/command-runner.ts +48 -4
  131. package/src/server/index.ts +4 -0
  132. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  133. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  134. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  135. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  136. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  137. package/src/skills/typeclaw-config/SKILL.md +5 -5
  138. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  139. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  140. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  141. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  142. package/typeclaw.schema.json +20 -0
@@ -0,0 +1,302 @@
1
+ import type {
2
+ ReviewFinding,
3
+ ReviewSubmitter,
4
+ SubmitReviewErrorCode,
5
+ SubmitReviewRequest,
6
+ SubmitReviewResult,
7
+ } from '@/channels/types'
8
+
9
+ import type { GithubAuthContext } from './auth'
10
+ import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
11
+
12
+ const MAX_HEAD_STABILITY_ATTEMPTS = 3
13
+
14
+ export function createGithubReviewSubmitter(deps: {
15
+ token: (context?: GithubAuthContext) => Promise<string>
16
+ allowApprove: () => boolean
17
+ fetchImpl?: typeof fetch
18
+ }): ReviewSubmitter {
19
+ const fetchImpl = deps.fetchImpl ?? fetch
20
+ return async (req): Promise<SubmitReviewResult> => {
21
+ if (req.adapter !== 'github') return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'unsupported' }
22
+ const target = parseTarget(req)
23
+ if (target === null) {
24
+ return {
25
+ ok: false,
26
+ error: `unparseable github review target (workspace=${req.workspace}, chat=${req.chat})`,
27
+ code: 'transient',
28
+ }
29
+ }
30
+
31
+ const token = await deps.token({ repoSlug: `${target.owner}/${target.repo}` })
32
+ const stable = await fetchStableAnchors(fetchImpl, token, target)
33
+ if (!stable.ok) return stable
34
+
35
+ const { inline, reanchored } = partitionComments(req.comments, stable.anchors)
36
+ const downgraded = req.event === 'APPROVE' && !deps.allowApprove()
37
+ const event = downgraded ? 'COMMENT' : req.event
38
+ const posted = await postReview(fetchImpl, token, target, {
39
+ event,
40
+ body: appendReanchored(req.body, reanchored),
41
+ commitId: stable.headSha,
42
+ comments: inline,
43
+ })
44
+ if (!posted.ok) return posted
45
+ const verified = await verifyReview(fetchImpl, token, target, posted.reviewId, event)
46
+ if (!verified.ok) return { ...verified, submitted: true }
47
+ return {
48
+ ok: true,
49
+ reviewId: verified.reviewId,
50
+ state: verified.state,
51
+ ...(downgraded ? { downgraded: true } : {}),
52
+ ...(reanchored.length > 0 ? { reanchored } : {}),
53
+ }
54
+ }
55
+ }
56
+
57
+ async function fetchStableAnchors(
58
+ fetchImpl: typeof fetch,
59
+ token: string,
60
+ target: ReviewTarget,
61
+ ): Promise<{ ok: true; headSha: string; anchors: Set<string> } | (SubmitReviewResult & { ok: false })> {
62
+ for (let attempt = 0; attempt < MAX_HEAD_STABILITY_ATTEMPTS; attempt++) {
63
+ const before = await fetchPull(fetchImpl, token, target)
64
+ if (!before.ok) return before
65
+ const anchors = await fetchAnchors(fetchImpl, token, target)
66
+ if (!anchors.ok) return anchors
67
+ const after = await fetchPull(fetchImpl, token, target)
68
+ if (!after.ok) return after
69
+ if (before.headSha === after.headSha) return { ok: true, headSha: before.headSha, anchors: anchors.anchors }
70
+ }
71
+ return { ok: false, error: 'GitHub pull request head changed during anchor collection', code: 'transient' }
72
+ }
73
+
74
+ type ReviewTarget = { owner: string; repo: string; prNumber: number }
75
+
76
+ function parseTarget(req: SubmitReviewRequest): ReviewTarget | null {
77
+ const [owner, repo, ...rest] = req.workspace.split('/')
78
+ const match = /^pr:(\d+)$/.exec(req.chat)
79
+ const prNumber = match === null ? null : parseDecimalId(match[1])
80
+ if (!owner || !repo || rest.length > 0 || prNumber === null) return null
81
+ return { owner, repo, prNumber }
82
+ }
83
+
84
+ function parseDecimalId(value: string | undefined): number | null {
85
+ if (value === undefined || !/^\d+$/.test(value)) return null
86
+ const parsed = Number(value)
87
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null
88
+ }
89
+
90
+ async function fetchPull(
91
+ fetchImpl: typeof fetch,
92
+ token: string,
93
+ target: ReviewTarget,
94
+ ): Promise<{ ok: true; headSha: string } | (SubmitReviewResult & { ok: false })> {
95
+ const response = await githubFetch(fetchImpl, token, pullUrl(target))
96
+ if (!response.ok) return responseError(response, 'GitHub pull request fetch')
97
+ const body = await readJson<PullResponse>(response)
98
+ if (typeof body?.head?.sha !== 'string' || body.head.sha === '') {
99
+ return { ok: false, error: 'GitHub pull request response missing head.sha', code: 'transient' }
100
+ }
101
+ return { ok: true, headSha: body.head.sha }
102
+ }
103
+
104
+ async function fetchAnchors(
105
+ fetchImpl: typeof fetch,
106
+ token: string,
107
+ target: ReviewTarget,
108
+ ): Promise<{ ok: true; anchors: Set<string> } | (SubmitReviewResult & { ok: false })> {
109
+ const anchors = new Set<string>()
110
+ let url: string | null = `${pullUrl(target)}/files?per_page=100`
111
+ while (url !== null) {
112
+ const response = await githubFetch(fetchImpl, token, url)
113
+ if (!response.ok) return responseError(response, 'GitHub pull request files fetch')
114
+ const body = await readJson<PullFilesResponse>(response)
115
+ if (!Array.isArray(body)) {
116
+ return { ok: false, error: 'GitHub pull request files response was not an array', code: 'transient' }
117
+ }
118
+ for (const file of body) {
119
+ if (typeof file.filename === 'string' && typeof file.patch === 'string') {
120
+ addPatchAnchors(anchors, file.filename, file.patch)
121
+ }
122
+ }
123
+ url = nextLink(response.headers.get('link'))
124
+ }
125
+ return { ok: true, anchors }
126
+ }
127
+
128
+ function addPatchAnchors(anchors: Set<string>, path: string, patch: string): void {
129
+ let left = 0
130
+ let right = 0
131
+ for (const raw of patch.split('\n')) {
132
+ const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw)
133
+ if (hunk !== null) {
134
+ left = Number(hunk[1])
135
+ right = Number(hunk[2])
136
+ continue
137
+ }
138
+ if (raw.startsWith('+++') || raw.startsWith('---')) continue
139
+ if (raw.startsWith('+')) {
140
+ anchors.add(anchorKey(path, right, 'RIGHT'))
141
+ right += 1
142
+ } else if (raw.startsWith('-')) {
143
+ anchors.add(anchorKey(path, left, 'LEFT'))
144
+ left += 1
145
+ } else if (raw.startsWith(' ')) {
146
+ anchors.add(anchorKey(path, right, 'RIGHT'))
147
+ left += 1
148
+ right += 1
149
+ }
150
+ }
151
+ }
152
+
153
+ function partitionComments(
154
+ comments: readonly ReviewFinding[],
155
+ anchors: ReadonlySet<string>,
156
+ ): { inline: ReviewFinding[]; reanchored: ReviewFinding[] } {
157
+ const inline: ReviewFinding[] = []
158
+ const reanchored: ReviewFinding[] = []
159
+ for (const comment of comments) {
160
+ const side = comment.side ?? 'RIGHT'
161
+ const lineOk = anchors.has(anchorKey(comment.path, comment.line, side))
162
+ const startSide = comment.startSide ?? side
163
+ const rangePaired = (comment.startLine === undefined) === (comment.startSide === undefined)
164
+ const startOk =
165
+ rangePaired &&
166
+ (comment.startLine === undefined ||
167
+ (startSide === side &&
168
+ comment.startLine <= comment.line &&
169
+ anchors.has(anchorKey(comment.path, comment.startLine, startSide))))
170
+ ;(lineOk && startOk ? inline : reanchored).push(comment)
171
+ }
172
+ return { inline, reanchored }
173
+ }
174
+
175
+ function appendReanchored(body: string, reanchored: readonly ReviewFinding[]): string {
176
+ if (reanchored.length === 0) return body
177
+ const findings = reanchored
178
+ .map((finding) => `- ${finding.path}:${finding.line} (${finding.side ?? 'RIGHT'}): ${finding.body}`)
179
+ .join('\n')
180
+ return `${body}\n\nOut-of-diff findings moved from inline comments:\n${findings}`
181
+ }
182
+
183
+ async function postReview(
184
+ fetchImpl: typeof fetch,
185
+ token: string,
186
+ target: ReviewTarget,
187
+ review: { event: SubmitReviewRequest['event']; body: string; commitId: string; comments: ReviewFinding[] },
188
+ ): Promise<{ ok: true; reviewId: number } | (SubmitReviewResult & { ok: false })> {
189
+ const response = await githubFetch(fetchImpl, token, `${pullUrl(target)}/reviews`, {
190
+ method: 'POST',
191
+ body: JSON.stringify({
192
+ event: review.event,
193
+ body: review.body,
194
+ commit_id: review.commitId,
195
+ comments: review.comments.map(toGithubComment),
196
+ }),
197
+ })
198
+ if (!response.ok) return responseError(response, 'GitHub review submit')
199
+ const posted = await readJson<{ id?: unknown }>(response)
200
+ if (typeof posted?.id !== 'number') {
201
+ return { ok: false, error: 'GitHub review submit response missing review id', code: 'transient' }
202
+ }
203
+ return { ok: true, reviewId: posted.id }
204
+ }
205
+
206
+ function toGithubComment(comment: ReviewFinding): Record<string, unknown> {
207
+ return {
208
+ path: comment.path,
209
+ line: comment.line,
210
+ side: comment.side ?? 'RIGHT',
211
+ body: comment.body,
212
+ ...(comment.startLine !== undefined && comment.startSide !== undefined
213
+ ? { start_line: comment.startLine, start_side: comment.startSide }
214
+ : {}),
215
+ }
216
+ }
217
+
218
+ async function verifyReview(
219
+ fetchImpl: typeof fetch,
220
+ token: string,
221
+ target: ReviewTarget,
222
+ reviewId: number,
223
+ event: SubmitReviewRequest['event'],
224
+ ): Promise<{ ok: true; reviewId: number; state: string } | (SubmitReviewResult & { ok: false })> {
225
+ const response = await githubFetch(fetchImpl, token, `${pullUrl(target)}/reviews/${reviewId}`)
226
+ if (!response.ok) return responseError(response, 'GitHub review verify')
227
+ const body = await readJson<{ id?: unknown; state?: unknown }>(response)
228
+ const expectedState =
229
+ event === 'APPROVE' ? 'APPROVED' : event === 'REQUEST_CHANGES' ? 'CHANGES_REQUESTED' : 'COMMENTED'
230
+ if (body?.id !== reviewId || body.state !== expectedState) {
231
+ return {
232
+ ok: false,
233
+ error: 'GitHub review verification response did not match the posted review',
234
+ code: 'transient',
235
+ }
236
+ }
237
+ return { ok: true, reviewId, state: expectedState }
238
+ }
239
+
240
+ async function githubFetch(
241
+ fetchImpl: typeof fetch,
242
+ token: string,
243
+ url: string,
244
+ init: RequestInit = {},
245
+ ): Promise<Response> {
246
+ try {
247
+ return await fetchImpl(url, { ...init, headers: { ...githubJsonHeaders(token), ...headersRecord(init.headers) } })
248
+ } catch (error) {
249
+ return new Response(error instanceof Error ? error.message : String(error), { status: 599 })
250
+ }
251
+ }
252
+
253
+ async function readJson<T>(response: Response): Promise<T | null> {
254
+ try {
255
+ return (await response.json()) as T
256
+ } catch (error) {
257
+ void error
258
+ return null
259
+ }
260
+ }
261
+
262
+ function headersRecord(headers: HeadersInit | undefined): Record<string, string> {
263
+ if (headers === undefined) return {}
264
+ if (headers instanceof Headers) return Object.fromEntries(headers.entries())
265
+ if (Array.isArray(headers)) return Object.fromEntries(headers)
266
+ return headers
267
+ }
268
+
269
+ async function responseError(response: Response, label: string): Promise<SubmitReviewResult & { ok: false }> {
270
+ const text = await response.text()
271
+ return {
272
+ ok: false,
273
+ error: `${label} ${response.status}${text !== '' ? `: ${text}` : ''}`,
274
+ code: response.status === 422 ? 'bad-anchor' : classifyStatus(response.status),
275
+ }
276
+ }
277
+
278
+ function classifyStatus(status: number): SubmitReviewErrorCode {
279
+ if (status === 401 || status === 403) return 'permission-denied'
280
+ if (status === 404) return 'not-found'
281
+ return 'transient'
282
+ }
283
+
284
+ function nextLink(header: string | null): string | null {
285
+ if (header === null) return null
286
+ for (const part of header.split(',')) {
287
+ const match = /<([^>]+)>;\s*rel="next"/.exec(part)
288
+ if (match !== null) return match[1] ?? null
289
+ }
290
+ return null
291
+ }
292
+
293
+ function pullUrl(target: ReviewTarget): string {
294
+ return `${GITHUB_API_BASE}/repos/${target.owner}/${target.repo}/pulls/${target.prNumber}`
295
+ }
296
+
297
+ function anchorKey(path: string, line: number, side: 'LEFT' | 'RIGHT'): string {
298
+ return `${path}\0${side}\0${line}`
299
+ }
300
+
301
+ type PullResponse = { head?: { sha?: unknown } }
302
+ type PullFilesResponse = Array<{ filename?: unknown; patch?: unknown }>
@@ -17,9 +17,11 @@ export type KakaoChatLookupValue = {
17
17
  isDm: boolean
18
18
  // True while the entry is a placeholder from `ingestProvisional` (a chat seen
19
19
  // on an inbound push but not yet surfaced by getChats). Its `workspace` is a
20
- // strict-bucket guess (@kakao-group), NOT the authoritative kind — callers
21
- // that must know the real type (e.g. typing, which skips OpenChat) treat a
22
- // provisional entry as unclassified until a real refresh upgrades it.
20
+ // strict-bucket guess (@kakao-group), NOT the authoritative kind. Callers that
21
+ // must know the real type decide per-feature: typing sends for provisional
22
+ // entries (the @kakao-group guess is never @kakao-open, and a mis-guessed
23
+ // OpenChat's linkless ACTION fails soft), while allow-rule enforcement keeps
24
+ // treating the strict bucket as authoritative until a real refresh upgrades it.
23
25
  provisional: boolean
24
26
  }
25
27
 
@@ -1,3 +1,8 @@
1
+ import {
2
+ DEFAULT_ATTACHMENT_MAX_BYTES,
3
+ readAttachmentErrorSnippet,
4
+ readAttachmentResponse,
5
+ } from '@/channels/fetch-attachment'
1
6
  import type { FetchAttachmentCallback } from '@/channels/types'
2
7
 
3
8
  import type { KakaotalkAdapterLogger } from './kakaotalk'
@@ -21,7 +26,7 @@ export function createFetchAttachmentCallback(deps: {
21
26
  }): FetchAttachmentCallback {
22
27
  const { logger } = deps
23
28
  const fetchImpl = deps.fetchImpl ?? fetch
24
- return async ({ ref, filename }) => {
29
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
25
30
  let url: URL
26
31
  try {
27
32
  url = new URL(ref)
@@ -37,7 +42,7 @@ export function createFetchAttachmentCallback(deps: {
37
42
  try {
38
43
  const res = await fetchImpl(url.toString())
39
44
  if (!res.ok) {
40
- const body = await res.text().catch(() => '')
45
+ const body = await readAttachmentErrorSnippet(res)
41
46
  // 403 from kakaocdn almost always means the pre-signed URL expired
42
47
  // (the `expires=` query param has a fixed TTL — empirically ~3
43
48
  // days from the push event). Surfacing that distinction lets the
@@ -49,8 +54,7 @@ export function createFetchAttachmentCallback(deps: {
49
54
  logger.error(`[kakaotalk] fetchAttachment failed for ${url.toString()}: ${message}`)
50
55
  return { ok: false, error: message }
51
56
  }
52
- const arrayBuffer = await res.arrayBuffer()
53
- const buffer = Buffer.from(arrayBuffer)
57
+ const buffer = await readAttachmentResponse(res, maxBytes)
54
58
  const inferredFilename = filename ?? deriveFilename(url) ?? 'attachment'
55
59
  const contentType = res.headers.get('content-type') ?? undefined
56
60
  logger.info(
@@ -30,23 +30,24 @@ export type KakaoTypingCallbackHandle = {
30
30
  // expiry even with scheduler/network jitter (a 5000ms interval has no margin).
31
31
  export const KAKAO_TYPING_HEARTBEAT_MS = 4000
32
32
 
33
- // Per-chat send decision, resolved live at each tick rather than from the
34
- // (stale) session-key workspace:
35
- // send — an authoritative DM/group chat; emit the ACTION packet.
36
- // skip-open — a confirmed OpenChat; the LOCO ACTION needs a `linkId`
37
- // the resolver does not surface today, so skip (logged once,
38
- // mirroring markReadIfSupported).
39
- // skip-unresolved — unknown or provisional entry: the resolver has not yet
40
- // confirmed the kind (a chat seen on an inbound push but not
41
- // surfaced by getChats is cached as a strict @kakao-group
42
- // GUESS). Skip silently — sending could hit an OpenChat
43
- // without its linkId, and a later refresh upgrades the entry.
33
+ // Per-chat send decision, resolved live at each tick:
34
+ // send — authoritative DM/group, OR provisional. Emit the packet.
35
+ // skip-open — confirmed OpenChat; the LOCO ACTION needs a `linkId` the
36
+ // resolver does not surface today (logged once).
37
+ // skip-unresolved — chat unknown to the resolver; skip silently.
38
+ //
39
+ // Provisional entries send on purpose. A chat getChats never surfaces (e.g. a
40
+ // stale sub-device session returns a partial list) stays provisional forever, so
41
+ // skipping it disabled typing for exactly the chats a user actively messages. The
42
+ // inbound push proves the chat is real; the provisional bucket is @kakao-group
43
+ // (never @kakao-open), and a provisional-that-is-actually-OpenChat fails soft —
44
+ // sendTyping throws on non-success and the callback swallows it as a warn.
44
45
  export type KakaoTypingChatClass = 'send' | 'skip-open' | 'skip-unresolved'
45
46
 
46
47
  export function kakaoTypingClassFromLookup(
47
48
  lookup: { workspace: string; provisional: boolean } | null,
48
49
  ): KakaoTypingChatClass {
49
- if (lookup === null || lookup.provisional) return 'skip-unresolved'
50
+ if (lookup === null) return 'skip-unresolved'
50
51
  if (lookup.workspace === '@kakao-open') return 'skip-open'
51
52
  return 'send'
52
53
  }
@@ -54,9 +55,10 @@ export function kakaoTypingClassFromLookup(
54
55
  export function createKakaoTypingCallback(deps: {
55
56
  logger: KakaoTypingLogger
56
57
  sendTyping: KakaoTypingSender
57
- // Live per-chat classifier — consults the channel resolver at send time so a
58
- // provisional/unknown room (or one that refreshed into OpenChat after the
59
- // session key was minted) is suppressed, not judged by the stale target.
58
+ // Live per-chat classifier — consults the channel resolver at send time, not
59
+ // the (stale) session-key target: an unknown room is skipped, a room confirmed
60
+ // as OpenChat after the session key was minted is skipped, and a provisional or
61
+ // authoritative DM/group room sends.
60
62
  classifyChat: (chatId: string) => KakaoTypingChatClass
61
63
  formatChannelTag?: (workspace: string, chat: string) => Promise<string>
62
64
  }): KakaoTypingCallbackHandle {
@@ -0,0 +1,71 @@
1
+ import {
2
+ discardAttachmentResponse,
3
+ readAttachmentErrorSnippet,
4
+ readAttachmentResponse,
5
+ } from '@/channels/fetch-attachment'
6
+
7
+ const MAX_SLACK_REDIRECTS = 5
8
+ const SLACK_DOWNLOAD_HOSTS = ['slack.com', 'slack-edge.com', 'slack-files.com'] as const
9
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])
10
+
11
+ export type SlackDownloadMetadata = {
12
+ name?: string
13
+ mimetype?: string
14
+ size?: number
15
+ url_private?: string
16
+ url_private_download?: string
17
+ }
18
+
19
+ export type SlackAttachmentFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
20
+
21
+ export async function downloadSlackAttachment(options: {
22
+ metadata: SlackDownloadMetadata
23
+ token: string
24
+ cookie?: string
25
+ maxBytes: number
26
+ fetchImpl?: SlackAttachmentFetch
27
+ }): Promise<{ buffer: Buffer; url: URL }> {
28
+ const rawUrl = options.metadata.url_private_download ?? options.metadata.url_private
29
+ if (rawUrl === undefined || rawUrl === '') throw new Error('Slack file metadata has no private download URL')
30
+ const fetchImpl = options.fetchImpl ?? fetch
31
+ let url = parseTrustedSlackUrl(rawUrl)
32
+
33
+ for (let redirects = 0; ; redirects++) {
34
+ const response = await fetchImpl(url, {
35
+ headers: {
36
+ Authorization: `Bearer ${options.token}`,
37
+ ...(options.cookie === undefined ? {} : { Cookie: `d=${options.cookie}` }),
38
+ },
39
+ redirect: 'manual',
40
+ })
41
+ if (REDIRECT_STATUSES.has(response.status)) {
42
+ await discardAttachmentResponse(response)
43
+ if (redirects >= MAX_SLACK_REDIRECTS) throw new Error('Slack attachment redirect limit exceeded')
44
+ const location = response.headers.get('location')
45
+ if (location === null) throw new Error('Slack attachment redirect omitted Location')
46
+ url = parseTrustedSlackUrl(new URL(location, url).toString())
47
+ continue
48
+ }
49
+ if (!response.ok) {
50
+ const snippet = await readAttachmentErrorSnippet(response)
51
+ throw new Error(`Slack attachment download failed (${response.status})${snippet === '' ? '' : `: ${snippet}`}`)
52
+ }
53
+ const contentType = response.headers.get('content-type')?.toLocaleLowerCase() ?? ''
54
+ if (contentType.includes('text/html') || contentType.includes('application/xhtml+xml')) {
55
+ await discardAttachmentResponse(response)
56
+ throw new Error('Slack attachment download returned an HTML login response')
57
+ }
58
+ return { buffer: await readAttachmentResponse(response, options.maxBytes), url }
59
+ }
60
+ }
61
+
62
+ function parseTrustedSlackUrl(raw: string): URL {
63
+ const url = new URL(raw)
64
+ if (
65
+ url.protocol !== 'https:' ||
66
+ !SLACK_DOWNLOAD_HOSTS.some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`))
67
+ ) {
68
+ throw new Error(`refusing untrusted Slack attachment URL host: ${url.hostname}`)
69
+ }
70
+ return url
71
+ }
@@ -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 {
@@ -1049,24 +1051,33 @@ export function createOutboundCallback(deps: {
1049
1051
  // (legacy persisted state may still carry the old prompt-visible `id=` shape,
1050
1052
  // which channel_fetch_attachment strips before reaching this callback).
1051
1053
  export function createFetchAttachmentCallback(deps: {
1052
- client: Pick<SlackBotClient, 'downloadFile'>
1054
+ client: Pick<SlackBotClient, 'getFileInfo'>
1055
+ token: string
1056
+ fetchImpl?: SlackAttachmentFetch
1053
1057
  logger: SlackBotAdapterLogger
1054
1058
  }): FetchAttachmentCallback {
1055
1059
  const { client, logger } = deps
1056
- return async ({ ref, filename }) => {
1060
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
1057
1061
  const fileId = ref.trim()
1058
1062
  if (!/^F[A-Z0-9]+$/.test(fileId)) {
1059
1063
  return { ok: false, error: `invalid Slack file id: ${ref}` }
1060
1064
  }
1061
1065
  try {
1062
- const { buffer, file } = await client.downloadFile(fileId)
1063
- logger.info(`[slack-bot] downloaded id=${file.id} name=${file.name} size=${file.size}`)
1066
+ const metadata = await client.getFileInfo(fileId)
1067
+ enforceAttachmentMetadataSize(metadata.size, maxBytes)
1068
+ const { buffer } = await downloadSlackAttachment({
1069
+ metadata,
1070
+ token: deps.token,
1071
+ maxBytes,
1072
+ fetchImpl: deps.fetchImpl,
1073
+ })
1074
+ logger.info(`[slack-bot] downloaded id=${fileId} name=${metadata.name} size=${buffer.length}`)
1064
1075
  return {
1065
1076
  ok: true,
1066
1077
  buffer,
1067
- filename: filename ?? file.name,
1068
- mimetype: file.mimetype,
1069
- size: file.size,
1078
+ filename: filename ?? metadata.name,
1079
+ mimetype: metadata.mimetype,
1080
+ size: buffer.length,
1070
1081
  }
1071
1082
  } catch (err) {
1072
1083
  const message = err instanceof Error ? err.message : String(err)
@@ -1184,7 +1195,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1184
1195
  typingTracker,
1185
1196
  })
1186
1197
 
1187
- const fetchAttachmentCallback = createFetchAttachmentCallback({ client, logger })
1198
+ const fetchAttachmentCallback = createFetchAttachmentCallback({ client, logger, token: options.token })
1188
1199
 
1189
1200
  const reactionCallback = createSlackReactionCallback({ client })
1190
1201
  const removeReactionCallback = createSlackRemoveReactionCallback({ client })
@@ -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
  }