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
@@ -64,10 +64,12 @@ import {
64
64
  } from './persistence'
65
65
  import {
66
66
  ADAPTER_READ_CAPABILITIES,
67
+ ADAPTER_WRITE_CAPABILITIES,
67
68
  QUOTED_REPLY_EXCERPT_MAX_CHARS,
68
69
  type AdapterId,
69
70
  type ChannelAdapterConfig,
70
71
  type ReadCapability,
72
+ type WriteCapability,
71
73
  } from './schema'
72
74
  import type {
73
75
  ChannelHistoryMessage,
@@ -75,6 +77,9 @@ import type {
75
77
  ChannelNameResolver,
76
78
  ChannelSelfIdentity,
77
79
  ChannelSelfIdentityResolver,
80
+ EditMessageCallback,
81
+ EditMessageRequest,
82
+ EditMessageResult,
78
83
  FetchAttachmentArgs,
79
84
  FetchAttachmentCallback,
80
85
  FetchAttachmentResult,
@@ -125,6 +130,10 @@ export const CONTEXT_BUFFER_SIZE = 20
125
130
  export const OBSERVED_MESSAGE_MAX_CHARS = 800
126
131
  // Discord's typing indicator expires after ~10s; an 8s heartbeat keeps it
127
132
  // continuously visible while we debounce + generate without spamming the API.
133
+ // This is the default; an adapter whose platform expires the indicator sooner
134
+ // registers a shorter interval via `setTypingHeartbeatInterval` (e.g. KakaoTalk
135
+ // auto-expires after ~5s) so the router itself paces the refresh — the adapter
136
+ // callback stays stateless instead of running its own timer.
128
137
  export const TYPING_HEARTBEAT_MS = 8000
129
138
  // A stuck model call or an agent that never yields should not keep re-arming
130
139
  // platform-side typing forever. Slack Assistant status in particular has a
@@ -780,6 +789,19 @@ type LiveSession = {
780
789
  // origin so `channel_react` reacts to the triggering message, not whichever
781
790
  // inbound happens to be latest in the queue. Null on reminder-only turns.
782
791
  currentTurnReactionRef: ReactionRef | null
792
+ // True when the inbound that triggered THIS turn (the message
793
+ // `currentTurnReactionRef` points at — last item of the drained batch) was
794
+ // EXPLICITLY addressed to the bot: a DM, an @-mention/alias (`isBotMention`
795
+ // folds plain-name matching in at the adapter classify layer), or a reply to
796
+ // the bot's own message. Gates the PERSISTENT silent-ack :eyes: (see
797
+ // `armSilentTurnAck`): a deliberate silence on a message aimed AT us earns a
798
+ // courteous "seen, nothing to add" 👀, but staying quiet during ambient
799
+ // human-to-human chatter (sticky observation, solo-human fallback) must leave
800
+ // NO mark — otherwise a busy room accumulates stale 👀 on messages the bot
801
+ // was never part of. Computed from the SAME message the reaction targets so
802
+ // eligibility and target can never disagree. Reset with `currentTurnReactionRef`
803
+ // in the drain finally; preserved across reminder-only iterations exactly like it.
804
+ currentTurnExplicitlyAddressed: boolean
783
805
  // Typing-status anchor of the inbound that triggered THIS turn (last item in
784
806
  // the drained batch, mirroring `currentTurnReactionRef`). Adapter-opaque ts
785
807
  // carried only to the typing path; null when the triggering inbound supplied
@@ -952,6 +974,18 @@ type LiveSession = {
952
974
  // turn can never trigger a nudge on a later one. `null` when no such reply
953
975
  // ended this turn.
954
976
  lastTerminalReplyAbort: { turnSeq: number; text: string } | null
977
+ // Stamped by `installChannelReplyTerminalHook` when a successful `channel_reply`
978
+ // set `continue: true` — the machine-readable "I'll keep working this turn"
979
+ // promise. `validateChannelTurn` reads it to recover a turn that made that promise,
980
+ // did more work, then ended on a fresh empty `stop` (dropped its conclusion) —
981
+ // independent of what natural-language phrase the ack used, so a persona speaking
982
+ // any language/register is covered where the willingness phrase table would miss.
983
+ // `turnSeq`-stamped so a stale promise can't fire on a later turn. `sendCount` is
984
+ // `successfulChannelSends` AT the ack (which already counts the ack itself); the
985
+ // recovery fires only while it still equals the live count — a later substantive
986
+ // send (e.g. a `channel_send` final answer) bumps the count and invalidates the
987
+ // promise, so an empty stop after the real answer is NOT re-nudged.
988
+ continueReplyTurn: { turnSeq: number; sendCount: number } | null
955
989
  // Stamped by router abort sites and read by `validateChannelTurn` for
956
990
  // reason-specific stranded-toolUse recovery logs. `turnSeq`-stamped so stale
957
991
  // abort provenance from an earlier turn can never leak into a later retry.
@@ -1168,6 +1202,11 @@ export type ChannelRouter = {
1168
1202
  // the wrong signal. autoReactOnEngage reads this to post :eyes: only as a
1169
1203
  // fallback when no visible typing exists. Unset defaults to false.
1170
1204
  setTypingCapability: (adapter: ChannelKey['adapter'], supported: boolean) => void
1205
+ // Override the typing heartbeat interval for one adapter. Adapters whose
1206
+ // platform expires the indicator faster than the default TYPING_HEARTBEAT_MS
1207
+ // register a shorter interval here so the router paces their refresh; the
1208
+ // adapter callback stays stateless. Unset adapters use TYPING_HEARTBEAT_MS.
1209
+ setTypingHeartbeatInterval: (adapter: ChannelKey['adapter'], intervalMs: number) => void
1171
1210
  // Set by the manager for every adapter present in typeclaw.json#channels,
1172
1211
  // independent of whether the adapter's start() succeeded (a failed login never
1173
1212
  // registers callbacks). Combined with the adapter's static read-capability set
@@ -1203,6 +1242,16 @@ export type ChannelRouter = {
1203
1242
  registerList: (adapter: ChannelKey['adapter'], cb: ListCallback) => void
1204
1243
  unregisterList: (adapter: ChannelKey['adapter'], cb: ListCallback) => void
1205
1244
  listChannels: (adapter: ChannelKey['adapter'], args: ListChannelsArgs) => Promise<ListChannelsResult>
1245
+ // Message editing is opt-in per adapter, Set-based like reactions/outbound so
1246
+ // future multi-account setups can register more than one. A missing callback
1247
+ // resolves to `code: 'not-supported'`, or `code: 'adapter-unavailable'` when
1248
+ // the static write-capability table (ADAPTER_WRITE_CAPABILITIES) says this
1249
+ // adapter edits but no live callback exists (failed start). Kept off the
1250
+ // outbound path: an edit mutates an existing post, so it must not flow through
1251
+ // send()'s flood/cap/dup/sticky guards.
1252
+ registerEditMessage: (adapter: ChannelKey['adapter'], cb: EditMessageCallback) => void
1253
+ unregisterEditMessage: (adapter: ChannelKey['adapter'], cb: EditMessageCallback) => void
1254
+ editMessage: (req: EditMessageRequest) => Promise<EditMessageResult>
1206
1255
  registerFetchAttachment: (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback) => void
1207
1256
  unregisterFetchAttachment: (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback) => void
1208
1257
  fetchAttachment: (adapter: ChannelKey['adapter'], args: FetchAttachmentArgs) => Promise<FetchAttachmentResult>
@@ -1342,6 +1391,7 @@ export type ChannelRouter = {
1342
1391
  typingEpoch: (key: ChannelKey) => number | undefined
1343
1392
  isTypingActive: (key: ChannelKey) => boolean
1344
1393
  stopTyping: (key: ChannelKey) => Promise<void>
1394
+ typingHeartbeatIntervalFor: (adapter: ChannelKey['adapter']) => number
1345
1395
  runIdleGc: () => Promise<void>
1346
1396
  // Returns the seeded author state on the live session matching
1347
1397
  // `key`, or undefined when no live session exists. Tests use this
@@ -1391,6 +1441,10 @@ export type CreateChannelRouterOptions = {
1391
1441
  logger?: RouterLogger
1392
1442
  // Test seam: clock for sticky/debounce/participants. Defaults to Date.now.
1393
1443
  now?: () => number
1444
+ // Test seams for synchronizing strict post-tool retry backoff without global
1445
+ // random/timer mutation. Production defaults remain Math.random and no hook.
1446
+ retryRandom?: () => number
1447
+ onRetryBackoffStart?: () => void
1394
1448
  // Test seam: measure a transcript file's byte size for the soft-TTL grace
1395
1449
  // decision. Defaults to a stat()-based reader returning 0 for a missing or
1396
1450
  // unreadable file (grace then fails closed to roll-over-at-soft-TTL).
@@ -1542,6 +1596,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1542
1596
  const removeReactionCallbacks = new Map<ChannelKey['adapter'], Set<RemoveReactionCallback>>()
1543
1597
  const typingCallbacks = new Map<ChannelKey['adapter'], Set<TypingCallback>>()
1544
1598
  const typingCapableAdapters = new Set<ChannelKey['adapter']>()
1599
+ const typingHeartbeatIntervals = new Map<ChannelKey['adapter'], number>()
1545
1600
  const configuredAdapters = new Set<ChannelKey['adapter']>()
1546
1601
  const channelNameResolvers = new Map<ChannelKey['adapter'], Set<ChannelNameResolver>>()
1547
1602
  const membershipResolvers = new Map<ChannelKey['adapter'], Set<MembershipResolver>>()
@@ -1550,6 +1605,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1550
1605
  const historyCallbacks = new Map<ChannelKey['adapter'], Set<HistoryCallback>>()
1551
1606
  const messageGetCallbacks = new Map<ChannelKey['adapter'], MessageGetCallback>()
1552
1607
  const listCallbacks = new Map<ChannelKey['adapter'], ListCallback>()
1608
+ const editMessageCallbacks = new Map<ChannelKey['adapter'], Set<EditMessageCallback>>()
1553
1609
  const fetchAttachmentCallbacks = new Map<ChannelKey['adapter'], Set<FetchAttachmentCallback>>()
1554
1610
  const reviewThreadResolvers = new Map<ChannelKey['adapter'], ReviewThreadResolver>()
1555
1611
  const reviewStateResolvers = new Map<ChannelKey['adapter'], ReviewStateResolver>()
@@ -2065,6 +2121,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2065
2121
  currentTurnAuthorId: null,
2066
2122
  currentTurnAuthorIds: new Set(),
2067
2123
  currentTurnReactionRef: null,
2124
+ currentTurnExplicitlyAddressed: false,
2068
2125
  currentTurnTypingThread: null,
2069
2126
  dirtyTypingThreads: new Set(),
2070
2127
  currentTurnEngageReactions: [],
@@ -2098,6 +2155,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2098
2155
  emptyStopAfterToolWorkArmed: false,
2099
2156
  willingnessNudges: 0,
2100
2157
  lastTerminalReplyAbort: null,
2158
+ continueReplyTurn: null,
2101
2159
  abortReasonThisTurn: null,
2102
2160
  nextPromptMaxTokens: undefined,
2103
2161
  skippedTurn: null,
@@ -2486,6 +2544,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2486
2544
  const details = context.result.details as { ok?: unknown; continue?: unknown } | undefined
2487
2545
  const succeeded = context.toolCall.name === 'channel_reply' && !context.isError && details?.ok === true
2488
2546
  const keepTurnAlive = details?.continue === true
2547
+ if (succeeded && keepTurnAlive) {
2548
+ live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
2549
+ }
2489
2550
  if (succeeded && !keepTurnAlive && agent.signal?.aborted !== true) {
2490
2551
  logger.info(`[channels] ${live.keyId} terminal_after_channel_reply`)
2491
2552
  const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
@@ -2548,7 +2609,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2548
2609
  return
2549
2610
  }
2550
2611
  void fireTyping(live, 'tick', epoch)
2551
- }, TYPING_HEARTBEAT_MS)
2612
+ }, typingHeartbeatIntervalFor(live.key.adapter))
2552
2613
  }
2553
2614
 
2554
2615
  const stopTypingHeartbeat = async (live: LiveSession): Promise<void> => {
@@ -2696,6 +2757,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2696
2757
  live.firstUnprocessedAt = 0
2697
2758
  live.promptQueue.length = 0
2698
2759
  live.pendingSystemReminders.length = 0
2760
+ live.continueReplyTurn = null
2699
2761
  await stopTypingHeartbeat(live)
2700
2762
  try {
2701
2763
  await live.session.abort()
@@ -2705,9 +2767,26 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2705
2767
  }
2706
2768
  }
2707
2769
 
2770
+ // ensureLive() installs a session BEFORE the engage/observe decision, so a
2771
+ // bystander agent that only OBSERVED a thread still holds an exact-thread
2772
+ // session with nothing running. Without this gate that agent aborts its idle
2773
+ // session and posts "stopped" in a multi-agent channel. Mirrors exactly what
2774
+ // stopCurrentChannelTurn cancels: in-flight drain, queued prompts, reminders.
2775
+ const hasStoppableWork = (live: LiveSession): boolean =>
2776
+ live.draining || live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0
2777
+
2778
+ const hasPendingContinueReply = (live: LiveSession): boolean => {
2779
+ const progressReply = live.continueReplyTurn
2780
+ return (
2781
+ progressReply !== null &&
2782
+ progressReply.turnSeq === live.turnSeq &&
2783
+ progressReply.sendCount === live.successfulChannelSends
2784
+ )
2785
+ }
2786
+
2708
2787
  const maybePostDeferredProviderError = async (
2709
2788
  live: LiveSession,
2710
- sentReplyThisTurn: boolean,
2789
+ completedReplyThisTurn: boolean,
2711
2790
  retryQueued: boolean,
2712
2791
  ): Promise<void> => {
2713
2792
  const pending = live.pendingProviderError
@@ -2717,7 +2796,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2717
2796
  }
2718
2797
  // The turn recovered and replied — the provider blip was transient, so a
2719
2798
  // failure notice would be a false alarm stranded above the real reply.
2720
- if (sentReplyThisTurn) {
2799
+ if (completedReplyThisTurn) {
2721
2800
  live.pendingProviderError = null
2722
2801
  return
2723
2802
  }
@@ -2798,6 +2877,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2798
2877
  live.currentTurnAuthorId = batch[batch.length - 1]!.authorId
2799
2878
  live.currentTurnAuthorIds = new Set(batch.map((m) => m.authorId))
2800
2879
  live.currentTurnReactionRef = batch[batch.length - 1]!.reactionRef ?? null
2880
+ const trigger = batch[batch.length - 1]!
2881
+ live.currentTurnExplicitlyAddressed =
2882
+ trigger.isDm || trigger.isBotMention || trigger.replyToBotMessageId !== null
2801
2883
  live.currentTurnTypingThread = batch[batch.length - 1]!.typingThread ?? null
2802
2884
  live.currentTurnEngageReactions = batch.flatMap((m) =>
2803
2885
  m.engageReaction !== undefined ? [m.engageReaction] : [],
@@ -2868,12 +2950,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2868
2950
  const successfulSendsBeforePrompt = live.successfulChannelSends
2869
2951
  const emptyTurnRetriesBeforePrompt = live.emptyTurnRetries
2870
2952
  const toolLeakRetriesBeforePrompt = live.toolLeakRetries
2953
+ const willingnessNudgesBeforePrompt = live.willingnessNudges
2871
2954
  const engageAddPromises = live.currentTurnEngageReactions
2872
2955
  live.turnSeq++
2873
2956
  live.successfulSendsAtTurnStart = successfulSendsBeforePrompt
2874
2957
  live.skipLockedSendTurn = null
2875
2958
  live.disengagedTurn = null
2876
2959
  live.emptyTurnFallbackTurn = null
2960
+ live.continueReplyTurn = null
2877
2961
  live.policyDeniedToolSendsThisTurn.clear()
2878
2962
  resetReviewTurn(live.sessionId)
2879
2963
  const isRealUserTurn = batch.length > 0
@@ -2897,6 +2981,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2897
2981
  session: live.session,
2898
2982
  text: promptText,
2899
2983
  shouldFailover: (err) => isFailoverWorthy(err.message),
2984
+ authorizeRetryAfterCompletedToolResult: () => hasPendingContinueReply(live),
2985
+ ...(options.retryRandom !== undefined ? { retryRandom: options.retryRandom } : {}),
2986
+ ...(options.onRetryBackoffStart !== undefined ? { onRetryBackoffStart: options.onRetryBackoffStart } : {}),
2900
2987
  setModelForRef: async (ref) => {
2901
2988
  await live.session.setModel(applyModelRuntimeOverrides(resolveModel(ref), ref))
2902
2989
  live.activeModelRef = ref
@@ -2929,7 +3016,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2929
3016
  // tool-leak retry that later replies must commit the signal AT the
2930
3017
  // successful retry, not clear it after the first suppressed attempt.
2931
3018
  const retryQueuedThisTurn =
2932
- live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
3019
+ live.emptyTurnRetries > emptyTurnRetriesBeforePrompt ||
3020
+ live.toolLeakRetries > toolLeakRetriesBeforePrompt ||
3021
+ live.willingnessNudges > willingnessNudgesBeforePrompt
2933
3022
  const providerErrorThisTurn = assistantLeafStopReason(live.session) === 'error'
2934
3023
  const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
2935
3024
  const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
@@ -2996,8 +3085,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2996
3085
  // Either retry budget keeps the turn in flight, so a deferred provider
2997
3086
  // error must wait for the reminder-only iteration that actually ends it.
2998
3087
  const retryQueuedThisTurn =
2999
- live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
3000
- await maybePostDeferredProviderError(live, sentReplyThisTurn, retryQueuedThisTurn)
3088
+ live.emptyTurnRetries > emptyTurnRetriesBeforePrompt ||
3089
+ live.toolLeakRetries > toolLeakRetriesBeforePrompt ||
3090
+ live.willingnessNudges > willingnessNudgesBeforePrompt
3091
+ await maybePostDeferredProviderError(
3092
+ live,
3093
+ sentReplyThisTurn && !hasPendingContinueReply(live),
3094
+ retryQueuedThisTurn,
3095
+ )
3001
3096
  await fireSessionTurnEnd(live)
3002
3097
  }
3003
3098
  await fireSessionIdle(live)
@@ -3013,6 +3108,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3013
3108
  live.currentTurnAuthorId = null
3014
3109
  live.currentTurnAuthorIds = new Set()
3015
3110
  live.currentTurnReactionRef = null
3111
+ live.currentTurnExplicitlyAddressed = false
3016
3112
  live.currentTurnEngageReactions = []
3017
3113
  // Drop any still-held reactions if the loop exited without running the
3018
3114
  // per-turn finally (e.g. session destroyed mid-drain): never leave a
@@ -3709,6 +3805,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3709
3805
  else typingCapableAdapters.delete(adapter)
3710
3806
  }
3711
3807
 
3808
+ const setTypingHeartbeatInterval = (adapter: ChannelKey['adapter'], intervalMs: number): void => {
3809
+ typingHeartbeatIntervals.set(adapter, intervalMs)
3810
+ }
3811
+
3812
+ const typingHeartbeatIntervalFor = (adapter: ChannelKey['adapter']): number =>
3813
+ typingHeartbeatIntervals.get(adapter) ?? TYPING_HEARTBEAT_MS
3814
+
3712
3815
  const setAdapterConfigured = (adapter: ChannelKey['adapter'], configured: boolean): void => {
3713
3816
  if (configured) configuredAdapters.add(adapter)
3714
3817
  else configuredAdapters.delete(adapter)
@@ -3786,6 +3889,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3786
3889
  ? `${capability}-adapter-unavailable: the "${adapter}" adapter is configured but not currently running (it likely failed to start, e.g. an expired token or auth error — check the container logs and re-authenticate)`
3787
3890
  : `${capability}-not-supported`
3788
3891
 
3892
+ const isWriteCapabilityUnavailable = (adapter: ChannelKey['adapter'], capability: WriteCapability): boolean =>
3893
+ configuredAdapters.has(adapter) && ADAPTER_WRITE_CAPABILITIES[adapter].includes(capability)
3894
+
3789
3895
  const fetchHistory = async (adapter: ChannelKey['adapter'], args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
3790
3896
  const callbacks = historyCallbacks.get(adapter)
3791
3897
  if (!callbacks || callbacks.size === 0) {
@@ -3852,6 +3958,59 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3852
3958
  }
3853
3959
  }
3854
3960
 
3961
+ const registerEditMessage = (adapter: ChannelKey['adapter'], cb: EditMessageCallback): void => {
3962
+ let set = editMessageCallbacks.get(adapter)
3963
+ if (!set) {
3964
+ set = new Set()
3965
+ editMessageCallbacks.set(adapter, set)
3966
+ }
3967
+ set.add(cb)
3968
+ }
3969
+
3970
+ const unregisterEditMessage = (adapter: ChannelKey['adapter'], cb: EditMessageCallback): void => {
3971
+ editMessageCallbacks.get(adapter)?.delete(cb)
3972
+ }
3973
+
3974
+ const editMessage = async (req: EditMessageRequest): Promise<EditMessageResult> => {
3975
+ // Strip leaked `<think>` blocks before the edit reaches any adapter, exactly
3976
+ // as the send path does via normalizeSendText — an edit is another way text
3977
+ // reaches the chat, so it must not become a hole that writes raw reasoning a
3978
+ // send would have suppressed. A replacement that is ONLY a think block leaves
3979
+ // nothing visible, so refuse rather than blank the message.
3980
+ const normalized = normalizeSendText(req.text)
3981
+ if (normalized === undefined) {
3982
+ return { ok: false, error: 'message-edit-empty-after-normalization', code: 'not-found' }
3983
+ }
3984
+ const normalizedReq = normalized === req.text ? req : { ...req, text: normalized }
3985
+ const callbacks = editMessageCallbacks.get(req.adapter)
3986
+ if (!callbacks || callbacks.size === 0) {
3987
+ return isWriteCapabilityUnavailable(req.adapter, 'message-edit')
3988
+ ? {
3989
+ ok: false,
3990
+ error: `message-edit-adapter-unavailable: the "${req.adapter}" adapter is configured but not currently running (it likely failed to start, e.g. an expired token or auth error — check the container logs and re-authenticate)`,
3991
+ code: 'adapter-unavailable',
3992
+ }
3993
+ : { ok: false, error: 'message-edit-not-supported', code: 'not-supported' }
3994
+ }
3995
+ const snapshot = Array.from(callbacks)
3996
+ let lastError: EditMessageResult & { ok: false } = { ok: false, error: 'message-edit-not-supported' }
3997
+ for (const cb of snapshot) {
3998
+ try {
3999
+ const result = await raceWithTimeout(
4000
+ cb(normalizedReq),
4001
+ fetchHistoryTimeoutMs,
4002
+ `[channels] ${req.adapter} edit message`,
4003
+ )
4004
+ if (result.ok) return result
4005
+ lastError = result
4006
+ } catch (err) {
4007
+ logger.warn(`[channels] edit message threw for ${req.adapter}: ${describe(err)}`)
4008
+ lastError = { ok: false, error: `edit message failed: ${describe(err)}` }
4009
+ }
4010
+ }
4011
+ return lastError
4012
+ }
4013
+
3855
4014
  const registerFetchAttachment = (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback): void => {
3856
4015
  let set = fetchAttachmentCallbacks.get(adapter)
3857
4016
  if (!set) {
@@ -4356,6 +4515,47 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4356
4515
  if (live.successfulChannelSends > successfulSendsBeforePrompt) {
4357
4516
  maybeNudgeContinuationWillingness(live)
4358
4517
 
4518
+ // A `channel_reply({ continue: true })` progress ack landed this turn (the
4519
+ // machine-readable "I'll keep working" promise — `continueReplyTurn` is stamped
4520
+ // by installChannelReplyTerminalHook), the model did more work, then ended on a
4521
+ // FRESH empty `stop` — dropping its conclusion. This is the SAME degeneration as
4522
+ // the phrase-gated `channel_send` branch below, but keyed on the `continue: true`
4523
+ // FLAG instead of a natural-language willingness phrase. The flag is the robust
4524
+ // signal: it fires regardless of the ack's language or register, closing the gap
4525
+ // where a persona speaking a phrasing outside the willingness table (e.g. casual
4526
+ // Korean "확인해볼게") stranded the user in silence. The `attemptMadeToolCall`
4527
+ // half ties the first trigger to real post-ack work; `willingnessNudges > 0`
4528
+ // lets a retry that re-emitted `continue: true` and re-stranded spend the shared
4529
+ // budget toward the visible fallback instead of bailing silent. Same
4530
+ // MAX_WILLINGNESS_NUDGES bound, same empty-`promptQueue` gate (a coalesced live
4531
+ // inbound supersedes this turn's silence), and same nudge/fallback path as the
4532
+ // send-ack branch. Placed FIRST so the flag catch wins when both signals are
4533
+ // present; the phrase branch remains the only recovery for `channel_send`, which
4534
+ // stamps no flag. The `sendCount === successfulChannelSends` check requires the
4535
+ // continue-reply to STILL be the latest successful send: if a later substantive
4536
+ // send (e.g. a `channel_send` final answer) landed after the ack, the user was
4537
+ // already answered and a trailing empty stop must NOT be re-nudged.
4538
+ if (
4539
+ live.promptQueue.length === 0 &&
4540
+ live.currentTurnAuthorId !== null &&
4541
+ live.continueReplyTurn?.turnSeq === live.turnSeq &&
4542
+ live.continueReplyTurn.sendCount === live.successfulChannelSends &&
4543
+ isFreshEmptyStopAfterSend(live) &&
4544
+ (attemptMadeToolCall(live.session) || live.willingnessNudges > 0)
4545
+ ) {
4546
+ if (live.willingnessNudges < MAX_WILLINGNESS_NUDGES) {
4547
+ live.willingnessNudges++
4548
+ logger.warn(
4549
+ `[channels] ${live.keyId} send_willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES} ` +
4550
+ `cause=empty_stop_after_continue_reply`,
4551
+ )
4552
+ live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
4553
+ } else {
4554
+ await postEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
4555
+ }
4556
+ return
4557
+ }
4558
+
4359
4559
  // A `channel_send` ack that promised to keep working, fresh post-ack work,
4360
4560
  // then an EMPTY `stop` leaf: the model computed the answer in its reasoning
4361
4561
  // / tool results but never sent it (the Kimi/Fireworks empty-completion
@@ -4620,6 +4820,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4620
4820
  return
4621
4821
  }
4622
4822
 
4823
+ // Prose-then-trailing-call leak: the model wrote a real reply and then
4824
+ // serialized a tool decision as a trailing block (the Discord skip_response
4825
+ // incident). Strip the plumbing and keep the prose BEFORE the whole-message
4826
+ // classification below, so a message that was ONLY the call still reaches the
4827
+ // existing name-dependent suppress/recover path, while a message with real
4828
+ // prose keeps that prose. Prefix-first: no arg-recovery, no nudge, no ack.
4829
+ const trailingLeak = stripTrailingLeakedToolCall(assistantText)
4830
+ if (trailingLeak !== null && trailingLeak.text !== '') {
4831
+ logger.warn(
4832
+ `[channels] ${live.keyId}: stripped trailing_tool_call_leak tool=${trailingLeak.toolName} ` +
4833
+ `text_len=${trailingLeak.text.length}`,
4834
+ )
4835
+ assistantText = trailingLeak.text
4836
+ }
4837
+
4623
4838
  if (isUpstreamEmptyResponseSentinel(assistantText)) {
4624
4839
  logger.warn(
4625
4840
  `[channels] ${live.keyId}: suppressed upstream_empty_response_sentinel text_len=${assistantText.length}`,
@@ -5130,6 +5345,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5130
5345
  if (resolved.kind === 'ambiguous') {
5131
5346
  return { kind: 'ambiguous', matchCount: resolved.count }
5132
5347
  }
5348
+ // A resolved session that isn't actually running has nothing for /stop to
5349
+ // cancel; report it as no-live-session so bystander agents stay silent.
5350
+ if (lowered === 'stop' && !hasStoppableWork(resolved.session)) {
5351
+ return { kind: 'no-live-session' }
5352
+ }
5133
5353
  live = resolved.session
5134
5354
  } else if (commandInfo.wantsLiveSession) {
5135
5355
  // Best-effort: resolve a session if exactly one matches, but never fail
@@ -5344,6 +5564,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5344
5564
  }
5345
5565
 
5346
5566
  const armSilentTurnAck = (live: LiveSession, reason: SilentAckReason): void => {
5567
+ // A GitHub review IS its own emoji-shaped output, so it always earns the
5568
+ // 👀; every other deliberate silence earns one ONLY when the triggering
5569
+ // message was addressed to the bot. Staying quiet in ambient chatter leaves
5570
+ // no mark, so a busy room never accumulates stale 👀 on messages the bot
5571
+ // was never part of.
5572
+ const eligible =
5573
+ reason === 'github_review_output' ? live.key.adapter === 'github' : live.currentTurnExplicitlyAddressed
5574
+ if (!eligible) return
5347
5575
  live.silentAckTurn = { turnSeq: live.turnSeq, reason }
5348
5576
  }
5349
5577
 
@@ -5436,6 +5664,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5436
5664
  registerTyping,
5437
5665
  unregisterTyping,
5438
5666
  setTypingCapability,
5667
+ setTypingHeartbeatInterval,
5439
5668
  setAdapterConfigured,
5440
5669
  registerChannelNameResolver,
5441
5670
  unregisterChannelNameResolver,
@@ -5452,6 +5681,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5452
5681
  registerList,
5453
5682
  unregisterList,
5454
5683
  listChannels,
5684
+ registerEditMessage,
5685
+ unregisterEditMessage,
5686
+ editMessage,
5455
5687
  registerFetchAttachment,
5456
5688
  unregisterFetchAttachment,
5457
5689
  fetchAttachment,
@@ -5530,6 +5762,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5530
5762
  if (!live) return
5531
5763
  await stopTypingHeartbeat(live)
5532
5764
  },
5765
+ typingHeartbeatIntervalFor,
5533
5766
  runIdleGc,
5534
5767
  getLiveOriginSnapshot: (key: ChannelKey) => {
5535
5768
  const live = liveSessions.get(channelKeyId(key))
@@ -6097,10 +6330,19 @@ export type ResolveLiveSessionResult =
6097
6330
  // return 'ambiguous' so the caller can refuse to act rather than abort an
6098
6331
  // arbitrary session.
6099
6332
  //
6100
- // Why the fallback: Slack slash commands carry channel_id but no thread_ts,
6101
- // so a slash invocation from a thread-keyed live session would otherwise
6102
- // report no-live-session. Discord doesn't hit this — Discord treats threads
6103
- // as channels, so the exact-key path already resolves.
6333
+ // Why the fallback: Slack slash commands carry channel_id but no thread_ts
6334
+ // (`thread: null`), so a slash invocation from a thread-keyed live session
6335
+ // would otherwise report no-live-session. Discord doesn't hit this — Discord
6336
+ // treats threads as channels, so the exact-key path already resolves.
6337
+ //
6338
+ // Why the fallback is thread-null-ONLY: a `!stop` typed INSIDE a Slack thread
6339
+ // carries the real `thread_ts`, so it pinpoints one exact thread. Falling back
6340
+ // to "any session in this channel" for a thread-specific key would let the
6341
+ // command hit an UNRELATED session in a different thread (or a channel-level
6342
+ // observe-only session) — the multi-agent bug where a bystander bot that only
6343
+ // observed the thread aborts its own idle session and posts "stopped". A
6344
+ // non-null thread that misses the exact lookup therefore returns 'none', never
6345
+ // the cross-thread fallback.
6104
6346
  //
6105
6347
  // Why ambiguity-rejection: "first match wins" map-iteration semantics would
6106
6348
  // abort an arbitrary thread when multiple thread-keyed sessions coexist in
@@ -6114,6 +6356,8 @@ export function resolveLiveSessionForCommand(
6114
6356
  const exact = liveSessions.get(channelKeyId(key))
6115
6357
  if (exact && !exact.destroyed) return { kind: 'found', session: exact }
6116
6358
 
6359
+ if (key.thread !== null) return { kind: 'none' }
6360
+
6117
6361
  const matches: LiveSession[] = []
6118
6362
  for (const candidate of liveSessions.values()) {
6119
6363
  if (candidate.destroyed) continue
@@ -6375,20 +6619,29 @@ function leafIsStrandedToolUse(session: AgentSession): boolean {
6375
6619
  return false
6376
6620
  }
6377
6621
 
6378
- // True when the turn-end leaf is a FRESH empty `stop` (no text, no tool call,
6379
- // distinct from the leaf in place at the last successful send) AND the most
6380
- // recent send to this target was a continuation-willingness ack. This is the
6381
- // `channel_send` analogue of the `channel_reply` willingness path: the model
6382
- // acked "I'll check…", did post-ack work, then the follow-up came back as a
6383
- // clean empty completion that would otherwise be read as a deliberate `NO_REPLY`.
6384
- // The fresh-leaf check (`!== lastSendLeafId`) is what separates this degeneration
6385
- // from a legitimate ack-then-stop where the model meant to wait for the user.
6386
- function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
6622
+ // The turn-end leaf is a FRESH empty `stop` — an assistant message with no visible
6623
+ // text and no tool call, distinct from the leaf in place at the last successful
6624
+ // send. "Fresh" (`!== lastSendLeafId`) is what separates a post-send degeneration
6625
+ // (the model did more work, then dropped its conclusion) from a legitimate
6626
+ // ack-then-stop where the model meant to wait for the user (leaf unchanged since
6627
+ // the send). The two willingness paths below layer their own promise-signal on top
6628
+ // of this shape: `channel_reply({ continue: true })` via `continueReplyTurn`, and
6629
+ // `channel_send` acks via the willingness phrase table.
6630
+ function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
6387
6631
  const leaf = live.session.sessionManager.getLeafEntry()
6388
6632
  if (!leaf || leaf.type !== 'message' || leaf.message.role !== 'assistant') return false
6389
6633
  if (leaf.message.stopReason !== 'stop') return false
6390
6634
  if (hasToolCall(leaf.message) || visibleAssistantText(leaf.message).trim() !== '') return false
6391
- if (leaf.id === live.lastSendLeafId) return false
6635
+ return leaf.id !== live.lastSendLeafId
6636
+ }
6637
+
6638
+ // The `channel_send` analogue of the `continue: true` recovery: the most recent
6639
+ // send to this target was a continuation-willingness ack (by phrase), then the
6640
+ // model produced a fresh empty stop. `channel_send` keeps the turn alive without a
6641
+ // `continue: true` flag and stamps no semantic marker, so the phrase table is the
6642
+ // only "I promised to keep working" signal available for that shape.
6643
+ function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
6644
+ if (!isFreshEmptyStopAfterSend(live)) return false
6392
6645
  const ackText = live.lastSentText.get(consecutiveSendKey(live.key.chat, live.key.thread))
6393
6646
  return ackText !== undefined && detectContinuationWillingness(ackText)
6394
6647
  }
@@ -6700,6 +6953,233 @@ export function isWholeMessageToolCall(text: string): string | null {
6700
6953
  return null
6701
6954
  }
6702
6955
 
6956
+ export type TrailingToolCallLeak = { text: string; toolName: string; leakedCall: string }
6957
+
6958
+ // Catches the sibling leak that `isWholeMessageToolCall` cannot: the model wrote
6959
+ // a REAL reply, then serialized a tool decision as a trailing block instead of
6960
+ // emitting a real tool call. The production incident (Discord) was Korean prose,
6961
+ // a blank line, then `skip_response({ reason: "..." })` — the whole-message
6962
+ // parser saw prose before the call, returned null, and the plumbing shipped
6963
+ // verbatim, confirming to probing users that it's a bot and exposing an internal
6964
+ // tool name.
6965
+ //
6966
+ // The whole-message contract of `isWholeMessageToolCall` is deliberately NOT
6967
+ // broadened: it stays "the entire message is a call" so a name-dependent
6968
+ // disposition (reply/send recover, skip silent, else nudge) still applies to a
6969
+ // message that is nothing but a call. This is the STRICTLY narrower sibling —
6970
+ // "prose, THEN a trailing standalone call block" — with a prefix-first
6971
+ // disposition: the prose is a legitimate reply the user must see, so we post it
6972
+ // and drop only the trailing plumbing, regardless of which tool leaked. No
6973
+ // arg-recovery, no nudge, no silent-turn ack — the prose already satisfied the
6974
+ // turn.
6975
+ //
6976
+ // The false-positive surface is contained by three STRUCTURAL (language-agnostic,
6977
+ // per the repo's multi-language rule) signals, none of which interpret prose:
6978
+ // 1. a BLANK line must separate prefix from the trailing block — an adjacent
6979
+ // final line (`Explanation:\nskip_response()`) is left untouched, since a
6980
+ // model teaching a tool inline never blank-line-separates the example;
6981
+ // 2. the trailing block must independently satisfy `isWholeMessageToolCall`
6982
+ // (bracket-aware, quote-honoring) — a bare `channel_react whenever…` word or
6983
+ // `read({...}) loads a file` mid-sentence is not a whole call;
6984
+ // 3. the block must NOT begin inside a Markdown fenced code block — a fenced
6985
+ // ``` example ending in a call is legitimate teaching output.
6986
+ // The prefix must stay non-empty after trimming, else this is the whole-message
6987
+ // case and belongs to the existing parser.
6988
+ //
6989
+ // Multiple contiguous trailing call blocks are stripped iteratively (each must
6990
+ // independently pass the predicate); the loop stops at the first non-call block.
6991
+ export function stripTrailingLeakedToolCall(text: string): TrailingToolCallLeak | null {
6992
+ const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
6993
+ let body = normalized
6994
+ let outerToolName: string | null = null
6995
+ let outerLeakedCall = ''
6996
+
6997
+ for (;;) {
6998
+ // Locate the final blank-line-separated block: <prefix>\n[ \t]*\n<candidate>,
6999
+ // where <candidate> is the trailing run with no interior blank line.
7000
+ const match = /\n[ \t]*\n([^\n]*(?:\n(?![ \t]*\n)[^\n]*)*)[ \t\n]*$/.exec(body)
7001
+ if (match === null) break
7002
+ const rawCandidate = match[1]!
7003
+ const candidate = rawCandidate.trim()
7004
+ if (candidate === '') break
7005
+ const prefix = body.slice(0, match.index)
7006
+ if (prefix.trim() === '') break
7007
+
7008
+ // Classify BEFORE the fence check: a whole-message tool call can never itself
7009
+ // be a fence marker, which is what lets the fence scanner treat the
7010
+ // candidate's first line purely as a container-continuation signal.
7011
+ const toolName = isWholeMessageToolCall(candidate)
7012
+ if (toolName === null) break
7013
+
7014
+ // The candidate's own first line decides whether it still continues an open
7015
+ // list/blockquote container: an unquoted or dedented candidate has LEFT the
7016
+ // container, so a container-owned fence no longer protects it.
7017
+ const candidateFirstLine = rawCandidate.split('\n', 1)[0]!
7018
+ if (startsInsideFencedCodeBlock(prefix, candidateFirstLine)) break
7019
+
7020
+ if (outerToolName === null) {
7021
+ outerToolName = toolName
7022
+ outerLeakedCall = candidate
7023
+ }
7024
+ body = prefix
7025
+ }
7026
+
7027
+ if (outerToolName === null) return null
7028
+ return { text: body.trimEnd(), toolName: outerToolName, leakedCall: outerLeakedCall }
7029
+ }
7030
+
7031
+ // A fence carries the container requirements it was opened under. Both are
7032
+ // independent: a `> - ``` ` opener requires BOTH a blockquote (`requiresQuote`)
7033
+ // and the list content column, so leaving EITHER container abandons the fence.
7034
+ // This captures at most one blockquote requirement + one post-blockquote list
7035
+ // column — a bounded stack, not an arbitrary container parser.
7036
+ type FenceOwner = { requiresQuote: boolean; listContentColumn: number | null }
7037
+ type OpenFence = { char: '`' | '~'; len: number; owner: FenceOwner }
7038
+
7039
+ // Best-effort fenced-code detection for the trailing-tool-call safety guard.
7040
+ // Returns true when the candidate (whose first raw line is `candidateFirstLine`)
7041
+ // sits inside a still-open Markdown fence — meaning the trailing call is fenced
7042
+ // example content and must NOT be stripped.
7043
+ //
7044
+ // Top-level and blockquote-prefixed fences use normal opener/closer bookkeeping;
7045
+ // list-marker-prefixed fences are recognized as OPENERS only. An open
7046
+ // blockquote-owned fence is abandoned by an unquoted non-blank line, and an open
7047
+ // list-owned fence by a non-blank line indented before the marker's recorded
7048
+ // content column (see `abandonIfLeftContainer`). The candidate's OWN first line is
7049
+ // run through the same abandon check last: an unquoted/dedented candidate has left
7050
+ // its container, so a container-owned fence no longer protects it and the call is
7051
+ // stripped. Blank lines never abandon; top-level fences are never abandoned, so a
7052
+ // column-zero candidate under an ordinary open top-level fence stays protected.
7053
+ //
7054
+ // This deliberately approximates container continuity: a fence tracks at most one
7055
+ // blockquote requirement plus one post-blockquote list content column (so a
7056
+ // `> - ``` ` fence requires BOTH), while paragraph lazy continuation, exact
7057
+ // CommonMark list padding, DEEPER nested stacks (list-in-list, quote-in-list-in-
7058
+ // quote), and container re-entry are out of scope. The safety bias is toward "in a
7059
+ // fence" (a missed close leaves a legitimate example unstripped, safer than
7060
+ // stripping it), bounded by the container-exit rules so a real leak that has left
7061
+ // its container is still caught.
7062
+ function startsInsideFencedCodeBlock(prefix: string, candidateFirstLine: string): boolean {
7063
+ let open: OpenFence | null = null
7064
+ // The list item currently in effect (measured post-blockquote-strip), so a
7065
+ // fence that opens on a list item's CONTINUATION line — `- item`\n` ``` `,
7066
+ // not the `- ``` ` marker line — inherits the item's content column and is
7067
+ // abandoned when a later line dedents out of it. Tracks its own quote
7068
+ // requirement so an unquoted line can't inherit a list started inside `> …`.
7069
+ let activeListItem: { contentColumn: number; requiresQuote: boolean } | null = null
7070
+
7071
+ for (const rawLine of prefix.split('\n')) {
7072
+ open = abandonIfLeftContainer(open, rawLine)
7073
+ const { line, quoted } = stripBlockquoteMarkers(rawLine)
7074
+
7075
+ // Maintain the active list item only outside a fence (fenced content must not
7076
+ // create list state): a marker line replaces it; a non-blank line that leaves
7077
+ // its quote context or dedents before its content column expires it; blank
7078
+ // lines preserve it.
7079
+ if (open === null) {
7080
+ const listItem = /^( {0,3})((?:[-+*]|\d{1,9}[.)])[ \t]+)/.exec(line)
7081
+ if (listItem !== null) {
7082
+ activeListItem = { contentColumn: columnWidth(listItem[1]! + listItem[2]!), requiresQuote: quoted }
7083
+ } else if (
7084
+ line.trim() !== '' &&
7085
+ activeListItem !== null &&
7086
+ (activeListItem.requiresQuote !== quoted || leadingIndentColumns(line) < activeListItem.contentColumn)
7087
+ ) {
7088
+ activeListItem = null
7089
+ }
7090
+ }
7091
+
7092
+ const plainFence = /^( {0,3})(`{3,}|~{3,})([^\n]*)$/.exec(line)
7093
+ if (plainFence !== null) {
7094
+ const indent = plainFence[1]!
7095
+ const run = plainFence[2]!
7096
+ const char = run[0] as '`' | '~'
7097
+ const rest = plainFence[3]!
7098
+ if (open === null) {
7099
+ if (char === '`' && rest.includes('`')) continue
7100
+ // A plain opener indented into the active list item inherits its content
7101
+ // column (continuation-line fence); a genuinely top-level opener keeps null.
7102
+ const listContentColumn =
7103
+ activeListItem !== null &&
7104
+ activeListItem.requiresQuote === quoted &&
7105
+ columnWidth(indent) >= activeListItem.contentColumn
7106
+ ? activeListItem.contentColumn
7107
+ : null
7108
+ open = { char, len: run.length, owner: { requiresQuote: quoted, listContentColumn } }
7109
+ } else if (char === open.char && run.length >= open.len && rest.trim() === '') {
7110
+ open = null
7111
+ }
7112
+ continue
7113
+ }
7114
+
7115
+ // A list-marker-prefixed fence only ever OPENS; inside an open fence it is
7116
+ // fenced content, not a closer. It records BOTH requirements it was opened
7117
+ // under: the blockquote (`> - ``` `) and the list content column — the full
7118
+ // width of the marker prefix (`- `, `1. `, nested chains, post-quote-strip),
7119
+ // tabs expanded — so a later line that leaves EITHER has left the item.
7120
+ if (open !== null) continue
7121
+ const listFence = /^((?: {0,3}(?:[-+*]|\d{1,9}[.)])[ \t]+)+) {0,3}(`{3,}|~{3,})([^\n]*)$/.exec(line)
7122
+ if (listFence === null) continue
7123
+ const markerPrefix = listFence[1]!
7124
+ const run = listFence[2]!
7125
+ const char = run[0] as '`' | '~'
7126
+ const rest = listFence[3]!
7127
+ if (char === '`' && rest.includes('`')) continue
7128
+ open = { char, len: run.length, owner: { requiresQuote: quoted, listContentColumn: columnWidth(markerPrefix) } }
7129
+ }
7130
+ // The candidate's own first line is the final container-continuation signal: an
7131
+ // unquoted (blockquote) or dedented (list) candidate has left the container, so
7132
+ // a container-owned fence no longer protects it. The candidate is never itself a
7133
+ // fence marker (it already passed isWholeMessageToolCall), so only the abandon
7134
+ // check applies here — no fence open/close bookkeeping.
7135
+ return abandonIfLeftContainer(open, candidateFirstLine) !== null
7136
+ }
7137
+
7138
+ // Returns the fence with its owning container(s) still intact, or null when the
7139
+ // given raw line has LEFT any required container: a fence that requires a
7140
+ // blockquote is abandoned by an unquoted non-blank line, and a fence with a list
7141
+ // content column is abandoned by a non-blank line indented before it. The two
7142
+ // requirements are independent (OR), so a `> - ``` ` fence is abandoned by leaving
7143
+ // EITHER the blockquote or the list. A fence with no requirements (top-level) and
7144
+ // blank lines never abandon.
7145
+ function abandonIfLeftContainer(open: OpenFence | null, rawLine: string): OpenFence | null {
7146
+ if (open === null) return null
7147
+ const { line, quoted } = stripBlockquoteMarkers(rawLine)
7148
+ if (line.trim() === '') return open
7149
+ if (open.owner.requiresQuote && !quoted) return null
7150
+ if (open.owner.listContentColumn !== null && leadingIndentColumns(line) < open.owner.listContentColumn) return null
7151
+ return open
7152
+ }
7153
+
7154
+ // Removes one or more leading blockquote markers so a `> ```` fence participates
7155
+ // in bookkeeping as if unquoted, and reports whether the line was quoted so the
7156
+ // caller can detect the blockquote-exit that abandons a blockquote-owned fence.
7157
+ function stripBlockquoteMarkers(line: string): { line: string; quoted: boolean } {
7158
+ const match = /^(?: {0,3}>[ \t]?)+(.*)$/.exec(line)
7159
+ return match === null ? { line, quoted: false } : { line: match[1]!, quoted: true }
7160
+ }
7161
+
7162
+ // Leading-indent width in columns (whitespace only, stopping at the first
7163
+ // non-space), expanding tabs to the next 4-column stop. Used to compare a later
7164
+ // line's indentation against a list item's content column.
7165
+ function leadingIndentColumns(line: string): number {
7166
+ let column = 0
7167
+ for (const char of line) {
7168
+ if (char === ' ') column += 1
7169
+ else if (char === '\t') column += 4 - (column % 4)
7170
+ else break
7171
+ }
7172
+ return column
7173
+ }
7174
+
7175
+ // Full display width of a string in columns, expanding tabs to the next 4-column
7176
+ // stop. Used to measure a list marker prefix so the content column lands after it.
7177
+ function columnWidth(s: string): number {
7178
+ let column = 0
7179
+ for (const char of s) column += char === '\t' ? 4 - (column % 4) : 1
7180
+ return column
7181
+ }
7182
+
6703
7183
  // Tolerant single-purpose scanner that pulls the `text` argument out of a
6704
7184
  // plain-text-serialized `channel_reply(...)` / `channel_send(...)` leak. A
6705
7185
  // single regex covering every shape (double/single/unquoted keys, escaped