typeclaw 0.45.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.
@@ -79,6 +79,72 @@ export async function retryTurnOnPersistentSession(
79
79
  return true
80
80
  }
81
81
 
82
+ // Resume only the post-tool provider-failure shape. Unlike the generic helper,
83
+ // this deliberately refuses a trailing user leaf or an assistant error whose
84
+ // predecessor is anything other than the completed tool result. Callers use it
85
+ // after externally visible tool activity, where replaying the original turn
86
+ // could duplicate side effects.
87
+ export async function retryTurnAfterCompletedToolResult(
88
+ session: AgentSession,
89
+ opts: {
90
+ attempt: number
91
+ signal?: AbortSignal
92
+ random?: () => number
93
+ authorize: () => boolean
94
+ onBackoffStart?: () => void
95
+ },
96
+ ): Promise<boolean> {
97
+ const agent = (session as { agent?: ContinuableAgent }).agent
98
+ if (!agent || typeof agent.continue !== 'function') return false
99
+ if (!hasCompletedToolResultErrorTail(agent.state?.messages)) return false
100
+
101
+ opts.onBackoffStart?.()
102
+ await sleep(retryBackoffMs(opts.attempt, opts.random), opts.signal)
103
+ if (opts.signal?.aborted) return false
104
+
105
+ // Re-read after the backoff: another actor may have advanced the transcript
106
+ // while we slept. Mutation is safe only while the exact tail still holds.
107
+ const messages = agent.state?.messages
108
+ if (!hasCompletedToolResultErrorTail(messages)) return false
109
+ if (opts.authorize() !== true) return false
110
+
111
+ const originalMessages = messages
112
+ const prefix = messages.slice(0, -1)
113
+ ;(agent.state as { messages: unknown }).messages = prefix
114
+ try {
115
+ await agent.continue()
116
+ } catch (err) {
117
+ if (hasSameEntries(agent.state?.messages, prefix)) {
118
+ ;(agent.state as { messages: unknown }).messages = originalMessages
119
+ }
120
+ throw err
121
+ }
122
+ return true
123
+ }
124
+
125
+ function hasCompletedToolResultErrorTail(messages: unknown): messages is unknown[] {
126
+ if (!Array.isArray(messages) || messages.length < 2) return false
127
+ const predecessor = messages[messages.length - 2]
128
+ const leaf = messages[messages.length - 1]
129
+ return (
130
+ typeof predecessor === 'object' &&
131
+ predecessor !== null &&
132
+ (predecessor as { role?: unknown }).role === 'toolResult' &&
133
+ typeof leaf === 'object' &&
134
+ leaf !== null &&
135
+ (leaf as { role?: unknown }).role === 'assistant' &&
136
+ (leaf as { stopReason?: unknown }).stopReason === 'error'
137
+ )
138
+ }
139
+
140
+ function hasSameEntries(messages: unknown, expected: unknown[]): boolean {
141
+ return (
142
+ Array.isArray(messages) &&
143
+ messages.length === expected.length &&
144
+ messages.every((entry, i) => entry === expected[i])
145
+ )
146
+ }
147
+
82
148
  // Same-ref retry for DIRECT `session.prompt()` call sites that bypass the model
83
149
  // fallback helpers (non-stream TUI, slash commands, subagent drain/required-block
84
150
  // nudges, multimodal look-at). These lost the SDK's built-in retry when it was
@@ -367,6 +367,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
367
367
  },
368
368
  })
369
369
  if (result.success) activeModelRef = result.refUsed
370
+ throwIfLoopGuardAborted(session)
370
371
  } finally {
371
372
  if (hooks && turnEvent !== undefined) {
372
373
  await hooks.runSessionTurnEnd(turnEvent)
@@ -377,10 +378,12 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
377
378
  drain: backgroundDrain,
378
379
  prompt: async (text) => {
379
380
  await promptWithSameRefRetryOnly(session, `${renderTurnTimeAnchor()}\n\n${text}`)
381
+ throwIfLoopGuardAborted(session)
380
382
  },
381
383
  cancelled: () => aborted,
382
384
  })
383
385
  }
386
+ throwIfLoopGuardAborted(session)
384
387
  // Required-block guard (mirrors the channel empty-response guard): a subagent
385
388
  // that owes a result block but ended without one gets a bounded re-prompt to
386
389
  // emit it as text, then an honest fallback — never a silent stale-preamble
@@ -400,6 +403,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
400
403
  session,
401
404
  `${renderTurnTimeAnchor()}\n\n${renderRequiredBlockRetryNudge(requiredBlockTag)}`,
402
405
  )
406
+ throwIfLoopGuardAborted(session)
403
407
  }
404
408
  if (!aborted && !capture.hasRequiredBlock()) {
405
409
  console.warn(`[subagent] ${name} required_block_fallback tag=${requiredBlockTag}`)
@@ -448,6 +452,19 @@ export class SubagentTimeoutError extends Error {
448
452
  }
449
453
  }
450
454
 
455
+ class SubagentLoopGuardAbortError extends Error {
456
+ override readonly name = 'SubagentLoopGuardAbortError'
457
+
458
+ constructor(readonly reason: string) {
459
+ super(`subagent aborted by loop guard (${reason})`)
460
+ }
461
+ }
462
+
463
+ function throwIfLoopGuardAborted(session: AgentSession): void {
464
+ const reason = (session as AgentSession & { getAbortReason?: () => string | undefined }).getAbortReason?.()
465
+ if (reason?.startsWith('loop_guard:') === true) throw new SubagentLoopGuardAbortError(reason)
466
+ }
467
+
451
468
  export function isSubagentTimeoutError(err: unknown): err is SubagentTimeoutError {
452
469
  return err instanceof SubagentTimeoutError
453
470
  }
@@ -544,7 +561,7 @@ export function startSubagent(name: string, options: StartSubagentOptions): Star
544
561
  if (!handleSettled) {
545
562
  rejectHandle(err instanceof Error ? err : new Error(error))
546
563
  }
547
- return { ok: false as const, error }
564
+ return { ok: false as const, error, ...(finalMessage !== undefined ? { finalMessage } : {}) }
548
565
  })
549
566
 
550
567
  const timeoutMs = options.registry[name]?.timeoutMs
@@ -688,7 +705,7 @@ function attachFinalMessageCapture(
688
705
  let lastReview: string | null = null
689
706
  let lastRequired: string | null = null
690
707
  try {
691
- session.subscribe((event: unknown) => {
708
+ subscribeToAwaitedAgentEvents(session, (event: unknown) => {
692
709
  const ev = event as { type?: string; message?: { role?: string; content?: unknown } }
693
710
  if (ev?.type !== 'message_end') return
694
711
  // Real assistant messages carry role 'assistant'; older test doubles omit
@@ -731,6 +748,15 @@ function attachFinalMessageCapture(
731
748
  }
732
749
  }
733
750
 
751
+ function subscribeToAwaitedAgentEvents(session: AgentSession, listener: (event: unknown) => void): () => void {
752
+ const agent = (
753
+ session as AgentSession & {
754
+ agent?: { subscribe?: (listener: (event: unknown) => void) => () => void }
755
+ }
756
+ ).agent
757
+ return agent?.subscribe?.(listener) ?? session.subscribe(listener)
758
+ }
759
+
734
760
  function extractFinalMessageText(content: unknown): string | null {
735
761
  if (typeof content === 'string') {
736
762
  const trimmed = content.trim()
@@ -7,6 +7,7 @@ import {
7
7
  containsKimiToolDelimiter,
8
8
  isNoReplySignal,
9
9
  isUpstreamEmptyResponseSentinel,
10
+ stripTrailingLeakedToolCall,
10
11
  type ChannelRouter,
11
12
  } from '@/channels/router'
12
13
  import type { AdapterId } from '@/channels/schema'
@@ -100,7 +101,7 @@ export function createChannelReplyTool({
100
101
  }),
101
102
 
102
103
  async execute(_toolCallId, params) {
103
- const text = params.text
104
+ let text = params.text
104
105
  const attachments = params.attachments
105
106
  const keepTurnAlive = params.continue === true
106
107
  if ((text === undefined || text === '') && (attachments === undefined || attachments.length === 0)) {
@@ -140,6 +141,19 @@ export function createChannelReplyTool({
140
141
  }
141
142
  }
142
143
 
144
+ // Prose-then-trailing-call leak (mirrors router.ts + channel-send.ts):
145
+ // strip a serialized trailing tool call while keeping the real reply
146
+ // prose, rather than denying and stranding the user's answer.
147
+ if (text !== undefined) {
148
+ const trailingLeak = stripTrailingLeakedToolCall(text)
149
+ if (trailingLeak !== null && trailingLeak.text !== '') {
150
+ logger.warn(
151
+ formatChannelToolFailure('channel_reply', `stripped trailing_tool_call_leak tool=${trailingLeak.toolName}`),
152
+ )
153
+ text = trailingLeak.text
154
+ }
155
+ }
156
+
143
157
  // Required-choice guard: a terminal github review-thread text reply must
144
158
  // make an explicit resolve_review_thread choice. The model kept silently
145
159
  // omitting the flag after acknowledging a fix, leaving the thread open;
@@ -8,6 +8,7 @@ import {
8
8
  containsKimiToolDelimiter,
9
9
  isNoReplySignal,
10
10
  isUpstreamEmptyResponseSentinel,
11
+ stripTrailingLeakedToolCall,
11
12
  type ChannelRouter,
12
13
  } from '@/channels/router'
13
14
  import { ADAPTER_IDS, type AdapterId } from '@/channels/schema'
@@ -124,7 +125,7 @@ export function createChannelSendTool({
124
125
 
125
126
  async execute(_toolCallId, params) {
126
127
  const adapter = params.adapter as AdapterId
127
- const bodyText = params.text
128
+ let bodyText = params.text
128
129
  const attachments = params.attachments
129
130
  if ((bodyText === undefined || bodyText === '') && (attachments === undefined || attachments.length === 0)) {
130
131
  logger.warn(formatChannelToolFailure('channel_send', 'missing text and attachments'))
@@ -163,6 +164,21 @@ export function createChannelSendTool({
163
164
  }
164
165
  }
165
166
 
167
+ // Prose-then-trailing-call leak (mirrors router.ts validateChannelTurn):
168
+ // the model put a real reply plus a serialized trailing tool call in the
169
+ // `text` arg. Strip the plumbing and keep the prose rather than denying,
170
+ // so the legitimate reply still reaches the channel. Whole-message calls
171
+ // (no prose prefix) are untouched here and left to the router's recovery.
172
+ if (bodyText !== undefined) {
173
+ const trailingLeak = stripTrailingLeakedToolCall(bodyText)
174
+ if (trailingLeak !== null && trailingLeak.text !== '') {
175
+ logger.warn(
176
+ formatChannelToolFailure('channel_send', `stripped trailing_tool_call_leak tool=${trailingLeak.toolName}`),
177
+ )
178
+ bodyText = trailingLeak.text
179
+ }
180
+ }
181
+
166
182
  // Required-choice guard (mirrors channel_reply): a github PR review-thread
167
183
  // send with text must make an explicit resolve_review_thread choice. The
168
184
  // `pull_request.synchronize` recheck routes the post-push close-out HERE
@@ -2,7 +2,7 @@ import type { ModelRef } from '@/config/providers'
2
2
 
3
3
  import type { AgentSession } from './index'
4
4
  import { detectProviderError, isRetryableSameRef, subscribeProviderErrors } from './provider-error'
5
- import { RETRIES_PER_REF, retryTurnOnPersistentSession } from './retry-same-ref'
5
+ import { RETRIES_PER_REF, retryTurnAfterCompletedToolResult, retryTurnOnPersistentSession } from './retry-same-ref'
6
6
  import { modelThrottleCircuit, type ThrottleCircuit } from './throttle-circuit'
7
7
 
8
8
  export type PersistentTurnAttempt = {
@@ -34,6 +34,9 @@ export async function promptPersistentTurnWithFallback(opts: {
34
34
  circuit?: ThrottleCircuit
35
35
  skipProviderErrorSubscription?: boolean
36
36
  detectSoftErrorFromLeaf?: boolean
37
+ authorizeRetryAfterCompletedToolResult?: () => boolean
38
+ retryRandom?: () => number
39
+ onRetryBackoffStart?: () => void
37
40
  beforeAttempt?: (ref: ModelRef) => void
38
41
  onAttemptFailed?: (attempt: PersistentTurnAttempt) => void
39
42
  }): Promise<PersistentTurnResult> {
@@ -78,6 +81,7 @@ export async function promptPersistentTurnWithFallback(opts: {
78
81
  // advancing the chain. `retry === 0` is the first, prompt()-driven attempt;
79
82
  // later iterations resume via agent.continue() (no user-message re-append).
80
83
  let outcome: AttemptOutcome | undefined
84
+ let retryAfterCompletedToolResult = false
81
85
  for (let retry = 0; ; retry++) {
82
86
  softError = undefined
83
87
  let outcomeThisAttempt: AttemptOutcome | undefined
@@ -85,7 +89,14 @@ export async function promptPersistentTurnWithFallback(opts: {
85
89
  if (retry === 0) {
86
90
  await opts.session.prompt(opts.text)
87
91
  } else {
88
- const retried = await retryTurnOnPersistentSession(opts.session, { attempt: retry - 1 })
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 })
89
100
  // The safe continue-recipe couldn't apply: keep the PREVIOUS failure
90
101
  // outcome (never cleared) and let it drive the advance/return below.
91
102
  if (!retried) break
@@ -96,13 +107,16 @@ export async function promptPersistentTurnWithFallback(opts: {
96
107
  }
97
108
  outcome = outcomeThisAttempt
98
109
  if (outcome === undefined) break
99
- // Only keep retrying while the failure is same-ref retryable, the turn
100
- // stayed idempotent (no output/tool-exec yet), and budget remains.
101
- const mayRetry =
102
- retry < RETRIES_PER_REF &&
103
- isRetryableSameRef(outcome.error.message) &&
104
- !activity.producedAssistantOutput &&
105
- !activity.startedToolExecution
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)
106
120
  if (!mayRetry) break
107
121
  }
108
122
 
@@ -99,6 +99,7 @@ Prioritize in this order:
99
99
  - **Restating the code.** "This function reads the file and returns its contents" is not a finding.
100
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.)
101
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.
102
103
 
103
104
  ## Severity hints specific to code
104
105
 
@@ -107,6 +108,8 @@ Prioritize in this order:
107
108
  - **nit** — Naming, micro-readability, suboptimal-but-correct code. Optional. The author can decline and you should not push back.
108
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.
109
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
+
110
113
  ## Verdict mapping
111
114
 
112
115
  - **approve** — Zero blockers. Concerns are minor, isolated, or already discussed.
@@ -122,6 +125,8 @@ This includes payloads where the parent says the author **addressed your prior b
122
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).
123
126
  - Return **request-changes** if any blocker remains or a new one appeared.
124
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
+
125
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.
126
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\`.
127
132
 
@@ -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,
@@ -121,6 +121,8 @@ export type DiscordBotAdapterOptions = {
121
121
  // exact REST calls without monkey-patching globalThis.fetch. Production
122
122
  // callers leave it undefined to use the global fetch.
123
123
  fetchImpl?: typeof fetch
124
+ createClient?: () => DiscordBotClient
125
+ createListener?: (client: DiscordBotClient, options: DiscordBotListenerOptions) => DiscordBotListener
124
126
  }
125
127
 
126
128
  export type DiscordBotAdapter = {
@@ -1018,10 +1020,14 @@ export const DISCORD_SLASH_COMMAND_NAMES = SLASH_COMMAND_NAMES
1018
1020
 
1019
1021
  export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): DiscordBotAdapter {
1020
1022
  const logger = options.logger ?? consoleLogger
1021
- 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()
1022
1027
  const fetchImpl = options.fetchImpl ?? fetch
1023
1028
  let listener: DiscordBotListener | null = null
1024
1029
  let botUserId: string | null = null
1030
+ let connected = false
1025
1031
  let started = false
1026
1032
  let inflightInbounds = 0
1027
1033
  let stopWaiters: Array<() => void> = []
@@ -1178,8 +1184,9 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1178
1184
  throw err
1179
1185
  }
1180
1186
 
1181
- listener = new DiscordBotListener(client, { intents: DISCORD_BOT_INTENTS })
1187
+ listener = createListener(client, { intents: DISCORD_BOT_INTENTS })
1182
1188
  listener.on('connected', (info) => {
1189
+ connected = true
1183
1190
  botUserId = info.user.id
1184
1191
  logger.info(`[discord-bot] connected as ${info.user.username} (${info.user.id})`)
1185
1192
  // For bots, the gateway's user.id IS the application id — the same
@@ -1211,9 +1218,15 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1211
1218
  })
1212
1219
  })
1213
1220
  listener.on('disconnected', () => {
1221
+ connected = false
1214
1222
  logger.warn('[discord-bot] disconnected; SDK will reconnect with backoff')
1215
1223
  })
1216
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
1217
1230
  logger.error(`[discord-bot] gateway error: ${describe(err)}`)
1218
1231
  })
1219
1232
  listener.on('message_create', (event) => {
@@ -1259,6 +1272,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1259
1272
  options.router.unregisterMembership('discord-bot', membershipResolver)
1260
1273
  listener = null
1261
1274
  botUserId = null
1275
+ connected = false
1262
1276
  started = false
1263
1277
  logger.error(`[discord-bot] listener start failed: ${describe(err)}`)
1264
1278
  throw err
@@ -1288,14 +1302,21 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1288
1302
  }
1289
1303
  listener?.stop()
1290
1304
  listener = null
1305
+ connected = false
1291
1306
  },
1292
1307
 
1293
1308
  isConnected(): boolean {
1294
- return botUserId !== null
1309
+ return started && connected
1295
1310
  },
1296
1311
  }
1297
1312
  }
1298
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
+
1299
1320
  function describe(err: unknown): string {
1300
1321
  return err instanceof Error ? err.message : String(err)
1301
1322
  }
@@ -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
 
@@ -0,0 +1,125 @@
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 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.
44
+ export type KakaoTypingChatClass = 'send' | 'skip-open' | 'skip-unresolved'
45
+
46
+ export function kakaoTypingClassFromLookup(
47
+ lookup: { workspace: string; provisional: boolean } | null,
48
+ ): KakaoTypingChatClass {
49
+ if (lookup === null || lookup.provisional) return 'skip-unresolved'
50
+ if (lookup.workspace === '@kakao-open') return 'skip-open'
51
+ return 'send'
52
+ }
53
+
54
+ export function createKakaoTypingCallback(deps: {
55
+ logger: KakaoTypingLogger
56
+ 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.
60
+ classifyChat: (chatId: string) => KakaoTypingChatClass
61
+ formatChannelTag?: (workspace: string, chat: string) => Promise<string>
62
+ }): KakaoTypingCallbackHandle {
63
+ const { logger, sendTyping, classifyChat, formatChannelTag } = deps
64
+ // Per-chat FIFO mirrors the webex/slack pattern: chaining each request through
65
+ // the per-chat tail keeps on-the-wire order matching enqueue order even under
66
+ // network jitter, so a slow send can't reorder behind a later tick.
67
+ const queues = new Map<string, Promise<void>>()
68
+ // Per-chat generation token, independent of any timer. A pulse captures the
69
+ // chat's generation when it's accepted and re-checks it immediately before
70
+ // sending; 'stop' and `reset` delete the generation, so a pulse already queued
71
+ // behind an in-flight send is dropped instead of raising the indicator after
72
+ // the turn (or the adapter) has stopped.
73
+ const activeGeneration = new Map<string, number>()
74
+ const openChatSkipLogged = new Set<string>()
75
+ let generationCounter = 0
76
+
77
+ const callback: TypingCallback = async (target) => {
78
+ if (target.adapter !== 'kakaotalk') return
79
+ // No stop API: the indicator auto-expires ~5s after the last packet and a
80
+ // delivered message clears it client-side, so 'stop' sends no packet. It
81
+ // must still invalidate any queued pulse for this chat.
82
+ if (target.phase !== 'tick') {
83
+ activeGeneration.delete(target.chat)
84
+ return
85
+ }
86
+ const chatClass = classifyChat(target.chat)
87
+ if (chatClass !== 'send') {
88
+ if (chatClass === 'skip-open' && !openChatSkipLogged.has(target.chat)) {
89
+ openChatSkipLogged.add(target.chat)
90
+ logger.info(`[kakaotalk:typing] skipped chat=${target.chat} reason=open_chat_link_id_unsupported`)
91
+ }
92
+ return
93
+ }
94
+
95
+ if (!activeGeneration.has(target.chat)) activeGeneration.set(target.chat, ++generationCounter)
96
+ const generation = activeGeneration.get(target.chat)
97
+ const prev = queues.get(target.chat) ?? Promise.resolve()
98
+ const next = prev
99
+ .catch(() => {})
100
+ .then(async () => {
101
+ if (activeGeneration.get(target.chat) !== generation) return
102
+ const result = await sendTyping(target.chat)
103
+ if (!result.success) {
104
+ throw new Error(`kakaotalk ACTION rejected: status_code=${result.status_code}`)
105
+ }
106
+ })
107
+ .catch(async (err: unknown) => {
108
+ const tag = formatChannelTag
109
+ ? await formatChannelTag(target.workspace, target.chat).catch(() => `chat=${target.chat}`)
110
+ : `chat=${target.chat}`
111
+ logger.warn(`[kakaotalk:typing] ${tag} phase=${target.phase} failed: ${describeError(err)}`)
112
+ })
113
+ queues.set(target.chat, next)
114
+ void next.finally(() => {
115
+ if (queues.get(target.chat) === next) queues.delete(target.chat)
116
+ })
117
+ await next
118
+ }
119
+
120
+ const reset = (): void => {
121
+ activeGeneration.clear()
122
+ }
123
+
124
+ return { callback, reset }
125
+ }
@@ -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)