typeclaw 0.45.0 → 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 (147) 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 +67 -25
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/loop-guard.ts +208 -10
  7. package/src/agent/multimodal/index.ts +1 -1
  8. package/src/agent/multimodal/look-at.ts +78 -44
  9. package/src/agent/multimodal/looker.ts +151 -39
  10. package/src/agent/network/response-body.ts +26 -0
  11. package/src/agent/network/safe-http.ts +198 -0
  12. package/src/agent/plugin-tools.ts +438 -162
  13. package/src/agent/provider-error.ts +62 -4
  14. package/src/agent/restart/index.ts +61 -40
  15. package/src/agent/restart-handoff/index.ts +73 -4
  16. package/src/agent/retry-same-ref.ts +66 -0
  17. package/src/agent/reviewer-bash-policy.ts +42 -1
  18. package/src/agent/session-origin.ts +2 -0
  19. package/src/agent/subagent-drain.ts +117 -7
  20. package/src/agent/subagents.ts +77 -18
  21. package/src/agent/throttle-circuit.ts +25 -5
  22. package/src/agent/tool-error-remediation.ts +72 -0
  23. package/src/agent/tool-file-safety.ts +1050 -0
  24. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  25. package/src/agent/tools/channel-reply.ts +15 -1
  26. package/src/agent/tools/channel-send.ts +17 -1
  27. package/src/agent/tools/ddg.ts +16 -2
  28. package/src/agent/tools/post-github-review.ts +199 -0
  29. package/src/agent/tools/spawn-subagent.ts +21 -18
  30. package/src/agent/tools/webfetch/fetch.ts +143 -183
  31. package/src/agent/tools/webfetch/tool.ts +2 -3
  32. package/src/agent/tools/websearch.ts +23 -2
  33. package/src/agent/tools-without-local-file-operands.ts +27 -0
  34. package/src/agent/turn-runner.ts +109 -15
  35. package/src/bundled-plugins/backup/index.ts +2 -1
  36. package/src/bundled-plugins/backup/runner.ts +2 -1
  37. package/src/bundled-plugins/doc-render/render.ts +93 -12
  38. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  39. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  40. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  41. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  42. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  43. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  44. package/src/bundled-plugins/memory/README.md +23 -11
  45. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  46. package/src/bundled-plugins/memory/citations.ts +22 -9
  47. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  48. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  49. package/src/bundled-plugins/memory/index.ts +0 -4
  50. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  51. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  52. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  53. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  54. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  55. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  56. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  57. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  58. package/src/bundled-plugins/reviewer/index.ts +2 -2
  59. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  60. package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
  61. package/src/bundled-plugins/scout/scout.ts +8 -0
  62. package/src/bundled-plugins/security/index.ts +4 -4
  63. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  64. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  65. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  66. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  67. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  68. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  69. package/src/channels/adapters/discord-bot.ts +91 -10
  70. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  71. package/src/channels/adapters/discord-id.ts +4 -0
  72. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  73. package/src/channels/adapters/discord.ts +57 -7
  74. package/src/channels/adapters/github/auth-app.ts +41 -12
  75. package/src/channels/adapters/github/index.ts +23 -11
  76. package/src/channels/adapters/github/review-submitter.ts +302 -0
  77. package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
  78. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  79. package/src/channels/adapters/kakaotalk-typing.ts +127 -0
  80. package/src/channels/adapters/kakaotalk.ts +19 -0
  81. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  82. package/src/channels/adapters/slack-bot.ts +19 -8
  83. package/src/channels/adapters/slack-classify.ts +21 -2
  84. package/src/channels/adapters/slack.ts +59 -7
  85. package/src/channels/adapters/telegram-bot.ts +18 -5
  86. package/src/channels/adapters/webex-bot.ts +8 -3
  87. package/src/channels/adapters/webex.ts +8 -3
  88. package/src/channels/fetch-attachment.ts +43 -0
  89. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  90. package/src/channels/github-token-bridge.ts +10 -3
  91. package/src/channels/manager.ts +9 -0
  92. package/src/channels/router.ts +568 -12
  93. package/src/channels/types.ts +28 -1
  94. package/src/cli/channel.ts +1 -1
  95. package/src/cli/init.ts +1 -1
  96. package/src/cli/model.ts +57 -7
  97. package/src/compose/stop.ts +17 -5
  98. package/src/config/config.ts +6 -6
  99. package/src/config/models-mutation.ts +13 -1
  100. package/src/config/providers.ts +176 -0
  101. package/src/container/start.ts +49 -10
  102. package/src/doctor/checks.ts +3 -1
  103. package/src/doctor/commit.ts +2 -1
  104. package/src/doctor/file-ownership.ts +52 -0
  105. package/src/dreams/git.ts +2 -1
  106. package/src/git/hookless.ts +5 -0
  107. package/src/git/reconcile-ignored.ts +18 -5
  108. package/src/git/secret-history.ts +371 -0
  109. package/src/git/system-commit.ts +12 -6
  110. package/src/init/dockerfile.ts +86 -5
  111. package/src/init/index.ts +17 -5
  112. package/src/init/models-dev.ts +4 -0
  113. package/src/init/validate-api-key.ts +2 -0
  114. package/src/mcp/tools.ts +16 -3
  115. package/src/permissions/builtins.ts +3 -1
  116. package/src/plugin/context.ts +2 -0
  117. package/src/plugin/index.ts +1 -0
  118. package/src/plugin/manager.ts +4 -0
  119. package/src/plugin/types.ts +21 -0
  120. package/src/run/index.ts +40 -0
  121. package/src/run/llm-fetch-observer.ts +188 -13
  122. package/src/sandbox/build.ts +37 -15
  123. package/src/sandbox/canonical-secrets.ts +18 -0
  124. package/src/sandbox/env-exposure.ts +80 -0
  125. package/src/sandbox/errors.ts +13 -6
  126. package/src/sandbox/hidden-paths.ts +102 -44
  127. package/src/sandbox/index.ts +22 -4
  128. package/src/sandbox/package-install.ts +3 -27
  129. package/src/sandbox/policy.ts +11 -25
  130. package/src/sandbox/privileged-runtime.ts +255 -0
  131. package/src/sandbox/session-tmp.ts +8 -2
  132. package/src/sandbox/writable-zones.ts +204 -140
  133. package/src/secrets/index.ts +8 -0
  134. package/src/secrets/refresh-provider-oauth.ts +128 -0
  135. package/src/server/command-runner.ts +48 -4
  136. package/src/server/index.ts +4 -0
  137. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  138. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  139. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  140. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  141. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  142. package/src/skills/typeclaw-config/SKILL.md +5 -5
  143. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  144. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  145. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  146. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  147. package/typeclaw.schema.json +20 -0
@@ -24,6 +24,7 @@ import { createGithubReactionCallback, createGithubRemoveReactionCallback } from
24
24
  import { reconcileOpenPrs } from './reconcile-open-prs'
25
25
  import { createRecoveredGuidLog, recoverFailedGithubDeliveries } from './recover-failed-deliveries'
26
26
  import { createGithubReviewStateResolver } from './review-state'
27
+ import { createGithubReviewSubmitter } from './review-submitter'
27
28
  import { createGithubReviewThreadResolver } from './review-thread-resolver'
28
29
  import { createTeamMembershipChecker } from './team-membership'
29
30
  import { deregisterGithubWebhooks, registerGithubWebhooks, type WebhookRegistrationResult } from './webhook-register'
@@ -169,6 +170,11 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
169
170
  approve: () => options.configRef().review.approve,
170
171
  fetchImpl,
171
172
  })
173
+ const reviewSubmitter = createGithubReviewSubmitter({
174
+ token: authToken,
175
+ allowApprove: () => options.configRef().review.approve,
176
+ fetchImpl,
177
+ })
172
178
  const channelNameResolver = createGithubChannelNameResolver({ token: authToken, fetchImpl })
173
179
  // GitHub addresses by `@login`, not the numeric id, so `username` carries
174
180
  // the login the model should type; the id is kept for completeness.
@@ -227,6 +233,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
227
233
  options.router.registerSelfIdentity('github', selfIdentityResolver)
228
234
  options.router.registerReviewThreadResolver('github', reviewThreadResolver)
229
235
  options.router.registerReviewStateResolver('github', reviewStateResolver)
236
+ options.router.registerReviewSubmitter('github', reviewSubmitter)
230
237
  options.router.registerFetchAttachment('github', fetchAttachment)
231
238
  try {
232
239
  server = (options.httpListenImpl ?? listenWithBun)(options.configRef().webhookPort, handler)
@@ -243,6 +250,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
243
250
  options.router.unregisterSelfIdentity('github', selfIdentityResolver)
244
251
  options.router.unregisterReviewThreadResolver('github', reviewThreadResolver)
245
252
  options.router.unregisterReviewStateResolver('github', reviewStateResolver)
253
+ options.router.unregisterReviewSubmitter('github', reviewSubmitter)
246
254
  options.router.unregisterFetchAttachment('github', fetchAttachment)
247
255
  await auth.dispose()
248
256
  delete process.env.GH_TOKEN
@@ -284,17 +292,20 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
284
292
  // would mint an installation-wide token for any repo the App is installed
285
293
  // on — a cross-tenant leak under a multi-owner App. Enforced here, not in
286
294
  // the parser, because this adapter is the authority that owns repos[].
287
- unregisterTokenBridge = options.githubTokenBridge.registerResolver((repoSlug) => {
288
- const allowed = new Set((options.configRef().repos ?? []).map(canonicalRepoSlug))
289
- if (!allowed.has(canonicalRepoSlug(repoSlug))) {
290
- throw new Error(
291
- `repo \`${repoSlug}\` is not in this agent's configured \`channels.github.repos[]\`; ` +
292
- 'refusing to mint a GitHub App token for it. Target a configured repo, ' +
293
- 'or add it to `repos[]` if the agent is meant to operate there.',
294
- )
295
- }
296
- return auth.token({ repoSlug })
297
- })
295
+ unregisterTokenBridge = options.githubTokenBridge.registerResolver(
296
+ (repoSlug) => {
297
+ const allowed = new Set((options.configRef().repos ?? []).map(canonicalRepoSlug))
298
+ if (!allowed.has(canonicalRepoSlug(repoSlug))) {
299
+ throw new Error(
300
+ `repo \`${repoSlug}\` is not in this agent's configured \`channels.github.repos[]\`; ` +
301
+ 'refusing to mint a GitHub App token for it. Target a configured repo, ' +
302
+ 'or add it to `repos[]` if the agent is meant to operate there.',
303
+ )
304
+ }
305
+ return auth.token({ repoSlug })
306
+ },
307
+ () => selfLogin,
308
+ )
298
309
  }
299
310
  logger.info(`[github] webhook listening on port ${options.configRef().webhookPort} as @${self.login}`)
300
311
  // Best-effort: App-only preflight that compares the installation's granted
@@ -417,6 +428,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
417
428
  options.router.unregisterSelfIdentity('github', selfIdentityResolver)
418
429
  options.router.unregisterReviewThreadResolver('github', reviewThreadResolver)
419
430
  options.router.unregisterReviewStateResolver('github', reviewStateResolver)
431
+ options.router.unregisterReviewSubmitter('github', reviewSubmitter)
420
432
  options.router.unregisterFetchAttachment('github', fetchAttachment)
421
433
  await server?.stop()
422
434
  // Detach hooks AFTER closing the listener so any in-flight deliveries
@@ -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 }>
@@ -15,6 +15,14 @@ export function kakaoWorkspaceForType(kind: KakaoChatKind): KakaoWorkspace {
15
15
  export type KakaoChatLookupValue = {
16
16
  workspace: KakaoWorkspace
17
17
  isDm: boolean
18
+ // True while the entry is a placeholder from `ingestProvisional` (a chat seen
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 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.
25
+ provisional: boolean
18
26
  }
19
27
 
20
28
  export type KakaoChannelResolver = {
@@ -43,6 +51,7 @@ type Entry = {
43
51
  isDm: boolean
44
52
  chatName: string | null
45
53
  expiresAt: number
54
+ provisional: boolean
46
55
  }
47
56
 
48
57
  export function createKakaoChannelResolver(options: KakaoChannelResolverOptions): KakaoChannelResolver {
@@ -81,6 +90,7 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
81
90
  isDm: kind === 'dm',
82
91
  chatName: chat.title ?? chat.display_name,
83
92
  expiresAt,
93
+ provisional: false,
84
94
  })
85
95
  }
86
96
 
@@ -102,7 +112,7 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
102
112
  const lookupChat = (chatId: string): KakaoChatLookupValue | null => {
103
113
  const entry = cache.get(chatId)
104
114
  if (entry === undefined || entry.expiresAt <= now()) return null
105
- return { workspace: entry.workspace, isDm: entry.isDm }
115
+ return { workspace: entry.workspace, isDm: entry.isDm, provisional: entry.provisional }
106
116
  }
107
117
 
108
118
  const ingestProvisional = (chatId: string): void => {
@@ -113,6 +123,7 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
113
123
  isDm: false,
114
124
  chatName: null,
115
125
  expiresAt: now() + ttlMs,
126
+ provisional: true,
116
127
  })
117
128
  }
118
129
 
@@ -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(
@@ -0,0 +1,127 @@
1
+ import type { KakaoTypingResult } from 'agent-messenger/kakaotalk'
2
+
3
+ import type { TypingCallback } from '@/channels/types'
4
+
5
+ import { describeError } from './describe-error'
6
+
7
+ export type KakaoTypingLogger = {
8
+ info: (msg: string) => void
9
+ warn: (msg: string) => void
10
+ error: (msg: string) => void
11
+ }
12
+
13
+ // Emits the LOCO ACTION packet directly from the sub-device session via
14
+ // `KakaoTalkClient.sendTyping` (agent-messenger#302). `type=1` is the value the
15
+ // official app uses for the animated "…" composing indicator; the SDK omits
16
+ // `linkId` unless it's an OpenChat room.
17
+ export type KakaoTypingSender = (chatId: string, opts?: { linkId?: string }) => Promise<KakaoTypingResult>
18
+
19
+ export type KakaoTypingCallbackHandle = {
20
+ callback: TypingCallback
21
+ // Invalidate every in-flight/queued pulse. Called on adapter stop so a pulse
22
+ // already accepted into a per-chat queue cannot reach the wire after teardown.
23
+ reset: () => void
24
+ }
25
+
26
+ // KakaoTalk auto-expires the composing indicator ~5s after the last ACTION
27
+ // packet. The router paces the refresh via a heartbeat the adapter registers
28
+ // (setTypingHeartbeatInterval), so this callback holds no timer of its own.
29
+ // 4000ms sits ~20% below the ~5s expiry so a replacement packet lands before
30
+ // expiry even with scheduler/network jitter (a 5000ms interval has no margin).
31
+ export const KAKAO_TYPING_HEARTBEAT_MS = 4000
32
+
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.
45
+ export type KakaoTypingChatClass = 'send' | 'skip-open' | 'skip-unresolved'
46
+
47
+ export function kakaoTypingClassFromLookup(
48
+ lookup: { workspace: string; provisional: boolean } | null,
49
+ ): KakaoTypingChatClass {
50
+ if (lookup === null) return 'skip-unresolved'
51
+ if (lookup.workspace === '@kakao-open') return 'skip-open'
52
+ return 'send'
53
+ }
54
+
55
+ export function createKakaoTypingCallback(deps: {
56
+ logger: KakaoTypingLogger
57
+ sendTyping: KakaoTypingSender
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.
62
+ classifyChat: (chatId: string) => KakaoTypingChatClass
63
+ formatChannelTag?: (workspace: string, chat: string) => Promise<string>
64
+ }): KakaoTypingCallbackHandle {
65
+ const { logger, sendTyping, classifyChat, formatChannelTag } = deps
66
+ // Per-chat FIFO mirrors the webex/slack pattern: chaining each request through
67
+ // the per-chat tail keeps on-the-wire order matching enqueue order even under
68
+ // network jitter, so a slow send can't reorder behind a later tick.
69
+ const queues = new Map<string, Promise<void>>()
70
+ // Per-chat generation token, independent of any timer. A pulse captures the
71
+ // chat's generation when it's accepted and re-checks it immediately before
72
+ // sending; 'stop' and `reset` delete the generation, so a pulse already queued
73
+ // behind an in-flight send is dropped instead of raising the indicator after
74
+ // the turn (or the adapter) has stopped.
75
+ const activeGeneration = new Map<string, number>()
76
+ const openChatSkipLogged = new Set<string>()
77
+ let generationCounter = 0
78
+
79
+ const callback: TypingCallback = async (target) => {
80
+ if (target.adapter !== 'kakaotalk') return
81
+ // No stop API: the indicator auto-expires ~5s after the last packet and a
82
+ // delivered message clears it client-side, so 'stop' sends no packet. It
83
+ // must still invalidate any queued pulse for this chat.
84
+ if (target.phase !== 'tick') {
85
+ activeGeneration.delete(target.chat)
86
+ return
87
+ }
88
+ const chatClass = classifyChat(target.chat)
89
+ if (chatClass !== 'send') {
90
+ if (chatClass === 'skip-open' && !openChatSkipLogged.has(target.chat)) {
91
+ openChatSkipLogged.add(target.chat)
92
+ logger.info(`[kakaotalk:typing] skipped chat=${target.chat} reason=open_chat_link_id_unsupported`)
93
+ }
94
+ return
95
+ }
96
+
97
+ if (!activeGeneration.has(target.chat)) activeGeneration.set(target.chat, ++generationCounter)
98
+ const generation = activeGeneration.get(target.chat)
99
+ const prev = queues.get(target.chat) ?? Promise.resolve()
100
+ const next = prev
101
+ .catch(() => {})
102
+ .then(async () => {
103
+ if (activeGeneration.get(target.chat) !== generation) return
104
+ const result = await sendTyping(target.chat)
105
+ if (!result.success) {
106
+ throw new Error(`kakaotalk ACTION rejected: status_code=${result.status_code}`)
107
+ }
108
+ })
109
+ .catch(async (err: unknown) => {
110
+ const tag = formatChannelTag
111
+ ? await formatChannelTag(target.workspace, target.chat).catch(() => `chat=${target.chat}`)
112
+ : `chat=${target.chat}`
113
+ logger.warn(`[kakaotalk:typing] ${tag} phase=${target.phase} failed: ${describeError(err)}`)
114
+ })
115
+ queues.set(target.chat, next)
116
+ void next.finally(() => {
117
+ if (queues.get(target.chat) === next) queues.delete(target.chat)
118
+ })
119
+ await next
120
+ }
121
+
122
+ const reset = (): void => {
123
+ activeGeneration.clear()
124
+ }
125
+
126
+ return { callback, reset }
127
+ }
@@ -15,6 +15,7 @@ import {
15
15
  type KakaoTalkListenerEventMap,
16
16
  type KakaoTalkPushEmoticonEvent,
17
17
  type KakaoTalkPushMessageEvent,
18
+ type KakaoTypingResult,
18
19
  } from 'agent-messenger/kakaotalk'
19
20
  import type { KakaoAccountCredentials, KakaoConfig, PendingLoginState } from 'agent-messenger/kakaotalk'
20
21
 
@@ -45,6 +46,7 @@ import { classifyInbound, type InboundDropReason } from './kakaotalk-classify'
45
46
  import { createFetchAttachmentCallback } from './kakaotalk-fetch-attachment'
46
47
  import { toKakaoPlainText } from './kakaotalk-format'
47
48
  import { createKakaoMembershipResolver } from './kakaotalk-membership'
49
+ import { createKakaoTypingCallback, kakaoTypingClassFromLookup, KAKAO_TYPING_HEARTBEAT_MS } from './kakaotalk-typing'
48
50
 
49
51
  // Structural duck-type of the upstream KakaoTalkClient class. The upstream
50
52
  // type is a class with private fields, and TypeScript treats those
@@ -68,6 +70,7 @@ export interface KakaoTalkClient {
68
70
  ): Promise<KakaoSendResult>
69
71
  sendAttachment(chatId: string, attachments: ReadonlyArray<AttachmentInput>): Promise<KakaoSendResult>
70
72
  markRead(chatId: string, logId: string, opts?: { linkId?: string }): Promise<KakaoMarkReadResult>
73
+ sendTyping(chatId: string, opts?: { linkId?: string }): Promise<KakaoTypingResult>
71
74
  getProfile(): Promise<KakaoProfile>
72
75
  getMembers(chatId: string): Promise<KakaoMember[]>
73
76
  lookupAuthorName(chatId: string, authorId: number): string | null
@@ -403,6 +406,13 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
403
406
  formatChannelTag,
404
407
  })
405
408
 
409
+ const typing = createKakaoTypingCallback({
410
+ logger,
411
+ sendTyping: (chatId, opts) => client.sendTyping(chatId, opts),
412
+ classifyChat: (chatId) => kakaoTypingClassFromLookup(channelResolver.lookupChat(chatId)),
413
+ formatChannelTag,
414
+ })
415
+
406
416
  const fetchAttachmentCallback = createFetchAttachmentCallback({ logger })
407
417
 
408
418
  const handleMessageEvent = async (event: KakaoTalkPushMessageEvent): Promise<void> => {
@@ -669,6 +679,12 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
669
679
  // but outboundCallback would still send via a dead client). Stop()
670
680
  // unregisters in the inverse order.
671
681
  options.router.registerOutbound('kakaotalk', outboundCallback)
682
+ options.router.registerTyping('kakaotalk', typing.callback)
683
+ options.router.setTypingCapability('kakaotalk', true)
684
+ // KakaoTalk expires the indicator ~5s after the last packet, faster than
685
+ // the default 8s heartbeat, so the router paces our refresh at 4s and the
686
+ // callback holds no timer of its own.
687
+ options.router.setTypingHeartbeatInterval('kakaotalk', KAKAO_TYPING_HEARTBEAT_MS)
672
688
  options.router.registerChannelNameResolver('kakaotalk', channelResolver.resolve)
673
689
  options.router.registerHistory('kakaotalk', historyCallback)
674
690
  options.router.registerFetchAttachment('kakaotalk', fetchAttachmentCallback)
@@ -679,6 +695,9 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
679
695
  if (!started) return
680
696
  started = false
681
697
  options.router.unregisterOutbound('kakaotalk', outboundCallback)
698
+ options.router.unregisterTyping('kakaotalk', typing.callback)
699
+ options.router.setTypingCapability('kakaotalk', false)
700
+ typing.reset()
682
701
  options.router.unregisterChannelNameResolver('kakaotalk', channelResolver.resolve)
683
702
  options.router.unregisterHistory('kakaotalk', historyCallback)
684
703
  options.router.unregisterFetchAttachment('kakaotalk', fetchAttachmentCallback)