typeclaw 0.43.1 → 0.45.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 (86) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +7 -6
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +25 -2
  6. package/src/agent/model-fallback.ts +59 -40
  7. package/src/agent/multimodal/look-at.ts +29 -10
  8. package/src/agent/plugin-tools.ts +9 -4
  9. package/src/agent/provider-error.ts +71 -18
  10. package/src/agent/retry-same-ref.ts +139 -0
  11. package/src/agent/session-origin.ts +1 -0
  12. package/src/agent/subagents.ts +6 -2
  13. package/src/agent/tools/channel-edit.ts +144 -0
  14. package/src/agent/tools/channel-fetch-attachment.ts +51 -8
  15. package/src/agent/tools/channel-reply.ts +41 -18
  16. package/src/agent/tools/channel-send.ts +82 -13
  17. package/src/agent/tools/curl-impersonate.ts +40 -1
  18. package/src/agent/tools/webfetch/fetch.ts +86 -3
  19. package/src/agent/tools/webfetch/tool.ts +26 -3
  20. package/src/agent/tools/webfetch/types.ts +8 -0
  21. package/src/agent/turn-runner.ts +65 -36
  22. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
  23. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  24. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  25. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  26. package/src/bundled-plugins/memory/README.md +9 -9
  27. package/src/bundled-plugins/memory/index.ts +40 -9
  28. package/src/bundled-plugins/reviewer/skills/code-review.ts +22 -2
  29. package/src/channels/adapters/discord-bot-edit.ts +49 -0
  30. package/src/channels/adapters/discord-bot.ts +5 -0
  31. package/src/channels/adapters/discord-edit.ts +51 -0
  32. package/src/channels/adapters/discord.ts +4 -0
  33. package/src/channels/adapters/github/inbound.ts +20 -14
  34. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  35. package/src/channels/adapters/slack-bot-edit.ts +58 -0
  36. package/src/channels/adapters/slack-bot.ts +18 -6
  37. package/src/channels/adapters/slack-edit.ts +47 -0
  38. package/src/channels/adapters/slack.ts +5 -0
  39. package/src/channels/adapters/teams-classify.ts +144 -0
  40. package/src/channels/adapters/teams-edit.ts +61 -0
  41. package/src/channels/adapters/teams-id-token.ts +112 -0
  42. package/src/channels/adapters/teams-key.ts +32 -0
  43. package/src/channels/adapters/teams.ts +523 -0
  44. package/src/channels/adapters/telegram-bot-edit.ts +51 -0
  45. package/src/channels/adapters/telegram-bot.ts +5 -0
  46. package/src/channels/adapters/webex-bot.ts +5 -0
  47. package/src/channels/adapters/webex-edit.ts +47 -0
  48. package/src/channels/adapters/webex.ts +5 -0
  49. package/src/channels/continuation-willingness.ts +227 -35
  50. package/src/channels/github-review-turn-ledger.ts +43 -0
  51. package/src/channels/index.ts +1 -1
  52. package/src/channels/manager.ts +54 -1
  53. package/src/channels/router.ts +482 -53
  54. package/src/channels/schema.ts +33 -0
  55. package/src/channels/types.ts +36 -0
  56. package/src/cli/channel.ts +92 -4
  57. package/src/cli/hostd.ts +41 -0
  58. package/src/cli/init.ts +58 -1
  59. package/src/config/channels-mutation.ts +9 -1
  60. package/src/cron/index.ts +16 -4
  61. package/src/cron/reloadable.ts +25 -7
  62. package/src/cron/scheduler.ts +4 -0
  63. package/src/cron/schema.ts +143 -35
  64. package/src/doctor/channel-checks.ts +27 -0
  65. package/src/hostd/daemon.ts +23 -3
  66. package/src/hostd/protocol.ts +2 -0
  67. package/src/hostd/teams-renewal-manager.ts +212 -0
  68. package/src/init/checkpoint.ts +1 -1
  69. package/src/init/index.ts +68 -1
  70. package/src/init/run-owner-claim.ts +1 -0
  71. package/src/init/teams-auth.ts +111 -0
  72. package/src/inspect/label.ts +4 -0
  73. package/src/permissions/match-rule.ts +11 -1
  74. package/src/permissions/resolve.ts +1 -0
  75. package/src/role-claim/match-rule.ts +2 -1
  76. package/src/run/index.ts +35 -8
  77. package/src/run/llm-fetch-observer.ts +27 -5
  78. package/src/sandbox/build.ts +12 -0
  79. package/src/sandbox/policy.ts +13 -0
  80. package/src/sandbox/writable-zones.ts +46 -10
  81. package/src/secrets/schema.ts +32 -0
  82. package/src/secrets/teams-renewal.ts +229 -0
  83. package/src/secrets/teams-store.ts +108 -0
  84. package/src/server/command-runner.ts +2 -1
  85. package/src/server/index.ts +2 -1
  86. package/typeclaw.schema.json +163 -3
@@ -44,7 +44,7 @@ import {
44
44
  } from './engagement'
45
45
  import { checkFalseReceipt } from './github-false-receipt'
46
46
  import { evaluateRereviewGuard } from './github-rereview-guard'
47
- import { resetReviewTurn } from './github-review-turn-ledger'
47
+ import { resetReviewTurn, type ReviewOutputState } from './github-review-turn-ledger'
48
48
  import { renderPrVerdictStandDownReminder } from './github-verdict-activity'
49
49
  import {
50
50
  MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
@@ -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,
@@ -185,7 +190,7 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
185
190
  return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
186
191
  }
187
192
 
188
- type SilentAckReason = 'skip_response' | 'no_reply' | 'skip_response_text_leak'
193
+ type SilentAckReason = 'skip_response' | 'no_reply' | 'skip_response_text_leak' | 'github_review_output'
189
194
 
190
195
  // Wake nudge pushed into a resumed channel session at boot so drain() has a
191
196
  // non-empty batch and fires a turn. The substantive instruction the model acts
@@ -482,21 +487,26 @@ export const SESSION_FRESHNESS_TTL_MS = 5 * 60 * 1000
482
487
  export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
483
488
 
484
489
  /**
485
- * Absolute ceiling on how long a running background subagent may pin its parent
486
- * channel session against idle GC and stale-rollover. A still-running child defers
487
- * teardown because the next inbound otherwise starts a fresh session that has lost
488
- * track of the in-flight task and spawns a DUPLICATE child for the same work. The
489
- * pin is bounded so a stuck/never-completing child cannot make the session
490
- * immortal: past this age the session is GC'd / rolled over anyway, falling back
491
- * to the completion-reroute behavior. Measured from the child's start.
490
+ * Leak guard — NOT a freshness cap. A running background subagent pins its parent
491
+ * channel session against idle GC and stale-rollover for as long as the child is
492
+ * actually running, because the next inbound would otherwise start a fresh session
493
+ * that has lost track of the in-flight task and spawns a DUPLICATE child, and — the
494
+ * bug this backstop is sized around — a completion arriving after teardown has no
495
+ * live session to deliver its system-reminder to and is silently dropped.
492
496
  *
493
- * Set above SESSION_IDLE_MS (30m) — not equal — so a child spawned at session
494
- * birth still pins the session through its first idle sweep instead of the two
495
- * windows coinciding. Comfortably above SESSION_GRACE_HARD_TTL_MS (10m) too:
496
- * real research runs can exceed it (an observed run took 9m18s), so the 10m cap
497
- * is far too tight to bound the pin.
497
+ * The pin is bounded only so a genuinely stuck/wedged child cannot make the session
498
+ * immortal. Subagent `timeoutMs` is optional (operator declares none), so a hung
499
+ * child stays `status: 'running'` forever; without this ceiling its parent session
500
+ * would leak indefinitely. Past this age the child is treated as stuck: GC/rollover
501
+ * proceeds and the session falls back to completion-reroute.
502
+ *
503
+ * Sized as an ANOMALY threshold, deliberately far above any legitimate run (deep
504
+ * operator work is minutes-to-an-hour, not hours), so it never fires for real work.
505
+ * The prior 45m value was close enough to plausible deep work to turn a legitimate
506
+ * long run into a routine drop — the reported 65m completion loss. 6h is clearly
507
+ * "this child is wedged," not "this child is busy".
498
508
  */
499
- export const SESSION_CHILD_PIN_MAX_MS = 45 * 60 * 1000
509
+ export const SESSION_CHILD_STUCK_BACKSTOP_MS = 6 * 60 * 60 * 1000
500
510
 
501
511
  /**
502
512
  * Cost-aware grace decision for the soft→hard TTL band. Returns true when reusing
@@ -780,6 +790,15 @@ type LiveSession = {
780
790
  // carried only to the typing path; null when the triggering inbound supplied
781
791
  // none (every non-DM inbound, and reminder-only turns).
782
792
  currentTurnTypingThread: string | null
793
+ // Every flat-DM typingThread anchor a 'tick' set a non-expiring status on but
794
+ // that has not yet been cleared. In a flat DM each inbound stamps its OWN ts
795
+ // as `typingThread`, so `currentTurnTypingThread` migrates from ts=A to ts=B
796
+ // when a second message coalesces a new turn before the first turn's stop. A
797
+ // single-anchor stop would then clear only B and strand A's "is typing..."
798
+ // forever (Slack has no auto-expiry). Recording every ticked anchor lets the
799
+ // stop clear ALL of them, not just the latest. An anchor is added when its
800
+ // 'tick' dispatches and removed when its 'stop' clear dispatches.
801
+ dirtyTypingThreads: Set<string>
783
802
  // One engage-:eyes:-add promise per inbound coalesced into THIS turn, each
784
803
  // resolving to its removable per-instance ref (or null). A debounced turn can
785
804
  // batch several inbounds that each got their own :eyes:, so every entry is
@@ -801,6 +820,24 @@ type LiveSession = {
801
820
  // one toggle would otherwise have the engage-drop remove the only visible
802
821
  // :eyes:. See `reactOnSilentAck`.
803
822
  silentAckTurn: { turnSeq: number; reason: SilentAckReason } | null
823
+ // One silent-ack-:eyes:-add promise per PERSISTENT ack `reactOnSilentAck` has
824
+ // planted on a trigger message, each resolving to its removable ref (or null).
825
+ // Mirrors `currentTurnEngageReactions`: the PROMISE is pushed synchronously at
826
+ // arm time, so a later replied-turn cleanup that snapshots this array always
827
+ // sees every in-flight add and awaits it before removing — storing only the
828
+ // resolved ref raced (cleanup could snapshot an empty array, then a slow add
829
+ // append its ref afterward, stranding the :eyes:). Cross-turn state on purpose:
830
+ // a silent turn means "seen, not replying FOR NOW", and once the same sticky
831
+ // conversation gets a genuine reply those marks read as stale/contradictory —
832
+ // so they are retired on the next replied turn (see dropSilentAckReactions).
833
+ // Conversation-scoped, NOT per-trigger-message: coalescing means the silent
834
+ // turn's trigger (message N) and the eventual reply's trigger (message N+1)
835
+ // routinely differ, so exact-message scoping would strand the mark. NOT reset
836
+ // in drain's outer per-turn finally. On teardown the entries are dropped
837
+ // WITHOUT removing the reactions: a session that ends without ever replying
838
+ // legitimately keeps its "seen, not replying" ack, unlike the transient
839
+ // engage :eyes: which teardown must strip.
840
+ activeSilentAckReactions: Array<Promise<ReactionRef | null>>
804
841
  lastTurnAuthorIds: Set<string>
805
842
  // Mirror of currentTurnAuthorId at end-of-turn (the LAST speaker of the
806
843
  // prior batch), preserved across the drain finally-block which resets
@@ -920,6 +957,18 @@ type LiveSession = {
920
957
  // turn can never trigger a nudge on a later one. `null` when no such reply
921
958
  // ended this turn.
922
959
  lastTerminalReplyAbort: { turnSeq: number; text: string } | null
960
+ // Stamped by `installChannelReplyTerminalHook` when a successful `channel_reply`
961
+ // set `continue: true` — the machine-readable "I'll keep working this turn"
962
+ // promise. `validateChannelTurn` reads it to recover a turn that made that promise,
963
+ // did more work, then ended on a fresh empty `stop` (dropped its conclusion) —
964
+ // independent of what natural-language phrase the ack used, so a persona speaking
965
+ // any language/register is covered where the willingness phrase table would miss.
966
+ // `turnSeq`-stamped so a stale promise can't fire on a later turn. `sendCount` is
967
+ // `successfulChannelSends` AT the ack (which already counts the ack itself); the
968
+ // recovery fires only while it still equals the live count — a later substantive
969
+ // send (e.g. a `channel_send` final answer) bumps the count and invalidates the
970
+ // promise, so an empty stop after the real answer is NOT re-nudged.
971
+ continueReplyTurn: { turnSeq: number; sendCount: number } | null
923
972
  // Stamped by router abort sites and read by `validateChannelTurn` for
924
973
  // reason-specific stranded-toolUse recovery logs. `turnSeq`-stamped so stale
925
974
  // abort provenance from an earlier turn can never leak into a later retry.
@@ -970,6 +1019,19 @@ type LiveSession = {
970
1019
  // question escalation. Compared by `turnSeq` so a stale value can't leak across
971
1020
  // turns.
972
1021
  emptyTurnFallbackTurn: number | null
1022
+ // Stamped with `turnSeq` when a formal GitHub review (APPROVE / REQUEST_CHANGES /
1023
+ // COMMENT) lands during this LOGICAL turn, via noteGithubReviewOutput off the
1024
+ // review-output observer. On a github PR channel the agent's real deliverable is
1025
+ // the review — posted through the GitHub API by the bash tool, NOT through
1026
+ // channel_reply/channel_send — so it never bumps `successfulChannelSends`. An
1027
+ // empty completion afterward would otherwise look like a dead turn and fire the
1028
+ // "I got stuck" empty-turn fallback (a real verdict, then a contradictory fallback
1029
+ // seconds later). validateChannelTurn reads this to treat such an empty stop as a
1030
+ // legitimate silent completion. Reset ONLY on a real user batch (with the retry
1031
+ // budgets) so it survives reminder-only retry iterations — the review lands in an
1032
+ // EARLIER iteration than the fallback; resetting per-iteration (beside
1033
+ // resetReviewTurn) would recreate the bug.
1034
+ githubReviewOutputTurn: number | null
973
1035
  // Captured by drain() at batch dequeue; read+cleared by send() on the
974
1036
  // first tool-source send of the turn. The anchor decision (delay
975
1037
  // threshold + intervening-observed check) is evaluated at SEND time
@@ -1018,6 +1080,13 @@ type LiveSession = {
1018
1080
  // crashed prior turn can't leak into the next.
1019
1081
  pendingProviderError: { turnSeq: number; safeMessage: string } | null
1020
1082
  destroyed: boolean
1083
+ // Set by tearDownAllLive when a reload/roles/auth swap wants to recreate this
1084
+ // session but a turn is mid-flight. Aborting now would strand the in-flight
1085
+ // reply (the reload's own turn goes silent). Instead the session stays live
1086
+ // and finishes its current reply with pre-reload state; the drain loop's
1087
+ // finally tears it down once the turn drains, so the next inbound rehydrates
1088
+ // with fresh role/auth/prompt state. Idle sessions are torn down immediately.
1089
+ pendingTeardown: boolean
1021
1090
  unsubProviderErrors: (() => void) | null
1022
1091
  unsubTypingActivity: (() => void) | null
1023
1092
  unsubTodoOutcome: (() => void) | null
@@ -1151,6 +1220,16 @@ export type ChannelRouter = {
1151
1220
  registerList: (adapter: ChannelKey['adapter'], cb: ListCallback) => void
1152
1221
  unregisterList: (adapter: ChannelKey['adapter'], cb: ListCallback) => void
1153
1222
  listChannels: (adapter: ChannelKey['adapter'], args: ListChannelsArgs) => Promise<ListChannelsResult>
1223
+ // Message editing is opt-in per adapter, Set-based like reactions/outbound so
1224
+ // future multi-account setups can register more than one. A missing callback
1225
+ // resolves to `code: 'not-supported'`, or `code: 'adapter-unavailable'` when
1226
+ // the static write-capability table (ADAPTER_WRITE_CAPABILITIES) says this
1227
+ // adapter edits but no live callback exists (failed start). Kept off the
1228
+ // outbound path: an edit mutates an existing post, so it must not flow through
1229
+ // send()'s flood/cap/dup/sticky guards.
1230
+ registerEditMessage: (adapter: ChannelKey['adapter'], cb: EditMessageCallback) => void
1231
+ unregisterEditMessage: (adapter: ChannelKey['adapter'], cb: EditMessageCallback) => void
1232
+ editMessage: (req: EditMessageRequest) => Promise<EditMessageResult>
1154
1233
  registerFetchAttachment: (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback) => void
1155
1234
  unregisterFetchAttachment: (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback) => void
1156
1235
  fetchAttachment: (adapter: ChannelKey['adapter'], args: FetchAttachmentArgs) => Promise<FetchAttachmentResult>
@@ -1224,6 +1303,12 @@ export type ChannelRouter = {
1224
1303
  verdict: 'APPROVE' | 'REQUEST_CHANGES'
1225
1304
  sessionId: string
1226
1305
  }) => { kind: 'delivered'; count: number }
1306
+ noteGithubReviewOutput: (args: {
1307
+ sessionId: string
1308
+ workspace: string
1309
+ prNumber: number
1310
+ state: ReviewOutputState
1311
+ }) => { kind: 'stamped' | 'no-live-session' }
1227
1312
  // Record that the agent invoked `skip_response` during the current turn
1228
1313
  // for the channel session identified by `parentSessionId`. The reason is
1229
1314
  // logged at INFO level inside `validateChannelTurn` (single log line per
@@ -1396,12 +1481,12 @@ export type CreateChannelRouterOptions = {
1396
1481
  // Returns the start time (epoch ms) of the NEWEST still-running background
1397
1482
  // subagent spawned from `sessionId`, or null when none is running. Lets idle
1398
1483
  // GC and stale-rollover pin a session whose child is still working (the next
1399
- // inbound would otherwise spawn a duplicate child), bounded by
1400
- // SESSION_CHILD_PIN_MAX_MS measured from that start. Newest — not oldest — so a
1401
- // long-running child that crossed the cap cannot unpin the session while a more
1402
- // recently spawned child is still inside its own protection window. Production
1403
- // wiring forwards the LiveSubagentRegistry; omitted (tests, no-subagent setups)
1404
- // means no pin.
1484
+ // inbound would otherwise spawn a duplicate child, and a completion arriving
1485
+ // after teardown is dropped), bounded only by SESSION_CHILD_STUCK_BACKSTOP_MS
1486
+ // measured from that start. Newest — not oldest — so a long-running child that
1487
+ // crossed the stuck backstop cannot unpin the session while a more recently
1488
+ // spawned child is still inside its window. Production wiring forwards the
1489
+ // LiveSubagentRegistry; omitted (tests, no-subagent setups) means no pin.
1405
1490
  newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
1406
1491
  }
1407
1492
 
@@ -1492,6 +1577,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1492
1577
  const historyCallbacks = new Map<ChannelKey['adapter'], Set<HistoryCallback>>()
1493
1578
  const messageGetCallbacks = new Map<ChannelKey['adapter'], MessageGetCallback>()
1494
1579
  const listCallbacks = new Map<ChannelKey['adapter'], ListCallback>()
1580
+ const editMessageCallbacks = new Map<ChannelKey['adapter'], Set<EditMessageCallback>>()
1495
1581
  const fetchAttachmentCallbacks = new Map<ChannelKey['adapter'], Set<FetchAttachmentCallback>>()
1496
1582
  const reviewThreadResolvers = new Map<ChannelKey['adapter'], ReviewThreadResolver>()
1497
1583
  const reviewStateResolvers = new Map<ChannelKey['adapter'], ReviewStateResolver>()
@@ -1731,19 +1817,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1731
1817
  }
1732
1818
 
1733
1819
  // True while a background child spawned from this session is still running AND
1734
- // the newest such child is within SESSION_CHILD_PIN_MAX_MS of its start. Using
1735
- // the newest child keeps the session pinned as long as ANY running child is
1736
- // still inside its protection window — an older child that already crossed the
1737
- // cap must not unpin the session out from under a freshly spawned one. Tearing
1738
- // the session down mid-child lets the next inbound spawn a duplicate child, so
1739
- // GC/rollover defer to this. `label` only annotates the override log.
1820
+ // the newest such child has not outlived the stuck backstop. Using the newest
1821
+ // child keeps the session pinned as long as ANY running child is still inside
1822
+ // its window — an older child past the backstop must not unpin the session out
1823
+ // from under a freshly spawned one. Tearing the session down mid-child lets the
1824
+ // next inbound spawn a duplicate child AND drops the child's completion when it
1825
+ // lands after teardown, so GC/rollover defer to this. Crossing the backstop is
1826
+ // an anomaly (a wedged, timeout-less child), logged at warn. `label` only
1827
+ // annotates the override log.
1740
1828
  const isPinnedByRunningChild = (sessionId: string, keyId: string, label: string): boolean => {
1741
1829
  const childStartedAt = newestRunningChildSubagentStartedAt(sessionId)
1742
1830
  if (childStartedAt === null) return false
1743
1831
  const pinnedForMs = now() - childStartedAt
1744
- if (pinnedForMs <= SESSION_CHILD_PIN_MAX_MS) return true
1745
- logger.info(
1746
- `[channels] ${keyId}: ${label} despite running child (newest pinned ${pinnedForMs}ms, past child-pin cap)`,
1832
+ if (pinnedForMs <= SESSION_CHILD_STUCK_BACKSTOP_MS) return true
1833
+ logger.warn(
1834
+ `[channels] ${keyId}: ${label} despite running child (newest pinned ${pinnedForMs}ms, past stuck-child backstop; suspected stuck running child)`,
1747
1835
  )
1748
1836
  return false
1749
1837
  }
@@ -2006,9 +2094,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2006
2094
  currentTurnAuthorIds: new Set(),
2007
2095
  currentTurnReactionRef: null,
2008
2096
  currentTurnTypingThread: null,
2097
+ dirtyTypingThreads: new Set(),
2009
2098
  currentTurnEngageReactions: [],
2010
2099
  pendingTurnReactions: [],
2011
2100
  silentAckTurn: null,
2101
+ activeSilentAckReactions: [],
2012
2102
  // `lastTurnAuthorId` (string, used for `lastInboundAuthorId` in
2013
2103
  // origin) and `lastTurnAuthorIds` (Set, used by
2014
2104
  // `grantStickyForReplyTargets` as the fallback when
@@ -2036,12 +2126,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2036
2126
  emptyStopAfterToolWorkArmed: false,
2037
2127
  willingnessNudges: 0,
2038
2128
  lastTerminalReplyAbort: null,
2129
+ continueReplyTurn: null,
2039
2130
  abortReasonThisTurn: null,
2040
2131
  nextPromptMaxTokens: undefined,
2041
2132
  skippedTurn: null,
2042
2133
  skipLockedSendTurn: null,
2043
2134
  disengagedTurn: null,
2044
2135
  emptyTurnFallbackTurn: null,
2136
+ githubReviewOutputTurn: null,
2045
2137
  pendingQuoteCandidate: null,
2046
2138
  recentEngagedPeerBotTurns: [],
2047
2139
  consecutiveEngagedPeerBotTurns: 0,
@@ -2052,6 +2144,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2052
2144
  membershipFetch,
2053
2145
  pendingProviderError: null,
2054
2146
  destroyed: false,
2147
+ pendingTeardown: false,
2055
2148
  unsubProviderErrors: null,
2056
2149
  unsubTypingActivity: null,
2057
2150
  unsubTodoOutcome: null,
@@ -2265,14 +2358,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2265
2358
  await persist()
2266
2359
  }
2267
2360
 
2268
- const fireTyping = async (live: LiveSession, phase: 'tick' | 'stop', epoch?: number): Promise<void> => {
2361
+ const fireTyping = async (
2362
+ live: LiveSession,
2363
+ phase: 'tick' | 'stop',
2364
+ epoch?: number,
2365
+ typingThreadOverride?: string,
2366
+ ): Promise<void> => {
2269
2367
  // Drop a stale 'tick' that a since-cancelled interval still dispatched:
2270
2368
  // once the heartbeat stopped (or a new one started) the captured epoch no
2271
2369
  // longer matches, and forwarding it would re-set the indicator after the
2272
- // stop clear. 'stop' is never epoch-gated — it must always clear.
2370
+ // stop clear. 'stop' is never epoch-gated — it must always clear. Marking
2371
+ // dirty happens after this gate so a dropped tick is never recorded.
2273
2372
  if (phase === 'tick' && epoch !== undefined && epoch !== live.typingEpoch) return
2274
2373
  const callbacks = typingCallbacks.get(live.key.adapter)
2275
2374
  if (!callbacks || callbacks.size === 0) return
2375
+ // A 'stop' clears an explicit anchor (fireTypingStop's per-dirty-thread
2376
+ // clear); a 'tick' always targets the live turn anchor.
2377
+ const typingThread = typingThreadOverride ?? live.currentTurnTypingThread
2378
+ if (phase === 'tick' && typingThread !== null) live.dirtyTypingThreads.add(typingThread)
2276
2379
  // Snapshot before iterating: a callback could unregister mid-call.
2277
2380
  const snapshot = Array.from(callbacks)
2278
2381
  const target = {
@@ -2280,7 +2383,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2280
2383
  workspace: live.key.workspace,
2281
2384
  chat: live.key.chat,
2282
2385
  thread: live.key.thread,
2283
- ...(live.currentTurnTypingThread !== null ? { typingThread: live.currentTurnTypingThread } : {}),
2386
+ ...(typingThread !== null ? { typingThread } : {}),
2284
2387
  phase,
2285
2388
  }
2286
2389
  await Promise.all(
@@ -2290,6 +2393,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2290
2393
  }),
2291
2394
  ),
2292
2395
  )
2396
+ if (phase === 'stop' && typingThread !== null) live.dirtyTypingThreads.delete(typingThread)
2397
+ }
2398
+
2399
+ // A 'stop' must clear EVERY flat-DM typingThread a tick set a status on this
2400
+ // session — not just the current anchor — or a migrated-away anchor strands
2401
+ // its "is typing..." (see `dirtyTypingThreads`). Clears run concurrently; each
2402
+ // dirty thread is dispatched once and removed by fireTyping's stop path.
2403
+ const fireTypingStop = async (live: LiveSession): Promise<void> => {
2404
+ const dirty = new Set(live.dirtyTypingThreads)
2405
+ if (live.currentTurnTypingThread !== null) dirty.add(live.currentTurnTypingThread)
2406
+ if (dirty.size === 0) {
2407
+ await fireTyping(live, 'stop')
2408
+ return
2409
+ }
2410
+ await Promise.all(Array.from(dirty, (typingThread) => fireTyping(live, 'stop', undefined, typingThread)))
2293
2411
  }
2294
2412
 
2295
2413
  const bumpTypingActivity = (live: LiveSession): void => {
@@ -2397,6 +2515,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2397
2515
  const details = context.result.details as { ok?: unknown; continue?: unknown } | undefined
2398
2516
  const succeeded = context.toolCall.name === 'channel_reply' && !context.isError && details?.ok === true
2399
2517
  const keepTurnAlive = details?.continue === true
2518
+ if (succeeded && keepTurnAlive) {
2519
+ live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
2520
+ }
2400
2521
  if (succeeded && !keepTurnAlive && agent.signal?.aborted !== true) {
2401
2522
  logger.info(`[channels] ${live.keyId} terminal_after_channel_reply`)
2402
2523
  const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
@@ -2478,7 +2599,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2478
2599
  // clear platform-side state (e.g. Slack's 2-min server timeout) on
2479
2600
  // teardown. The FIFO inside the slack adapter ensures this clear lands
2480
2601
  // AFTER any in-flight 'tick' from the heartbeat that just stopped.
2481
- const stopped = fireTyping(live, 'stop').finally(() => {
2602
+ const stopped = fireTypingStop(live).finally(() => {
2482
2603
  if (live.typingStopPromise === stopped) live.typingStopPromise = null
2483
2604
  })
2484
2605
  live.typingStopPromise = stopped
@@ -2616,6 +2737,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2616
2737
  }
2617
2738
  }
2618
2739
 
2740
+ // ensureLive() installs a session BEFORE the engage/observe decision, so a
2741
+ // bystander agent that only OBSERVED a thread still holds an exact-thread
2742
+ // session with nothing running. Without this gate that agent aborts its idle
2743
+ // session and posts "stopped" in a multi-agent channel. Mirrors exactly what
2744
+ // stopCurrentChannelTurn cancels: in-flight drain, queued prompts, reminders.
2745
+ const hasStoppableWork = (live: LiveSession): boolean =>
2746
+ live.draining || live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0
2747
+
2619
2748
  const maybePostDeferredProviderError = async (
2620
2749
  live: LiveSession,
2621
2750
  sentReplyThisTurn: boolean,
@@ -2670,7 +2799,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2670
2799
  if (live.draining || live.destroyed) return
2671
2800
  live.draining = true
2672
2801
  try {
2673
- while ((live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) && !live.destroyed) {
2802
+ // `!live.pendingTeardown`: once a reload marks this draining session for
2803
+ // teardown, finish ONLY the in-flight prompt (its batch was already
2804
+ // spliced out of promptQueue at the top of the current iteration) and
2805
+ // stop — do NOT splice a fresh batch of post-reload inbounds onto the
2806
+ // stale, about-to-be-recreated session. Those queued inbounds are handed
2807
+ // to the fresh successor in the teardown block below.
2808
+ while (
2809
+ (live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) &&
2810
+ !live.destroyed &&
2811
+ !live.pendingTeardown
2812
+ ) {
2674
2813
  live.typingTimedOut = false
2675
2814
  // Each turn starts with no held reactions; the model re-requests them
2676
2815
  // via channel_react during this turn, and the finally flushes or drops.
@@ -2719,6 +2858,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2719
2858
  live.willingnessNudges = 0
2720
2859
  live.abortReasonThisTurn = null
2721
2860
  live.nextPromptMaxTokens = undefined
2861
+ // Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
2862
+ // review landed earlier in this logical turn keeps suppressing the
2863
+ // empty-turn fallback across the reminder-only retry iterations.
2864
+ live.githubReviewOutputTurn = null
2722
2865
  } else if (live.lastTurnAuthorId !== null) {
2723
2866
  live.currentTurnEngageReactions = []
2724
2867
  // Reminder-only turn (batch.length === 0, reminders.length > 0):
@@ -2771,6 +2914,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2771
2914
  live.skipLockedSendTurn = null
2772
2915
  live.disengagedTurn = null
2773
2916
  live.emptyTurnFallbackTurn = null
2917
+ live.continueReplyTurn = null
2774
2918
  live.policyDeniedToolSendsThisTurn.clear()
2775
2919
  resetReviewTurn(live.sessionId)
2776
2920
  const isRealUserTurn = batch.length > 0
@@ -2886,8 +3030,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2886
3030
  sentReplyThisTurn &&
2887
3031
  live.emptyTurnFallbackTurn !== live.turnSeq &&
2888
3032
  assistantLeafStopReason(live.session) !== 'error'
2889
- if (usableReplyThisTurn) flushPendingReactions(live)
2890
- else live.pendingTurnReactions = []
3033
+ if (usableReplyThisTurn) {
3034
+ flushPendingReactions(live)
3035
+ void dropSilentAckReactions(live)
3036
+ } else live.pendingTurnReactions = []
2891
3037
  // Either retry budget keeps the turn in flight, so a deferred provider
2892
3038
  // error must wait for the reminder-only iteration that actually ends it.
2893
3039
  const retryQueuedThisTurn =
@@ -2919,6 +3065,60 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2919
3065
  await stopTypingHeartbeat(live)
2920
3066
  live.currentTurnTypingThread = null
2921
3067
  }
3068
+ // A reload deferred this session's teardown so its in-flight reply could
3069
+ // land; now that the turn drained (and the loop stopped BEFORE draining any
3070
+ // post-reload inbound), complete the recreate so the fresh session picks up
3071
+ // the swapped role/auth/prompt state. Guarded on !destroyed so a concurrent
3072
+ // stop()/idle-gc that already tore it down wins the race without a double
3073
+ // teardown.
3074
+ if (live.pendingTeardown && !live.destroyed) {
3075
+ live.pendingTeardown = false
3076
+ // Snapshot the post-reload inbounds that arrived during the held prompt
3077
+ // BEFORE tearDownLive (its clearQueuedEngageReactions must not drop the
3078
+ // engage acks we are handing to the successor). Clear the source arrays so
3079
+ // the dying session owns nothing we are moving forward.
3080
+ const carriedInbounds = live.promptQueue.splice(0, live.promptQueue.length)
3081
+ const carriedObserved = live.contextBuffer.splice(0, live.contextBuffer.length)
3082
+ const carriedReminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
3083
+ liveSessions.delete(live.keyId)
3084
+ await tearDownLive(live)
3085
+ await handOffToSuccessor(live.key, carriedInbounds, carriedObserved, carriedReminders)
3086
+ }
3087
+ }
3088
+
3089
+ // Rebuild a live session for a channel key after a reload tore its predecessor
3090
+ // down mid-drain, and replay the post-reload work that predecessor never got
3091
+ // to process. The carried inbounds already have their engagement decided (they
3092
+ // were enqueued while draining), so they are transplanted straight onto the
3093
+ // fresh session's queues rather than re-routed through route() — re-routing
3094
+ // would re-run the claim/command/permission gates and re-derive engagement
3095
+ // from a lossy QueuedInbound projection. Best-effort: a recreate failure logs
3096
+ // and drops the batch rather than throwing out of the predecessor's drain.
3097
+ const handOffToSuccessor = async (
3098
+ key: ChannelKey,
3099
+ inbounds: QueuedInbound[],
3100
+ observed: ObservedInbound[],
3101
+ reminders: string[],
3102
+ ): Promise<void> => {
3103
+ // Observed context alone is carried too: observe() can buffer post-reload
3104
+ // messages onto contextBuffer with no queued prompt, and dropping them would
3105
+ // lose the successor's "recent context". Only skip when nothing at all was
3106
+ // carried.
3107
+ if (inbounds.length === 0 && reminders.length === 0 && observed.length === 0) return
3108
+ let successor: LiveSession
3109
+ try {
3110
+ successor = await ensureLive(key)
3111
+ } catch (err) {
3112
+ logger.warn(`[channels] ${channelKeyId(key)}: successor recreate after reload failed: ${describe(err)}`)
3113
+ return
3114
+ }
3115
+ if (successor.destroyed) return
3116
+ successor.promptQueue.push(...inbounds)
3117
+ successor.contextBuffer.push(...observed)
3118
+ successor.pendingSystemReminders.push(...reminders)
3119
+ // Observed-only context is NOT a turn trigger — it waits on contextBuffer for
3120
+ // a real inbound. Drain only when there is actual work (a prompt or reminder).
3121
+ if ((inbounds.length > 0 || reminders.length > 0) && !successor.draining) void drain(successor)
2922
3122
  }
2923
3123
 
2924
3124
  const scheduleDebouncedDrain = (live: LiveSession): void => {
@@ -3627,6 +3827,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3627
3827
  ? `${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)`
3628
3828
  : `${capability}-not-supported`
3629
3829
 
3830
+ const isWriteCapabilityUnavailable = (adapter: ChannelKey['adapter'], capability: WriteCapability): boolean =>
3831
+ configuredAdapters.has(adapter) && ADAPTER_WRITE_CAPABILITIES[adapter].includes(capability)
3832
+
3630
3833
  const fetchHistory = async (adapter: ChannelKey['adapter'], args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
3631
3834
  const callbacks = historyCallbacks.get(adapter)
3632
3835
  if (!callbacks || callbacks.size === 0) {
@@ -3693,6 +3896,59 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3693
3896
  }
3694
3897
  }
3695
3898
 
3899
+ const registerEditMessage = (adapter: ChannelKey['adapter'], cb: EditMessageCallback): void => {
3900
+ let set = editMessageCallbacks.get(adapter)
3901
+ if (!set) {
3902
+ set = new Set()
3903
+ editMessageCallbacks.set(adapter, set)
3904
+ }
3905
+ set.add(cb)
3906
+ }
3907
+
3908
+ const unregisterEditMessage = (adapter: ChannelKey['adapter'], cb: EditMessageCallback): void => {
3909
+ editMessageCallbacks.get(adapter)?.delete(cb)
3910
+ }
3911
+
3912
+ const editMessage = async (req: EditMessageRequest): Promise<EditMessageResult> => {
3913
+ // Strip leaked `<think>` blocks before the edit reaches any adapter, exactly
3914
+ // as the send path does via normalizeSendText — an edit is another way text
3915
+ // reaches the chat, so it must not become a hole that writes raw reasoning a
3916
+ // send would have suppressed. A replacement that is ONLY a think block leaves
3917
+ // nothing visible, so refuse rather than blank the message.
3918
+ const normalized = normalizeSendText(req.text)
3919
+ if (normalized === undefined) {
3920
+ return { ok: false, error: 'message-edit-empty-after-normalization', code: 'not-found' }
3921
+ }
3922
+ const normalizedReq = normalized === req.text ? req : { ...req, text: normalized }
3923
+ const callbacks = editMessageCallbacks.get(req.adapter)
3924
+ if (!callbacks || callbacks.size === 0) {
3925
+ return isWriteCapabilityUnavailable(req.adapter, 'message-edit')
3926
+ ? {
3927
+ ok: false,
3928
+ 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)`,
3929
+ code: 'adapter-unavailable',
3930
+ }
3931
+ : { ok: false, error: 'message-edit-not-supported', code: 'not-supported' }
3932
+ }
3933
+ const snapshot = Array.from(callbacks)
3934
+ let lastError: EditMessageResult & { ok: false } = { ok: false, error: 'message-edit-not-supported' }
3935
+ for (const cb of snapshot) {
3936
+ try {
3937
+ const result = await raceWithTimeout(
3938
+ cb(normalizedReq),
3939
+ fetchHistoryTimeoutMs,
3940
+ `[channels] ${req.adapter} edit message`,
3941
+ )
3942
+ if (result.ok) return result
3943
+ lastError = result
3944
+ } catch (err) {
3945
+ logger.warn(`[channels] edit message threw for ${req.adapter}: ${describe(err)}`)
3946
+ lastError = { ok: false, error: `edit message failed: ${describe(err)}` }
3947
+ }
3948
+ }
3949
+ return lastError
3950
+ }
3951
+
3696
3952
  const registerFetchAttachment = (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback): void => {
3697
3953
  let set = fetchAttachmentCallbacks.get(adapter)
3698
3954
  if (!set) {
@@ -4145,6 +4401,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4145
4401
  }
4146
4402
  }
4147
4403
 
4404
+ // A formal GitHub review already landed this logical turn (APPROVE /
4405
+ // REQUEST_CHANGES / COMMENT, stamped via noteGithubReviewOutput). That review IS
4406
+ // the turn's user-facing output — it just went through the GitHub review API, not
4407
+ // channel_reply/channel_send, so `successfulChannelSends` never moved. An empty
4408
+ // completion afterward is the agent legitimately having nothing more to say, NOT
4409
+ // a dead turn: skip the empty-turn retries AND the "I got stuck" fallback and
4410
+ // treat it as silent completion. Gated on no channel send this turn so a turn
4411
+ // that ALSO replied in-channel still runs the normal reply-recovery below.
4412
+ if (
4413
+ live.githubReviewOutputTurn === live.turnSeq &&
4414
+ live.successfulChannelSends === successfulSendsBeforePrompt &&
4415
+ live.currentTurnAuthorId !== null
4416
+ ) {
4417
+ logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=github_review_output_this_turn`)
4418
+ armSilentTurnAck(live, 'github_review_output')
4419
+ return
4420
+ }
4421
+
4148
4422
  // Suppress a leaked tool call (never post the plumbing) and, while budget
4149
4423
  // remains, push a self-correction reminder so the same logical turn
4150
4424
  // re-prompts and the model can redo it with a real tool call. On exhaustion
@@ -4179,6 +4453,47 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4179
4453
  if (live.successfulChannelSends > successfulSendsBeforePrompt) {
4180
4454
  maybeNudgeContinuationWillingness(live)
4181
4455
 
4456
+ // A `channel_reply({ continue: true })` progress ack landed this turn (the
4457
+ // machine-readable "I'll keep working" promise — `continueReplyTurn` is stamped
4458
+ // by installChannelReplyTerminalHook), the model did more work, then ended on a
4459
+ // FRESH empty `stop` — dropping its conclusion. This is the SAME degeneration as
4460
+ // the phrase-gated `channel_send` branch below, but keyed on the `continue: true`
4461
+ // FLAG instead of a natural-language willingness phrase. The flag is the robust
4462
+ // signal: it fires regardless of the ack's language or register, closing the gap
4463
+ // where a persona speaking a phrasing outside the willingness table (e.g. casual
4464
+ // Korean "확인해볼게") stranded the user in silence. The `attemptMadeToolCall`
4465
+ // half ties the first trigger to real post-ack work; `willingnessNudges > 0`
4466
+ // lets a retry that re-emitted `continue: true` and re-stranded spend the shared
4467
+ // budget toward the visible fallback instead of bailing silent. Same
4468
+ // MAX_WILLINGNESS_NUDGES bound, same empty-`promptQueue` gate (a coalesced live
4469
+ // inbound supersedes this turn's silence), and same nudge/fallback path as the
4470
+ // send-ack branch. Placed FIRST so the flag catch wins when both signals are
4471
+ // present; the phrase branch remains the only recovery for `channel_send`, which
4472
+ // stamps no flag. The `sendCount === successfulChannelSends` check requires the
4473
+ // continue-reply to STILL be the latest successful send: if a later substantive
4474
+ // send (e.g. a `channel_send` final answer) landed after the ack, the user was
4475
+ // already answered and a trailing empty stop must NOT be re-nudged.
4476
+ if (
4477
+ live.promptQueue.length === 0 &&
4478
+ live.currentTurnAuthorId !== null &&
4479
+ live.continueReplyTurn?.turnSeq === live.turnSeq &&
4480
+ live.continueReplyTurn.sendCount === live.successfulChannelSends &&
4481
+ isFreshEmptyStopAfterSend(live) &&
4482
+ (attemptMadeToolCall(live.session) || live.willingnessNudges > 0)
4483
+ ) {
4484
+ if (live.willingnessNudges < MAX_WILLINGNESS_NUDGES) {
4485
+ live.willingnessNudges++
4486
+ logger.warn(
4487
+ `[channels] ${live.keyId} send_willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES} ` +
4488
+ `cause=empty_stop_after_continue_reply`,
4489
+ )
4490
+ live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
4491
+ } else {
4492
+ await postEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
4493
+ }
4494
+ return
4495
+ }
4496
+
4182
4497
  // A `channel_send` ack that promised to keep working, fresh post-ack work,
4183
4498
  // then an EMPTY `stop` leaf: the model computed the answer in its reasoning
4184
4499
  // / tool results but never sent it (the Kimi/Fireworks empty-completion
@@ -4741,11 +5056,26 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4741
5056
  const tearDownAllLive = async (): Promise<void> => {
4742
5057
  liveGeneration++
4743
5058
  const all = Array.from(liveSessions.values())
5059
+ // A session mid-turn is deferred, not aborted: tearing it down here calls
5060
+ // session.abort(), which kills the in-flight reply — including the very turn
5061
+ // that triggered this reload, leaving the user in silence. Such a session
5062
+ // stays in liveSessions (so a concurrent inbound coalesces into the running
5063
+ // turn instead of spawning a duplicate) and is torn down by the drain
5064
+ // finally once its turn drains. Idle sessions tear down immediately below.
5065
+ const deferred: LiveSession[] = []
5066
+ const immediate: LiveSession[] = []
5067
+ for (const live of all) {
5068
+ if (live.draining && !live.destroyed) {
5069
+ live.pendingTeardown = true
5070
+ deferred.push(live)
5071
+ } else immediate.push(live)
5072
+ }
4744
5073
  liveSessions.clear()
5074
+ for (const live of deferred) liveSessions.set(live.keyId, live)
4745
5075
  // Seal only around the flush — unlike stop() the router keeps serving after a
4746
5076
  // roles reload, so re-enable persist() once pending writes have drained.
4747
5077
  closing = true
4748
- for (const live of all) {
5078
+ for (const live of immediate) {
4749
5079
  await tearDownLive(live)
4750
5080
  }
4751
5081
  await persistChain
@@ -4938,6 +5268,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4938
5268
  if (resolved.kind === 'ambiguous') {
4939
5269
  return { kind: 'ambiguous', matchCount: resolved.count }
4940
5270
  }
5271
+ // A resolved session that isn't actually running has nothing for /stop to
5272
+ // cancel; report it as no-live-session so bystander agents stay silent.
5273
+ if (lowered === 'stop' && !hasStoppableWork(resolved.session)) {
5274
+ return { kind: 'no-live-session' }
5275
+ }
4941
5276
  live = resolved.session
4942
5277
  } else if (commandInfo.wantsLiveSession) {
4943
5278
  // Best-effort: resolve a session if exactly one matches, but never fail
@@ -5060,6 +5395,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5060
5395
  return { kind: 'delivered', count }
5061
5396
  }
5062
5397
 
5398
+ // Stamp the review-output flag on the session that just landed a formal GitHub
5399
+ // review this turn. Matched by sessionId (the recorder records the exact
5400
+ // event.sessionId), and confirmed to be the right github PR live session so a
5401
+ // stray/mismatched signal can't suppress an unrelated turn's fallback. See
5402
+ // `githubReviewOutputTurn`.
5403
+ const noteGithubReviewOutput = (args: {
5404
+ sessionId: string
5405
+ workspace: string
5406
+ prNumber: number
5407
+ state: ReviewOutputState
5408
+ }): { kind: 'stamped' | 'no-live-session' } => {
5409
+ const chat = `pr:${args.prNumber}`
5410
+ for (const live of liveSessions.values()) {
5411
+ if (live.destroyed) continue
5412
+ if (live.sessionId !== args.sessionId) continue
5413
+ if (live.key.adapter !== 'github') continue
5414
+ if (live.key.workspace !== args.workspace || live.key.chat !== chat) continue
5415
+ live.githubReviewOutputTurn = live.turnSeq
5416
+ logger.info(`[channels] ${live.keyId}: github_review_output state=${args.state} turn=${live.turnSeq}`)
5417
+ return { kind: 'stamped' }
5418
+ }
5419
+ return { kind: 'no-live-session' }
5420
+ }
5421
+
5063
5422
  const markTurnSkipped = (args: {
5064
5423
  parentSessionId: string
5065
5424
  reason: string
@@ -5137,7 +5496,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5137
5496
  live.silentAckTurn = null
5138
5497
  const reactionRef = live.currentTurnReactionRef
5139
5498
  if (reactionRef === null) return
5140
- void react({
5499
+ const addResult = react({
5141
5500
  adapter: live.key.adapter,
5142
5501
  workspace: live.key.workspace,
5143
5502
  chat: live.key.chat,
@@ -5145,6 +5504,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5145
5504
  reactionRef,
5146
5505
  emoji: ENGAGE_REACTION_EMOJI,
5147
5506
  })
5507
+ void addResult
5148
5508
  .then((result) => {
5149
5509
  if (!result.ok && result.code !== 'unsupported') {
5150
5510
  logger.info(
@@ -5157,6 +5517,49 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5157
5517
  `[channels] silent-ack-react threw reason=${reason} adapter=${live.key.adapter} chat=${live.key.chat}: ${describe(err)}`,
5158
5518
  )
5159
5519
  })
5520
+ // Register the add promise (not its resolved ref) SYNCHRONOUSLY, so a later
5521
+ // replied-turn cleanup can never race ahead of a still-in-flight add.
5522
+ live.activeSilentAckReactions.push(addResult.then((r) => (r.ok ? (r.reactionRef ?? null) : null)).catch(() => null))
5523
+ }
5524
+
5525
+ // Retire every persistent silent-ack :eyes: outstanding in this live session
5526
+ // once the agent posts a genuine reply — the "seen, not replying" mark is now
5527
+ // contradicted. Snapshot-and-clear the promise array BEFORE awaiting, so a
5528
+ // concurrent later silent turn appending a fresh add is never swept by this
5529
+ // in-flight cleanup. Each entry is AWAITED to its resolved ref before removal,
5530
+ // so an add still in flight when the reply lands is still retired. Failures are
5531
+ // logged, never retried: stale emoji cleanup must never block routing.
5532
+ const dropSilentAckReactions = (live: LiveSession): Promise<void> => {
5533
+ const addPromises = live.activeSilentAckReactions
5534
+ if (addPromises.length === 0) return Promise.resolve()
5535
+ live.activeSilentAckReactions = []
5536
+ return Promise.all(
5537
+ addPromises.map((addPromise) =>
5538
+ addPromise
5539
+ .then((reactionRef) => {
5540
+ if (reactionRef === null) return undefined
5541
+ return removeReaction({
5542
+ adapter: live.key.adapter,
5543
+ workspace: live.key.workspace,
5544
+ chat: live.key.chat,
5545
+ thread: live.key.thread,
5546
+ reactionRef,
5547
+ })
5548
+ })
5549
+ .then((result) => {
5550
+ if (result && !result.ok && result.code !== 'unsupported' && result.code !== 'not-found') {
5551
+ logger.info(
5552
+ `[channels] silent-ack-unreact failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
5553
+ )
5554
+ }
5555
+ })
5556
+ .catch((err) => {
5557
+ logger.info(
5558
+ `[channels] silent-ack-unreact threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describe(err)}`,
5559
+ )
5560
+ }),
5561
+ ),
5562
+ ).then(() => undefined)
5160
5563
  }
5161
5564
 
5162
5565
  return {
@@ -5192,6 +5595,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5192
5595
  registerList,
5193
5596
  unregisterList,
5194
5597
  listChannels,
5598
+ registerEditMessage,
5599
+ unregisterEditMessage,
5600
+ editMessage,
5195
5601
  registerFetchAttachment,
5196
5602
  unregisterFetchAttachment,
5197
5603
  fetchAttachment,
@@ -5208,6 +5614,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5208
5614
  getSelfAliases: computeSelfAliases,
5209
5615
  injectSubagentCompletionReminder,
5210
5616
  injectPrVerdictActivity,
5617
+ noteGithubReviewOutput,
5211
5618
  markTurnSkipped,
5212
5619
  clearSticky,
5213
5620
  reserveRestartHandoff,
@@ -5558,6 +5965,7 @@ export function formatAuthorAttribution(adapter: AdapterId, authorId: string, au
5558
5965
  case 'telegram-bot':
5559
5966
  case 'webex':
5560
5967
  case 'webex-bot':
5968
+ case 'teams':
5561
5969
  case 'instagram':
5562
5970
  case 'line':
5563
5971
  case 'kakaotalk':
@@ -5591,6 +5999,7 @@ function formatAuthorReference(adapter: AdapterId, authorId: string, authorName:
5591
5999
  case 'telegram-bot':
5592
6000
  case 'webex':
5593
6001
  case 'webex-bot':
6002
+ case 'teams':
5594
6003
  case 'instagram':
5595
6004
  case 'line':
5596
6005
  case 'kakaotalk':
@@ -5834,10 +6243,19 @@ export type ResolveLiveSessionResult =
5834
6243
  // return 'ambiguous' so the caller can refuse to act rather than abort an
5835
6244
  // arbitrary session.
5836
6245
  //
5837
- // Why the fallback: Slack slash commands carry channel_id but no thread_ts,
5838
- // so a slash invocation from a thread-keyed live session would otherwise
5839
- // report no-live-session. Discord doesn't hit this — Discord treats threads
5840
- // as channels, so the exact-key path already resolves.
6246
+ // Why the fallback: Slack slash commands carry channel_id but no thread_ts
6247
+ // (`thread: null`), so a slash invocation from a thread-keyed live session
6248
+ // would otherwise report no-live-session. Discord doesn't hit this — Discord
6249
+ // treats threads as channels, so the exact-key path already resolves.
6250
+ //
6251
+ // Why the fallback is thread-null-ONLY: a `!stop` typed INSIDE a Slack thread
6252
+ // carries the real `thread_ts`, so it pinpoints one exact thread. Falling back
6253
+ // to "any session in this channel" for a thread-specific key would let the
6254
+ // command hit an UNRELATED session in a different thread (or a channel-level
6255
+ // observe-only session) — the multi-agent bug where a bystander bot that only
6256
+ // observed the thread aborts its own idle session and posts "stopped". A
6257
+ // non-null thread that misses the exact lookup therefore returns 'none', never
6258
+ // the cross-thread fallback.
5841
6259
  //
5842
6260
  // Why ambiguity-rejection: "first match wins" map-iteration semantics would
5843
6261
  // abort an arbitrary thread when multiple thread-keyed sessions coexist in
@@ -5851,6 +6269,8 @@ export function resolveLiveSessionForCommand(
5851
6269
  const exact = liveSessions.get(channelKeyId(key))
5852
6270
  if (exact && !exact.destroyed) return { kind: 'found', session: exact }
5853
6271
 
6272
+ if (key.thread !== null) return { kind: 'none' }
6273
+
5854
6274
  const matches: LiveSession[] = []
5855
6275
  for (const candidate of liveSessions.values()) {
5856
6276
  if (candidate.destroyed) continue
@@ -6112,20 +6532,29 @@ function leafIsStrandedToolUse(session: AgentSession): boolean {
6112
6532
  return false
6113
6533
  }
6114
6534
 
6115
- // True when the turn-end leaf is a FRESH empty `stop` (no text, no tool call,
6116
- // distinct from the leaf in place at the last successful send) AND the most
6117
- // recent send to this target was a continuation-willingness ack. This is the
6118
- // `channel_send` analogue of the `channel_reply` willingness path: the model
6119
- // acked "I'll check…", did post-ack work, then the follow-up came back as a
6120
- // clean empty completion that would otherwise be read as a deliberate `NO_REPLY`.
6121
- // The fresh-leaf check (`!== lastSendLeafId`) is what separates this degeneration
6122
- // from a legitimate ack-then-stop where the model meant to wait for the user.
6123
- function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
6535
+ // The turn-end leaf is a FRESH empty `stop` — an assistant message with no visible
6536
+ // text and no tool call, distinct from the leaf in place at the last successful
6537
+ // send. "Fresh" (`!== lastSendLeafId`) is what separates a post-send degeneration
6538
+ // (the model did more work, then dropped its conclusion) from a legitimate
6539
+ // ack-then-stop where the model meant to wait for the user (leaf unchanged since
6540
+ // the send). The two willingness paths below layer their own promise-signal on top
6541
+ // of this shape: `channel_reply({ continue: true })` via `continueReplyTurn`, and
6542
+ // `channel_send` acks via the willingness phrase table.
6543
+ function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
6124
6544
  const leaf = live.session.sessionManager.getLeafEntry()
6125
6545
  if (!leaf || leaf.type !== 'message' || leaf.message.role !== 'assistant') return false
6126
6546
  if (leaf.message.stopReason !== 'stop') return false
6127
6547
  if (hasToolCall(leaf.message) || visibleAssistantText(leaf.message).trim() !== '') return false
6128
- if (leaf.id === live.lastSendLeafId) return false
6548
+ return leaf.id !== live.lastSendLeafId
6549
+ }
6550
+
6551
+ // The `channel_send` analogue of the `continue: true` recovery: the most recent
6552
+ // send to this target was a continuation-willingness ack (by phrase), then the
6553
+ // model produced a fresh empty stop. `channel_send` keeps the turn alive without a
6554
+ // `continue: true` flag and stamps no semantic marker, so the phrase table is the
6555
+ // only "I promised to keep working" signal available for that shape.
6556
+ function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
6557
+ if (!isFreshEmptyStopAfterSend(live)) return false
6129
6558
  const ackText = live.lastSentText.get(consecutiveSendKey(live.key.chat, live.key.thread))
6130
6559
  return ackText !== undefined && detectContinuationWillingness(ackText)
6131
6560
  }