typeclaw 0.44.0 → 0.45.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 (45) hide show
  1. package/package.json +7 -6
  2. package/src/agent/index.ts +42 -3
  3. package/src/agent/loop-guard.ts +208 -10
  4. package/src/agent/model-fallback.ts +59 -40
  5. package/src/agent/multimodal/look-at.ts +2 -1
  6. package/src/agent/plugin-tools.ts +59 -5
  7. package/src/agent/provider-error.ts +78 -18
  8. package/src/agent/retry-same-ref.ts +205 -0
  9. package/src/agent/subagents.ts +34 -4
  10. package/src/agent/tools/channel-edit.ts +144 -0
  11. package/src/agent/tools/channel-fetch-attachment.ts +6 -5
  12. package/src/agent/tools/channel-reply.ts +15 -1
  13. package/src/agent/tools/channel-send.ts +17 -1
  14. package/src/agent/tools/curl-impersonate.ts +40 -1
  15. package/src/agent/tools/webfetch/fetch.ts +86 -3
  16. package/src/agent/tools/webfetch/tool.ts +26 -3
  17. package/src/agent/tools/webfetch/types.ts +8 -0
  18. package/src/agent/turn-runner.ts +79 -36
  19. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
  20. package/src/bundled-plugins/reviewer/skills/code-review.ts +27 -2
  21. package/src/channels/adapters/discord-bot-edit.ts +49 -0
  22. package/src/channels/adapters/discord-bot.ts +30 -4
  23. package/src/channels/adapters/discord-edit.ts +51 -0
  24. package/src/channels/adapters/discord.ts +4 -0
  25. package/src/channels/adapters/kakaotalk-channel-resolver.ts +10 -1
  26. package/src/channels/adapters/kakaotalk-typing.ts +125 -0
  27. package/src/channels/adapters/kakaotalk.ts +19 -0
  28. package/src/channels/adapters/slack-bot-edit.ts +58 -0
  29. package/src/channels/adapters/slack-bot.ts +18 -6
  30. package/src/channels/adapters/slack-edit.ts +47 -0
  31. package/src/channels/adapters/slack.ts +5 -0
  32. package/src/channels/adapters/teams-edit.ts +61 -0
  33. package/src/channels/adapters/teams.ts +4 -0
  34. package/src/channels/adapters/telegram-bot-edit.ts +51 -0
  35. package/src/channels/adapters/telegram-bot.ts +5 -0
  36. package/src/channels/adapters/webex-bot.ts +5 -0
  37. package/src/channels/adapters/webex-edit.ts +47 -0
  38. package/src/channels/adapters/webex.ts +5 -0
  39. package/src/channels/continuation-willingness.ts +227 -35
  40. package/src/channels/router.ts +500 -20
  41. package/src/channels/schema.ts +24 -0
  42. package/src/channels/types.ts +36 -0
  43. package/src/run/llm-fetch-observer.ts +147 -9
  44. package/src/server/command-runner.ts +2 -1
  45. package/src/server/index.ts +2 -1
@@ -1,7 +1,8 @@
1
1
  import type { ModelRef } from '@/config/providers'
2
2
 
3
3
  import type { AgentSession } from './index'
4
- import { detectProviderError, subscribeProviderErrors } from './provider-error'
4
+ import { detectProviderError, isRetryableSameRef, subscribeProviderErrors } from './provider-error'
5
+ import { RETRIES_PER_REF, retryTurnAfterCompletedToolResult, retryTurnOnPersistentSession } from './retry-same-ref'
5
6
  import { modelThrottleCircuit, type ThrottleCircuit } from './throttle-circuit'
6
7
 
7
8
  export type PersistentTurnAttempt = {
@@ -33,6 +34,9 @@ export async function promptPersistentTurnWithFallback(opts: {
33
34
  circuit?: ThrottleCircuit
34
35
  skipProviderErrorSubscription?: boolean
35
36
  detectSoftErrorFromLeaf?: boolean
37
+ authorizeRetryAfterCompletedToolResult?: () => boolean
38
+ retryRandom?: () => number
39
+ onRetryBackoffStart?: () => void
36
40
  beforeAttempt?: (ref: ModelRef) => void
37
41
  onAttemptFailed?: (attempt: PersistentTurnAttempt) => void
38
42
  }): Promise<PersistentTurnResult> {
@@ -73,44 +77,68 @@ export async function promptPersistentTurnWithFallback(opts: {
73
77
  if (softError === undefined) softError = new Error(err.message)
74
78
  })
75
79
  try {
76
- try {
77
- await opts.session.prompt(opts.text)
78
- } catch (err) {
79
- const error = err instanceof Error ? err : new Error(String(err))
80
- const attempt: PersistentTurnAttempt = { ref, outcome: 'hard', errorMessage: error.message }
81
- attempts.push(attempt)
82
- lastError = error
83
- if (opts.shouldFailover(error)) circuit.recordThrottle({ profile: opts.profile, ref })
84
- if (isLast || !canAdvance(error, activity, opts.shouldFailover)) throw error
85
- opts.onAttemptFailed?.(attempt)
86
- continue
87
- }
88
- if (softError !== undefined) {
89
- const attempt: PersistentTurnAttempt = { ref, outcome: 'soft', errorMessage: softError.message }
90
- attempts.push(attempt)
91
- lastError = softError
92
- if (opts.shouldFailover(softError)) circuit.recordThrottle({ profile: opts.profile, ref })
93
- if (isLast || !canAdvance(softError, activity, opts.shouldFailover)) {
94
- return { success: false, refUsed: ref, attempts, lastError }
80
+ // Same-ref retry loop: replay this ref on a transient failure before
81
+ // advancing the chain. `retry === 0` is the first, prompt()-driven attempt;
82
+ // later iterations resume via agent.continue() (no user-message re-append).
83
+ let outcome: AttemptOutcome | undefined
84
+ let retryAfterCompletedToolResult = false
85
+ for (let retry = 0; ; retry++) {
86
+ softError = undefined
87
+ let outcomeThisAttempt: AttemptOutcome | undefined
88
+ try {
89
+ if (retry === 0) {
90
+ await opts.session.prompt(opts.text)
91
+ } else {
92
+ const retried = retryAfterCompletedToolResult
93
+ ? await retryTurnAfterCompletedToolResult(opts.session, {
94
+ attempt: retry - 1,
95
+ authorize: () => opts.authorizeRetryAfterCompletedToolResult?.() === true,
96
+ ...(opts.retryRandom !== undefined ? { random: opts.retryRandom } : {}),
97
+ ...(opts.onRetryBackoffStart !== undefined ? { onBackoffStart: opts.onRetryBackoffStart } : {}),
98
+ })
99
+ : await retryTurnOnPersistentSession(opts.session, { attempt: retry - 1 })
100
+ // The safe continue-recipe couldn't apply: keep the PREVIOUS failure
101
+ // outcome (never cleared) and let it drive the advance/return below.
102
+ if (!retried) break
103
+ }
104
+ outcomeThisAttempt = classifySoftOutcome(softError, opts)
105
+ } catch (err) {
106
+ outcomeThisAttempt = { kind: 'hard', error: err instanceof Error ? err : new Error(String(err)) }
95
107
  }
96
- opts.onAttemptFailed?.(attempt)
97
- continue
108
+ outcome = outcomeThisAttempt
109
+ if (outcome === undefined) break
110
+ // Retry within budget only when the failure is same-ref retryable and
111
+ // either no visible/tool activity occurred, or the caller explicitly
112
+ // authorizes the strict post-tool-result resume recipe.
113
+ const retryableWithinBudget = retry < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message)
114
+ const mayRetryWithoutActivity = !activity.producedAssistantOutput && !activity.startedToolExecution
115
+ retryAfterCompletedToolResult =
116
+ retryableWithinBudget &&
117
+ activity.startedToolExecution &&
118
+ opts.authorizeRetryAfterCompletedToolResult?.() === true
119
+ const mayRetry = retryableWithinBudget && (mayRetryWithoutActivity || retryAfterCompletedToolResult)
120
+ if (!mayRetry) break
98
121
  }
99
- const leafSoftError = opts.detectSoftErrorFromLeaf ? detectLeafSoftError(opts.session) : undefined
100
- if (leafSoftError !== undefined) {
101
- const attempt: PersistentTurnAttempt = { ref, outcome: 'soft', errorMessage: leafSoftError.message }
102
- attempts.push(attempt)
103
- lastError = leafSoftError
104
- if (opts.shouldFailover(leafSoftError)) circuit.recordThrottle({ profile: opts.profile, ref })
105
- if (isLast || !canAdvance(leafSoftError, activity, opts.shouldFailover)) {
106
- return { success: false, refUsed: ref, attempts, lastError }
107
- }
108
- opts.onAttemptFailed?.(attempt)
109
- continue
122
+
123
+ if (outcome === undefined) {
124
+ attempts.push({ ref, outcome: 'success' })
125
+ circuit.recordSuccess({ profile: opts.profile, ref })
126
+ return { success: true, refUsed: ref, attempts }
127
+ }
128
+
129
+ // Ref abandoned after exhausting same-ref retries. Record throttle ONCE
130
+ // here (not per internal retry) so a single turn can't self-trip the
131
+ // circuit breaker.
132
+ const attempt: PersistentTurnAttempt = { ref, outcome: outcome.kind, errorMessage: outcome.error.message }
133
+ attempts.push(attempt)
134
+ lastError = outcome.error
135
+ if (opts.shouldFailover(outcome.error)) circuit.recordThrottle({ profile: opts.profile, ref })
136
+ if (isLast || !canAdvance(outcome.error, activity, opts.shouldFailover)) {
137
+ if (outcome.kind === 'hard') throw outcome.error
138
+ return { success: false, refUsed: ref, attempts, lastError }
110
139
  }
111
- attempts.push({ ref, outcome: 'success' })
112
- circuit.recordSuccess({ profile: opts.profile, ref })
113
- return { success: true, refUsed: ref, attempts }
140
+ opts.onAttemptFailed?.(attempt)
141
+ continue
114
142
  } finally {
115
143
  unsubProvider()
116
144
  unsubActivity()
@@ -119,6 +147,21 @@ export async function promptPersistentTurnWithFallback(opts: {
119
147
  return { success: false, refUsed: opts.refs[opts.refs.length - 1]!, attempts, lastError }
120
148
  }
121
149
 
150
+ type AttemptOutcome = { kind: 'hard' | 'soft'; error: Error }
151
+
152
+ // Classify a completed (non-throwing) attempt: a captured soft error, else a
153
+ // leaf soft error (subagent path), else success (undefined). Mirrors the two
154
+ // soft-error sources the loop handled inline before the retry refactor.
155
+ function classifySoftOutcome(
156
+ softError: Error | undefined,
157
+ opts: { session: AgentSession; detectSoftErrorFromLeaf?: boolean },
158
+ ): AttemptOutcome | undefined {
159
+ if (softError !== undefined) return { kind: 'soft', error: softError }
160
+ const leafSoftError = opts.detectSoftErrorFromLeaf ? detectLeafSoftError(opts.session) : undefined
161
+ if (leafSoftError !== undefined) return { kind: 'soft', error: leafSoftError }
162
+ return undefined
163
+ }
164
+
122
165
  function canAdvance(error: Error, activity: AttemptActivity, shouldFailover: (err: Error) => boolean): boolean {
123
166
  return shouldFailover(error) && !activity.producedAssistantOutput && !activity.startedToolExecution
124
167
  }
@@ -15,10 +15,12 @@ already downloaded, so the CLI is ready to use out of the box.
15
15
 
16
16
  ## Human-in-the-loop via the dashboard
17
17
 
18
- You run inside a Docker container with no display, no clipboard, and no way to
19
- hand the keyboard over directly. The **dashboard is your only path to bring a
20
- human into a browser session** — it streams every session's live viewport,
21
- console, and command activity to a web UI the user opens on their host machine.
18
+ You run inside a Docker container. Chrome renders to the in-container virtual X
19
+ display (Xvfb, `DISPLAY=:99`), but there is no human-accessible display or
20
+ clipboard and no way to hand the keyboard over directly. The **dashboard is your
21
+ only path to bring a human into a browser session** — it streams every session's
22
+ live viewport, console, and command activity to a web UI the user opens on their
23
+ host machine.
22
24
 
23
25
  **Start the dashboard _before_ the step that needs a human, not after it fails.**
24
26
  The dashboard takes a moment to come up and the user needs time to open the URL.
@@ -91,13 +93,28 @@ you just want to show the user a single page or a captured state:
91
93
  Reserve the dashboard for cases that genuinely need live interaction or
92
94
  watching a multi-step flow unfold.
93
95
 
94
- ### Headless only
95
-
96
- Never pass `--headed` to any `agent-browser` command — the container has no X
97
- server or `$DISPLAY`, and a headed launch fails with `Missing X server or
98
- $DISPLAY / The platform failed to initialize.` The dashboard is the substitute
99
- for a headed browser. Use the default headless mode for everything, including
100
- dogfooding and Electron flows.
96
+ ### Headed vs headless
97
+
98
+ By default the container ships a virtual X server: the entrypoint spawns Xvfb
99
+ and exports `DISPLAY=:99`, so `--headed` (or `AGENT_BROWSER_HEADED=1`) launches a
100
+ real headed Chrome. Headless is fine for ordinary automation — dogfooding, form
101
+ filling, Electron flows, capturing a page you can already reach.
102
+
103
+ Prefer `--headed` when a site is guarded by a WAF/anti-bot layer (Akamai Bot
104
+ Manager, Cloudflare, PerimeterX — common on large e-commerce and portal sites).
105
+ Chrome's `--headless`/`--headless=new` modes are fingerprinted by these stacks
106
+ via signals no UA spoof can patch, so a headless launch draws a `403 Access
107
+ Denied` / CAPTCHA where a headed one under Xvfb passes. This is the whole reason
108
+ the container runs Xvfb. For a hard case, combine headed mode with a persistent
109
+ `--profile` and warm the session (land on the homepage, then navigate
110
+ organically) so the site's trust cookie is issued before you hit the target
111
+ page.
112
+
113
+ The one exception: if the agent folder sets `docker.file.xvfb: false`, there is
114
+ no `DISPLAY` and a headed launch fails with `Missing X server or $DISPLAY / The
115
+ platform failed to initialize.` In that configuration, stay headless and use the
116
+ dashboard for anything that needs a human. If a `--headed` command ever returns
117
+ that error, the toggle is off — fall back to headless rather than retrying.
101
118
 
102
119
  ## Start here
103
120
 
@@ -3,7 +3,7 @@ import type { LoadableSkill } from '@/plugin'
3
3
  export const CODE_REVIEW_SKILL_NAME = 'code-review'
4
4
 
5
5
  export const CODE_REVIEW_SKILL_DESCRIPTION =
6
- 'Review code: a pull request, a commit, a single file, or a module. Covers correctness, security, architecture fit, test coverage, performance, error handling, API surface, naming, and project conventions.'
6
+ 'Review code: a pull request, a commit, a single file, or a module. Covers correctness, security, architecture fit, test coverage, performance, error handling, API surface, naming, project conventions, and the PR title/body itself as a record — whether it captures the why behind each change for future readers.'
7
7
 
8
8
  export const CODE_REVIEW_SKILL_CONTENT = `# code-review
9
9
 
@@ -55,6 +55,26 @@ A finding without context is noise. Before forming findings:
55
55
  3. **Read the project's conventions.** \`AGENTS.md\`, \`CONTRIBUTING.md\`, \`CLAUDE.md\`, \`README.md\`, the test layout, the linter config. Deviation from established convention is a finding worth raising; following convention is not worth praising.
56
56
  4. **Read the tests.** Existing tests show what the project considers important to verify. New tests show what the author considers important to lock in. The gap between them is often where the bugs hide.
57
57
 
58
+ ## Review the PR title and body as an artifact, not just as context
59
+
60
+ Steps above use the PR title and body as *input* — the author's stated intent, which you check the code against. But the description is also a **deliverable in its own right, and it is part of your review scope.** Most harnesses only diff code and never review the prose; you are the one pass that can, so treat the title and body as a first-class review target alongside the diff.
61
+
62
+ Why this matters — the frame that decides your findings here:
63
+
64
+ - **A PR is a record, not a showcase.** Its dominant purpose is not to display the code or even to solicit code review — it is to **record the translation from the business need into the code change**: *why* this change became necessary, what business or product context forced it, what decision was made and what was rejected. The code shows *what* changed; the body is the only place *why* survives. When the why is absent, it is gone the moment the author forgets it.
65
+ - **The audience is the reviewer and future-self, who do NOT share the author's context.** The current reviewer, a teammate six months from now, or the author themselves later, all read this record under real cognitive load, missing the context that was obvious the day it was written. A good body exists to *lower that load*. Judge the body by whether a reader without the author's head can reconstruct why each change was made.
66
+ - **The concrete failure is a change whose context is silently dropped.** A large task drags in incidental side changes; the low-importance ones lose their rationale first, and later someone does redundant or wrong work because the record never explained the earlier decision (e.g. a field added in one PR with no note that it duplicates an existing one, so a later PR "fixes" a problem that was actually intentional). This is the highest-value thing to catch: a change in the diff that the body leaves **unexplained or unconnected to its reason**.
67
+
68
+ What to look for in the title and body:
69
+
70
+ 1. **Rationale for every meaningful change, not just the headline one.** The primary change is usually explained. The finding is the *secondary* change — a schema tweak, a config flip, a "while I was here" refactor, a new field — that appears in the diff with no corresponding why in the body. Anchor the finding to the diff hunk whose rationale is missing, and name what a future reader would fail to reconstruct.
71
+ 2. **Title accuracy and scope match.** Does the title name what the change actually does? Does the body's described scope match the diff — nothing significant in the diff that the body never mentions, and nothing promised in the body that the diff never delivers? A title that says A while the diff also does B is a scope/record defect: the B change is now unfindable by anyone searching the history for it.
72
+ 3. **Meaning-unit separation.** When the diff bundles several unrelated logical changes under one description, the context for each is harder to recover and the record is degraded even if every line is correct. Flag it as a record problem — the fix may be to split the PR, or at minimum to give each logical unit its own explained section in the body — not as a code defect.
73
+ 4. **Decision and trade-off capture.** For a change that chose one approach over an obvious alternative, or that is a deliberate one-way door (schema, public API, migration), does the body record the decision and why? A silent irreversible decision is a record gap worth raising even when the code is correct.
74
+ 5. **Linked context integrity.** Referenced issues/tickets/prior PRs actually correspond to this change; a load-bearing claim in the body ("as decided in #123") points where it says it does. A dangling or wrong reference breaks the record's chain.
75
+
76
+ Keep the anti-noise line from below firmly in view: **do not confuse restating the description with reviewing it.** Summarizing what the PR does back to the author is noise (see "What NOT to find"). The review work here is the *gap* — a change with no recorded reason, a title that misleads, a bundled scope that buries context, a decision left unexplained. Anchor these to the specific diff hunk or the quoted body passage; use \`location="general"\` only for a whole-description defect (e.g. an empty body on a non-trivial change) and say why in the \`<issue>\`. Calibrate severity to consequence, not to prose taste: an unexplained behavior-changing hunk or a title that hides a real change is a \`concern\` (a \`blocker\` when the missing context is what stops a future reader from avoiding a concrete mistake); a thin-but-adequate body is at most a \`nit\`. A body's writing quality is not the target — its function as a record is.
77
+
58
78
  ## What to look for
59
79
 
60
80
  Prioritize in this order:
@@ -77,8 +97,9 @@ Prioritize in this order:
77
97
  - **Settled convention objections.** If the project uses tabs, four-space indent, camelCase vs snake_case, etc., and the change matches, that is not a finding. Only the deviation is.
78
98
  - **Generic best-practice essays.** "Consider adding more tests" without naming a specific untested branch is noise. "Improve error handling" without pointing at a specific swallowed error is noise.
79
99
  - **Restating the code.** "This function reads the file and returns its contents" is not a finding.
80
- - **Restating the change description.** Summarizing what the PR does back to its author — "this PR adds caching to the user lookup" — is not a review. They wrote the description; they know.
100
+ - **Restating the change description.** Summarizing what the PR does back to its author — "this PR adds caching to the user lookup" — is not a review. They wrote the description; they know. (This forbids *echoing* the body, not *reviewing* it: judging whether the body records the why, matches the diff, and separates its meaning units is in scope — see "Review the PR title and body as an artifact". The line is echo vs. evaluate.)
81
101
  - **Already-acknowledged gaps.** A weakness the author already flagged with a \`TODO\`/\`FIXME\` in the diff, or named in the PR body as out of scope, is not a finding — they're already aware. Only raise it if you have new information: the gap is worse than they think, or it's a blocker they've mislabeled as deferrable. Say which.
102
+ - **Disproportionate theoretical corners on best-effort code.** Weigh every finding by \`(realistic probability of the input) × (cost of the bad outcome)\` against the cost of the fix. When the code is explicitly a **best-effort heuristic, approximation, or partial parser** — and says so, in a comment or the PR body, with a stated scope boundary — an edge case that lies OUTSIDE that boundary and cannot arise from realistic inputs is not a finding; it is scope the author already priced in. A guard that "should ideally handle every case in spec X" is being measured against the wrong bar: the bar is *the failure mode that actually occurs in this system's traffic*, not spec-completeness. Before raising such a corner, ask: can you construct a REALISTIC input (not a synthetic worst case) that triggers it, and is the bad outcome worse than the complexity the fix adds? If either answer is no, drop it — or, at most, note the boundary once and move on. Do NOT walk a partial implementation through progressively deeper theoretical inputs across re-reviews; a heuristic that is sound for real inputs and honest about its documented limits is DONE, and demanding it grow into a full parser to satisfy spec-completeness is exactly the noise this rule forbids. If you genuinely believe the stated scope boundary is wrong, that is ONE finding challenging the boundary itself (with a realistic triggering input as evidence) — not a standing series of ever-deeper corner reports.
82
103
 
83
104
  ## Severity hints specific to code
84
105
 
@@ -87,6 +108,8 @@ Prioritize in this order:
87
108
  - **nit** — Naming, micro-readability, suboptimal-but-correct code. Optional. The author can decline and you should not push back.
88
109
  - **praise** — Non-obvious good design: a tricky invariant carefully preserved, a test that catches a subtle regression, a name that captures the domain precisely. Rare on purpose.
89
110
 
111
+ Calibrate to consequence, not to spec-completeness. Severity is \`(realistic probability) × (impact)\`, weighed against the fix's cost — not "how far from ideal is this". On code that declares itself a best-effort heuristic with a documented scope boundary, an edge case outside that boundary that no realistic input reaches is not a \`blocker\` or a \`concern\`; it is out-of-scope by the author's stated design, and re-raising it (or a deeper variant of it) on a re-review is noise, not diligence. Escalate a corner case only when you can show a realistic input that hits it AND the outcome justifies the added complexity; otherwise leave it out or note the boundary once. See "Disproportionate theoretical corners on best-effort code" under "What NOT to find".
112
+
90
113
  ## Verdict mapping
91
114
 
92
115
  - **approve** — Zero blockers. Concerns are minor, isolated, or already discussed.
@@ -102,6 +125,8 @@ This includes payloads where the parent says the author **addressed your prior b
102
125
  - Return **approve** if the blockers that drove the prior \`request-changes\` are resolved (leftover nits do not block — \`approve\` with inline nits is correct).
103
126
  - Return **request-changes** if any blocker remains or a new one appeared.
104
127
 
128
+ A re-review is a decision, not a fresh hunt for something new to block on. If the author resolved your prior blockers, the default outcome is \`approve\` — do not manufacture a new \`request-changes\` by escalating into a deeper theoretical corner of the same best-effort code you already accepted the shape of. A "new blocker" on re-review must clear the same bar as any blocker: a realistic input triggers it and the impact justifies the fix. A strictly-deeper variant of an already-addressed edge case, on code that documents its scope boundary, is not a new blocker — it is the "disproportionate theoretical corners" noise the What-NOT-to-find rule forbids, and repeating it across pushes is how a re-review loop fails to converge. When the fix satisfies the boundary and the remaining corners are out of scope by design, say so in the \`<summary>\` and \`approve\`.
129
+
105
130
  **Account for resolved threads in the \`<summary>\`, not as \`praise\` findings.** A re-review tempts you to emit one \`praise\` finding per prior concern the author fixed — "Thread 123 is addressed", "Thread 456 is addressed". Do **not**. \`praise\` is reserved for *non-obvious good work*, and a routine "you fixed what I asked" is neither non-obvious nor a finding the parent should post inline (it strips \`praise\` from inline comments anyway, so these become dead weight). Instead, state the resolution accounting in one sentence in your \`<summary>\` — e.g. "Both prior blockers (the unfenced table scan and the backtick-wrap span) are resolved at head \`<sha>\`; one new concern below." Reserve actual \`<finding>\` entries for what still needs action: a prior blocker that is **only partially** fixed (\`blocker\`/\`concern\`, anchored to the line that's still wrong), a **regression the fix introduced** (\`blocker\`/\`concern\`), or a genuinely non-obvious fix worth a rare \`praise\`. A clean re-review where everything was addressed is an \`approve\` whose \`<summary>\` says so and whose \`<findings>\` is empty — not a wall of \`praise\` receipts.
106
131
  - **Do NOT return \`comment\` on a re-review.** \`comment\` is for ambiguous partial reviews with no accept/reject signal; a re-review is the opposite — it is precisely an accept/reject decision. A \`comment\` verdict here leaves the PR's \`REQUEST_CHANGES\` state stuck (a plain comment does not clear it on GitHub), which is the exact failure a re-review exists to resolve. The only escape hatch is the same one that always applies: if you genuinely cannot reach the diff or the prior context, return one \`blocker\` finding stating what you need and a \`comment\` verdict — but a reachable, reviewable re-review must end in \`approve\` or \`request-changes\`.
107
132
 
@@ -0,0 +1,49 @@
1
+ import type { DiscordBotClient } from 'agent-messenger/discordbot'
2
+
3
+ import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
+
5
+ export function createDiscordEditMessageCallback(deps: {
6
+ client: Pick<DiscordBotClient, 'editMessage'>
7
+ }): EditMessageCallback {
8
+ return async (req): Promise<EditMessageResult> => {
9
+ if (req.adapter !== 'discord-bot') {
10
+ return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
11
+ }
12
+ // A Discord thread is its own channel id, so a message posted into a thread
13
+ // must be PATCHed against the thread, not its parent — mirroring the
14
+ // `thread ?? chat` routing the send/message-get paths use. Editing against
15
+ // `chat` alone would 404 on any threaded message.
16
+ const channelId = req.thread ?? req.chat
17
+ try {
18
+ await deps.client.editMessage(channelId, req.messageId, req.text)
19
+ } catch (err) {
20
+ return { ok: false, error: describe(err), code: classifyEditError(err) }
21
+ }
22
+ return { ok: true }
23
+ }
24
+ }
25
+
26
+ // Discord only lets a bot edit its OWN messages: a PATCH on someone else's
27
+ // message returns 50005 (Cannot edit a message authored by another user),
28
+ // mapped to permission-denied. 10008/10003 are the gone-message/channel cases.
29
+ function classifyEditError(err: unknown): NonNullable<(EditMessageResult & { ok: false })['code']> {
30
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code: unknown }).code) : ''
31
+ switch (code) {
32
+ case '10003': // Unknown Channel
33
+ case '10008': // Unknown Message
34
+ case 'http_404':
35
+ return 'not-found'
36
+ case '50005': // Cannot edit a message authored by another user
37
+ case '50001': // Missing Access
38
+ case '50013': // Missing Permissions
39
+ case 'http_403':
40
+ case 'http_401':
41
+ return 'permission-denied'
42
+ default:
43
+ return 'not-found'
44
+ }
45
+ }
46
+
47
+ function describe(err: unknown): string {
48
+ return err instanceof Error ? err.message : String(err)
49
+ }
@@ -1,6 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises'
2
2
 
3
- import { DiscordBotClient, DiscordBotListener } from 'agent-messenger/discordbot'
3
+ import { DiscordBotClient, DiscordBotListener, type DiscordBotListenerOptions } from 'agent-messenger/discordbot'
4
4
  import {
5
5
  DiscordIntent,
6
6
  type DiscordFile,
@@ -48,6 +48,7 @@ import {
48
48
  type InboundDropReason,
49
49
  renderPlaceholder,
50
50
  } from './discord-bot-classify'
51
+ import { createDiscordEditMessageCallback } from './discord-bot-edit'
51
52
  import { convertDiscordTables } from './discord-bot-format'
52
53
  import { createDiscordReactionCallback, createDiscordRemoveReactionCallback } from './discord-bot-reactions'
53
54
  import { enrichDiscordMessageReferences } from './discord-bot-reference'
@@ -120,6 +121,8 @@ export type DiscordBotAdapterOptions = {
120
121
  // exact REST calls without monkey-patching globalThis.fetch. Production
121
122
  // callers leave it undefined to use the global fetch.
122
123
  fetchImpl?: typeof fetch
124
+ createClient?: () => DiscordBotClient
125
+ createListener?: (client: DiscordBotClient, options: DiscordBotListenerOptions) => DiscordBotListener
123
126
  }
124
127
 
125
128
  export type DiscordBotAdapter = {
@@ -1017,10 +1020,14 @@ export const DISCORD_SLASH_COMMAND_NAMES = SLASH_COMMAND_NAMES
1017
1020
 
1018
1021
  export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): DiscordBotAdapter {
1019
1022
  const logger = options.logger ?? consoleLogger
1020
- const client = new DiscordBotClient()
1023
+ const createClient = options.createClient ?? (() => new DiscordBotClient())
1024
+ const createListener =
1025
+ options.createListener ?? ((client, listenerOptions) => new DiscordBotListener(client, listenerOptions))
1026
+ const client = createClient()
1021
1027
  const fetchImpl = options.fetchImpl ?? fetch
1022
1028
  let listener: DiscordBotListener | null = null
1023
1029
  let botUserId: string | null = null
1030
+ let connected = false
1024
1031
  let started = false
1025
1032
  let inflightInbounds = 0
1026
1033
  let stopWaiters: Array<() => void> = []
@@ -1078,6 +1085,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1078
1085
 
1079
1086
  const reactionCallback = createDiscordReactionCallback({ client })
1080
1087
  const removeReactionCallback = createDiscordRemoveReactionCallback({ client })
1088
+ const editMessageCallback = createDiscordEditMessageCallback({ client })
1081
1089
 
1082
1090
  const interactionHandler = createInteractionHandler({
1083
1091
  router: options.router,
@@ -1176,8 +1184,9 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1176
1184
  throw err
1177
1185
  }
1178
1186
 
1179
- listener = new DiscordBotListener(client, { intents: DISCORD_BOT_INTENTS })
1187
+ listener = createListener(client, { intents: DISCORD_BOT_INTENTS })
1180
1188
  listener.on('connected', (info) => {
1189
+ connected = true
1181
1190
  botUserId = info.user.id
1182
1191
  logger.info(`[discord-bot] connected as ${info.user.username} (${info.user.id})`)
1183
1192
  // For bots, the gateway's user.id IS the application id — the same
@@ -1209,9 +1218,15 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1209
1218
  })
1210
1219
  })
1211
1220
  listener.on('disconnected', () => {
1221
+ connected = false
1212
1222
  logger.warn('[discord-bot] disconnected; SDK will reconnect with backoff')
1213
1223
  })
1214
1224
  listener.on('error', (err) => {
1225
+ // agent-messenger 2.30.0 emits only `error` (not `disconnected`)
1226
+ // when a terminal Gateway close stops the listener. Match that
1227
+ // distinct SDK error contract without treating transient transport
1228
+ // errors as disconnects.
1229
+ if (isTerminalGatewayClose(err)) connected = false
1215
1230
  logger.error(`[discord-bot] gateway error: ${describe(err)}`)
1216
1231
  })
1217
1232
  listener.on('message_create', (event) => {
@@ -1231,6 +1246,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1231
1246
  options.router.registerHistory('discord-bot', historyCallback)
1232
1247
  options.router.registerMessageGet('discord-bot', messageGetCallback)
1233
1248
  options.router.registerList('discord-bot', listCallback)
1249
+ options.router.registerEditMessage('discord-bot', editMessageCallback)
1234
1250
  options.router.registerFetchAttachment('discord-bot', fetchAttachmentCallback)
1235
1251
  options.router.registerMembership('discord-bot', membershipResolver)
1236
1252
 
@@ -1251,10 +1267,12 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1251
1267
  options.router.unregisterHistory('discord-bot', historyCallback)
1252
1268
  options.router.unregisterMessageGet('discord-bot', messageGetCallback)
1253
1269
  options.router.unregisterList('discord-bot', listCallback)
1270
+ options.router.unregisterEditMessage('discord-bot', editMessageCallback)
1254
1271
  options.router.unregisterFetchAttachment('discord-bot', fetchAttachmentCallback)
1255
1272
  options.router.unregisterMembership('discord-bot', membershipResolver)
1256
1273
  listener = null
1257
1274
  botUserId = null
1275
+ connected = false
1258
1276
  started = false
1259
1277
  logger.error(`[discord-bot] listener start failed: ${describe(err)}`)
1260
1278
  throw err
@@ -1274,6 +1292,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1274
1292
  options.router.unregisterHistory('discord-bot', historyCallback)
1275
1293
  options.router.unregisterMessageGet('discord-bot', messageGetCallback)
1276
1294
  options.router.unregisterList('discord-bot', listCallback)
1295
+ options.router.unregisterEditMessage('discord-bot', editMessageCallback)
1277
1296
  options.router.unregisterFetchAttachment('discord-bot', fetchAttachmentCallback)
1278
1297
  options.router.unregisterMembership('discord-bot', membershipResolver)
1279
1298
  if (inflightInbounds > 0) {
@@ -1283,14 +1302,21 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1283
1302
  }
1284
1303
  listener?.stop()
1285
1304
  listener = null
1305
+ connected = false
1286
1306
  },
1287
1307
 
1288
1308
  isConnected(): boolean {
1289
- return botUserId !== null
1309
+ return started && connected
1290
1310
  },
1291
1311
  }
1292
1312
  }
1293
1313
 
1314
+ const TERMINAL_GATEWAY_CLOSE_PATTERN = /^Discord gateway closed with non-recoverable code \d+$/
1315
+
1316
+ function isTerminalGatewayClose(err: unknown): boolean {
1317
+ return err instanceof Error && TERMINAL_GATEWAY_CLOSE_PATTERN.test(err.message)
1318
+ }
1319
+
1294
1320
  function describe(err: unknown): string {
1295
1321
  return err instanceof Error ? err.message : String(err)
1296
1322
  }
@@ -0,0 +1,51 @@
1
+ import type { DiscordClient } from 'agent-messenger/discord'
2
+
3
+ import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
+
5
+ export function createDiscordUserEditMessageCallback(deps: {
6
+ client: Pick<DiscordClient, 'editMessage'>
7
+ }): EditMessageCallback {
8
+ return async (req): Promise<EditMessageResult> => {
9
+ if (req.adapter !== 'discord') {
10
+ return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
11
+ }
12
+ // A Discord thread is its own channel id, so a message posted into a thread
13
+ // must be PATCHed against the thread, not its parent — mirroring the
14
+ // `thread ?? chat` routing the send/message-get paths use. Editing against
15
+ // `chat` alone would 404 on any threaded message.
16
+ const channelId = req.thread ?? req.chat
17
+ try {
18
+ await deps.client.editMessage(channelId, req.messageId, req.text)
19
+ } catch (err) {
20
+ return { ok: false, error: describe(err), code: classifyEditError(err) }
21
+ }
22
+ return { ok: true }
23
+ }
24
+ }
25
+
26
+ // Discord only lets you edit your OWN messages: a PATCH on someone else's
27
+ // message returns 50005 (Cannot edit a message authored by another user),
28
+ // mapped to permission-denied. 10008/10003 are the gone-message/channel cases.
29
+ // The user client throws DiscordError with the Discord API error code, or
30
+ // `http_<status>` when the body carries no code (same shape as discord-bot).
31
+ function classifyEditError(err: unknown): NonNullable<(EditMessageResult & { ok: false })['code']> {
32
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code: unknown }).code) : ''
33
+ switch (code) {
34
+ case '10003': // Unknown Channel
35
+ case '10008': // Unknown Message
36
+ case 'http_404':
37
+ return 'not-found'
38
+ case '50005': // Cannot edit a message authored by another user
39
+ case '50001': // Missing Access
40
+ case '50013': // Missing Permissions
41
+ case 'http_403':
42
+ case 'http_401':
43
+ return 'permission-denied'
44
+ default:
45
+ return 'not-found'
46
+ }
47
+ }
48
+
49
+ function describe(err: unknown): string {
50
+ return err instanceof Error ? err.message : String(err)
51
+ }
@@ -28,6 +28,7 @@ import { describeError } from './describe-error'
28
28
  import { createDiscordAuthorResolver } from './discord-author-resolver'
29
29
  import { createDiscordChannelResolver } from './discord-channel-resolver'
30
30
  import { classifyInbound, type InboundDropReason } from './discord-classify'
31
+ import { createDiscordUserEditMessageCallback } from './discord-edit'
31
32
  import { createDiscordReactionCallback, createDiscordRemoveReactionCallback } from './discord-reactions'
32
33
 
33
34
  export type DiscordAdapterLogger = {
@@ -215,6 +216,7 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
215
216
  })
216
217
  const reactionCallback = createDiscordReactionCallback({ client })
217
218
  const removeReactionCallback = createDiscordRemoveReactionCallback({ client })
219
+ const editMessageCallback = createDiscordUserEditMessageCallback({ client })
218
220
 
219
221
  const handleMessage = async (event: DiscordGatewayMessageCreateEvent): Promise<void> => {
220
222
  inflightInbounds++
@@ -367,6 +369,7 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
367
369
  router.registerMembership('discord', membershipResolver)
368
370
  router.registerReaction('discord', reactionCallback)
369
371
  router.registerRemoveReaction('discord', removeReactionCallback)
372
+ router.registerEditMessage('discord', editMessageCallback)
370
373
  }
371
374
 
372
375
  function unregisterCallbacks(router: ChannelRouter): void {
@@ -379,6 +382,7 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
379
382
  router.unregisterMembership('discord', membershipResolver)
380
383
  router.unregisterReaction('discord', reactionCallback)
381
384
  router.unregisterRemoveReaction('discord', removeReactionCallback)
385
+ router.unregisterEditMessage('discord', editMessageCallback)
382
386
  }
383
387
  }
384
388
 
@@ -15,6 +15,12 @@ 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
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.
23
+ provisional: boolean
18
24
  }
19
25
 
20
26
  export type KakaoChannelResolver = {
@@ -43,6 +49,7 @@ type Entry = {
43
49
  isDm: boolean
44
50
  chatName: string | null
45
51
  expiresAt: number
52
+ provisional: boolean
46
53
  }
47
54
 
48
55
  export function createKakaoChannelResolver(options: KakaoChannelResolverOptions): KakaoChannelResolver {
@@ -81,6 +88,7 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
81
88
  isDm: kind === 'dm',
82
89
  chatName: chat.title ?? chat.display_name,
83
90
  expiresAt,
91
+ provisional: false,
84
92
  })
85
93
  }
86
94
 
@@ -102,7 +110,7 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
102
110
  const lookupChat = (chatId: string): KakaoChatLookupValue | null => {
103
111
  const entry = cache.get(chatId)
104
112
  if (entry === undefined || entry.expiresAt <= now()) return null
105
- return { workspace: entry.workspace, isDm: entry.isDm }
113
+ return { workspace: entry.workspace, isDm: entry.isDm, provisional: entry.provisional }
106
114
  }
107
115
 
108
116
  const ingestProvisional = (chatId: string): void => {
@@ -113,6 +121,7 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
113
121
  isDm: false,
114
122
  chatName: null,
115
123
  expiresAt: now() + ttlMs,
124
+ provisional: true,
116
125
  })
117
126
  }
118
127