typeclaw 0.50.0 → 0.52.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 (258) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +17 -0
  2. package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
  3. package/dist/types/agent/bash-sandbox.d.ts +98 -0
  4. package/dist/types/agent/compaction.d.ts +4 -4
  5. package/dist/types/agent/idle-compaction.d.ts +1 -0
  6. package/dist/types/agent/index.d.ts +10 -17
  7. package/dist/types/agent/multimodal/look-at.d.ts +1 -1
  8. package/dist/types/agent/output-allowance.d.ts +4 -0
  9. package/dist/types/agent/plugin-tools.d.ts +8 -75
  10. package/dist/types/agent/prompt-cache-key.d.ts +1 -0
  11. package/dist/types/agent/session-tail.d.ts +12 -0
  12. package/dist/types/agent/subagents.d.ts +5 -0
  13. package/dist/types/agent/system-prompt-composition.d.ts +18 -0
  14. package/dist/types/agent/system-prompt.d.ts +2 -0
  15. package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
  16. package/dist/types/agent/tools/channel-edit.d.ts +1 -1
  17. package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
  18. package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
  19. package/dist/types/agent/tools/channel-history.d.ts +1 -1
  20. package/dist/types/agent/tools/channel-react.d.ts +1 -1
  21. package/dist/types/agent/tools/channel-read.d.ts +10 -2
  22. package/dist/types/agent/tools/channel-reply.d.ts +1 -1
  23. package/dist/types/agent/tools/channel-send.d.ts +1 -1
  24. package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
  25. package/dist/types/agent/tools/ddg.d.ts +9 -0
  26. package/dist/types/agent/tools/grant-role.d.ts +1 -1
  27. package/dist/types/agent/tools/post-github-review.d.ts +1 -1
  28. package/dist/types/agent/tools/restart.d.ts +1 -1
  29. package/dist/types/agent/tools/skip-response.d.ts +1 -1
  30. package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
  31. package/dist/types/agent/tools/stream-snapshot.d.ts +2 -2
  32. package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
  33. package/dist/types/agent/tools/subagent-output.d.ts +1 -1
  34. package/dist/types/agent/tools/todo/index.d.ts +1 -1
  35. package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
  36. package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
  37. package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
  38. package/dist/types/agent/tools/websearch.d.ts +1 -1
  39. package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
  40. package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
  41. package/dist/types/channels/adapters/github/auth.d.ts +24 -0
  42. package/dist/types/channels/github-review-check.d.ts +1 -1
  43. package/dist/types/channels/github-token-bridge.d.ts +4 -0
  44. package/dist/types/channels/lost-background-context.d.ts +2 -0
  45. package/dist/types/channels/persistence.d.ts +1 -0
  46. package/dist/types/channels/router.d.ts +16 -50
  47. package/dist/types/channels/types.d.ts +1 -0
  48. package/dist/types/coding-agent/tool.d.ts +1 -1
  49. package/dist/types/config/config.d.ts +22 -0
  50. package/dist/types/config/providers.d.ts +50 -1
  51. package/dist/types/container/start.d.ts +1 -0
  52. package/dist/types/eval/cell.d.ts +26 -0
  53. package/dist/types/eval/config.d.ts +19 -0
  54. package/dist/types/eval/dispatch.d.ts +7 -0
  55. package/dist/types/eval/kernel.d.ts +28 -0
  56. package/dist/types/eval/process.d.ts +23 -0
  57. package/dist/types/eval/protocol.d.ts +34 -0
  58. package/dist/types/eval/sandbox.d.ts +12 -0
  59. package/dist/types/eval/tool.d.ts +17 -0
  60. package/dist/types/eval/wire.d.ts +33 -0
  61. package/dist/types/git/resolve-identity.d.ts +2 -0
  62. package/dist/types/init/dockerfile.d.ts +1 -0
  63. package/dist/types/init/gitignore.d.ts +1 -1
  64. package/dist/types/permissions/builtins.d.ts +1 -0
  65. package/dist/types/plugin/types.d.ts +3 -0
  66. package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
  67. package/dist/types/sandbox/coding-agent.d.ts +1 -1
  68. package/dist/types/sandbox/dependency-bins.d.ts +1 -0
  69. package/dist/types/sandbox/dev-source.d.ts +2 -2
  70. package/dist/types/sandbox/env-exposure.d.ts +2 -0
  71. package/dist/types/sandbox/hidden-paths.d.ts +1 -0
  72. package/dist/types/sandbox/index.d.ts +1 -1
  73. package/dist/types/sandbox/policy.d.ts +3 -0
  74. package/dist/types/typevault/cli-path.d.ts +2 -0
  75. package/dist/types/typevault/envelope-store.d.ts +11 -0
  76. package/dist/types/typevault/lifecycle.d.ts +13 -0
  77. package/dist/types/typevault/vault.d.ts +27 -0
  78. package/package.json +8 -7
  79. package/scripts/test.ts +252 -0
  80. package/src/agent/bash-sandbox-env.ts +136 -0
  81. package/src/agent/bash-sandbox-proc.ts +70 -0
  82. package/src/agent/bash-sandbox.ts +239 -0
  83. package/src/agent/compaction.ts +22 -10
  84. package/src/agent/idle-compaction.ts +7 -3
  85. package/src/agent/index.ts +185 -187
  86. package/src/agent/multimodal/look-at.ts +1 -1
  87. package/src/agent/output-allowance.ts +7 -0
  88. package/src/agent/plugin-tools.ts +64 -380
  89. package/src/agent/prompt-cache-key.ts +26 -3
  90. package/src/agent/session-origin.ts +41 -19
  91. package/src/agent/session-tail.ts +28 -0
  92. package/src/agent/subagent-completion-reminder.ts +2 -2
  93. package/src/agent/subagents.ts +21 -2
  94. package/src/agent/system-prompt-composition.ts +159 -0
  95. package/src/agent/system-prompt.ts +43 -5
  96. package/src/agent/todo/scope.ts +1 -1
  97. package/src/agent/tool-error-remediation.ts +18 -3
  98. package/src/agent/tools/channel-disengage.ts +1 -1
  99. package/src/agent/tools/channel-edit.ts +1 -1
  100. package/src/agent/tools/channel-fetch-attachment.ts +1 -1
  101. package/src/agent/tools/channel-handoff.ts +3 -2
  102. package/src/agent/tools/channel-history.ts +2 -1
  103. package/src/agent/tools/channel-react.ts +1 -1
  104. package/src/agent/tools/channel-read.ts +36 -3
  105. package/src/agent/tools/channel-reply.ts +1 -1
  106. package/src/agent/tools/channel-send.ts +4 -3
  107. package/src/agent/tools/channel-session-search.ts +13 -4
  108. package/src/agent/tools/ddg.ts +71 -11
  109. package/src/agent/tools/grant-role.ts +1 -1
  110. package/src/agent/tools/post-github-review.ts +1 -1
  111. package/src/agent/tools/restart.ts +1 -1
  112. package/src/agent/tools/skip-response.ts +1 -1
  113. package/src/agent/tools/spawn-subagent.ts +15 -1
  114. package/src/agent/tools/stream-snapshot.ts +1 -1
  115. package/src/agent/tools/subagent-cancel.ts +1 -1
  116. package/src/agent/tools/subagent-output.ts +1 -1
  117. package/src/agent/tools/todo/index.ts +1 -1
  118. package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
  119. package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
  120. package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
  121. package/src/agent/tools/webfetch/tool.ts +6 -5
  122. package/src/agent/tools/websearch.ts +1 -1
  123. package/src/agent/tools-without-local-file-operands.ts +4 -0
  124. package/src/browser/dockerfile.ts +1 -1
  125. package/src/browser/fill-secret.ts +364 -0
  126. package/src/browser/registry.ts +6 -6
  127. package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
  128. package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
  129. package/src/bundled-plugins/backup/index.ts +17 -2
  130. package/src/bundled-plugins/backup/runner.ts +37 -2
  131. package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
  132. package/src/bundled-plugins/browser-agent/index.ts +12 -5
  133. package/src/bundled-plugins/explorer/explorer.ts +1 -1
  134. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
  135. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
  136. package/src/bundled-plugins/github-cli-auth/index.ts +10 -1
  137. package/src/bundled-plugins/managed-browser/index.ts +130 -2
  138. package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
  139. package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
  140. package/src/bundled-plugins/memory/README.md +23 -2
  141. package/src/bundled-plugins/memory/append-fragment.ts +133 -0
  142. package/src/bundled-plugins/memory/append-tool.ts +80 -149
  143. package/src/bundled-plugins/memory/dreaming.ts +6 -1
  144. package/src/bundled-plugins/memory/index.ts +33 -6
  145. package/src/bundled-plugins/memory/load-memory.ts +2 -4
  146. package/src/bundled-plugins/memory/memory-logger.ts +200 -6
  147. package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
  148. package/src/bundled-plugins/memory/remember-tool.ts +81 -0
  149. package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
  150. package/src/bundled-plugins/memory/search-tool.ts +58 -12
  151. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  152. package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
  153. package/src/bundled-plugins/memory/transcript-preload.ts +208 -0
  154. package/src/bundled-plugins/memory/transcript-view.ts +36 -0
  155. package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
  156. package/src/bundled-plugins/memory/watermark.ts +19 -10
  157. package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
  158. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
  159. package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
  160. package/src/bundled-plugins/security/policies/private-surface-read.ts +166 -201
  161. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
  162. package/src/bundled-plugins/typevault/grants.ts +119 -0
  163. package/src/bundled-plugins/typevault/index.ts +152 -0
  164. package/src/bundled-plugins/typevault/request.ts +87 -0
  165. package/src/bundled-plugins/typevault/runtime.ts +45 -0
  166. package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
  167. package/src/channels/adapter-halt.ts +17 -0
  168. package/src/channels/adapters/discord-bot-reference.ts +5 -4
  169. package/src/channels/adapters/discord-bot.ts +1 -0
  170. package/src/channels/adapters/discord-classify.ts +8 -3
  171. package/src/channels/adapters/discord.ts +29 -0
  172. package/src/channels/adapters/github/history.ts +23 -2
  173. package/src/channels/adapters/github/inbound.ts +60 -1
  174. package/src/channels/adapters/github/index.ts +27 -5
  175. package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
  176. package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
  177. package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
  178. package/src/channels/adapters/kakaotalk-classify.ts +7 -9
  179. package/src/channels/adapters/kakaotalk-list.ts +62 -0
  180. package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
  181. package/src/channels/adapters/kakaotalk-membership.ts +27 -10
  182. package/src/channels/adapters/kakaotalk-mention.ts +61 -0
  183. package/src/channels/adapters/kakaotalk.ts +159 -125
  184. package/src/channels/adapters/teams-classify.ts +18 -8
  185. package/src/channels/github-review-check.ts +5 -1
  186. package/src/channels/github-review-verdict-coordinator.ts +68 -2
  187. package/src/channels/github-token-bridge.ts +13 -0
  188. package/src/channels/lost-background-context.ts +46 -0
  189. package/src/channels/manager.ts +52 -3
  190. package/src/channels/persistence.ts +5 -0
  191. package/src/channels/router.ts +208 -128
  192. package/src/channels/schema.ts +1 -1
  193. package/src/channels/subagent-completion-bridge.ts +3 -2
  194. package/src/channels/types.ts +3 -0
  195. package/src/cli/hostd.ts +3 -0
  196. package/src/coding-agent/tool.ts +1 -1
  197. package/src/config/config.ts +35 -1
  198. package/src/config/providers.ts +75 -4
  199. package/src/container/start.ts +52 -3
  200. package/src/doctor/channel-checks.ts +33 -0
  201. package/src/doctor/checks.ts +37 -18
  202. package/src/doctor/index.ts +48 -12
  203. package/src/doctor/operational-incidents.ts +16 -1
  204. package/src/doctor/plugin-bridge.ts +14 -1
  205. package/src/doctor/stage.ts +14 -0
  206. package/src/doctor/types.ts +6 -0
  207. package/src/eval/cell.ts +93 -0
  208. package/src/eval/config.ts +32 -0
  209. package/src/eval/dispatch.ts +67 -0
  210. package/src/eval/entry.ts +261 -0
  211. package/src/eval/kernel.ts +154 -0
  212. package/src/eval/process.ts +113 -0
  213. package/src/eval/protocol.ts +26 -0
  214. package/src/eval/redeclare.ts +174 -0
  215. package/src/eval/sandbox.ts +117 -0
  216. package/src/eval/tool.ts +99 -0
  217. package/src/eval/wire.ts +93 -0
  218. package/src/git/resolve-identity.ts +67 -2
  219. package/src/git/system-commit.ts +7 -0
  220. package/src/init/dockerfile.ts +5 -1
  221. package/src/init/gitignore.ts +3 -3
  222. package/src/init/index.ts +1 -0
  223. package/src/init/models-dev.ts +2 -0
  224. package/src/init/validate-api-key.ts +5 -0
  225. package/src/migrations/secrets-v1-to-v2.ts +2 -0
  226. package/src/operations/classify-tool-outcome.ts +1 -1
  227. package/src/permissions/builtins.ts +8 -0
  228. package/src/plugin/core-tool-names.ts +6 -1
  229. package/src/plugin/types.ts +6 -0
  230. package/src/run/bundled-plugins.ts +12 -0
  231. package/src/run/channel-session-factory.ts +3 -0
  232. package/src/run/index.ts +13 -2
  233. package/src/sandbox/build.ts +1 -0
  234. package/src/sandbox/canonical-secrets.ts +6 -0
  235. package/src/sandbox/dependency-bins.ts +13 -1
  236. package/src/sandbox/dev-source.ts +21 -12
  237. package/src/sandbox/env-exposure.ts +20 -0
  238. package/src/sandbox/hidden-paths.ts +1 -1
  239. package/src/sandbox/index.ts +1 -0
  240. package/src/sandbox/policy.ts +5 -0
  241. package/src/secrets/hydrate.ts +4 -1
  242. package/src/secrets/storage.ts +10 -1
  243. package/src/server/command-runner.ts +4 -0
  244. package/src/server/index.ts +54 -12
  245. package/src/skills/typeclaw-config/SKILL.md +36 -2
  246. package/src/skills/typeclaw-memory/SKILL.md +3 -1
  247. package/src/skills/typeclaw-permissions/SKILL.md +8 -8
  248. package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
  249. package/src/tunnels/active.ts +14 -0
  250. package/src/typevault/bash-cli.ts +18 -0
  251. package/src/typevault/cli-path.ts +11 -0
  252. package/src/typevault/envelope-helper.ts +17 -0
  253. package/src/typevault/envelope-store.ts +98 -0
  254. package/src/typevault/lifecycle.ts +132 -0
  255. package/src/typevault/prompt-tunnel.ts +33 -0
  256. package/src/typevault/redaction.ts +37 -0
  257. package/src/typevault/vault.ts +283 -0
  258. package/typeclaw.schema.json +92 -10
@@ -1,5 +1,4 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { statSync } from 'node:fs'
3
2
  import { basename } from 'node:path'
4
3
 
5
4
  import { createAssistantMessageEventStream, type AssistantMessage, type ToolResultMessage } from '@earendil-works/pi-ai'
@@ -11,6 +10,7 @@ import { resolveFallbackChain } from '@/agent/model-fallback'
11
10
  import { applyModelRuntimeOverrides } from '@/agent/model-overrides'
12
11
  import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
13
12
  import {
13
+ type DetectedProviderError,
14
14
  detectHardProviderError,
15
15
  isFailoverWorthy,
16
16
  isTransientProviderFailure,
@@ -85,6 +85,7 @@ import {
85
85
  } from './github-review-verdict-coordinator'
86
86
  import { renderPrVerdictStandDownReminder } from './github-verdict-activity'
87
87
  import { InboundJournal, type InboundRecord, type InboundRef } from './inbound-journal'
88
+ import { takeLostBackgroundContext } from './lost-background-context'
88
89
  import {
89
90
  MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
90
91
  type MembershipCount,
@@ -273,7 +274,15 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
273
274
  return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
274
275
  }
275
276
 
276
- type PendingProviderError = { turnSeq: number; safeMessage: string; retryAndSee: boolean }
277
+ type PendingProviderError = { turnSeq: number; safeMessage: string; retryAndSee: boolean; unclassified: boolean }
278
+
279
+ // Transient overloads share the generic notice text, so the notice alone can't
280
+ // identify a failure nothing is known about; the raw text has to rule them out.
281
+ function providerFailureSurface(err: DetectedProviderError): { retryAndSee: boolean; unclassified: boolean } {
282
+ const transient = isTransientProviderFailure(err.message)
283
+ const unclassified = !transient && isUnclassifiedProviderNotice(err.safeMessage)
284
+ return { retryAndSee: transient || unclassified, unclassified }
285
+ }
277
286
 
278
287
  type SilentAckReason = 'github_review_output' | 'awaiting_background_child'
279
288
 
@@ -561,38 +570,16 @@ export const SEND_RATE_WARN_THRESHOLD = 3
561
570
  export const OUTBOUND_FLOOD_ERROR = 'outbound message denied: content looks like a repeated-character flood'
562
571
 
563
572
  /**
564
- * Soft freshness boundary: the age of the last engaged inbound past which the
565
- * provider's server-side KV prompt-cache for this session's prefix is assumed
566
- * cold. Set to the LLM provider's KV-cache TTL (5 min) so a session reused
567
- * WITHIN this window is guaranteed a cache hit on the provider side.
568
- *
569
- * Reaching this boundary no longer forces an immediate rollover. Between the
570
- * soft boundary and SESSION_GRACE_HARD_TTL_MS, the live path defers to a
571
- * cost-aware grace decision (see `isGraceWorthReusing`): a session whose fixed
572
- * base context (rendered system prompt + injected memory + prefetched channel
573
- * context) still costs more to rebuild than its accumulated transcript is
574
- * reused for one more turn rather than torn down. This targets the common
575
- * channel shape — a human replying a few minutes past the cache TTL — where a
576
- * full cold-start rebuild of a large memory/index-mode base context dominates
577
- * the cost of carrying a modest transcript forward.
573
+ * Roll over only after more than 60 minutes without an engaged inbound.
574
+ * Continuity of an active conversation outweighs one cold prefix resend;
575
+ * compaction bounds the transcript carried by that resend.
578
576
  *
579
- * Unlike SESSION_IDLE_MS (which evicts the in-memory entry without rollover), a
580
- * rollover triggers a full tearDownLive + recreate on the next engaged inbound.
581
- * The old session's transcript is preserved on disk; only the in-memory live
582
- * entry and sessions.json pointer are replaced.
583
- */
584
- export const SESSION_FRESHNESS_TTL_MS = 5 * 60 * 1000
585
-
586
- /**
587
- * Hard ceiling on the cost-aware grace window. Past this age the live session is
588
- * rolled over unconditionally regardless of base-vs-transcript cost: the grace
589
- * decision only defers rollover, it never makes the session immortal. Bounding
590
- * grace at 2x the soft TTL keeps a never-quite-idle session from accumulating an
591
- * ever-growing, fully-uncached prefix (every turn past the soft boundary re-sends
592
- * the whole prefix at no provider-cache discount) and prevents grace from
593
- * silently becoming an unbounded TTL increase.
577
+ * SESSION_IDLE_MS (30 minutes) only evicts the in-memory entry: the next inbound
578
+ * within this freshness window rehydrates the same session file without rollover.
579
+ * A rollover tears down the live entry and replaces the sessions.json pointer;
580
+ * the old transcript remains on disk.
594
581
  */
595
- export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
582
+ export const SESSION_FRESHNESS_TTL_MS = 60 * 60 * 1000
596
583
 
597
584
  /**
598
585
  * Leak guard — NOT a freshness cap. A running background subagent pins its parent
@@ -616,37 +603,6 @@ export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
616
603
  */
617
604
  export const SESSION_CHILD_STUCK_BACKSTOP_MS = 6 * 60 * 60 * 1000
618
605
 
619
- /**
620
- * Cost-aware grace decision for the soft→hard TTL band. Returns true when reusing
621
- * the (now cache-cold) live session is cheaper than a fresh cold-start.
622
- *
623
- * After the soft TTL the provider prefix is cold either way, so the choice is:
624
- * - rollover: pay to rebuild the fixed base context (system prompt + memory +
625
- * prefetched context) plus a fresh first model call, OR
626
- * - reuse: re-send the cold base context PLUS the accumulated transcript.
627
- *
628
- * Rollover only wins once the transcript a reused session would carry forward
629
- * exceeds the base context a rollover would rebuild. We approximate both with the
630
- * session transcript file: `baseContextBytes` is its size captured right after
631
- * cold-start (the rendered prompt before any user turn), and the live delta is
632
- * the growth since. While `baseContextBytes > transcriptDeltaBytes`, the fixed
633
- * rebuild is the larger cost and grace is worth it. A `baseContextBytes` of 0
634
- * (no transcript path available) disables grace — fail closed to the prior
635
- * roll-over-at-soft-TTL behavior.
636
- */
637
- export function isGraceWorthReusing(baseContextBytes: number, transcriptDeltaBytes: number): boolean {
638
- if (baseContextBytes <= 0) return false
639
- return baseContextBytes > transcriptDeltaBytes
640
- }
641
-
642
- function defaultMeasureTranscriptBytes(path: string): number {
643
- try {
644
- return statSync(path).size
645
- } catch {
646
- return 0
647
- }
648
- }
649
-
650
606
  // Watchdog ceiling for ensureLive's full async chain (resolve names →
651
607
  // fetch membership → open session manager → persist mapping → prefetch
652
608
  // history). A legitimate cold-start completes in well under a second;
@@ -823,7 +779,7 @@ type ObservedInbound = {
823
779
 
824
780
  type TimedAttachment = { ts: number; attachment: InboundAttachment; current?: boolean }
825
781
 
826
- type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined }
782
+ type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined; resetLoopGuard?: () => void }
827
783
 
828
784
  // Provenance of a queued system reminder, which decides whether the
829
785
  // reminder-only drain iteration it drives CONTINUES the current logical turn or
@@ -957,6 +913,10 @@ type LiveSession = {
957
913
  })
958
914
  | null
959
915
  githubReviewThreadCloseoutDecisionTurn: number | null
916
+ // When this session last resolved its review thread. A reply written before
917
+ // that resolution was already answered by it, so it must not re-arm the
918
+ // close-out obligation and force a duplicate reply or the canned fallback.
919
+ githubReviewThreadResolvedAt: { rootCommentId: string; at: number } | null
960
920
  // Round key of a close-out that arrived while the round was still pending
961
921
  // completion. Replayed once the round completes; see replayPendingRoundCloseouts.
962
922
  pendingGithubReviewRoundCloseout: string | null
@@ -999,12 +959,6 @@ type LiveSession = {
999
959
  promptInFlight: boolean
1000
960
  lastInboundAt: number
1001
961
  recentMessages: SessionActivity[]
1002
- // Transcript-file size (bytes) captured immediately after cold-start, before
1003
- // any user turn — a proxy for the fixed base-context rebuild cost (rendered
1004
- // system prompt + injected memory + prefetched channel context). Read by the
1005
- // soft-TTL grace decision against the current transcript size to weigh reuse
1006
- // vs rollover. 0 when no transcript path is available, which disables grace.
1007
- baseContextBytes: number
1008
962
  firstUnprocessedAt: number
1009
963
  currentTurnAuthorId: string | null
1010
964
  currentTurnAuthorAdapter: AdapterId
@@ -1092,6 +1046,8 @@ type LiveSession = {
1092
1046
  // the drain loop's run condition checks BOTH queues so a system
1093
1047
  // reminder alone is enough to trigger a turn.
1094
1048
  pendingSystemReminders: PendingSystemReminder[]
1049
+ // Passive context only: it must never become work in the reminder queue.
1050
+ restoredBackgroundContextPending: boolean
1095
1051
  // Identity-only cache; every durable transition resolves ownership in its lane.
1096
1052
  backgroundCoverage: string[]
1097
1053
  inboundCoverage: string[]
@@ -1137,6 +1093,9 @@ type LiveSession = {
1137
1093
  // future hard cap without picking a threshold out of thin air.
1138
1094
  sendTimestamps: Map<string, number[]>
1139
1095
  successfulChannelSends: number
1096
+ // Durable twin of `successfulChannelSends > 0`, restored from the persisted
1097
+ // mapping so `botInThread` survives restarts and rollovers.
1098
+ botParticipated: boolean
1140
1099
  // Monotonic per-LiveSession turn counter incremented just before each
1141
1100
  // `live.session.prompt(...)` call in `drain()`. Used as a turn identity
1142
1101
  // so `skip_response` can record "I skipped turn N" without leaking
@@ -1348,7 +1307,7 @@ type LiveSession = {
1348
1307
  // the turn already ran tools. The same failure must not resurface as a
1349
1308
  // live-turn-ended notice, so turn-end settles held coverage silently.
1350
1309
  // Cleared with the other logical-turn state.
1351
- providerErrorSilencedThisLogicalTurn: boolean
1310
+ providerErrorSilencedThisLogicalTurn: 'tool-activity' | 'unclassified-failure' | null
1352
1311
  // Successful, non-communication, non-control tool output observed during
1353
1312
  // this logical turn. Unlike toolExecutionThisLogicalTurn, channel_reply and
1354
1313
  // todo/control calls cannot satisfy a later durable completion claim.
@@ -1880,10 +1839,6 @@ export type CreateChannelRouterOptions = {
1880
1839
  // random/timer mutation. Production defaults remain Math.random and no hook.
1881
1840
  retryRandom?: () => number
1882
1841
  onRetryBackoffStart?: () => void
1883
- // Test seam: measure a transcript file's byte size for the soft-TTL grace
1884
- // decision. Defaults to a stat()-based reader returning 0 for a missing or
1885
- // unreadable file (grace then fails closed to roll-over-at-soft-TTL).
1886
- measureTranscriptBytes?: (path: string) => number
1887
1842
  // Test seam: the idle/todo continuation driver, invoked from
1888
1843
  // maybeContinueTodosChannel AFTER validateChannelTurn. Defaults to the real
1889
1844
  // runIdleContinuation. Injecting it lets a test deliver the continuation at the
@@ -2029,7 +1984,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2029
1984
  const recoveryOutbox =
2030
1985
  options.recoveryOutbox ?? new RecoveryOutbox(options.agentDir, { epoch: backgroundObligations.epoch })
2031
1986
  void ready.catch((error) => logger.error(`[channels] inbound journal initialization failed: ${describeError(error)}`))
2032
- const measureTranscriptBytes = options.measureTranscriptBytes ?? defaultMeasureTranscriptBytes
2033
1987
  const ensureLiveTimeoutMs = options.ensureLiveTimeoutMs ?? ENSURE_LIVE_TIMEOUT_MS
2034
1988
  const handoffRetryRetentionMs = options.handoffRetryRetentionMs ?? RELOAD_HANDOFF_RETENTION_MS
2035
1989
  const handoffRetryItemLimit = options.handoffRetryItemLimit ?? MAX_PENDING_RELOAD_HANDOFF_ITEMS_PER_KEY
@@ -2457,22 +2411,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2457
2411
  if (live.draining) return false
2458
2412
  if (isPinnedByRunningChild(live.sessionId, live.keyId, 'stale-rollover')) return false
2459
2413
  if (idleMs <= SESSION_FRESHNESS_TTL_MS) return false
2460
- if (idleMs > SESSION_GRACE_HARD_TTL_MS) {
2461
- logger.info(`[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle, past grace cap)`)
2462
- return true
2463
- }
2464
- const transcriptPath = live.getTranscriptPath?.()
2465
- const transcriptBytes = transcriptPath !== undefined ? measureTranscriptBytes(transcriptPath) : 0
2466
- const transcriptDeltaBytes = Math.max(0, transcriptBytes - live.baseContextBytes)
2467
- if (isGraceWorthReusing(live.baseContextBytes, transcriptDeltaBytes)) {
2468
- logger.info(
2469
- `[channels] ${live.keyId}: grace-reuse (live: ${idleMs}ms idle, base=${live.baseContextBytes}B delta=${transcriptDeltaBytes}B)`,
2470
- )
2471
- return false
2472
- }
2473
- logger.info(
2474
- `[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle, base=${live.baseContextBytes}B delta=${transcriptDeltaBytes}B)`,
2475
- )
2414
+ logger.info(`[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle)`)
2476
2415
  return true
2477
2416
  }
2478
2417
 
@@ -3000,7 +2939,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3000
2939
  // Restart-resume only: force rehydration of this exact (sessionId,
3001
2940
  // sessionFile) and bypass stale-rollover, so the originating session's
3002
2941
  // `typeclaw.restart-self` entry is reopened rather than rolled into a fresh
3003
- // session (a restart easily outlasts SESSION_FRESHNESS_TTL_MS). The mapping
2942
+ // session, even if the restart outlasts SESSION_FRESHNESS_TTL_MS. The mapping
3004
2943
  // is persisted only through the normal success path below — no pre-mutation
3005
2944
  // — so a reopen failure leaves the durable mapping untouched.
3006
2945
  resumeTarget?: { sessionId: string; sessionFile: string },
@@ -3022,7 +2961,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3022
2961
  adoptPendingReloadHandoff(existing)
3023
2962
  return existing
3024
2963
  }
3025
- // Rollover decision (soft TTL → cost-aware grace → hard cap) lives in
2964
+ // The 60-minute idle rollover decision lives in
3026
2965
  // shouldRolloverLive, which also skips draining sessions so a mid-prompt
3027
2966
  // turn is never aborted by a follow-up's idle check (PR #359 incident).
3028
2967
  const idleMs = now() - existing.lastInboundAt
@@ -3046,6 +2985,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3046
2985
  chat: prev.chat,
3047
2986
  thread: prev.thread,
3048
2987
  participants: prev.participants,
2988
+ ...(prev.botParticipated === true ? { botParticipated: true as const } : {}),
3049
2989
  lastInboundAt: 0,
3050
2990
  ...(prev.githubReviewThreadCloseout !== undefined && prev.githubReviewRound !== undefined
3051
2991
  ? { githubReviewRound: prev.githubReviewRound }
@@ -3096,6 +3036,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3096
3036
  chat: record.chat,
3097
3037
  thread: record.thread,
3098
3038
  participants: record.participants,
3039
+ ...(record.botParticipated === true ? { botParticipated: true as const } : {}),
3099
3040
  lastInboundAt: 0,
3100
3041
  ...(record.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
3101
3042
  ...(record.githubReviewThreadCloseout !== undefined
@@ -3128,6 +3069,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3128
3069
  sessionId: resumeTarget.sessionId,
3129
3070
  sessionFile: resumeTarget.sessionFile,
3130
3071
  participants: (record?.participants ?? []) as ChannelParticipant[],
3072
+ ...(record?.botParticipated === true ? { botParticipated: true as const } : {}),
3131
3073
  lastInboundAt: now(),
3132
3074
  ...(record?.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
3133
3075
  ...(record?.githubReviewThreadCloseout !== undefined
@@ -3233,6 +3175,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3233
3175
  ...(transcriptPath ? { sessionFile: basename(transcriptPath) } : {}),
3234
3176
  lastInboundAt: now(),
3235
3177
  participants,
3178
+ ...(resolvedRecord?.botParticipated === true ? { botParticipated: true as const } : {}),
3236
3179
  ...(restoredRound !== null && restoredRoundStatus !== null
3237
3180
  ? (() => {
3238
3181
  const state = githubReviewRoundPersistence(restoredRound, now)
@@ -3289,9 +3232,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3289
3232
  deferred: true,
3290
3233
  },
3291
3234
  githubReviewThreadCloseoutDecisionTurn: null,
3235
+ githubReviewThreadResolvedAt: null,
3292
3236
  pendingGithubReviewRoundCloseout: null,
3293
3237
  promptQueue: [],
3294
3238
  pendingSystemReminders: [],
3239
+ restoredBackgroundContextPending: !isColdStart,
3295
3240
  backgroundCoverage: [],
3296
3241
  inboundCoverage: [],
3297
3242
  backgroundStopVersion: 0,
@@ -3311,7 +3256,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3311
3256
  typingEpoch: 0,
3312
3257
  promptInFlight: false,
3313
3258
  lastInboundAt: now(),
3314
- baseContextBytes: 0,
3315
3259
  firstUnprocessedAt: 0,
3316
3260
  currentTurnAuthorId: null,
3317
3261
  recentMessages: [],
@@ -3348,6 +3292,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3348
3292
  lastSendLeafId: null,
3349
3293
  sendTimestamps: new Map(),
3350
3294
  successfulChannelSends: 0,
3295
+ botParticipated: resolvedRecord?.botParticipated === true,
3351
3296
  turnSeq: 0,
3352
3297
  logicalTurnStartedAt: now(),
3353
3298
  coverageDeferredSince: null,
@@ -3373,7 +3318,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3373
3318
  githubReviewOutputTurn: null,
3374
3319
  toolExecutionThisLogicalTurn: false,
3375
3320
  backgroundWakeLogicalTurn: false,
3376
- providerErrorSilencedThisLogicalTurn: false,
3321
+ providerErrorSilencedThisLogicalTurn: null,
3377
3322
  qualifyingWorkThisLogicalTurn: false,
3378
3323
  promisedWorkOutstandingThisLogicalTurn: false,
3379
3324
  statusOutputOutstandingThisLogicalTurn: false,
@@ -3408,7 +3353,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3408
3353
  live.pendingProviderError = {
3409
3354
  turnSeq: live.turnSeq,
3410
3355
  safeMessage: err.safeMessage,
3411
- retryAndSee: isTransientProviderFailure(err.message) || isUnclassifiedProviderNotice(err.safeMessage),
3356
+ ...providerFailureSurface(err),
3412
3357
  }
3413
3358
  })
3414
3359
  live.unsubTodoOutcome = created.session.subscribe((event: unknown) => {
@@ -3509,15 +3454,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3509
3454
  liveSessions.set(keyId, live)
3510
3455
  }
3511
3456
 
3512
- // Snapshot the rendered base context size now, after prefetch and before
3513
- // any user turn, so the soft-TTL grace decision can later compare it
3514
- // against transcript growth. Only meaningful on cold-start (a rehydrated
3515
- // session's file already holds prior conversation, not a clean base).
3516
- const transcriptPathForBase = live.getTranscriptPath?.()
3517
- if (isColdStart && transcriptPathForBase !== undefined) {
3518
- live.baseContextBytes = measureTranscriptBytes(transcriptPathForBase)
3519
- }
3520
-
3521
3457
  if (!isLatestCreation()) {
3522
3458
  await unwindInstalledLive(keyId, live)
3523
3459
  throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
@@ -3566,6 +3502,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3566
3502
  // emitting a misleading elision marker for a zero-length gap.
3567
3503
  const requested = head + tail + 1
3568
3504
  const result = await fetchHistory(live.key.adapter, {
3505
+ workspace: live.key.workspace,
3569
3506
  chat: live.key.chat,
3570
3507
  thread: live.key.thread,
3571
3508
  ...(live.githubReviewRound !== null ? { githubReviewRound: live.githubReviewRound } : {}),
@@ -3605,6 +3542,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3605
3542
  if (tail === 0) return
3606
3543
  head = 0
3607
3544
  const channelResult = await fetchHistory(live.key.adapter, {
3545
+ workspace: live.key.workspace,
3608
3546
  chat: live.key.chat,
3609
3547
  thread: null,
3610
3548
  limit: tail + 1,
@@ -3684,6 +3622,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3684
3622
  await persist()
3685
3623
  }
3686
3624
 
3625
+ const persistBotParticipation = async (live: LiveSession): Promise<void> => {
3626
+ if (mappings === null) return
3627
+ const idx = mappings.findIndex(
3628
+ (s) =>
3629
+ s.adapter === live.key.adapter &&
3630
+ s.workspace === live.key.workspace &&
3631
+ s.chat === live.key.chat &&
3632
+ (s.thread ?? null) === (live.key.thread ?? null),
3633
+ )
3634
+ if (idx < 0) return
3635
+ const next = mappings.slice()
3636
+ next[idx] = { ...next[idx]!, botParticipated: true }
3637
+ mappings = next
3638
+ await persist()
3639
+ }
3640
+
3687
3641
  const fireTyping = async (
3688
3642
  live: LiveSession,
3689
3643
  phase: 'tick' | 'stop',
@@ -4303,9 +4257,33 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4303
4257
  const isReviewStateUnknownDeferralActive = (closeout: GithubReviewThreadCloseout): boolean =>
4304
4258
  closeout.deferUntil?.kind === 'review-state-unknown' && closeout.deferUntil.expiresAt > now()
4305
4259
 
4260
+ // The carrier of a pending round may spawn its reviewer before a participant's
4261
+ // reply opens the thread close-out. That reviewer is still the one that will
4262
+ // close the thread, so wait from the round's start, not the obligation's.
4263
+ const closeoutChildWaitStartedAt = (
4264
+ live: LiveSession,
4265
+ closeout: GithubReviewThreadCloseout & { startedAt: number },
4266
+ ): number => {
4267
+ const round = live.githubReviewRound
4268
+ if (
4269
+ round === null ||
4270
+ round.carrierThread !== live.key.thread ||
4271
+ round.workspace !== closeout.workspace ||
4272
+ round.prNumber !== closeout.prNumber
4273
+ ) {
4274
+ return closeout.startedAt
4275
+ }
4276
+ const state = githubReviewRoundPersistence(round, now)
4277
+ if (state?.status !== 'pending') return closeout.startedAt
4278
+ return Math.min(closeout.startedAt, state.createdAt)
4279
+ }
4280
+
4306
4281
  const enforceGithubReviewThreadCloseout = async (live: LiveSession): Promise<void> => {
4307
4282
  const closeout = live.githubReviewThreadCloseout
4308
- if (closeout === null || isAwaitingBackgroundChild(live, 'github-thread-closeout', closeout.startedAt)) {
4283
+ if (
4284
+ closeout === null ||
4285
+ isAwaitingBackgroundChild(live, 'github-thread-closeout', closeoutChildWaitStartedAt(live, closeout))
4286
+ ) {
4309
4287
  return
4310
4288
  }
4311
4289
  if (isReviewStateUnknownDeferralActive(closeout)) {
@@ -4958,7 +4936,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4958
4936
  // record.
4959
4937
  if (live.toolExecutionThisLogicalTurn && !owesPromisedWork(live)) {
4960
4938
  live.pendingProviderError = null
4961
- live.providerErrorSilencedThisLogicalTurn = true
4939
+ live.providerErrorSilencedThisLogicalTurn = 'tool-activity'
4962
4940
  logger.warn(
4963
4941
  `[channels] ${live.keyId}: provider_error_notice_suppressed reason=tool_activity_this_turn notice="${pending.safeMessage}"`,
4964
4942
  )
@@ -5009,6 +4987,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5009
4987
  }
5010
4988
  return
5011
4989
  }
4990
+ // The reaction couldn't land (a reaction-less adapter, no reactable target, or
4991
+ // a refused call). An unclassified failure names nothing the user can act on,
4992
+ // so it isn't worth looking broken in the chat: the operator log carries it.
4993
+ // Promised work keeps the notice, since silence would leave the user waiting.
4994
+ if (pending.unclassified && !owesPromisedWork(live)) {
4995
+ live.providerErrorSilencedThisLogicalTurn = 'unclassified-failure'
4996
+ logger.warn(
4997
+ `[channels] ${live.keyId}: provider_error_notice_suppressed reason=unclassified_no_reaction notice="${pending.safeMessage}"`,
4998
+ )
4999
+ return
5000
+ }
5012
5001
  const result = await send(
5013
5002
  {
5014
5003
  adapter: live.key.adapter,
@@ -5043,17 +5032,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5043
5032
  // the journal rows stay owed meanwhile.
5044
5033
  // A logical turn that may not error out in the channel: one opened by background
5045
5034
  // work rather than a user, or one whose provider-error notice was already
5046
- // suppressed because it ran tools. Whatever such a turn leaves owed settles
5047
- // silently instead of becoming a live-turn-ended notice, wherever it ends.
5035
+ // suppressed. Whatever such a turn leaves owed settles silently instead of
5036
+ // becoming a live-turn-ended notice, wherever it ends.
5048
5037
  const silentTurnEnd = (live: LiveSession): { log: string; reason: string } | null =>
5049
5038
  live.backgroundWakeLogicalTurn
5050
5039
  ? { log: 'background_wake_turn_ended_silently', reason: 'background-wake-turn-ended' }
5051
- : live.providerErrorSilencedThisLogicalTurn
5040
+ : live.providerErrorSilencedThisLogicalTurn === 'tool-activity'
5052
5041
  ? {
5053
5042
  log: 'turn_end_notice_suppressed reason=provider_error_after_tool_activity',
5054
5043
  reason: 'provider-error-after-tool-activity',
5055
5044
  }
5056
- : null
5045
+ : live.providerErrorSilencedThisLogicalTurn === 'unclassified-failure'
5046
+ ? {
5047
+ log: 'turn_end_notice_suppressed reason=unclassified_provider_failure',
5048
+ reason: 'unclassified-provider-failure',
5049
+ }
5050
+ : null
5057
5051
 
5058
5052
  // Settles a source turn's held rows by their exact generations, for when a fresh
5059
5053
  // batch abandons a silent turn: the rows may be owned by a predecessor session,
@@ -5152,7 +5146,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5152
5146
  live.githubReviewOutputTurn = null
5153
5147
  live.toolExecutionThisLogicalTurn = false
5154
5148
  live.backgroundWakeLogicalTurn = true
5155
- live.providerErrorSilencedThisLogicalTurn = false
5149
+ live.providerErrorSilencedThisLogicalTurn = null
5156
5150
  live.qualifyingWorkThisLogicalTurn = false
5157
5151
  }
5158
5152
 
@@ -5537,18 +5531,43 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5537
5531
  live.emptyStopAfterToolWorkArmed = false
5538
5532
  live.willingnessNudges = 0
5539
5533
  live.logicalTurnStartedAt = now()
5540
- const stampedCloseout = batch.findLast((item) => item.githubReviewThreadCloseout !== undefined)
5534
+ const latestStampedCloseout = batch.findLast((item) => item.githubReviewThreadCloseout !== undefined)
5535
+ const resolvedAt = live.githubReviewThreadResolvedAt
5536
+ const alreadyResolved =
5537
+ latestStampedCloseout?.githubReviewThreadCloseout !== undefined &&
5538
+ resolvedAt !== null &&
5539
+ resolvedAt.rootCommentId === latestStampedCloseout.githubReviewThreadCloseout.rootCommentId &&
5540
+ latestStampedCloseout.ts > 0 &&
5541
+ latestStampedCloseout.ts <= resolvedAt.at
5542
+ if (alreadyResolved) {
5543
+ logger.info(
5544
+ `[channels] ${live.keyId} github_thread_closeout_already_resolved root=${resolvedAt?.rootCommentId} reply_ts=${latestStampedCloseout?.ts} resolved_at=${resolvedAt?.at}`,
5545
+ )
5546
+ }
5547
+ const stampedCloseout = alreadyResolved ? undefined : latestStampedCloseout
5541
5548
  const deferredCloseout =
5542
5549
  stampedCloseout?.githubReviewThreadCloseout === undefined &&
5543
5550
  live.githubReviewThreadCloseout !== null &&
5544
5551
  live.githubReviewThreadCloseout.deferred
5545
5552
  ? live.githubReviewThreadCloseout
5546
5553
  : null
5554
+ // A follow-up on a thread whose close-out is still open continues the
5555
+ // same obligation. Keep its start so a reviewer spawned for it before
5556
+ // this batch still holds the close-out instead of being treated as an
5557
+ // earlier turn's child and letting the canned fallback race its verdict.
5558
+ const openCloseout = live.githubReviewThreadCloseout
5559
+ const continuedStartedAt = (next: GithubReviewThreadCloseout): number =>
5560
+ openCloseout !== null &&
5561
+ openCloseout.workspace === next.workspace &&
5562
+ openCloseout.prNumber === next.prNumber &&
5563
+ openCloseout.rootCommentId === next.rootCommentId
5564
+ ? openCloseout.startedAt
5565
+ : live.logicalTurnStartedAt
5547
5566
  live.githubReviewThreadCloseout =
5548
5567
  stampedCloseout?.githubReviewThreadCloseout !== undefined
5549
5568
  ? {
5550
5569
  ...stampedCloseout.githubReviewThreadCloseout,
5551
- startedAt: live.logicalTurnStartedAt,
5570
+ startedAt: continuedStartedAt(stampedCloseout.githubReviewThreadCloseout),
5552
5571
  correctionAttempts: 0,
5553
5572
  deferred: false,
5554
5573
  }
@@ -5556,7 +5575,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5556
5575
  ? null
5557
5576
  : {
5558
5577
  ...deferredCloseout,
5559
- startedAt: live.logicalTurnStartedAt,
5578
+ startedAt: continuedStartedAt(deferredCloseout),
5560
5579
  correctionAttempts: 0,
5561
5580
  }
5562
5581
  if (stampedCloseout?.githubReviewThreadCloseout !== undefined) {
@@ -5583,7 +5602,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5583
5602
  live.githubReviewOutputTurn = null
5584
5603
  live.toolExecutionThisLogicalTurn = false
5585
5604
  live.backgroundWakeLogicalTurn = false
5586
- live.providerErrorSilencedThisLogicalTurn = false
5605
+ live.providerErrorSilencedThisLogicalTurn = null
5587
5606
  live.qualifyingWorkThisLogicalTurn = false
5588
5607
  live.promisedWorkOutstandingThisLogicalTurn = false
5589
5608
  live.statusOutputOutstandingThisLogicalTurn = false
@@ -5656,6 +5675,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5656
5675
  live.policyDeniedToolSendsThisTurn.clear()
5657
5676
  resetReviewTurn(live.sessionId)
5658
5677
  const isRealUserTurn = batch.length > 0
5678
+ // Only a fresh inbound batch is a new request. Retry and wakeup turns
5679
+ // (empty batch, reminders only) keep the loop guard's history so a
5680
+ // stranded or aborted cycle cannot clear itself through a retry.
5681
+ if (isRealUserTurn) live.session.resetLoopGuard?.()
5659
5682
  await awaitLatestTodoOutcomeWrite(live)
5660
5683
  await recordTodoTurnStart(live, isRealUserTurn)
5661
5684
  const retrievalQuery = composeRetrievalQuery(batch)
@@ -5678,7 +5701,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5678
5701
  )
5679
5702
  })
5680
5703
  if (!accountMayPrompt || live.backgroundStopVersion !== stopVersion) continue
5681
- const promptText = retrievalContext.results.length > 0 ? `${text}\n\n${retrievalContext.results}` : text
5704
+ // Taken only once this turn will prompt: the receipt is at-most-once.
5705
+ const restoredContext = live.restoredBackgroundContextPending
5706
+ ? await takeLostBackgroundContext(options.agentDir, backgroundObligations, live.sessionId)
5707
+ : []
5708
+ live.restoredBackgroundContextPending = false
5709
+ const promptText = [
5710
+ ...restoredContext,
5711
+ text,
5712
+ ...(retrievalContext.results ? [retrievalContext.results] : []),
5713
+ ].join('\n\n')
5682
5714
  applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
5683
5715
  live.promptInFlight = true
5684
5716
  try {
@@ -5776,9 +5808,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5776
5808
  live.pendingProviderError = {
5777
5809
  turnSeq: live.turnSeq,
5778
5810
  safeMessage: hardProviderError.safeMessage,
5779
- retryAndSee:
5780
- isTransientProviderFailure(hardProviderError.message) ||
5781
- isUnclassifiedProviderNotice(hardProviderError.safeMessage),
5811
+ ...providerFailureSurface(hardProviderError),
5782
5812
  }
5783
5813
  }
5784
5814
  live.consecutiveSends.clear()
@@ -6489,7 +6519,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6489
6519
  }
6490
6520
 
6491
6521
  const hasBotParticipated = (live: LiveSession): boolean => {
6492
- if (live.successfulChannelSends > 0) return true
6522
+ if (live.botParticipated || live.successfulChannelSends > 0) return true
6493
6523
  // Only OUR own prefetched history counts as participation — matching any
6494
6524
  // bot here let a PEER bot's buffered message flip botInThread=true,
6495
6525
  // neutralizing the replyToOtherMessageId suppressor and engaging us in a
@@ -7591,6 +7621,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7591
7621
 
7592
7622
  if (live) {
7593
7623
  live.successfulChannelSends++
7624
+ if (!live.botParticipated) {
7625
+ live.botParticipated = true
7626
+ void persistBotParticipation(live).catch((err) => {
7627
+ logger.warn(`[channels] ${live.keyId}: persisting bot participation failed: ${describeError(err)}`)
7628
+ })
7629
+ }
7594
7630
  // Promise fulfillment follows OUTPUT KIND, never source:
7595
7631
  // (a) ordinary substantive tool output clears;
7596
7632
  // (b) multilingual continuation-willingness/status output preserves, and
@@ -7757,6 +7793,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7757
7793
  live.skippedTurn = null
7758
7794
  armRetainedOutputAckIfEligible(live, successfulSendsBeforePrompt, true)
7759
7795
  logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
7796
+ // The model decided this turn owes the user nothing, so a provider failure
7797
+ // on the request after that decision lost nothing the user was waiting for.
7798
+ // A notice here would be a false alarm, typically stranded under the real
7799
+ // reply an earlier pass of the same logical turn already delivered.
7800
+ const pendingError = live.pendingProviderError
7801
+ if (pendingError !== null && pendingError.turnSeq === live.turnSeq) {
7802
+ live.pendingProviderError = null
7803
+ logger.warn(
7804
+ `[channels] ${live.keyId}: provider_error_notice_suppressed reason=explicit_skip_response notice="${pendingError.safeMessage}"`,
7805
+ )
7806
+ }
7807
+ // This session already resolved the thread and the model read the newer
7808
+ // reply and deliberately skipped it. Leaving a resolved thread resolved is
7809
+ // a close-out decision, so neither the reminder nor the "leaving it open"
7810
+ // fallback applies. A turn that ends silent without skip_response still owes one.
7811
+ const closeout = live.githubReviewThreadCloseout
7812
+ const resolvedAt = live.githubReviewThreadResolvedAt
7813
+ if (closeout !== null && resolvedAt !== null && resolvedAt.rootCommentId === closeout.rootCommentId) {
7814
+ clearGithubReviewThreadCloseout(live)
7815
+ live.githubReviewThreadCloseoutDecisionTurn = live.turnSeq
7816
+ logger.info(
7817
+ `[channels] ${live.keyId} github_thread_closeout_skipped_already_resolved pr=${closeout.prNumber} root=${closeout.rootCommentId}`,
7818
+ )
7819
+ }
7760
7820
  void dropContinuationReactions(live)
7761
7821
  return
7762
7822
  }
@@ -8303,6 +8363,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8303
8363
  // missing formal review on the model's behalf, and posting the unguarded ack
8304
8364
  // is worse than dropping it — the next inbound re-prompts the model, which
8305
8365
  // can then land the verdict properly.
8366
+ // Real leftover prose is still recovered while a background child runs (an
8367
+ // answer the model already wrote should land), but a lone identifier-shaped
8368
+ // ASCII token is model degeneration, not an answer: a bare `_RGCTX` once
8369
+ // landed as a public PR comment right after a reviewer spawn. The child's
8370
+ // completion turn owns the real reply, so drop it. Scoped to the awaiting
8371
+ // turn so ordinary recovery is untouched; non-Latin short replies never match.
8372
+ if (/^[A-Za-z0-9_]+$/.test(assistantText.trim()) && isAwaitingBackgroundChild(live, 'recovery_leaf')) {
8373
+ logger.info(
8374
+ `[channels] ${live.keyId} recovery_suppressed cause=awaiting_background_child text_len=${assistantText.length}`,
8375
+ )
8376
+ armSilentTurnAck(live, 'awaiting_background_child')
8377
+ return
8378
+ }
8379
+
8306
8380
  const recoveryBlock = await evaluateRecoveryReviewGuards(live, assistantText)
8307
8381
  if (recoveryBlock !== null) {
8308
8382
  logger.warn(
@@ -9164,9 +9238,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9164
9238
  }
9165
9239
  // The exact parent session is gone. If the subagent was spawned from a
9166
9240
  // channel session, the conversation may have rolled over
9167
- // (SESSION_FRESHNESS_TTL_MS) or been idle-evicted onto a fresh sessionId
9168
- // for the same channel key while the subagent ran. Fall back to the live
9169
- // successor for that key so a finished review/result still surfaces
9241
+ // after 60 minutes idle (SESSION_FRESHNESS_TTL_MS), or been idle-evicted
9242
+ // and rehydrated for the same channel key while the subagent ran. Fall back
9243
+ // to the live successor for that key so a finished review/result still surfaces
9170
9244
  // instead of being silently dropped.
9171
9245
  if (args.channelKey !== undefined) {
9172
9246
  const targetKeyId = channelKeyId(args.channelKey)
@@ -9307,7 +9381,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9307
9381
  const round = publisher?.githubReviewRound ?? persistedPublisher?.githubReviewRound
9308
9382
  if (round === null || round === undefined) {
9309
9383
  const resetRound = resetGithubReviewRoundCompletionForPr(args.workspace, args.prNumber, now)
9310
- if (resetRound !== null) persistMatchingGithubReviewRound(resetRound)
9384
+ // A first review never carries a round, so its verdict lands here every
9385
+ // time. Only a pending round the publisher failed to hold is worth a warning.
9386
+ if (resetRound === null) return { kind: 'no-round' }
9387
+ persistMatchingGithubReviewRound(resetRound)
9311
9388
  logger.warn(
9312
9389
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: no publisher session with round state session=${args.sessionId}`,
9313
9390
  )
@@ -9424,6 +9501,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9424
9501
  )
9425
9502
  if (live !== undefined) {
9426
9503
  live.githubReviewThreadCloseoutDecisionTurn = live.turnSeq
9504
+ if (args.decision === 'resolved' && args.thread !== null) {
9505
+ live.githubReviewThreadResolvedAt = { rootCommentId: args.thread, at: now() }
9506
+ }
9427
9507
  clearGithubReviewThreadCloseout(live)
9428
9508
  logger.info(
9429
9509
  `[channels] ${live.keyId} github_thread_closeout_decided decision=${args.decision} turn=${live.turnSeq}`,
@@ -9565,7 +9645,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9565
9645
  // Answers a failed turn with a reaction on its triggering message instead of
9566
9646
  // a chat line; in busy rooms the old text notices outnumbered real replies.
9567
9647
  // False when there is nothing reactable or the adapter refused, so the caller
9568
- // falls back to its text notice and the user is never left with silence.
9648
+ // decides whether the failure still earns its text notice.
9569
9649
  const reactTurnFailed = async (live: LiveSession): Promise<boolean> => {
9570
9650
  const reactionRef = live.currentTurnReactionRef
9571
9651
  if (reactionRef === null) return false
@@ -9578,7 +9658,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9578
9658
  emoji: TURN_FAILED_REACTION_EMOJI,
9579
9659
  })
9580
9660
  if (!result.ok && result.code !== 'unsupported') {
9581
- logger.info(`[channels] ${live.keyId}: turn-failed reaction failed, posting notice: ${result.error}`)
9661
+ logger.info(`[channels] ${live.keyId}: turn-failed reaction failed: ${result.error}`)
9582
9662
  }
9583
9663
  return result.ok
9584
9664
  }