typeclaw 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +67 -25
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/loop-guard.ts +208 -10
  7. package/src/agent/multimodal/index.ts +1 -1
  8. package/src/agent/multimodal/look-at.ts +78 -44
  9. package/src/agent/multimodal/looker.ts +151 -39
  10. package/src/agent/network/response-body.ts +26 -0
  11. package/src/agent/network/safe-http.ts +198 -0
  12. package/src/agent/plugin-tools.ts +438 -162
  13. package/src/agent/provider-error.ts +62 -4
  14. package/src/agent/restart/index.ts +61 -40
  15. package/src/agent/restart-handoff/index.ts +73 -4
  16. package/src/agent/retry-same-ref.ts +66 -0
  17. package/src/agent/reviewer-bash-policy.ts +42 -1
  18. package/src/agent/session-origin.ts +2 -0
  19. package/src/agent/subagent-drain.ts +117 -7
  20. package/src/agent/subagents.ts +77 -18
  21. package/src/agent/throttle-circuit.ts +25 -5
  22. package/src/agent/tool-error-remediation.ts +72 -0
  23. package/src/agent/tool-file-safety.ts +1050 -0
  24. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  25. package/src/agent/tools/channel-reply.ts +15 -1
  26. package/src/agent/tools/channel-send.ts +17 -1
  27. package/src/agent/tools/ddg.ts +16 -2
  28. package/src/agent/tools/post-github-review.ts +199 -0
  29. package/src/agent/tools/spawn-subagent.ts +21 -18
  30. package/src/agent/tools/webfetch/fetch.ts +143 -183
  31. package/src/agent/tools/webfetch/tool.ts +2 -3
  32. package/src/agent/tools/websearch.ts +23 -2
  33. package/src/agent/tools-without-local-file-operands.ts +27 -0
  34. package/src/agent/turn-runner.ts +109 -15
  35. package/src/bundled-plugins/backup/index.ts +2 -1
  36. package/src/bundled-plugins/backup/runner.ts +2 -1
  37. package/src/bundled-plugins/doc-render/render.ts +93 -12
  38. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  39. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  40. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  41. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  42. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  43. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  44. package/src/bundled-plugins/memory/README.md +23 -11
  45. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  46. package/src/bundled-plugins/memory/citations.ts +22 -9
  47. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  48. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  49. package/src/bundled-plugins/memory/index.ts +0 -4
  50. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  51. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  52. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  53. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  54. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  55. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  56. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  57. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  58. package/src/bundled-plugins/reviewer/index.ts +2 -2
  59. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  60. package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
  61. package/src/bundled-plugins/scout/scout.ts +8 -0
  62. package/src/bundled-plugins/security/index.ts +4 -4
  63. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  64. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  65. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  66. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  67. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  68. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  69. package/src/channels/adapters/discord-bot.ts +91 -10
  70. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  71. package/src/channels/adapters/discord-id.ts +4 -0
  72. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  73. package/src/channels/adapters/discord.ts +57 -7
  74. package/src/channels/adapters/github/auth-app.ts +41 -12
  75. package/src/channels/adapters/github/index.ts +23 -11
  76. package/src/channels/adapters/github/review-submitter.ts +302 -0
  77. package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
  78. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  79. package/src/channels/adapters/kakaotalk-typing.ts +127 -0
  80. package/src/channels/adapters/kakaotalk.ts +19 -0
  81. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  82. package/src/channels/adapters/slack-bot.ts +19 -8
  83. package/src/channels/adapters/slack-classify.ts +21 -2
  84. package/src/channels/adapters/slack.ts +59 -7
  85. package/src/channels/adapters/telegram-bot.ts +18 -5
  86. package/src/channels/adapters/webex-bot.ts +8 -3
  87. package/src/channels/adapters/webex.ts +8 -3
  88. package/src/channels/fetch-attachment.ts +43 -0
  89. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  90. package/src/channels/github-token-bridge.ts +10 -3
  91. package/src/channels/manager.ts +9 -0
  92. package/src/channels/router.ts +568 -12
  93. package/src/channels/types.ts +28 -1
  94. package/src/cli/channel.ts +1 -1
  95. package/src/cli/init.ts +1 -1
  96. package/src/cli/model.ts +57 -7
  97. package/src/compose/stop.ts +17 -5
  98. package/src/config/config.ts +6 -6
  99. package/src/config/models-mutation.ts +13 -1
  100. package/src/config/providers.ts +176 -0
  101. package/src/container/start.ts +49 -10
  102. package/src/doctor/checks.ts +3 -1
  103. package/src/doctor/commit.ts +2 -1
  104. package/src/doctor/file-ownership.ts +52 -0
  105. package/src/dreams/git.ts +2 -1
  106. package/src/git/hookless.ts +5 -0
  107. package/src/git/reconcile-ignored.ts +18 -5
  108. package/src/git/secret-history.ts +371 -0
  109. package/src/git/system-commit.ts +12 -6
  110. package/src/init/dockerfile.ts +86 -5
  111. package/src/init/index.ts +17 -5
  112. package/src/init/models-dev.ts +4 -0
  113. package/src/init/validate-api-key.ts +2 -0
  114. package/src/mcp/tools.ts +16 -3
  115. package/src/permissions/builtins.ts +3 -1
  116. package/src/plugin/context.ts +2 -0
  117. package/src/plugin/index.ts +1 -0
  118. package/src/plugin/manager.ts +4 -0
  119. package/src/plugin/types.ts +21 -0
  120. package/src/run/index.ts +40 -0
  121. package/src/run/llm-fetch-observer.ts +188 -13
  122. package/src/sandbox/build.ts +37 -15
  123. package/src/sandbox/canonical-secrets.ts +18 -0
  124. package/src/sandbox/env-exposure.ts +80 -0
  125. package/src/sandbox/errors.ts +13 -6
  126. package/src/sandbox/hidden-paths.ts +102 -44
  127. package/src/sandbox/index.ts +22 -4
  128. package/src/sandbox/package-install.ts +3 -27
  129. package/src/sandbox/policy.ts +11 -25
  130. package/src/sandbox/privileged-runtime.ts +255 -0
  131. package/src/sandbox/session-tmp.ts +8 -2
  132. package/src/sandbox/writable-zones.ts +204 -140
  133. package/src/secrets/index.ts +8 -0
  134. package/src/secrets/refresh-provider-oauth.ts +128 -0
  135. package/src/server/command-runner.ts +48 -4
  136. package/src/server/index.ts +4 -0
  137. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  138. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  139. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  140. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  141. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  142. package/src/skills/typeclaw-config/SKILL.md +5 -5
  143. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  144. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  145. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  146. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  147. package/typeclaw.schema.json +20 -0
@@ -10,7 +10,13 @@ import { resolveFallbackChain } from '@/agent/model-fallback'
10
10
  import { applyModelRuntimeOverrides } from '@/agent/model-overrides'
11
11
  import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
12
12
  import { detectHardProviderError, isFailoverWorthy, subscribeProviderErrors } from '@/agent/provider-error'
13
- import type { RestartHandoff } from '@/agent/restart-handoff'
13
+ import {
14
+ acquireRestartHandoffLock,
15
+ peekRestartHandoff,
16
+ RESTART_HANDOFF_TTL_MS,
17
+ type RestartHandoff,
18
+ writeRestartHandoff,
19
+ } from '@/agent/restart-handoff'
14
20
  import type { ChannelParticipant, SessionOrigin } from '@/agent/session-origin'
15
21
  import { renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
16
22
  import {
@@ -105,6 +111,7 @@ import type {
105
111
  ReactionRequest,
106
112
  ReactionResult,
107
113
  ResolvedChannelNames,
114
+ ReviewSubmitter,
108
115
  ReviewStateRequest,
109
116
  ReviewStateResolver,
110
117
  ReviewStateResult,
@@ -113,6 +120,8 @@ import type {
113
120
  ReviewThreadResolver,
114
121
  SendErrorCode,
115
122
  SendResult,
123
+ SubmitReviewRequest,
124
+ SubmitReviewResult,
116
125
  TypingCallback,
117
126
  } from './types'
118
127
  import { channelKeyId } from './types'
@@ -130,6 +139,10 @@ export const CONTEXT_BUFFER_SIZE = 20
130
139
  export const OBSERVED_MESSAGE_MAX_CHARS = 800
131
140
  // Discord's typing indicator expires after ~10s; an 8s heartbeat keeps it
132
141
  // continuously visible while we debounce + generate without spamming the API.
142
+ // This is the default; an adapter whose platform expires the indicator sooner
143
+ // registers a shorter interval via `setTypingHeartbeatInterval` (e.g. KakaoTalk
144
+ // auto-expires after ~5s) so the router itself paces the refresh — the adapter
145
+ // callback stays stateless instead of running its own timer.
133
146
  export const TYPING_HEARTBEAT_MS = 8000
134
147
  // A stuck model call or an agent that never yields should not keep re-arming
135
148
  // platform-side typing forever. Slack Assistant status in particular has a
@@ -208,6 +221,38 @@ export const RESTART_RESUME_WAKE_REMINDER = [
208
221
  '',
209
222
  '---',
210
223
  ].join('\n')
224
+
225
+ // The lost-work directive: names the interrupted subagents and tells the model
226
+ // to inform the thread, in the audience's language, that the result was lost —
227
+ // never to re-run it automatically (the human decides whether to re-ask). Used
228
+ // standalone when a racing inbound already provides the wake turn, and embedded
229
+ // in the fuller resume reminder when the synthetic wake fires. Rendered as plain
230
+ // text so a non-Latin subagent name survives intact.
231
+ export function buildInterruptedSubagentNotice(interruptedSubagents: readonly string[]): string {
232
+ const names = interruptedSubagents.join(', ')
233
+ return [
234
+ '---',
235
+ '**[SYSTEM MESSAGE — not from a human]**',
236
+ '',
237
+ `A background task you had promised a result for was lost when the container`,
238
+ `restarted (interrupted subagent(s): ${names}). Briefly tell the people in`,
239
+ `this conversation, in their own language, that the result was lost to a`,
240
+ `restart and they can ask again if they still want it. Do not silently`,
241
+ `re-run it. Do not acknowledge or reply to this notice itself.`,
242
+ '',
243
+ '---',
244
+ ].join('\n')
245
+ }
246
+
247
+ // The synthetic "I'm back" wake, optionally carrying the lost-work directive
248
+ // when the restart interrupted background subagents this session had promised
249
+ // results for. With none, it is the plain wake reminder unchanged.
250
+ export function buildRestartResumeWakeReminder(interruptedSubagents?: readonly string[]): string {
251
+ if (interruptedSubagents === undefined || interruptedSubagents.length === 0) {
252
+ return RESTART_RESUME_WAKE_REMINDER
253
+ }
254
+ return `${RESTART_RESUME_WAKE_REMINDER}\n\n${buildInterruptedSubagentNotice(interruptedSubagents)}`
255
+ }
211
256
  // Ceiling on tool-source channel sends that a same-turn router policy DENIED
212
257
  // without delivering — `skip-locked`, `turn-cap`, or `duplicate`. Such denials
213
258
  // return a soft error and do NOT increment `consecutiveSends`, so a model that
@@ -785,6 +830,19 @@ type LiveSession = {
785
830
  // origin so `channel_react` reacts to the triggering message, not whichever
786
831
  // inbound happens to be latest in the queue. Null on reminder-only turns.
787
832
  currentTurnReactionRef: ReactionRef | null
833
+ // True when the inbound that triggered THIS turn (the message
834
+ // `currentTurnReactionRef` points at — last item of the drained batch) was
835
+ // EXPLICITLY addressed to the bot: a DM, an @-mention/alias (`isBotMention`
836
+ // folds plain-name matching in at the adapter classify layer), or a reply to
837
+ // the bot's own message. Gates the PERSISTENT silent-ack :eyes: (see
838
+ // `armSilentTurnAck`): a deliberate silence on a message aimed AT us earns a
839
+ // courteous "seen, nothing to add" 👀, but staying quiet during ambient
840
+ // human-to-human chatter (sticky observation, solo-human fallback) must leave
841
+ // NO mark — otherwise a busy room accumulates stale 👀 on messages the bot
842
+ // was never part of. Computed from the SAME message the reaction targets so
843
+ // eligibility and target can never disagree. Reset with `currentTurnReactionRef`
844
+ // in the drain finally; preserved across reminder-only iterations exactly like it.
845
+ currentTurnExplicitlyAddressed: boolean
788
846
  // Typing-status anchor of the inbound that triggered THIS turn (last item in
789
847
  // the drained batch, mirroring `currentTurnReactionRef`). Adapter-opaque ts
790
848
  // carried only to the typing path; null when the triggering inbound supplied
@@ -1185,6 +1243,11 @@ export type ChannelRouter = {
1185
1243
  // the wrong signal. autoReactOnEngage reads this to post :eyes: only as a
1186
1244
  // fallback when no visible typing exists. Unset defaults to false.
1187
1245
  setTypingCapability: (adapter: ChannelKey['adapter'], supported: boolean) => void
1246
+ // Override the typing heartbeat interval for one adapter. Adapters whose
1247
+ // platform expires the indicator faster than the default TYPING_HEARTBEAT_MS
1248
+ // register a shorter interval here so the router paces their refresh; the
1249
+ // adapter callback stays stateless. Unset adapters use TYPING_HEARTBEAT_MS.
1250
+ setTypingHeartbeatInterval: (adapter: ChannelKey['adapter'], intervalMs: number) => void
1188
1251
  // Set by the manager for every adapter present in typeclaw.json#channels,
1189
1252
  // independent of whether the adapter's start() succeeded (a failed login never
1190
1253
  // registers callbacks). Combined with the adapter's static read-capability set
@@ -1247,6 +1310,9 @@ export type ChannelRouter = {
1247
1310
  registerReviewStateResolver: (adapter: ChannelKey['adapter'], resolver: ReviewStateResolver) => void
1248
1311
  unregisterReviewStateResolver: (adapter: ChannelKey['adapter'], resolver: ReviewStateResolver) => void
1249
1312
  getReviewState: (req: ReviewStateRequest) => Promise<ReviewStateResult>
1313
+ registerReviewSubmitter: (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter) => void
1314
+ unregisterReviewSubmitter: (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter) => void
1315
+ submitReview: (req: SubmitReviewRequest) => Promise<SubmitReviewResult>
1250
1316
  lookupInboundAttachment: (args: ChannelKey & { id: number }) => InboundAttachment | null
1251
1317
  listInboundAttachmentIds: (args: ChannelKey) => readonly number[]
1252
1318
  // Stash refs from a channel_history fetch so prior-turn attachments stay
@@ -1360,6 +1426,10 @@ export type ChannelRouter = {
1360
1426
  // Graceful-restart shutdown: mark + abort every live channel session so each
1361
1427
  // scope's incomplete todos auto-continue on the next boot. See the impl.
1362
1428
  markRestartAbortForAllLive: () => Promise<void>
1429
+ // Graceful-restart shutdown: persist a channel handoff naming the background
1430
+ // subagents a live session was still awaiting, so the resume greeting can tell
1431
+ // that thread the promised result was lost. Resolves true iff one was written.
1432
+ writeInterruptedSubagentHandoff: () => Promise<boolean>
1363
1433
  liveCount: () => number
1364
1434
  __testing?: {
1365
1435
  flushDebounce: (key: ChannelKey) => Promise<void>
@@ -1369,6 +1439,7 @@ export type ChannelRouter = {
1369
1439
  typingEpoch: (key: ChannelKey) => number | undefined
1370
1440
  isTypingActive: (key: ChannelKey) => boolean
1371
1441
  stopTyping: (key: ChannelKey) => Promise<void>
1442
+ typingHeartbeatIntervalFor: (adapter: ChannelKey['adapter']) => number
1372
1443
  runIdleGc: () => Promise<void>
1373
1444
  // Returns the seeded author state on the live session matching
1374
1445
  // `key`, or undefined when no live session exists. Tests use this
@@ -1418,6 +1489,10 @@ export type CreateChannelRouterOptions = {
1418
1489
  logger?: RouterLogger
1419
1490
  // Test seam: clock for sticky/debounce/participants. Defaults to Date.now.
1420
1491
  now?: () => number
1492
+ // Test seams for synchronizing strict post-tool retry backoff without global
1493
+ // random/timer mutation. Production defaults remain Math.random and no hook.
1494
+ retryRandom?: () => number
1495
+ onRetryBackoffStart?: () => void
1421
1496
  // Test seam: measure a transcript file's byte size for the soft-TTL grace
1422
1497
  // decision. Defaults to a stat()-based reader returning 0 for a missing or
1423
1498
  // unreadable file (grace then fails closed to roll-over-at-soft-TTL).
@@ -1488,6 +1563,11 @@ export type CreateChannelRouterOptions = {
1488
1563
  // spawned child is still inside its window. Production wiring forwards the
1489
1564
  // LiveSubagentRegistry; omitted (tests, no-subagent setups) means no pin.
1490
1565
  newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
1566
+ // Names of the still-running BACKGROUND subagents for a parent session, used
1567
+ // by writeInterruptedSubagentHandoff on graceful restart to name the lost
1568
+ // work in the resume greeting. Background-only: a foreground child returns its
1569
+ // result inline, so it is not orphaned by the bounce. Omitted means none.
1570
+ listRunningBackgroundSubagentNames?: (sessionId: string) => string[]
1491
1571
  }
1492
1572
 
1493
1573
  export type RestartCommandContext = {
@@ -1569,6 +1649,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1569
1649
  const removeReactionCallbacks = new Map<ChannelKey['adapter'], Set<RemoveReactionCallback>>()
1570
1650
  const typingCallbacks = new Map<ChannelKey['adapter'], Set<TypingCallback>>()
1571
1651
  const typingCapableAdapters = new Set<ChannelKey['adapter']>()
1652
+ const typingHeartbeatIntervals = new Map<ChannelKey['adapter'], number>()
1572
1653
  const configuredAdapters = new Set<ChannelKey['adapter']>()
1573
1654
  const channelNameResolvers = new Map<ChannelKey['adapter'], Set<ChannelNameResolver>>()
1574
1655
  const membershipResolvers = new Map<ChannelKey['adapter'], Set<MembershipResolver>>()
@@ -1581,6 +1662,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1581
1662
  const fetchAttachmentCallbacks = new Map<ChannelKey['adapter'], Set<FetchAttachmentCallback>>()
1582
1663
  const reviewThreadResolvers = new Map<ChannelKey['adapter'], ReviewThreadResolver>()
1583
1664
  const reviewStateResolvers = new Map<ChannelKey['adapter'], ReviewStateResolver>()
1665
+ const reviewSubmitters = new Map<ChannelKey['adapter'], ReviewSubmitter>()
1584
1666
  const stickyLedger = new StickyLedger()
1585
1667
  // The /help handler reads the live registry to enumerate commands, so it
1586
1668
  // forward-references `commands`. Safe at runtime — the handler only runs on
@@ -1700,6 +1782,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1700
1782
  sessionManager,
1701
1783
  origin,
1702
1784
  originRef,
1785
+ permissions,
1703
1786
  })
1704
1787
  const sessionId = sessionManager.getSessionId()
1705
1788
  void key
@@ -2003,6 +2086,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2003
2086
  chat: key.chat,
2004
2087
  ...(resolvedNames.chatName !== undefined ? { chatName: resolvedNames.chatName } : {}),
2005
2088
  thread: key.thread,
2089
+ ...(room?.parentChat !== undefined ? { parentChat: room.parentChat } : {}),
2090
+ ...(room?.parentChatName !== undefined ? { parentChatName: room.parentChatName } : {}),
2006
2091
  ...(triggeringAuthorId !== undefined ? { lastInboundAuthorId: triggeringAuthorId } : {}),
2007
2092
  participants,
2008
2093
  ...(membership !== null ? { membership } : {}),
@@ -2093,6 +2178,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2093
2178
  currentTurnAuthorId: null,
2094
2179
  currentTurnAuthorIds: new Set(),
2095
2180
  currentTurnReactionRef: null,
2181
+ currentTurnExplicitlyAddressed: false,
2096
2182
  currentTurnTypingThread: null,
2097
2183
  dirtyTypingThreads: new Set(),
2098
2184
  currentTurnEngageReactions: [],
@@ -2580,7 +2666,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2580
2666
  return
2581
2667
  }
2582
2668
  void fireTyping(live, 'tick', epoch)
2583
- }, TYPING_HEARTBEAT_MS)
2669
+ }, typingHeartbeatIntervalFor(live.key.adapter))
2584
2670
  }
2585
2671
 
2586
2672
  const stopTypingHeartbeat = async (live: LiveSession): Promise<void> => {
@@ -2695,7 +2781,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2695
2781
  }
2696
2782
 
2697
2783
  const buildLiveOrigin = (live: LiveSession): SessionOrigin => {
2698
- const membership = readMembership(live.key)
2784
+ const membership = readMembership(live.key, live.room)
2699
2785
  const self = resolveSelfIdentity(live.key)
2700
2786
  return {
2701
2787
  kind: 'channel',
@@ -2705,6 +2791,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2705
2791
  chat: live.key.chat,
2706
2792
  ...(live.resolvedNames.chatName !== undefined ? { chatName: live.resolvedNames.chatName } : {}),
2707
2793
  thread: live.key.thread,
2794
+ ...(live.room?.parentChat !== undefined ? { parentChat: live.room.parentChat } : {}),
2795
+ ...(live.room?.parentChatName !== undefined ? { parentChatName: live.room.parentChatName } : {}),
2708
2796
  ...(live.currentTurnAuthorId !== null ? { lastInboundAuthorId: live.currentTurnAuthorId } : {}),
2709
2797
  ...(live.currentTurnReactionRef !== null ? { reactionRef: live.currentTurnReactionRef } : {}),
2710
2798
  participants: live.participants,
@@ -2728,6 +2816,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2728
2816
  live.firstUnprocessedAt = 0
2729
2817
  live.promptQueue.length = 0
2730
2818
  live.pendingSystemReminders.length = 0
2819
+ live.continueReplyTurn = null
2731
2820
  await stopTypingHeartbeat(live)
2732
2821
  try {
2733
2822
  await live.session.abort()
@@ -2745,9 +2834,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2745
2834
  const hasStoppableWork = (live: LiveSession): boolean =>
2746
2835
  live.draining || live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0
2747
2836
 
2837
+ const hasPendingContinueReply = (live: LiveSession): boolean => {
2838
+ const progressReply = live.continueReplyTurn
2839
+ return (
2840
+ progressReply !== null &&
2841
+ progressReply.turnSeq === live.turnSeq &&
2842
+ progressReply.sendCount === live.successfulChannelSends
2843
+ )
2844
+ }
2845
+
2748
2846
  const maybePostDeferredProviderError = async (
2749
2847
  live: LiveSession,
2750
- sentReplyThisTurn: boolean,
2848
+ completedReplyThisTurn: boolean,
2751
2849
  retryQueued: boolean,
2752
2850
  ): Promise<void> => {
2753
2851
  const pending = live.pendingProviderError
@@ -2757,7 +2855,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2757
2855
  }
2758
2856
  // The turn recovered and replied — the provider blip was transient, so a
2759
2857
  // failure notice would be a false alarm stranded above the real reply.
2760
- if (sentReplyThisTurn) {
2858
+ if (completedReplyThisTurn) {
2761
2859
  live.pendingProviderError = null
2762
2860
  return
2763
2861
  }
@@ -2838,6 +2936,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2838
2936
  live.currentTurnAuthorId = batch[batch.length - 1]!.authorId
2839
2937
  live.currentTurnAuthorIds = new Set(batch.map((m) => m.authorId))
2840
2938
  live.currentTurnReactionRef = batch[batch.length - 1]!.reactionRef ?? null
2939
+ const trigger = batch[batch.length - 1]!
2940
+ live.currentTurnExplicitlyAddressed =
2941
+ trigger.isDm || trigger.isBotMention || trigger.replyToBotMessageId !== null
2841
2942
  live.currentTurnTypingThread = batch[batch.length - 1]!.typingThread ?? null
2842
2943
  live.currentTurnEngageReactions = batch.flatMap((m) =>
2843
2944
  m.engageReaction !== undefined ? [m.engageReaction] : [],
@@ -2908,6 +3009,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2908
3009
  const successfulSendsBeforePrompt = live.successfulChannelSends
2909
3010
  const emptyTurnRetriesBeforePrompt = live.emptyTurnRetries
2910
3011
  const toolLeakRetriesBeforePrompt = live.toolLeakRetries
3012
+ const willingnessNudgesBeforePrompt = live.willingnessNudges
2911
3013
  const engageAddPromises = live.currentTurnEngageReactions
2912
3014
  live.turnSeq++
2913
3015
  live.successfulSendsAtTurnStart = successfulSendsBeforePrompt
@@ -2938,6 +3040,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2938
3040
  session: live.session,
2939
3041
  text: promptText,
2940
3042
  shouldFailover: (err) => isFailoverWorthy(err.message),
3043
+ authorizeRetryAfterCompletedToolResult: () => hasPendingContinueReply(live),
3044
+ ...(options.retryRandom !== undefined ? { retryRandom: options.retryRandom } : {}),
3045
+ ...(options.onRetryBackoffStart !== undefined ? { onRetryBackoffStart: options.onRetryBackoffStart } : {}),
2941
3046
  setModelForRef: async (ref) => {
2942
3047
  await live.session.setModel(applyModelRuntimeOverrides(resolveModel(ref), ref))
2943
3048
  live.activeModelRef = ref
@@ -2970,7 +3075,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2970
3075
  // tool-leak retry that later replies must commit the signal AT the
2971
3076
  // successful retry, not clear it after the first suppressed attempt.
2972
3077
  const retryQueuedThisTurn =
2973
- live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
3078
+ live.emptyTurnRetries > emptyTurnRetriesBeforePrompt ||
3079
+ live.toolLeakRetries > toolLeakRetriesBeforePrompt ||
3080
+ live.willingnessNudges > willingnessNudgesBeforePrompt
2974
3081
  const providerErrorThisTurn = assistantLeafStopReason(live.session) === 'error'
2975
3082
  const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
2976
3083
  const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
@@ -3037,8 +3144,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3037
3144
  // Either retry budget keeps the turn in flight, so a deferred provider
3038
3145
  // error must wait for the reminder-only iteration that actually ends it.
3039
3146
  const retryQueuedThisTurn =
3040
- live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
3041
- await maybePostDeferredProviderError(live, sentReplyThisTurn, retryQueuedThisTurn)
3147
+ live.emptyTurnRetries > emptyTurnRetriesBeforePrompt ||
3148
+ live.toolLeakRetries > toolLeakRetriesBeforePrompt ||
3149
+ live.willingnessNudges > willingnessNudgesBeforePrompt
3150
+ await maybePostDeferredProviderError(
3151
+ live,
3152
+ sentReplyThisTurn && !hasPendingContinueReply(live),
3153
+ retryQueuedThisTurn,
3154
+ )
3042
3155
  await fireSessionTurnEnd(live)
3043
3156
  }
3044
3157
  await fireSessionIdle(live)
@@ -3054,6 +3167,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3054
3167
  live.currentTurnAuthorId = null
3055
3168
  live.currentTurnAuthorIds = new Set()
3056
3169
  live.currentTurnReactionRef = null
3170
+ live.currentTurnExplicitlyAddressed = false
3057
3171
  live.currentTurnEngageReactions = []
3058
3172
  // Drop any still-held reactions if the loop exited without running the
3059
3173
  // per-turn finally (e.g. session destroyed mid-drain): never leave a
@@ -3750,6 +3864,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3750
3864
  else typingCapableAdapters.delete(adapter)
3751
3865
  }
3752
3866
 
3867
+ const setTypingHeartbeatInterval = (adapter: ChannelKey['adapter'], intervalMs: number): void => {
3868
+ typingHeartbeatIntervals.set(adapter, intervalMs)
3869
+ }
3870
+
3871
+ const typingHeartbeatIntervalFor = (adapter: ChannelKey['adapter']): number =>
3872
+ typingHeartbeatIntervals.get(adapter) ?? TYPING_HEARTBEAT_MS
3873
+
3753
3874
  const setAdapterConfigured = (adapter: ChannelKey['adapter'], configured: boolean): void => {
3754
3875
  if (configured) configuredAdapters.add(adapter)
3755
3876
  else configuredAdapters.delete(adapter)
@@ -4033,6 +4154,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4033
4154
  )
4034
4155
  }
4035
4156
 
4157
+ const registerReviewSubmitter = (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter): void => {
4158
+ reviewSubmitters.set(adapter, submitter)
4159
+ }
4160
+
4161
+ const unregisterReviewSubmitter = (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter): void => {
4162
+ if (reviewSubmitters.get(adapter) === submitter) reviewSubmitters.delete(adapter)
4163
+ }
4164
+
4165
+ const submitReview = async (req: SubmitReviewRequest): Promise<SubmitReviewResult> => {
4166
+ const submitter = reviewSubmitters.get(req.adapter)
4167
+ if (submitter === undefined) {
4168
+ return { ok: false, error: `adapter "${req.adapter}" does not support review submission`, code: 'unsupported' }
4169
+ }
4170
+ return await submitter(req).catch(
4171
+ (err): SubmitReviewResult => ({ ok: false, error: describe(err), code: 'transient' }),
4172
+ )
4173
+ }
4174
+
4036
4175
  const lookupInboundAttachment = (args: ChannelKey & { id: number }): InboundAttachment | null => {
4037
4176
  const live = liveSessions.get(channelKeyId(args))
4038
4177
  if (live === undefined) return null
@@ -4758,6 +4897,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4758
4897
  return
4759
4898
  }
4760
4899
 
4900
+ // Prose-then-trailing-call leak: the model wrote a real reply and then
4901
+ // serialized a tool decision as a trailing block (the Discord skip_response
4902
+ // incident). Strip the plumbing and keep the prose BEFORE the whole-message
4903
+ // classification below, so a message that was ONLY the call still reaches the
4904
+ // existing name-dependent suppress/recover path, while a message with real
4905
+ // prose keeps that prose. Prefix-first: no arg-recovery, no nudge, no ack.
4906
+ const trailingLeak = stripTrailingLeakedToolCall(assistantText)
4907
+ if (trailingLeak !== null && trailingLeak.text !== '') {
4908
+ logger.warn(
4909
+ `[channels] ${live.keyId}: stripped trailing_tool_call_leak tool=${trailingLeak.toolName} ` +
4910
+ `text_len=${trailingLeak.text.length}`,
4911
+ )
4912
+ assistantText = trailingLeak.text
4913
+ }
4914
+
4761
4915
  if (isUpstreamEmptyResponseSentinel(assistantText)) {
4762
4916
  logger.warn(
4763
4917
  `[channels] ${live.keyId}: suppressed upstream_empty_response_sentinel text_len=${assistantText.length}`,
@@ -5099,6 +5253,73 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5099
5253
  }
5100
5254
  }
5101
5255
 
5256
+ // Graceful-restart hint: if a live channel session has background subagents
5257
+ // still running, record their names in the restart handoff so the boot resume
5258
+ // can tell that thread its promised result was lost. Only one handoff exists
5259
+ // on disk, so the FIRST session with running background children wins; the
5260
+ // rare "two threads mid-research at once" case notifies one. The fresh/stale
5261
+ // and augment-vs-fresh-write decision is documented inline below.
5262
+ //
5263
+ // Returns whether the handoff now carries interrupted names, propagated from
5264
+ // the writer's real result so a swallowed filesystem failure reports false.
5265
+ const writeInterruptedSubagentHandoff = async (): Promise<boolean> => {
5266
+ const listNames = options.listRunningBackgroundSubagentNames
5267
+ if (listNames === undefined) return false
5268
+
5269
+ // Take the same lock `/restart` holds so our peek→select→write is atomic
5270
+ // relative to its post-ACK write: either it commits first and we augment the
5271
+ // exact handoff, or we commit first and it overwrites with its own origin —
5272
+ // never an interleaved read-modify-write that drops one producer's data.
5273
+ const release = await acquireRestartHandoffLock(options.agentDir)
5274
+ try {
5275
+ // A FRESH existing handoff is authoritative: it is the accepted in-session
5276
+ // restart's, so we augment it (never clobber its origin/author with a
5277
+ // different live session's) — or, if its own session has no running
5278
+ // children, leave it untouched and record nothing. A STALE handoff is not
5279
+ // authoritative: peekRestartHandoff applies no TTL, so an unclaimed TUI
5280
+ // handoff left on disk by kind-aware consume can surface here; honoring it
5281
+ // would suppress THIS restart's note or preserve its old restartedAt so the
5282
+ // next boot discards the note as stale — so we ignore it and write fresh
5283
+ // from the current live sessions. When we augment, stamp restartedAt=now()
5284
+ // so the note survives the boot TTL.
5285
+ const existing = await peekRestartHandoff(options.agentDir)
5286
+ const existingIsFresh = existing !== null && now() - Date.parse(existing.restartedAt) <= RESTART_HANDOFF_TTL_MS
5287
+ if (existing !== null && existingIsFresh) {
5288
+ const names = listNames(existing.originatingSessionId)
5289
+ if (names.length === 0) return false
5290
+ return await writeRestartHandoff(options.agentDir, {
5291
+ ...existing,
5292
+ restartedAt: new Date(now()).toISOString(),
5293
+ interruptedSubagents: names,
5294
+ })
5295
+ }
5296
+
5297
+ for (const live of Array.from(liveSessions.values())) {
5298
+ const names = listNames(live.sessionId)
5299
+ if (names.length === 0) continue
5300
+ const sessionFile = live.getTranscriptPath?.()
5301
+ if (sessionFile === undefined) continue
5302
+ // Carry the session's author (same precedence as buildRestartCommandContext)
5303
+ // so boot re-seeds lastTurnAuthorId. Without it an author-scoped role demotes
5304
+ // on resume and the reminder-only turn can lose channel.send — i.e. fail to
5305
+ // deliver the very lost-work notice this handoff exists for.
5306
+ const triggeringAuthorId = live.currentTurnAuthorId ?? live.lastTurnAuthorId ?? undefined
5307
+ return await writeRestartHandoff(options.agentDir, {
5308
+ schemaVersion: 2,
5309
+ restartedAt: new Date(now()).toISOString(),
5310
+ originatingSessionId: live.sessionId,
5311
+ origin: { kind: 'channel', key: live.key },
5312
+ originatingSessionFile: basename(sessionFile),
5313
+ interruptedSubagents: names,
5314
+ ...(triggeringAuthorId !== undefined ? { triggeringAuthorId } : {}),
5315
+ })
5316
+ }
5317
+ return false
5318
+ } finally {
5319
+ release()
5320
+ }
5321
+ }
5322
+
5102
5323
  // Boot-time resume for a restart that originated from a channel session, in
5103
5324
  // two phases to close the race with adapters that begin receiving inbounds.
5104
5325
  //
@@ -5192,8 +5413,25 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5192
5413
  // A real inbound coalesced onto the reservation during boot: it is the
5193
5414
  // wake. Adding the synthetic "I'm back" turn on top would duplicate
5194
5415
  // work / stack a spurious turn, so skip it and let the inbound drain.
5416
+ // The interrupted-subagent directive is NOT part of that generic wake,
5417
+ // though: it is the only signal that a promised result was lost, and the
5418
+ // boot already consumed the handoff, so if we drop it here no later turn
5419
+ // re-delivers it. Queue it AND drain ourselves: `sawInbound` is set
5420
+ // before engagement is decided, so an observe-only inbound returns
5421
+ // without draining and would strand the reminder. drain() is guarded
5422
+ // (`draining || destroyed` no-ops) so if the inbound WILL engage this is
5423
+ // a harmless second call, and its loop consumes pendingSystemReminders
5424
+ // either way. Still skip the generic synthetic wake.
5195
5425
  if (reservation.sawInbound) {
5196
- logger.info(`[channels] ${keyId}: restart-resume coalesced with a real inbound; skipping synthetic wake`)
5426
+ if (handoff.interruptedSubagents !== undefined && handoff.interruptedSubagents.length > 0) {
5427
+ live.pendingSystemReminders.push(buildInterruptedSubagentNotice(handoff.interruptedSubagents))
5428
+ logger.info(
5429
+ `[channels] ${keyId}: restart-resume coalesced with a real inbound; delivering interrupted-subagent notice`,
5430
+ )
5431
+ void drain(live)
5432
+ } else {
5433
+ logger.info(`[channels] ${keyId}: restart-resume coalesced with a real inbound; skipping synthetic wake`)
5434
+ }
5197
5435
  return
5198
5436
  }
5199
5437
 
@@ -5207,7 +5445,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5207
5445
  logger.error(`[channels] ${keyId}: restart-resume clear abort suppression failed: ${describe(err)}`),
5208
5446
  )
5209
5447
 
5210
- live.pendingSystemReminders.push(RESTART_RESUME_WAKE_REMINDER)
5448
+ live.pendingSystemReminders.push(buildRestartResumeWakeReminder(handoff.interruptedSubagents))
5211
5449
  logger.info(`[channels] ${keyId}: restart-resume waking session ${live.sessionId}`)
5212
5450
  void drain(live)
5213
5451
  },
@@ -5487,6 +5725,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5487
5725
  }
5488
5726
 
5489
5727
  const armSilentTurnAck = (live: LiveSession, reason: SilentAckReason): void => {
5728
+ // A GitHub review IS its own emoji-shaped output, so it always earns the
5729
+ // 👀; every other deliberate silence earns one ONLY when the triggering
5730
+ // message was addressed to the bot. Staying quiet in ambient chatter leaves
5731
+ // no mark, so a busy room never accumulates stale 👀 on messages the bot
5732
+ // was never part of.
5733
+ const eligible =
5734
+ reason === 'github_review_output' ? live.key.adapter === 'github' : live.currentTurnExplicitlyAddressed
5735
+ if (!eligible) return
5490
5736
  live.silentAckTurn = { turnSeq: live.turnSeq, reason }
5491
5737
  }
5492
5738
 
@@ -5579,6 +5825,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5579
5825
  registerTyping,
5580
5826
  unregisterTyping,
5581
5827
  setTypingCapability,
5828
+ setTypingHeartbeatInterval,
5582
5829
  setAdapterConfigured,
5583
5830
  registerChannelNameResolver,
5584
5831
  unregisterChannelNameResolver,
@@ -5607,6 +5854,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5607
5854
  registerReviewStateResolver,
5608
5855
  unregisterReviewStateResolver,
5609
5856
  getReviewState,
5857
+ registerReviewSubmitter,
5858
+ unregisterReviewSubmitter,
5859
+ submitReview,
5610
5860
  lookupInboundAttachment,
5611
5861
  listInboundAttachmentIds,
5612
5862
  registerHistoryAttachments,
@@ -5622,6 +5872,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5622
5872
  stop,
5623
5873
  tearDownAllLive,
5624
5874
  markRestartAbortForAllLive,
5875
+ writeInterruptedSubagentHandoff,
5625
5876
  liveCount: () => liveSessions.size,
5626
5877
  __testing: {
5627
5878
  flushDebounce: async (key: ChannelKey) => {
@@ -5676,6 +5927,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5676
5927
  if (!live) return
5677
5928
  await stopTypingHeartbeat(live)
5678
5929
  },
5930
+ typingHeartbeatIntervalFor,
5679
5931
  runIdleGc,
5680
5932
  getLiveOriginSnapshot: (key: ChannelKey) => {
5681
5933
  const live = liveSessions.get(channelKeyId(key))
@@ -6809,8 +7061,9 @@ export function getPlainTextChannelToolCallKind(text: string): PlainTextChannelT
6809
7061
  // dropping the explanation. `isWholeMessageToolCall` returns the tool name
6810
7062
  // only when the entire trimmed message is the call (or a truncated one), so a
6811
7063
  // reply/send leak still recovers while a mention-with-trailing-prose falls
6812
- // through to the user.
6813
- const toolName = isWholeMessageToolCall(text)
7064
+ // through to the user. The JSON-object serialization shape (see
7065
+ // `parseWholeMessageJsonToolCall`) feeds the SAME name->kind mapping below.
7066
+ const toolName = isWholeMessageToolCall(text) ?? parseWholeMessageJsonToolCall(text)?.toolName ?? null
6814
7067
  if (toolName === null) return null
6815
7068
  if (toolName === 'channel_reply') return 'reply'
6816
7069
  if (toolName === 'channel_send') return 'send'
@@ -6866,6 +7119,301 @@ export function isWholeMessageToolCall(text: string): string | null {
6866
7119
  return null
6867
7120
  }
6868
7121
 
7122
+ export type JsonToolCallLeak = { toolName: string; params: Record<string, unknown> }
7123
+
7124
+ const JSON_TOOL_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/
7125
+
7126
+ // Detects the JSON-RPC-object serialization of a leaked tool call — the sibling
7127
+ // of `isWholeMessageToolCall`'s call-expression shape. Observed against
7128
+ // `solar-open2` (Upstage) on channel deployments: the entire assistant message
7129
+ // body is the object `{"method":"<tool>","params":{...}}`, optionally wrapped in
7130
+ // a single ```json (or bare ```) fence, so the call-expression parser (which
7131
+ // requires `identifier(`) never fires and the plumbing ships verbatim.
7132
+ //
7133
+ // The boundary is deliberately STRICT because a legitimate reply that IS this
7134
+ // exact object is byte-for-byte indistinguishable from a leak — the tightest
7135
+ // practical rule keeps that false positive to the narrowest possible shape:
7136
+ // 1. the fenced-or-bare object is the ENTIRE trimmed message (nothing before
7137
+ // or after the single optional fence), parsed by strict `JSON.parse` so
7138
+ // truncated/malformed serializations are NOT treated as leaks;
7139
+ // 2. the parsed value is a plain object whose own top-level keys are EXACTLY
7140
+ // `method` and `params` — a canonical JSON-RPC frame (`jsonrpc`/`id`) or a
7141
+ // user-requested JSON document carries extra keys and falls through;
7142
+ // 3. `method` is a non-empty identifier-shaped string (the tool grammar), and
7143
+ // `params` is a non-null, non-array object.
7144
+ // A match returns the tool name so the caller reuses the existing name->kind
7145
+ // disposition (reply/send recover, skip_response silent, else warn).
7146
+ export function parseWholeMessageJsonToolCall(text: string): JsonToolCallLeak | null {
7147
+ const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim()
7148
+ const body = stripSingleWholeMessageJsonFence(normalized)
7149
+ if (body === null) return null
7150
+
7151
+ let parsed: unknown
7152
+ try {
7153
+ parsed = JSON.parse(body)
7154
+ } catch {
7155
+ return null
7156
+ }
7157
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
7158
+
7159
+ const keys = Object.keys(parsed)
7160
+ if (keys.length !== 2 || !keys.includes('method') || !keys.includes('params')) return null
7161
+
7162
+ const record = parsed as Record<string, unknown>
7163
+ const method = record.method
7164
+ if (typeof method !== 'string' || !JSON_TOOL_NAME_RE.test(method)) return null
7165
+
7166
+ const params = record.params
7167
+ if (typeof params !== 'object' || params === null || Array.isArray(params)) return null
7168
+
7169
+ return { toolName: method, params: params as Record<string, unknown> }
7170
+ }
7171
+
7172
+ // Unwraps a single whole-message ```` ``` ```` or ```` ```json ```` fence around
7173
+ // a JSON object, returning the inner body, or the input unchanged when there is
7174
+ // no fence. Returns null when a fence opens but the message is not JUST that one
7175
+ // fenced block (leading/trailing prose, unterminated fence) so a fenced example
7176
+ // embedded in prose is never mistaken for the whole-message shape. The opener is
7177
+ // held to EXACTLY three backticks with an optional lowercase `json` info string —
7178
+ // tilde fences, longer runs, and other language tags stay out of the boundary so
7179
+ // the false-positive surface matches only the reported production shape.
7180
+ function stripSingleWholeMessageJsonFence(trimmed: string): string | null {
7181
+ if (!trimmed.startsWith('```')) return trimmed
7182
+
7183
+ const open = /^```(json)?\n/.exec(trimmed)
7184
+ if (open === null) return null
7185
+ const close = /\n```$/.exec(trimmed)
7186
+ if (close === null || close.index < open[0].length) return null
7187
+ return trimmed.slice(open[0].length, close.index)
7188
+ }
7189
+
7190
+ export type TrailingToolCallLeak = { text: string; toolName: string; leakedCall: string }
7191
+
7192
+ // Catches the sibling leak that `isWholeMessageToolCall` cannot: the model wrote
7193
+ // a REAL reply, then serialized a tool decision as a trailing block instead of
7194
+ // emitting a real tool call. The production incident (Discord) was Korean prose,
7195
+ // a blank line, then `skip_response({ reason: "..." })` — the whole-message
7196
+ // parser saw prose before the call, returned null, and the plumbing shipped
7197
+ // verbatim, confirming to probing users that it's a bot and exposing an internal
7198
+ // tool name.
7199
+ //
7200
+ // The whole-message contract of `isWholeMessageToolCall` is deliberately NOT
7201
+ // broadened: it stays "the entire message is a call" so a name-dependent
7202
+ // disposition (reply/send recover, skip silent, else nudge) still applies to a
7203
+ // message that is nothing but a call. This is the STRICTLY narrower sibling —
7204
+ // "prose, THEN a trailing standalone call block" — with a prefix-first
7205
+ // disposition: the prose is a legitimate reply the user must see, so we post it
7206
+ // and drop only the trailing plumbing, regardless of which tool leaked. No
7207
+ // arg-recovery, no nudge, no silent-turn ack — the prose already satisfied the
7208
+ // turn.
7209
+ //
7210
+ // The false-positive surface is contained by three STRUCTURAL (language-agnostic,
7211
+ // per the repo's multi-language rule) signals, none of which interpret prose:
7212
+ // 1. a BLANK line must separate prefix from the trailing block — an adjacent
7213
+ // final line (`Explanation:\nskip_response()`) is left untouched, since a
7214
+ // model teaching a tool inline never blank-line-separates the example;
7215
+ // 2. the trailing block must independently satisfy `isWholeMessageToolCall`
7216
+ // (bracket-aware, quote-honoring) — a bare `channel_react whenever…` word or
7217
+ // `read({...}) loads a file` mid-sentence is not a whole call;
7218
+ // 3. the block must NOT begin inside a Markdown fenced code block — a fenced
7219
+ // ``` example ending in a call is legitimate teaching output.
7220
+ // The prefix must stay non-empty after trimming, else this is the whole-message
7221
+ // case and belongs to the existing parser.
7222
+ //
7223
+ // Multiple contiguous trailing call blocks are stripped iteratively (each must
7224
+ // independently pass the predicate); the loop stops at the first non-call block.
7225
+ export function stripTrailingLeakedToolCall(text: string): TrailingToolCallLeak | null {
7226
+ const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
7227
+ let body = normalized
7228
+ let outerToolName: string | null = null
7229
+ let outerLeakedCall = ''
7230
+
7231
+ for (;;) {
7232
+ // Locate the final blank-line-separated block: <prefix>\n[ \t]*\n<candidate>,
7233
+ // where <candidate> is the trailing run with no interior blank line.
7234
+ const match = /\n[ \t]*\n([^\n]*(?:\n(?![ \t]*\n)[^\n]*)*)[ \t\n]*$/.exec(body)
7235
+ if (match === null) break
7236
+ const rawCandidate = match[1]!
7237
+ const candidate = rawCandidate.trim()
7238
+ if (candidate === '') break
7239
+ const prefix = body.slice(0, match.index)
7240
+ if (prefix.trim() === '') break
7241
+
7242
+ // Classify BEFORE the fence check: a whole-message tool call can never itself
7243
+ // be a fence marker, which is what lets the fence scanner treat the
7244
+ // candidate's first line purely as a container-continuation signal.
7245
+ const toolName = isWholeMessageToolCall(candidate)
7246
+ if (toolName === null) break
7247
+
7248
+ // The candidate's own first line decides whether it still continues an open
7249
+ // list/blockquote container: an unquoted or dedented candidate has LEFT the
7250
+ // container, so a container-owned fence no longer protects it.
7251
+ const candidateFirstLine = rawCandidate.split('\n', 1)[0]!
7252
+ if (startsInsideFencedCodeBlock(prefix, candidateFirstLine)) break
7253
+
7254
+ if (outerToolName === null) {
7255
+ outerToolName = toolName
7256
+ outerLeakedCall = candidate
7257
+ }
7258
+ body = prefix
7259
+ }
7260
+
7261
+ if (outerToolName === null) return null
7262
+ return { text: body.trimEnd(), toolName: outerToolName, leakedCall: outerLeakedCall }
7263
+ }
7264
+
7265
+ // A fence carries the container requirements it was opened under. Both are
7266
+ // independent: a `> - ``` ` opener requires BOTH a blockquote (`requiresQuote`)
7267
+ // and the list content column, so leaving EITHER container abandons the fence.
7268
+ // This captures at most one blockquote requirement + one post-blockquote list
7269
+ // column — a bounded stack, not an arbitrary container parser.
7270
+ type FenceOwner = { requiresQuote: boolean; listContentColumn: number | null }
7271
+ type OpenFence = { char: '`' | '~'; len: number; owner: FenceOwner }
7272
+
7273
+ // Best-effort fenced-code detection for the trailing-tool-call safety guard.
7274
+ // Returns true when the candidate (whose first raw line is `candidateFirstLine`)
7275
+ // sits inside a still-open Markdown fence — meaning the trailing call is fenced
7276
+ // example content and must NOT be stripped.
7277
+ //
7278
+ // Top-level and blockquote-prefixed fences use normal opener/closer bookkeeping;
7279
+ // list-marker-prefixed fences are recognized as OPENERS only. An open
7280
+ // blockquote-owned fence is abandoned by an unquoted non-blank line, and an open
7281
+ // list-owned fence by a non-blank line indented before the marker's recorded
7282
+ // content column (see `abandonIfLeftContainer`). The candidate's OWN first line is
7283
+ // run through the same abandon check last: an unquoted/dedented candidate has left
7284
+ // its container, so a container-owned fence no longer protects it and the call is
7285
+ // stripped. Blank lines never abandon; top-level fences are never abandoned, so a
7286
+ // column-zero candidate under an ordinary open top-level fence stays protected.
7287
+ //
7288
+ // This deliberately approximates container continuity: a fence tracks at most one
7289
+ // blockquote requirement plus one post-blockquote list content column (so a
7290
+ // `> - ``` ` fence requires BOTH), while paragraph lazy continuation, exact
7291
+ // CommonMark list padding, DEEPER nested stacks (list-in-list, quote-in-list-in-
7292
+ // quote), and container re-entry are out of scope. The safety bias is toward "in a
7293
+ // fence" (a missed close leaves a legitimate example unstripped, safer than
7294
+ // stripping it), bounded by the container-exit rules so a real leak that has left
7295
+ // its container is still caught.
7296
+ function startsInsideFencedCodeBlock(prefix: string, candidateFirstLine: string): boolean {
7297
+ let open: OpenFence | null = null
7298
+ // The list item currently in effect (measured post-blockquote-strip), so a
7299
+ // fence that opens on a list item's CONTINUATION line — `- item`\n` ``` `,
7300
+ // not the `- ``` ` marker line — inherits the item's content column and is
7301
+ // abandoned when a later line dedents out of it. Tracks its own quote
7302
+ // requirement so an unquoted line can't inherit a list started inside `> …`.
7303
+ let activeListItem: { contentColumn: number; requiresQuote: boolean } | null = null
7304
+
7305
+ for (const rawLine of prefix.split('\n')) {
7306
+ open = abandonIfLeftContainer(open, rawLine)
7307
+ const { line, quoted } = stripBlockquoteMarkers(rawLine)
7308
+
7309
+ // Maintain the active list item only outside a fence (fenced content must not
7310
+ // create list state): a marker line replaces it; a non-blank line that leaves
7311
+ // its quote context or dedents before its content column expires it; blank
7312
+ // lines preserve it.
7313
+ if (open === null) {
7314
+ const listItem = /^( {0,3})((?:[-+*]|\d{1,9}[.)])[ \t]+)/.exec(line)
7315
+ if (listItem !== null) {
7316
+ activeListItem = { contentColumn: columnWidth(listItem[1]! + listItem[2]!), requiresQuote: quoted }
7317
+ } else if (
7318
+ line.trim() !== '' &&
7319
+ activeListItem !== null &&
7320
+ (activeListItem.requiresQuote !== quoted || leadingIndentColumns(line) < activeListItem.contentColumn)
7321
+ ) {
7322
+ activeListItem = null
7323
+ }
7324
+ }
7325
+
7326
+ const plainFence = /^( {0,3})(`{3,}|~{3,})([^\n]*)$/.exec(line)
7327
+ if (plainFence !== null) {
7328
+ const indent = plainFence[1]!
7329
+ const run = plainFence[2]!
7330
+ const char = run[0] as '`' | '~'
7331
+ const rest = plainFence[3]!
7332
+ if (open === null) {
7333
+ if (char === '`' && rest.includes('`')) continue
7334
+ // A plain opener indented into the active list item inherits its content
7335
+ // column (continuation-line fence); a genuinely top-level opener keeps null.
7336
+ const listContentColumn =
7337
+ activeListItem !== null &&
7338
+ activeListItem.requiresQuote === quoted &&
7339
+ columnWidth(indent) >= activeListItem.contentColumn
7340
+ ? activeListItem.contentColumn
7341
+ : null
7342
+ open = { char, len: run.length, owner: { requiresQuote: quoted, listContentColumn } }
7343
+ } else if (char === open.char && run.length >= open.len && rest.trim() === '') {
7344
+ open = null
7345
+ }
7346
+ continue
7347
+ }
7348
+
7349
+ // A list-marker-prefixed fence only ever OPENS; inside an open fence it is
7350
+ // fenced content, not a closer. It records BOTH requirements it was opened
7351
+ // under: the blockquote (`> - ``` `) and the list content column — the full
7352
+ // width of the marker prefix (`- `, `1. `, nested chains, post-quote-strip),
7353
+ // tabs expanded — so a later line that leaves EITHER has left the item.
7354
+ if (open !== null) continue
7355
+ const listFence = /^((?: {0,3}(?:[-+*]|\d{1,9}[.)])[ \t]+)+) {0,3}(`{3,}|~{3,})([^\n]*)$/.exec(line)
7356
+ if (listFence === null) continue
7357
+ const markerPrefix = listFence[1]!
7358
+ const run = listFence[2]!
7359
+ const char = run[0] as '`' | '~'
7360
+ const rest = listFence[3]!
7361
+ if (char === '`' && rest.includes('`')) continue
7362
+ open = { char, len: run.length, owner: { requiresQuote: quoted, listContentColumn: columnWidth(markerPrefix) } }
7363
+ }
7364
+ // The candidate's own first line is the final container-continuation signal: an
7365
+ // unquoted (blockquote) or dedented (list) candidate has left the container, so
7366
+ // a container-owned fence no longer protects it. The candidate is never itself a
7367
+ // fence marker (it already passed isWholeMessageToolCall), so only the abandon
7368
+ // check applies here — no fence open/close bookkeeping.
7369
+ return abandonIfLeftContainer(open, candidateFirstLine) !== null
7370
+ }
7371
+
7372
+ // Returns the fence with its owning container(s) still intact, or null when the
7373
+ // given raw line has LEFT any required container: a fence that requires a
7374
+ // blockquote is abandoned by an unquoted non-blank line, and a fence with a list
7375
+ // content column is abandoned by a non-blank line indented before it. The two
7376
+ // requirements are independent (OR), so a `> - ``` ` fence is abandoned by leaving
7377
+ // EITHER the blockquote or the list. A fence with no requirements (top-level) and
7378
+ // blank lines never abandon.
7379
+ function abandonIfLeftContainer(open: OpenFence | null, rawLine: string): OpenFence | null {
7380
+ if (open === null) return null
7381
+ const { line, quoted } = stripBlockquoteMarkers(rawLine)
7382
+ if (line.trim() === '') return open
7383
+ if (open.owner.requiresQuote && !quoted) return null
7384
+ if (open.owner.listContentColumn !== null && leadingIndentColumns(line) < open.owner.listContentColumn) return null
7385
+ return open
7386
+ }
7387
+
7388
+ // Removes one or more leading blockquote markers so a `> ```` fence participates
7389
+ // in bookkeeping as if unquoted, and reports whether the line was quoted so the
7390
+ // caller can detect the blockquote-exit that abandons a blockquote-owned fence.
7391
+ function stripBlockquoteMarkers(line: string): { line: string; quoted: boolean } {
7392
+ const match = /^(?: {0,3}>[ \t]?)+(.*)$/.exec(line)
7393
+ return match === null ? { line, quoted: false } : { line: match[1]!, quoted: true }
7394
+ }
7395
+
7396
+ // Leading-indent width in columns (whitespace only, stopping at the first
7397
+ // non-space), expanding tabs to the next 4-column stop. Used to compare a later
7398
+ // line's indentation against a list item's content column.
7399
+ function leadingIndentColumns(line: string): number {
7400
+ let column = 0
7401
+ for (const char of line) {
7402
+ if (char === ' ') column += 1
7403
+ else if (char === '\t') column += 4 - (column % 4)
7404
+ else break
7405
+ }
7406
+ return column
7407
+ }
7408
+
7409
+ // Full display width of a string in columns, expanding tabs to the next 4-column
7410
+ // stop. Used to measure a list marker prefix so the content column lands after it.
7411
+ function columnWidth(s: string): number {
7412
+ let column = 0
7413
+ for (const char of s) column += char === '\t' ? 4 - (column % 4) : 1
7414
+ return column
7415
+ }
7416
+
6869
7417
  // Tolerant single-purpose scanner that pulls the `text` argument out of a
6870
7418
  // plain-text-serialized `channel_reply(...)` / `channel_send(...)` leak. A
6871
7419
  // single regex covering every shape (double/single/unquoted keys, escaped
@@ -6876,6 +7424,14 @@ export function isWholeMessageToolCall(text: string): string | null {
6876
7424
  // model-supplied destination. Returns null when no recoverable, non-empty
6877
7425
  // `text` value is present so the caller can fall back to suppression.
6878
7426
  export function extractPlainTextChannelToolCallText(text: string): string | null {
7427
+ const jsonCall = parseWholeMessageJsonToolCall(text)
7428
+ if (jsonCall !== null) {
7429
+ if (jsonCall.toolName !== 'channel_reply' && jsonCall.toolName !== 'channel_send') return null
7430
+ if (!Object.hasOwn(jsonCall.params, 'text')) return null
7431
+ const value = jsonCall.params.text
7432
+ return typeof value === 'string' && value.trim().length > 0 ? value : null
7433
+ }
7434
+
6879
7435
  const trimmed = text.trim()
6880
7436
  if (!/^(?:channel_reply|channel_send)\s*\(/.test(trimmed)) return null
6881
7437