typeclaw 0.43.1 → 0.44.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 (56) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +14 -2
  6. package/src/agent/multimodal/look-at.ts +27 -9
  7. package/src/agent/plugin-tools.ts +9 -4
  8. package/src/agent/session-origin.ts +1 -0
  9. package/src/agent/tools/channel-fetch-attachment.ts +45 -3
  10. package/src/agent/tools/channel-reply.ts +41 -18
  11. package/src/agent/tools/channel-send.ts +82 -13
  12. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  13. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  14. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  15. package/src/bundled-plugins/memory/README.md +9 -9
  16. package/src/bundled-plugins/memory/index.ts +40 -9
  17. package/src/channels/adapters/github/inbound.ts +20 -14
  18. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  19. package/src/channels/adapters/teams-classify.ts +144 -0
  20. package/src/channels/adapters/teams-id-token.ts +112 -0
  21. package/src/channels/adapters/teams-key.ts +32 -0
  22. package/src/channels/adapters/teams.ts +519 -0
  23. package/src/channels/github-review-turn-ledger.ts +43 -0
  24. package/src/channels/index.ts +1 -1
  25. package/src/channels/manager.ts +54 -1
  26. package/src/channels/router.ts +302 -39
  27. package/src/channels/schema.ts +9 -0
  28. package/src/cli/channel.ts +92 -4
  29. package/src/cli/hostd.ts +41 -0
  30. package/src/cli/init.ts +58 -1
  31. package/src/config/channels-mutation.ts +9 -1
  32. package/src/cron/index.ts +16 -4
  33. package/src/cron/reloadable.ts +25 -7
  34. package/src/cron/scheduler.ts +4 -0
  35. package/src/cron/schema.ts +143 -35
  36. package/src/doctor/channel-checks.ts +27 -0
  37. package/src/hostd/daemon.ts +23 -3
  38. package/src/hostd/protocol.ts +2 -0
  39. package/src/hostd/teams-renewal-manager.ts +212 -0
  40. package/src/init/checkpoint.ts +1 -1
  41. package/src/init/index.ts +68 -1
  42. package/src/init/run-owner-claim.ts +1 -0
  43. package/src/init/teams-auth.ts +111 -0
  44. package/src/inspect/label.ts +4 -0
  45. package/src/permissions/match-rule.ts +11 -1
  46. package/src/permissions/resolve.ts +1 -0
  47. package/src/role-claim/match-rule.ts +2 -1
  48. package/src/run/index.ts +35 -8
  49. package/src/run/llm-fetch-observer.ts +27 -5
  50. package/src/sandbox/build.ts +12 -0
  51. package/src/sandbox/policy.ts +13 -0
  52. package/src/sandbox/writable-zones.ts +46 -10
  53. package/src/secrets/schema.ts +32 -0
  54. package/src/secrets/teams-renewal.ts +229 -0
  55. package/src/secrets/teams-store.ts +108 -0
  56. 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,
@@ -185,7 +185,7 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
185
185
  return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
186
186
  }
187
187
 
188
- type SilentAckReason = 'skip_response' | 'no_reply' | 'skip_response_text_leak'
188
+ type SilentAckReason = 'skip_response' | 'no_reply' | 'skip_response_text_leak' | 'github_review_output'
189
189
 
190
190
  // Wake nudge pushed into a resumed channel session at boot so drain() has a
191
191
  // non-empty batch and fires a turn. The substantive instruction the model acts
@@ -482,21 +482,26 @@ export const SESSION_FRESHNESS_TTL_MS = 5 * 60 * 1000
482
482
  export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
483
483
 
484
484
  /**
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.
485
+ * Leak guard — NOT a freshness cap. A running background subagent pins its parent
486
+ * channel session against idle GC and stale-rollover for as long as the child is
487
+ * actually running, because the next inbound would otherwise start a fresh session
488
+ * that has lost track of the in-flight task and spawns a DUPLICATE child, and — the
489
+ * bug this backstop is sized around — a completion arriving after teardown has no
490
+ * live session to deliver its system-reminder to and is silently dropped.
492
491
  *
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.
492
+ * The pin is bounded only so a genuinely stuck/wedged child cannot make the session
493
+ * immortal. Subagent `timeoutMs` is optional (operator declares none), so a hung
494
+ * child stays `status: 'running'` forever; without this ceiling its parent session
495
+ * would leak indefinitely. Past this age the child is treated as stuck: GC/rollover
496
+ * proceeds and the session falls back to completion-reroute.
497
+ *
498
+ * Sized as an ANOMALY threshold, deliberately far above any legitimate run (deep
499
+ * operator work is minutes-to-an-hour, not hours), so it never fires for real work.
500
+ * The prior 45m value was close enough to plausible deep work to turn a legitimate
501
+ * long run into a routine drop — the reported 65m completion loss. 6h is clearly
502
+ * "this child is wedged," not "this child is busy".
498
503
  */
499
- export const SESSION_CHILD_PIN_MAX_MS = 45 * 60 * 1000
504
+ export const SESSION_CHILD_STUCK_BACKSTOP_MS = 6 * 60 * 60 * 1000
500
505
 
501
506
  /**
502
507
  * Cost-aware grace decision for the soft→hard TTL band. Returns true when reusing
@@ -780,6 +785,15 @@ type LiveSession = {
780
785
  // carried only to the typing path; null when the triggering inbound supplied
781
786
  // none (every non-DM inbound, and reminder-only turns).
782
787
  currentTurnTypingThread: string | null
788
+ // Every flat-DM typingThread anchor a 'tick' set a non-expiring status on but
789
+ // that has not yet been cleared. In a flat DM each inbound stamps its OWN ts
790
+ // as `typingThread`, so `currentTurnTypingThread` migrates from ts=A to ts=B
791
+ // when a second message coalesces a new turn before the first turn's stop. A
792
+ // single-anchor stop would then clear only B and strand A's "is typing..."
793
+ // forever (Slack has no auto-expiry). Recording every ticked anchor lets the
794
+ // stop clear ALL of them, not just the latest. An anchor is added when its
795
+ // 'tick' dispatches and removed when its 'stop' clear dispatches.
796
+ dirtyTypingThreads: Set<string>
783
797
  // One engage-:eyes:-add promise per inbound coalesced into THIS turn, each
784
798
  // resolving to its removable per-instance ref (or null). A debounced turn can
785
799
  // batch several inbounds that each got their own :eyes:, so every entry is
@@ -801,6 +815,24 @@ type LiveSession = {
801
815
  // one toggle would otherwise have the engage-drop remove the only visible
802
816
  // :eyes:. See `reactOnSilentAck`.
803
817
  silentAckTurn: { turnSeq: number; reason: SilentAckReason } | null
818
+ // One silent-ack-:eyes:-add promise per PERSISTENT ack `reactOnSilentAck` has
819
+ // planted on a trigger message, each resolving to its removable ref (or null).
820
+ // Mirrors `currentTurnEngageReactions`: the PROMISE is pushed synchronously at
821
+ // arm time, so a later replied-turn cleanup that snapshots this array always
822
+ // sees every in-flight add and awaits it before removing — storing only the
823
+ // resolved ref raced (cleanup could snapshot an empty array, then a slow add
824
+ // append its ref afterward, stranding the :eyes:). Cross-turn state on purpose:
825
+ // a silent turn means "seen, not replying FOR NOW", and once the same sticky
826
+ // conversation gets a genuine reply those marks read as stale/contradictory —
827
+ // so they are retired on the next replied turn (see dropSilentAckReactions).
828
+ // Conversation-scoped, NOT per-trigger-message: coalescing means the silent
829
+ // turn's trigger (message N) and the eventual reply's trigger (message N+1)
830
+ // routinely differ, so exact-message scoping would strand the mark. NOT reset
831
+ // in drain's outer per-turn finally. On teardown the entries are dropped
832
+ // WITHOUT removing the reactions: a session that ends without ever replying
833
+ // legitimately keeps its "seen, not replying" ack, unlike the transient
834
+ // engage :eyes: which teardown must strip.
835
+ activeSilentAckReactions: Array<Promise<ReactionRef | null>>
804
836
  lastTurnAuthorIds: Set<string>
805
837
  // Mirror of currentTurnAuthorId at end-of-turn (the LAST speaker of the
806
838
  // prior batch), preserved across the drain finally-block which resets
@@ -970,6 +1002,19 @@ type LiveSession = {
970
1002
  // question escalation. Compared by `turnSeq` so a stale value can't leak across
971
1003
  // turns.
972
1004
  emptyTurnFallbackTurn: number | null
1005
+ // Stamped with `turnSeq` when a formal GitHub review (APPROVE / REQUEST_CHANGES /
1006
+ // COMMENT) lands during this LOGICAL turn, via noteGithubReviewOutput off the
1007
+ // review-output observer. On a github PR channel the agent's real deliverable is
1008
+ // the review — posted through the GitHub API by the bash tool, NOT through
1009
+ // channel_reply/channel_send — so it never bumps `successfulChannelSends`. An
1010
+ // empty completion afterward would otherwise look like a dead turn and fire the
1011
+ // "I got stuck" empty-turn fallback (a real verdict, then a contradictory fallback
1012
+ // seconds later). validateChannelTurn reads this to treat such an empty stop as a
1013
+ // legitimate silent completion. Reset ONLY on a real user batch (with the retry
1014
+ // budgets) so it survives reminder-only retry iterations — the review lands in an
1015
+ // EARLIER iteration than the fallback; resetting per-iteration (beside
1016
+ // resetReviewTurn) would recreate the bug.
1017
+ githubReviewOutputTurn: number | null
973
1018
  // Captured by drain() at batch dequeue; read+cleared by send() on the
974
1019
  // first tool-source send of the turn. The anchor decision (delay
975
1020
  // threshold + intervening-observed check) is evaluated at SEND time
@@ -1018,6 +1063,13 @@ type LiveSession = {
1018
1063
  // crashed prior turn can't leak into the next.
1019
1064
  pendingProviderError: { turnSeq: number; safeMessage: string } | null
1020
1065
  destroyed: boolean
1066
+ // Set by tearDownAllLive when a reload/roles/auth swap wants to recreate this
1067
+ // session but a turn is mid-flight. Aborting now would strand the in-flight
1068
+ // reply (the reload's own turn goes silent). Instead the session stays live
1069
+ // and finishes its current reply with pre-reload state; the drain loop's
1070
+ // finally tears it down once the turn drains, so the next inbound rehydrates
1071
+ // with fresh role/auth/prompt state. Idle sessions are torn down immediately.
1072
+ pendingTeardown: boolean
1021
1073
  unsubProviderErrors: (() => void) | null
1022
1074
  unsubTypingActivity: (() => void) | null
1023
1075
  unsubTodoOutcome: (() => void) | null
@@ -1224,6 +1276,12 @@ export type ChannelRouter = {
1224
1276
  verdict: 'APPROVE' | 'REQUEST_CHANGES'
1225
1277
  sessionId: string
1226
1278
  }) => { kind: 'delivered'; count: number }
1279
+ noteGithubReviewOutput: (args: {
1280
+ sessionId: string
1281
+ workspace: string
1282
+ prNumber: number
1283
+ state: ReviewOutputState
1284
+ }) => { kind: 'stamped' | 'no-live-session' }
1227
1285
  // Record that the agent invoked `skip_response` during the current turn
1228
1286
  // for the channel session identified by `parentSessionId`. The reason is
1229
1287
  // logged at INFO level inside `validateChannelTurn` (single log line per
@@ -1396,12 +1454,12 @@ export type CreateChannelRouterOptions = {
1396
1454
  // Returns the start time (epoch ms) of the NEWEST still-running background
1397
1455
  // subagent spawned from `sessionId`, or null when none is running. Lets idle
1398
1456
  // 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.
1457
+ // inbound would otherwise spawn a duplicate child, and a completion arriving
1458
+ // after teardown is dropped), bounded only by SESSION_CHILD_STUCK_BACKSTOP_MS
1459
+ // measured from that start. Newest — not oldest — so a long-running child that
1460
+ // crossed the stuck backstop cannot unpin the session while a more recently
1461
+ // spawned child is still inside its window. Production wiring forwards the
1462
+ // LiveSubagentRegistry; omitted (tests, no-subagent setups) means no pin.
1405
1463
  newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
1406
1464
  }
1407
1465
 
@@ -1731,19 +1789,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1731
1789
  }
1732
1790
 
1733
1791
  // 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.
1792
+ // the newest such child has not outlived the stuck backstop. Using the newest
1793
+ // child keeps the session pinned as long as ANY running child is still inside
1794
+ // its window — an older child past the backstop must not unpin the session out
1795
+ // from under a freshly spawned one. Tearing the session down mid-child lets the
1796
+ // next inbound spawn a duplicate child AND drops the child's completion when it
1797
+ // lands after teardown, so GC/rollover defer to this. Crossing the backstop is
1798
+ // an anomaly (a wedged, timeout-less child), logged at warn. `label` only
1799
+ // annotates the override log.
1740
1800
  const isPinnedByRunningChild = (sessionId: string, keyId: string, label: string): boolean => {
1741
1801
  const childStartedAt = newestRunningChildSubagentStartedAt(sessionId)
1742
1802
  if (childStartedAt === null) return false
1743
1803
  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)`,
1804
+ if (pinnedForMs <= SESSION_CHILD_STUCK_BACKSTOP_MS) return true
1805
+ logger.warn(
1806
+ `[channels] ${keyId}: ${label} despite running child (newest pinned ${pinnedForMs}ms, past stuck-child backstop; suspected stuck running child)`,
1747
1807
  )
1748
1808
  return false
1749
1809
  }
@@ -2006,9 +2066,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2006
2066
  currentTurnAuthorIds: new Set(),
2007
2067
  currentTurnReactionRef: null,
2008
2068
  currentTurnTypingThread: null,
2069
+ dirtyTypingThreads: new Set(),
2009
2070
  currentTurnEngageReactions: [],
2010
2071
  pendingTurnReactions: [],
2011
2072
  silentAckTurn: null,
2073
+ activeSilentAckReactions: [],
2012
2074
  // `lastTurnAuthorId` (string, used for `lastInboundAuthorId` in
2013
2075
  // origin) and `lastTurnAuthorIds` (Set, used by
2014
2076
  // `grantStickyForReplyTargets` as the fallback when
@@ -2042,6 +2104,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2042
2104
  skipLockedSendTurn: null,
2043
2105
  disengagedTurn: null,
2044
2106
  emptyTurnFallbackTurn: null,
2107
+ githubReviewOutputTurn: null,
2045
2108
  pendingQuoteCandidate: null,
2046
2109
  recentEngagedPeerBotTurns: [],
2047
2110
  consecutiveEngagedPeerBotTurns: 0,
@@ -2052,6 +2115,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2052
2115
  membershipFetch,
2053
2116
  pendingProviderError: null,
2054
2117
  destroyed: false,
2118
+ pendingTeardown: false,
2055
2119
  unsubProviderErrors: null,
2056
2120
  unsubTypingActivity: null,
2057
2121
  unsubTodoOutcome: null,
@@ -2265,14 +2329,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2265
2329
  await persist()
2266
2330
  }
2267
2331
 
2268
- const fireTyping = async (live: LiveSession, phase: 'tick' | 'stop', epoch?: number): Promise<void> => {
2332
+ const fireTyping = async (
2333
+ live: LiveSession,
2334
+ phase: 'tick' | 'stop',
2335
+ epoch?: number,
2336
+ typingThreadOverride?: string,
2337
+ ): Promise<void> => {
2269
2338
  // Drop a stale 'tick' that a since-cancelled interval still dispatched:
2270
2339
  // once the heartbeat stopped (or a new one started) the captured epoch no
2271
2340
  // longer matches, and forwarding it would re-set the indicator after the
2272
- // stop clear. 'stop' is never epoch-gated — it must always clear.
2341
+ // stop clear. 'stop' is never epoch-gated — it must always clear. Marking
2342
+ // dirty happens after this gate so a dropped tick is never recorded.
2273
2343
  if (phase === 'tick' && epoch !== undefined && epoch !== live.typingEpoch) return
2274
2344
  const callbacks = typingCallbacks.get(live.key.adapter)
2275
2345
  if (!callbacks || callbacks.size === 0) return
2346
+ // A 'stop' clears an explicit anchor (fireTypingStop's per-dirty-thread
2347
+ // clear); a 'tick' always targets the live turn anchor.
2348
+ const typingThread = typingThreadOverride ?? live.currentTurnTypingThread
2349
+ if (phase === 'tick' && typingThread !== null) live.dirtyTypingThreads.add(typingThread)
2276
2350
  // Snapshot before iterating: a callback could unregister mid-call.
2277
2351
  const snapshot = Array.from(callbacks)
2278
2352
  const target = {
@@ -2280,7 +2354,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2280
2354
  workspace: live.key.workspace,
2281
2355
  chat: live.key.chat,
2282
2356
  thread: live.key.thread,
2283
- ...(live.currentTurnTypingThread !== null ? { typingThread: live.currentTurnTypingThread } : {}),
2357
+ ...(typingThread !== null ? { typingThread } : {}),
2284
2358
  phase,
2285
2359
  }
2286
2360
  await Promise.all(
@@ -2290,6 +2364,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2290
2364
  }),
2291
2365
  ),
2292
2366
  )
2367
+ if (phase === 'stop' && typingThread !== null) live.dirtyTypingThreads.delete(typingThread)
2368
+ }
2369
+
2370
+ // A 'stop' must clear EVERY flat-DM typingThread a tick set a status on this
2371
+ // session — not just the current anchor — or a migrated-away anchor strands
2372
+ // its "is typing..." (see `dirtyTypingThreads`). Clears run concurrently; each
2373
+ // dirty thread is dispatched once and removed by fireTyping's stop path.
2374
+ const fireTypingStop = async (live: LiveSession): Promise<void> => {
2375
+ const dirty = new Set(live.dirtyTypingThreads)
2376
+ if (live.currentTurnTypingThread !== null) dirty.add(live.currentTurnTypingThread)
2377
+ if (dirty.size === 0) {
2378
+ await fireTyping(live, 'stop')
2379
+ return
2380
+ }
2381
+ await Promise.all(Array.from(dirty, (typingThread) => fireTyping(live, 'stop', undefined, typingThread)))
2293
2382
  }
2294
2383
 
2295
2384
  const bumpTypingActivity = (live: LiveSession): void => {
@@ -2478,7 +2567,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2478
2567
  // clear platform-side state (e.g. Slack's 2-min server timeout) on
2479
2568
  // teardown. The FIFO inside the slack adapter ensures this clear lands
2480
2569
  // AFTER any in-flight 'tick' from the heartbeat that just stopped.
2481
- const stopped = fireTyping(live, 'stop').finally(() => {
2570
+ const stopped = fireTypingStop(live).finally(() => {
2482
2571
  if (live.typingStopPromise === stopped) live.typingStopPromise = null
2483
2572
  })
2484
2573
  live.typingStopPromise = stopped
@@ -2670,7 +2759,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2670
2759
  if (live.draining || live.destroyed) return
2671
2760
  live.draining = true
2672
2761
  try {
2673
- while ((live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) && !live.destroyed) {
2762
+ // `!live.pendingTeardown`: once a reload marks this draining session for
2763
+ // teardown, finish ONLY the in-flight prompt (its batch was already
2764
+ // spliced out of promptQueue at the top of the current iteration) and
2765
+ // stop — do NOT splice a fresh batch of post-reload inbounds onto the
2766
+ // stale, about-to-be-recreated session. Those queued inbounds are handed
2767
+ // to the fresh successor in the teardown block below.
2768
+ while (
2769
+ (live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) &&
2770
+ !live.destroyed &&
2771
+ !live.pendingTeardown
2772
+ ) {
2674
2773
  live.typingTimedOut = false
2675
2774
  // Each turn starts with no held reactions; the model re-requests them
2676
2775
  // via channel_react during this turn, and the finally flushes or drops.
@@ -2719,6 +2818,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2719
2818
  live.willingnessNudges = 0
2720
2819
  live.abortReasonThisTurn = null
2721
2820
  live.nextPromptMaxTokens = undefined
2821
+ // Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
2822
+ // review landed earlier in this logical turn keeps suppressing the
2823
+ // empty-turn fallback across the reminder-only retry iterations.
2824
+ live.githubReviewOutputTurn = null
2722
2825
  } else if (live.lastTurnAuthorId !== null) {
2723
2826
  live.currentTurnEngageReactions = []
2724
2827
  // Reminder-only turn (batch.length === 0, reminders.length > 0):
@@ -2886,8 +2989,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2886
2989
  sentReplyThisTurn &&
2887
2990
  live.emptyTurnFallbackTurn !== live.turnSeq &&
2888
2991
  assistantLeafStopReason(live.session) !== 'error'
2889
- if (usableReplyThisTurn) flushPendingReactions(live)
2890
- else live.pendingTurnReactions = []
2992
+ if (usableReplyThisTurn) {
2993
+ flushPendingReactions(live)
2994
+ void dropSilentAckReactions(live)
2995
+ } else live.pendingTurnReactions = []
2891
2996
  // Either retry budget keeps the turn in flight, so a deferred provider
2892
2997
  // error must wait for the reminder-only iteration that actually ends it.
2893
2998
  const retryQueuedThisTurn =
@@ -2919,6 +3024,60 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2919
3024
  await stopTypingHeartbeat(live)
2920
3025
  live.currentTurnTypingThread = null
2921
3026
  }
3027
+ // A reload deferred this session's teardown so its in-flight reply could
3028
+ // land; now that the turn drained (and the loop stopped BEFORE draining any
3029
+ // post-reload inbound), complete the recreate so the fresh session picks up
3030
+ // the swapped role/auth/prompt state. Guarded on !destroyed so a concurrent
3031
+ // stop()/idle-gc that already tore it down wins the race without a double
3032
+ // teardown.
3033
+ if (live.pendingTeardown && !live.destroyed) {
3034
+ live.pendingTeardown = false
3035
+ // Snapshot the post-reload inbounds that arrived during the held prompt
3036
+ // BEFORE tearDownLive (its clearQueuedEngageReactions must not drop the
3037
+ // engage acks we are handing to the successor). Clear the source arrays so
3038
+ // the dying session owns nothing we are moving forward.
3039
+ const carriedInbounds = live.promptQueue.splice(0, live.promptQueue.length)
3040
+ const carriedObserved = live.contextBuffer.splice(0, live.contextBuffer.length)
3041
+ const carriedReminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
3042
+ liveSessions.delete(live.keyId)
3043
+ await tearDownLive(live)
3044
+ await handOffToSuccessor(live.key, carriedInbounds, carriedObserved, carriedReminders)
3045
+ }
3046
+ }
3047
+
3048
+ // Rebuild a live session for a channel key after a reload tore its predecessor
3049
+ // down mid-drain, and replay the post-reload work that predecessor never got
3050
+ // to process. The carried inbounds already have their engagement decided (they
3051
+ // were enqueued while draining), so they are transplanted straight onto the
3052
+ // fresh session's queues rather than re-routed through route() — re-routing
3053
+ // would re-run the claim/command/permission gates and re-derive engagement
3054
+ // from a lossy QueuedInbound projection. Best-effort: a recreate failure logs
3055
+ // and drops the batch rather than throwing out of the predecessor's drain.
3056
+ const handOffToSuccessor = async (
3057
+ key: ChannelKey,
3058
+ inbounds: QueuedInbound[],
3059
+ observed: ObservedInbound[],
3060
+ reminders: string[],
3061
+ ): Promise<void> => {
3062
+ // Observed context alone is carried too: observe() can buffer post-reload
3063
+ // messages onto contextBuffer with no queued prompt, and dropping them would
3064
+ // lose the successor's "recent context". Only skip when nothing at all was
3065
+ // carried.
3066
+ if (inbounds.length === 0 && reminders.length === 0 && observed.length === 0) return
3067
+ let successor: LiveSession
3068
+ try {
3069
+ successor = await ensureLive(key)
3070
+ } catch (err) {
3071
+ logger.warn(`[channels] ${channelKeyId(key)}: successor recreate after reload failed: ${describe(err)}`)
3072
+ return
3073
+ }
3074
+ if (successor.destroyed) return
3075
+ successor.promptQueue.push(...inbounds)
3076
+ successor.contextBuffer.push(...observed)
3077
+ successor.pendingSystemReminders.push(...reminders)
3078
+ // Observed-only context is NOT a turn trigger — it waits on contextBuffer for
3079
+ // a real inbound. Drain only when there is actual work (a prompt or reminder).
3080
+ if ((inbounds.length > 0 || reminders.length > 0) && !successor.draining) void drain(successor)
2922
3081
  }
2923
3082
 
2924
3083
  const scheduleDebouncedDrain = (live: LiveSession): void => {
@@ -4145,6 +4304,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4145
4304
  }
4146
4305
  }
4147
4306
 
4307
+ // A formal GitHub review already landed this logical turn (APPROVE /
4308
+ // REQUEST_CHANGES / COMMENT, stamped via noteGithubReviewOutput). That review IS
4309
+ // the turn's user-facing output — it just went through the GitHub review API, not
4310
+ // channel_reply/channel_send, so `successfulChannelSends` never moved. An empty
4311
+ // completion afterward is the agent legitimately having nothing more to say, NOT
4312
+ // a dead turn: skip the empty-turn retries AND the "I got stuck" fallback and
4313
+ // treat it as silent completion. Gated on no channel send this turn so a turn
4314
+ // that ALSO replied in-channel still runs the normal reply-recovery below.
4315
+ if (
4316
+ live.githubReviewOutputTurn === live.turnSeq &&
4317
+ live.successfulChannelSends === successfulSendsBeforePrompt &&
4318
+ live.currentTurnAuthorId !== null
4319
+ ) {
4320
+ logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=github_review_output_this_turn`)
4321
+ armSilentTurnAck(live, 'github_review_output')
4322
+ return
4323
+ }
4324
+
4148
4325
  // Suppress a leaked tool call (never post the plumbing) and, while budget
4149
4326
  // remains, push a self-correction reminder so the same logical turn
4150
4327
  // re-prompts and the model can redo it with a real tool call. On exhaustion
@@ -4741,11 +4918,26 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4741
4918
  const tearDownAllLive = async (): Promise<void> => {
4742
4919
  liveGeneration++
4743
4920
  const all = Array.from(liveSessions.values())
4921
+ // A session mid-turn is deferred, not aborted: tearing it down here calls
4922
+ // session.abort(), which kills the in-flight reply — including the very turn
4923
+ // that triggered this reload, leaving the user in silence. Such a session
4924
+ // stays in liveSessions (so a concurrent inbound coalesces into the running
4925
+ // turn instead of spawning a duplicate) and is torn down by the drain
4926
+ // finally once its turn drains. Idle sessions tear down immediately below.
4927
+ const deferred: LiveSession[] = []
4928
+ const immediate: LiveSession[] = []
4929
+ for (const live of all) {
4930
+ if (live.draining && !live.destroyed) {
4931
+ live.pendingTeardown = true
4932
+ deferred.push(live)
4933
+ } else immediate.push(live)
4934
+ }
4744
4935
  liveSessions.clear()
4936
+ for (const live of deferred) liveSessions.set(live.keyId, live)
4745
4937
  // Seal only around the flush — unlike stop() the router keeps serving after a
4746
4938
  // roles reload, so re-enable persist() once pending writes have drained.
4747
4939
  closing = true
4748
- for (const live of all) {
4940
+ for (const live of immediate) {
4749
4941
  await tearDownLive(live)
4750
4942
  }
4751
4943
  await persistChain
@@ -5060,6 +5252,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5060
5252
  return { kind: 'delivered', count }
5061
5253
  }
5062
5254
 
5255
+ // Stamp the review-output flag on the session that just landed a formal GitHub
5256
+ // review this turn. Matched by sessionId (the recorder records the exact
5257
+ // event.sessionId), and confirmed to be the right github PR live session so a
5258
+ // stray/mismatched signal can't suppress an unrelated turn's fallback. See
5259
+ // `githubReviewOutputTurn`.
5260
+ const noteGithubReviewOutput = (args: {
5261
+ sessionId: string
5262
+ workspace: string
5263
+ prNumber: number
5264
+ state: ReviewOutputState
5265
+ }): { kind: 'stamped' | 'no-live-session' } => {
5266
+ const chat = `pr:${args.prNumber}`
5267
+ for (const live of liveSessions.values()) {
5268
+ if (live.destroyed) continue
5269
+ if (live.sessionId !== args.sessionId) continue
5270
+ if (live.key.adapter !== 'github') continue
5271
+ if (live.key.workspace !== args.workspace || live.key.chat !== chat) continue
5272
+ live.githubReviewOutputTurn = live.turnSeq
5273
+ logger.info(`[channels] ${live.keyId}: github_review_output state=${args.state} turn=${live.turnSeq}`)
5274
+ return { kind: 'stamped' }
5275
+ }
5276
+ return { kind: 'no-live-session' }
5277
+ }
5278
+
5063
5279
  const markTurnSkipped = (args: {
5064
5280
  parentSessionId: string
5065
5281
  reason: string
@@ -5137,7 +5353,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5137
5353
  live.silentAckTurn = null
5138
5354
  const reactionRef = live.currentTurnReactionRef
5139
5355
  if (reactionRef === null) return
5140
- void react({
5356
+ const addResult = react({
5141
5357
  adapter: live.key.adapter,
5142
5358
  workspace: live.key.workspace,
5143
5359
  chat: live.key.chat,
@@ -5145,6 +5361,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5145
5361
  reactionRef,
5146
5362
  emoji: ENGAGE_REACTION_EMOJI,
5147
5363
  })
5364
+ void addResult
5148
5365
  .then((result) => {
5149
5366
  if (!result.ok && result.code !== 'unsupported') {
5150
5367
  logger.info(
@@ -5157,6 +5374,49 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5157
5374
  `[channels] silent-ack-react threw reason=${reason} adapter=${live.key.adapter} chat=${live.key.chat}: ${describe(err)}`,
5158
5375
  )
5159
5376
  })
5377
+ // Register the add promise (not its resolved ref) SYNCHRONOUSLY, so a later
5378
+ // replied-turn cleanup can never race ahead of a still-in-flight add.
5379
+ live.activeSilentAckReactions.push(addResult.then((r) => (r.ok ? (r.reactionRef ?? null) : null)).catch(() => null))
5380
+ }
5381
+
5382
+ // Retire every persistent silent-ack :eyes: outstanding in this live session
5383
+ // once the agent posts a genuine reply — the "seen, not replying" mark is now
5384
+ // contradicted. Snapshot-and-clear the promise array BEFORE awaiting, so a
5385
+ // concurrent later silent turn appending a fresh add is never swept by this
5386
+ // in-flight cleanup. Each entry is AWAITED to its resolved ref before removal,
5387
+ // so an add still in flight when the reply lands is still retired. Failures are
5388
+ // logged, never retried: stale emoji cleanup must never block routing.
5389
+ const dropSilentAckReactions = (live: LiveSession): Promise<void> => {
5390
+ const addPromises = live.activeSilentAckReactions
5391
+ if (addPromises.length === 0) return Promise.resolve()
5392
+ live.activeSilentAckReactions = []
5393
+ return Promise.all(
5394
+ addPromises.map((addPromise) =>
5395
+ addPromise
5396
+ .then((reactionRef) => {
5397
+ if (reactionRef === null) return undefined
5398
+ return removeReaction({
5399
+ adapter: live.key.adapter,
5400
+ workspace: live.key.workspace,
5401
+ chat: live.key.chat,
5402
+ thread: live.key.thread,
5403
+ reactionRef,
5404
+ })
5405
+ })
5406
+ .then((result) => {
5407
+ if (result && !result.ok && result.code !== 'unsupported' && result.code !== 'not-found') {
5408
+ logger.info(
5409
+ `[channels] silent-ack-unreact failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
5410
+ )
5411
+ }
5412
+ })
5413
+ .catch((err) => {
5414
+ logger.info(
5415
+ `[channels] silent-ack-unreact threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describe(err)}`,
5416
+ )
5417
+ }),
5418
+ ),
5419
+ ).then(() => undefined)
5160
5420
  }
5161
5421
 
5162
5422
  return {
@@ -5208,6 +5468,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5208
5468
  getSelfAliases: computeSelfAliases,
5209
5469
  injectSubagentCompletionReminder,
5210
5470
  injectPrVerdictActivity,
5471
+ noteGithubReviewOutput,
5211
5472
  markTurnSkipped,
5212
5473
  clearSticky,
5213
5474
  reserveRestartHandoff,
@@ -5558,6 +5819,7 @@ export function formatAuthorAttribution(adapter: AdapterId, authorId: string, au
5558
5819
  case 'telegram-bot':
5559
5820
  case 'webex':
5560
5821
  case 'webex-bot':
5822
+ case 'teams':
5561
5823
  case 'instagram':
5562
5824
  case 'line':
5563
5825
  case 'kakaotalk':
@@ -5591,6 +5853,7 @@ function formatAuthorReference(adapter: AdapterId, authorId: string, authorName:
5591
5853
  case 'telegram-bot':
5592
5854
  case 'webex':
5593
5855
  case 'webex-bot':
5856
+ case 'teams':
5594
5857
  case 'instagram':
5595
5858
  case 'line':
5596
5859
  case 'kakaotalk':
@@ -9,6 +9,7 @@ export const ADAPTER_IDS = [
9
9
  'kakaotalk',
10
10
  'slack',
11
11
  'slack-bot',
12
+ 'teams',
12
13
  'telegram-bot',
13
14
  'webex',
14
15
  'webex-bot',
@@ -35,6 +36,7 @@ export const ADAPTER_READ_CAPABILITIES: Record<AdapterId, readonly ReadCapabilit
35
36
  kakaotalk: ['history'],
36
37
  slack: ['history'],
37
38
  'slack-bot': ['history', 'message-get', 'list'],
39
+ teams: ['history'],
38
40
  'telegram-bot': [],
39
41
  webex: ['history'],
40
42
  'webex-bot': ['history'],
@@ -303,6 +305,13 @@ export const channelsSchema = z
303
305
  kakaotalk: adapterSchema.optional(),
304
306
  slack: adapterSchema.optional(),
305
307
  'slack-bot': adapterSchema.optional(),
308
+ // Teams is a personal-account channel: user-account auth (no bot token),
309
+ // credentials in secrets.json#channels.teams. v1 is chat-only (1:1/group/
310
+ // self chats) driven by agent-messenger's TeamsListener (trouter
311
+ // WebSocket); Teams team/channel messaging is out of scope because the
312
+ // realtime event carries only a chatId, no team/channel id. Plain-text
313
+ // sends only; standard adapterSchema (engagement + history + enabled).
314
+ teams: adapterSchema.optional(),
306
315
  'telegram-bot': adapterSchema.optional(),
307
316
  webex: adapterSchema.optional(),
308
317
  // Webex bots receive messages in real time over a Mercury WebSocket