typeclaw 0.49.0 → 0.51.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 (502) hide show
  1. package/dist/types/agent/attention-escalation.d.ts +18 -0
  2. package/dist/types/agent/auth.d.ts +7 -0
  3. package/dist/types/agent/bash-sandbox-env.d.ts +15 -0
  4. package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
  5. package/dist/types/agent/bash-sandbox.d.ts +94 -0
  6. package/dist/types/agent/compaction.d.ts +8 -0
  7. package/dist/types/agent/git-nudge.d.ts +6 -0
  8. package/dist/types/agent/guard-types.d.ts +25 -0
  9. package/dist/types/agent/guards.d.ts +7 -0
  10. package/dist/types/agent/idle-compaction.d.ts +8 -0
  11. package/dist/types/agent/index.d.ts +151 -0
  12. package/dist/types/agent/live-subagents.d.ts +113 -0
  13. package/dist/types/agent/llm-replay-sanitizer.d.ts +11 -0
  14. package/dist/types/agent/loop-guard.d.ts +67 -0
  15. package/dist/types/agent/model-fallback.d.ts +29 -0
  16. package/dist/types/agent/model-overrides.d.ts +8 -0
  17. package/dist/types/agent/multimodal/index.d.ts +2 -0
  18. package/dist/types/agent/multimodal/look-at.d.ts +60 -0
  19. package/dist/types/agent/multimodal/looker.d.ts +61 -0
  20. package/dist/types/agent/multimodal/read-redirect.d.ts +6 -0
  21. package/dist/types/agent/network/response-body.d.ts +1 -0
  22. package/dist/types/agent/network/safe-http.d.ts +46 -0
  23. package/dist/types/agent/output-allowance.d.ts +4 -0
  24. package/dist/types/agent/plugin-tools.d.ts +58 -0
  25. package/dist/types/agent/proactive-next-step-nudge.d.ts +2 -0
  26. package/dist/types/agent/prompt-cache-key.d.ts +3 -0
  27. package/dist/types/agent/provider-error.d.ts +23 -0
  28. package/dist/types/agent/reload-tool.d.ts +10 -0
  29. package/dist/types/agent/restart/index.d.ts +31 -0
  30. package/dist/types/agent/restart-handoff/index.d.ts +32 -0
  31. package/dist/types/agent/restart-handoff/paths.d.ts +1 -0
  32. package/dist/types/agent/retry-same-ref.d.ts +41 -0
  33. package/dist/types/agent/reviewer-activity.d.ts +3 -0
  34. package/dist/types/agent/reviewer-bash-policy.d.ts +8 -0
  35. package/dist/types/agent/self.d.ts +1 -0
  36. package/dist/types/agent/session-meta.d.ts +28 -0
  37. package/dist/types/agent/session-origin.d.ts +65 -0
  38. package/dist/types/agent/subagent-cache-keepalive.d.ts +38 -0
  39. package/dist/types/agent/subagent-completion-reminder.d.ts +29 -0
  40. package/dist/types/agent/subagent-drain.d.ts +25 -0
  41. package/dist/types/agent/subagent-session.d.ts +3 -0
  42. package/dist/types/agent/subagents.d.ts +153 -0
  43. package/dist/types/agent/system-prompt-composition.d.ts +17 -0
  44. package/dist/types/agent/system-prompt.d.ts +7 -0
  45. package/dist/types/agent/throttle-circuit.d.ts +25 -0
  46. package/dist/types/agent/todo/continuation-policy.d.ts +54 -0
  47. package/dist/types/agent/todo/continuation-state.d.ts +11 -0
  48. package/dist/types/agent/todo/continuation-wiring.d.ts +32 -0
  49. package/dist/types/agent/todo/continuation.d.ts +21 -0
  50. package/dist/types/agent/todo/scope.d.ts +6 -0
  51. package/dist/types/agent/todo/store.d.ts +16 -0
  52. package/dist/types/agent/tool-error-remediation.d.ts +1 -0
  53. package/dist/types/agent/tool-file-safety.d.ts +78 -0
  54. package/dist/types/agent/tool-not-found-nudge.d.ts +9 -0
  55. package/dist/types/agent/tool-result-budget.d.ts +15 -0
  56. package/dist/types/agent/tools/channel-disengage.d.ts +18 -0
  57. package/dist/types/agent/tools/channel-edit.d.ts +19 -0
  58. package/dist/types/agent/tools/channel-fetch-attachment.d.ts +36 -0
  59. package/dist/types/agent/tools/channel-handoff.d.ts +13 -0
  60. package/dist/types/agent/tools/channel-history-render.d.ts +3 -0
  61. package/dist/types/agent/tools/channel-history.d.ts +25 -0
  62. package/dist/types/agent/tools/channel-log.d.ts +5 -0
  63. package/dist/types/agent/tools/channel-react.d.ts +23 -0
  64. package/dist/types/agent/tools/channel-read.d.ts +27 -0
  65. package/dist/types/agent/tools/channel-reply.d.ts +47 -0
  66. package/dist/types/agent/tools/channel-send.d.ts +42 -0
  67. package/dist/types/agent/tools/channel-session-search.d.ts +10 -0
  68. package/dist/types/agent/tools/curl-impersonate.d.ts +37 -0
  69. package/dist/types/agent/tools/ddg.d.ts +27 -0
  70. package/dist/types/agent/tools/grant-role.d.ts +25 -0
  71. package/dist/types/agent/tools/keyed-semaphore.d.ts +10 -0
  72. package/dist/types/agent/tools/post-github-review.d.ts +38 -0
  73. package/dist/types/agent/tools/restart.d.ts +25 -0
  74. package/dist/types/agent/tools/runtime-notice.d.ts +3 -0
  75. package/dist/types/agent/tools/search-retry.d.ts +16 -0
  76. package/dist/types/agent/tools/skip-response.d.ts +17 -0
  77. package/dist/types/agent/tools/spawn-subagent.d.ts +77 -0
  78. package/dist/types/agent/tools/stream-snapshot.d.ts +23 -0
  79. package/dist/types/agent/tools/subagent-access.d.ts +20 -0
  80. package/dist/types/agent/tools/subagent-cancel.d.ts +23 -0
  81. package/dist/types/agent/tools/subagent-output.d.ts +50 -0
  82. package/dist/types/agent/tools/todo/index.d.ts +14 -0
  83. package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +29 -0
  84. package/dist/types/agent/tools/webfetch/fetch.d.ts +26 -0
  85. package/dist/types/agent/tools/webfetch/html-lexical.d.ts +27 -0
  86. package/dist/types/agent/tools/webfetch/index.d.ts +1 -0
  87. package/dist/types/agent/tools/webfetch/inline-style-visibility.d.ts +3 -0
  88. package/dist/types/agent/tools/webfetch/strategies/grep.d.ts +11 -0
  89. package/dist/types/agent/tools/webfetch/strategies/jq.d.ts +4 -0
  90. package/dist/types/agent/tools/webfetch/strategies/raw.d.ts +1 -0
  91. package/dist/types/agent/tools/webfetch/strategies/readability.d.ts +16 -0
  92. package/dist/types/agent/tools/webfetch/strategies/selector.d.ts +4 -0
  93. package/dist/types/agent/tools/webfetch/strategies/snapshot.d.ts +1 -0
  94. package/dist/types/agent/tools/webfetch/tool.d.ts +15 -0
  95. package/dist/types/agent/tools/webfetch/types.d.ts +32 -0
  96. package/dist/types/agent/tools/websearch.d.ts +17 -0
  97. package/dist/types/agent/tools/wikipedia.d.ts +7 -0
  98. package/dist/types/agent/tools-without-local-file-operands.d.ts +1 -0
  99. package/dist/types/agent/turn-runner.d.ts +36 -0
  100. package/dist/types/agent-messenger/config-dir.d.ts +19 -0
  101. package/dist/types/browser/dockerfile.d.ts +2 -0
  102. package/dist/types/browser/registry.d.ts +49 -0
  103. package/dist/types/bundled-plugins/bun-hygiene/policy.d.ts +18 -0
  104. package/dist/types/bundled-plugins/github-cli-auth/git-askpass.d.ts +5 -0
  105. package/dist/types/bundled-plugins/guard/keys.d.ts +6 -0
  106. package/dist/types/bundled-plugins/guard/policies/managed-config.d.ts +7 -0
  107. package/dist/types/bundled-plugins/guard/policies/memory-topics-delete.d.ts +11 -0
  108. package/dist/types/bundled-plugins/guard/policies/memory-topics-write.d.ts +7 -0
  109. package/dist/types/bundled-plugins/guard/policies/non-workspace-write.d.ts +9 -0
  110. package/dist/types/bundled-plugins/guard/policies/skill-authoring.d.ts +20 -0
  111. package/dist/types/bundled-plugins/guard/policies/uncommitted-changes.d.ts +12 -0
  112. package/dist/types/bundled-plugins/guard/policy.d.ts +11 -0
  113. package/dist/types/bundled-plugins/memory/secret-detector.d.ts +11 -0
  114. package/dist/types/bundled-plugins/memory/slug.d.ts +4 -0
  115. package/dist/types/bundled-plugins/security/permissions.d.ts +20 -0
  116. package/dist/types/bundled-plugins/security/policies/private-surface-read.d.ts +34 -0
  117. package/dist/types/bundled-plugins/security/policies/ssrf.d.ts +18 -0
  118. package/dist/types/bundled-plugins/security/policy.d.ts +4 -0
  119. package/dist/types/channels/adapter-namespace.d.ts +2 -0
  120. package/dist/types/channels/adapters/mention-hints.d.ts +12 -0
  121. package/dist/types/channels/adapters/webex-id-ref.d.ts +5 -0
  122. package/dist/types/channels/background-handoff.d.ts +56 -0
  123. package/dist/types/channels/background-obligations.d.ts +135 -0
  124. package/dist/types/channels/catch-up.d.ts +26 -0
  125. package/dist/types/channels/commands.d.ts +2 -0
  126. package/dist/types/channels/completion-claim.d.ts +20 -0
  127. package/dist/types/channels/continuation-willingness.d.ts +1 -0
  128. package/dist/types/channels/continuity-types.d.ts +75 -0
  129. package/dist/types/channels/describe-error.d.ts +1 -0
  130. package/dist/types/channels/engagement.d.ts +34 -0
  131. package/dist/types/channels/github-false-receipt.d.ts +20 -0
  132. package/dist/types/channels/github-repo.d.ts +2 -0
  133. package/dist/types/channels/github-rereview-guard.d.ts +24 -0
  134. package/dist/types/channels/github-review-check.d.ts +135 -0
  135. package/dist/types/channels/github-review-claim.d.ts +3 -0
  136. package/dist/types/channels/github-review-turn-ledger.d.ts +71 -0
  137. package/dist/types/channels/github-review-verdict-coordinator.d.ts +117 -0
  138. package/dist/types/channels/github-token-bridge.d.ts +20 -0
  139. package/dist/types/channels/github-verdict-activity.d.ts +12 -0
  140. package/dist/types/channels/inbound-journal.d.ts +272 -0
  141. package/dist/types/channels/last-alive.d.ts +3 -0
  142. package/dist/types/channels/membership-cache.d.ts +27 -0
  143. package/dist/types/channels/membership.d.ts +21 -0
  144. package/dist/types/channels/outbound-flood-filter.d.ts +7 -0
  145. package/dist/types/channels/participants.d.ts +4 -0
  146. package/dist/types/channels/persistence.d.ts +32 -0
  147. package/dist/types/channels/recovery-notice.d.ts +26 -0
  148. package/dist/types/channels/recovery-outbox.d.ts +58 -0
  149. package/dist/types/channels/router.d.ts +760 -0
  150. package/dist/types/channels/schema.d.ts +501 -0
  151. package/dist/types/channels/session-handoff.d.ts +58 -0
  152. package/dist/types/channels/session-search.d.ts +29 -0
  153. package/dist/types/channels/types.d.ts +414 -0
  154. package/dist/types/channels/waiting-reactions.d.ts +25 -0
  155. package/dist/types/cli/builtins.d.ts +2 -0
  156. package/dist/types/cli/command-meta.d.ts +9 -0
  157. package/dist/types/coding-agent/broker-body.d.ts +7 -0
  158. package/dist/types/coding-agent/broker.d.ts +22 -0
  159. package/dist/types/coding-agent/claude.d.ts +22 -0
  160. package/dist/types/coding-agent/codex.d.ts +19 -0
  161. package/dist/types/coding-agent/index.d.ts +71 -0
  162. package/dist/types/coding-agent/omo-state.d.ts +2 -0
  163. package/dist/types/coding-agent/omo-stream.d.ts +22 -0
  164. package/dist/types/coding-agent/omo.d.ts +133 -0
  165. package/dist/types/coding-agent/runner.d.ts +35 -0
  166. package/dist/types/coding-agent/tool.d.ts +27 -0
  167. package/dist/types/coding-agent/worktree.d.ts +22 -0
  168. package/dist/types/commands/index.d.ts +45 -0
  169. package/dist/types/config/config.d.ts +827 -0
  170. package/dist/types/config/index.d.ts +3 -0
  171. package/dist/types/config/model-overrides.d.ts +3 -0
  172. package/dist/types/config/providers.d.ts +1458 -0
  173. package/dist/types/config/reloadable.d.ts +9 -0
  174. package/dist/types/container/agent-operation-lock.d.ts +31 -0
  175. package/dist/types/container/build-cache.d.ts +39 -0
  176. package/dist/types/container/compose-project.d.ts +1 -0
  177. package/dist/types/container/controller.d.ts +25 -0
  178. package/dist/types/container/docker-app.d.ts +23 -0
  179. package/dist/types/container/exit-reason.d.ts +10 -0
  180. package/dist/types/container/index.d.ts +14 -0
  181. package/dist/types/container/log-archive.d.ts +68 -0
  182. package/dist/types/container/log-colors.d.ts +3 -0
  183. package/dist/types/container/log-timestamps.d.ts +9 -0
  184. package/dist/types/container/logs.d.ts +37 -0
  185. package/dist/types/container/memory-limit.d.ts +13 -0
  186. package/dist/types/container/memory-oversubscription.d.ts +20 -0
  187. package/dist/types/container/oom-events.d.ts +18 -0
  188. package/dist/types/container/port.d.ts +18 -0
  189. package/dist/types/container/require-running.d.ts +16 -0
  190. package/dist/types/container/restart.d.ts +32 -0
  191. package/dist/types/container/shared.d.ts +93 -0
  192. package/dist/types/container/shell.d.ts +35 -0
  193. package/dist/types/container/start.d.ts +145 -0
  194. package/dist/types/container/stats.d.ts +31 -0
  195. package/dist/types/container/status.d.ts +25 -0
  196. package/dist/types/container/stop.d.ts +24 -0
  197. package/dist/types/container/tool-oom-priority.d.ts +4 -0
  198. package/dist/types/container/verify-running.d.ts +49 -0
  199. package/dist/types/cron/consumer.d.ts +42 -0
  200. package/dist/types/cron/count-state.d.ts +24 -0
  201. package/dist/types/cron/index.d.ts +21 -0
  202. package/dist/types/cron/list.d.ts +33 -0
  203. package/dist/types/cron/reloadable.d.ts +11 -0
  204. package/dist/types/cron/scheduler.d.ts +51 -0
  205. package/dist/types/cron/schema.d.ts +108 -0
  206. package/dist/types/dependencies/bin-resolver.d.ts +28 -0
  207. package/dist/types/dependencies/bins.d.ts +22 -0
  208. package/dist/types/dependencies/index.d.ts +2 -0
  209. package/dist/types/eval/cell.d.ts +26 -0
  210. package/dist/types/eval/config.d.ts +19 -0
  211. package/dist/types/eval/dispatch.d.ts +7 -0
  212. package/dist/types/eval/kernel.d.ts +28 -0
  213. package/dist/types/eval/process.d.ts +23 -0
  214. package/dist/types/eval/protocol.d.ts +34 -0
  215. package/dist/types/eval/sandbox.d.ts +10 -0
  216. package/dist/types/eval/tool.d.ts +17 -0
  217. package/dist/types/eval/wire.d.ts +33 -0
  218. package/dist/types/git/bound-gc-config.d.ts +4 -0
  219. package/dist/types/git/hookless.d.ts +1 -0
  220. package/dist/types/git/reconcile-ignored.d.ts +13 -0
  221. package/dist/types/git/resolve-agent-git.d.ts +8 -0
  222. package/dist/types/git/resolve-identity.d.ts +10 -0
  223. package/dist/types/git/run.d.ts +24 -0
  224. package/dist/types/git/system-commit.d.ts +2 -0
  225. package/dist/types/hostd/client.d.ts +13 -0
  226. package/dist/types/hostd/models.d.ts +1 -0
  227. package/dist/types/hostd/paths.d.ts +17 -0
  228. package/dist/types/hostd/protocol.d.ts +93 -0
  229. package/dist/types/hostd/spawn.d.ts +17 -0
  230. package/dist/types/hostd/version.d.ts +18 -0
  231. package/dist/types/init/auto-upgrade.d.ts +41 -0
  232. package/dist/types/init/cli-version.d.ts +7 -0
  233. package/dist/types/init/dockerfile.d.ts +34 -0
  234. package/dist/types/init/ensure-deps.d.ts +17 -0
  235. package/dist/types/init/env-file.d.ts +3 -0
  236. package/dist/types/init/gitignore.d.ts +5 -0
  237. package/dist/types/init/local-source-stamp.d.ts +3 -0
  238. package/dist/types/init/packagejson.d.ts +7 -0
  239. package/dist/types/init/paths.d.ts +3 -0
  240. package/dist/types/init/reconcile-plugin-deps.d.ts +13 -0
  241. package/dist/types/init/run-bun-install.d.ts +16 -0
  242. package/dist/types/init/windows-dev-link.d.ts +8 -0
  243. package/dist/types/mcp/catalog.d.ts +7 -0
  244. package/dist/types/mcp/client.d.ts +58 -0
  245. package/dist/types/mcp/manager.d.ts +56 -0
  246. package/dist/types/mcp/tools.d.ts +23 -0
  247. package/dist/types/models/embedding-model.d.ts +20 -0
  248. package/dist/types/models/transformers-version.d.ts +1 -0
  249. package/dist/types/network/internal-destinations.d.ts +29 -0
  250. package/dist/types/operations/classify-tool-outcome.d.ts +35 -0
  251. package/dist/types/operations/incidents.d.ts +47 -0
  252. package/dist/types/operations/index.d.ts +3 -0
  253. package/dist/types/operations/remediations.d.ts +25 -0
  254. package/dist/types/path-safety/real-intended-path.d.ts +9 -0
  255. package/dist/types/permissions/builtins.d.ts +25 -0
  256. package/dist/types/permissions/grant.d.ts +19 -0
  257. package/dist/types/permissions/index.d.ts +6 -0
  258. package/dist/types/permissions/match-rule.d.ts +28 -0
  259. package/dist/types/permissions/permissions.d.ts +42 -0
  260. package/dist/types/permissions/resolve.d.ts +25 -0
  261. package/dist/types/permissions/schema.d.ts +14 -0
  262. package/dist/types/plugin/context.d.ts +20 -0
  263. package/dist/types/plugin/core-tool-names.d.ts +4 -0
  264. package/dist/types/plugin/define.d.ts +46 -0
  265. package/dist/types/plugin/hooks.d.ts +52 -0
  266. package/dist/types/plugin/index.d.ts +11 -0
  267. package/dist/types/plugin/load-skill.d.ts +14 -0
  268. package/dist/types/plugin/loader.d.ts +25 -0
  269. package/dist/types/plugin/manager.d.ts +42 -0
  270. package/dist/types/plugin/registry.d.ts +73 -0
  271. package/dist/types/plugin/skills.d.ts +11 -0
  272. package/dist/types/plugin/types.d.ts +336 -0
  273. package/dist/types/plugin/zod-introspect.d.ts +11 -0
  274. package/dist/types/reload/client.d.ts +11 -0
  275. package/dist/types/reload/docker-exec-client.d.ts +11 -0
  276. package/dist/types/reload/format.d.ts +2 -0
  277. package/dist/types/reload/index.d.ts +6 -0
  278. package/dist/types/reload/recover.d.ts +22 -0
  279. package/dist/types/reload/registry.d.ts +10 -0
  280. package/dist/types/reload/types.d.ts +25 -0
  281. package/dist/types/role-claim/client.d.ts +20 -0
  282. package/dist/types/role-claim/code.d.ts +4 -0
  283. package/dist/types/role-claim/controller.d.ts +59 -0
  284. package/dist/types/role-claim/index.d.ts +6 -0
  285. package/dist/types/role-claim/match-rule.d.ts +9 -0
  286. package/dist/types/role-claim/pending.d.ts +35 -0
  287. package/dist/types/role-claim/reload-after-claim.d.ts +16 -0
  288. package/dist/types/run/llm-fetch-observer.d.ts +50 -0
  289. package/dist/types/sandbox/availability.d.ts +21 -0
  290. package/dist/types/sandbox/build.d.ts +7 -0
  291. package/dist/types/sandbox/canonical-secrets.d.ts +8 -0
  292. package/dist/types/sandbox/coding-agent.d.ts +20 -0
  293. package/dist/types/sandbox/dependency-bins.d.ts +19 -0
  294. package/dist/types/sandbox/dev-source.d.ts +4 -0
  295. package/dist/types/sandbox/env-exposure.d.ts +3 -0
  296. package/dist/types/sandbox/errors.d.ts +20 -0
  297. package/dist/types/sandbox/hidden-paths.d.ts +11 -0
  298. package/dist/types/sandbox/index.d.ts +14 -0
  299. package/dist/types/sandbox/package-install.d.ts +1 -0
  300. package/dist/types/sandbox/policy.d.ts +71 -0
  301. package/dist/types/sandbox/privileged-runtime.d.ts +13 -0
  302. package/dist/types/sandbox/quote.d.ts +2 -0
  303. package/dist/types/sandbox/runtime-private.d.ts +1 -0
  304. package/dist/types/sandbox/session-tmp.d.ts +6 -0
  305. package/dist/types/sandbox/symlinks.d.ts +6 -0
  306. package/dist/types/sandbox/writable-zones.d.ts +15 -0
  307. package/dist/types/secrets/coding-agent-auth.d.ts +25 -0
  308. package/dist/types/secrets/defaults.d.ts +21 -0
  309. package/dist/types/secrets/export-github-cli-store.d.ts +22 -0
  310. package/dist/types/secrets/hydrate.d.ts +7 -0
  311. package/dist/types/secrets/index.d.ts +7 -0
  312. package/dist/types/secrets/provision-github-cli-store.d.ts +45 -0
  313. package/dist/types/secrets/refresh-provider-oauth.d.ts +22 -0
  314. package/dist/types/secrets/resolve.d.ts +14 -0
  315. package/dist/types/secrets/schema.d.ts +840 -0
  316. package/dist/types/secrets/storage.d.ts +56 -0
  317. package/dist/types/shared/host-locale.d.ts +1 -0
  318. package/dist/types/shared/index.d.ts +5 -0
  319. package/dist/types/shared/local-time.d.ts +4 -0
  320. package/dist/types/shared/platform.d.ts +2 -0
  321. package/dist/types/shared/protocol.d.ts +424 -0
  322. package/dist/types/shared/style-text.d.ts +3 -0
  323. package/dist/types/shared/wsl.d.ts +17 -0
  324. package/dist/types/stream/broker.d.ts +2 -0
  325. package/dist/types/stream/index.d.ts +2 -0
  326. package/dist/types/stream/types.d.ts +71 -0
  327. package/package.json +13 -6
  328. package/scripts/build-plugin-types.ts +105 -0
  329. package/scripts/check-plugin-sdk.ts +111 -0
  330. package/scripts/require-parallel.ts +5 -32
  331. package/src/agent/bash-sandbox-env.ts +104 -0
  332. package/src/agent/bash-sandbox-proc.ts +70 -0
  333. package/src/agent/bash-sandbox.ts +225 -0
  334. package/src/agent/compaction.ts +22 -10
  335. package/src/agent/guard-types.ts +3 -0
  336. package/src/agent/guards.ts +4 -0
  337. package/src/agent/idle-compaction.ts +178 -0
  338. package/src/agent/index.ts +139 -172
  339. package/src/agent/live-subagents.ts +19 -0
  340. package/src/agent/multimodal/look-at.ts +22 -9
  341. package/src/agent/output-allowance.ts +7 -0
  342. package/src/agent/plugin-tools.ts +39 -377
  343. package/src/agent/reviewer-bash-policy.ts +41 -1
  344. package/src/agent/session-origin.ts +28 -11
  345. package/src/agent/subagent-cache-keepalive.ts +198 -0
  346. package/src/agent/subagent-completion-reminder.ts +2 -2
  347. package/src/agent/subagent-session.ts +6 -0
  348. package/src/agent/subagents.ts +46 -8
  349. package/src/agent/system-prompt-composition.ts +141 -0
  350. package/src/agent/system-prompt.ts +5 -5
  351. package/src/agent/todo/scope.ts +1 -1
  352. package/src/agent/tool-file-safety.ts +6 -1
  353. package/src/agent/tools/channel-edit.ts +20 -10
  354. package/src/agent/tools/channel-fetch-attachment.ts +12 -5
  355. package/src/agent/tools/channel-handoff.ts +72 -0
  356. package/src/agent/tools/channel-read.ts +57 -10
  357. package/src/agent/tools/channel-reply.ts +33 -26
  358. package/src/agent/tools/channel-send.ts +21 -13
  359. package/src/agent/tools/channel-session-search.ts +35 -0
  360. package/src/agent/tools/curl-impersonate.ts +11 -4
  361. package/src/agent/tools/ddg.ts +84 -16
  362. package/src/agent/tools/spawn-subagent.ts +27 -11
  363. package/src/agent/tools/stream-snapshot.ts +15 -2
  364. package/src/agent/tools/subagent-access.ts +11 -4
  365. package/src/agent/tools-without-local-file-operands.ts +4 -0
  366. package/src/browser/bsk-shim.mjs +74 -0
  367. package/src/browser/dockerfile.ts +84 -0
  368. package/src/browser/egress.ts +104 -0
  369. package/src/browser/fill-secret.ts +307 -0
  370. package/src/browser/managed-browser.ts +205 -0
  371. package/src/browser/registry.ts +110 -0
  372. package/src/browser/relay.ts +231 -0
  373. package/src/browser/sandbox-entry.ts +167 -0
  374. package/src/bundled-plugins/agent-browser/index.ts +2 -0
  375. package/src/bundled-plugins/browser-agent/browser-agent.ts +89 -0
  376. package/src/bundled-plugins/browser-agent/index.ts +12 -0
  377. package/src/bundled-plugins/doc-render/index.ts +0 -10
  378. package/src/bundled-plugins/doc-render/render.ts +83 -111
  379. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +152 -257
  380. package/src/bundled-plugins/explorer/explorer.ts +1 -1
  381. package/src/bundled-plugins/github-cli-auth/gh-command.ts +4 -0
  382. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
  383. package/src/bundled-plugins/github-cli-auth/git-auth-diagnostic.ts +95 -0
  384. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
  385. package/src/bundled-plugins/github-cli-auth/index.ts +85 -60
  386. package/src/bundled-plugins/managed-browser/index.ts +179 -0
  387. package/src/bundled-plugins/managed-browser/skills/browser-use/browser-use/SKILL.md +27 -0
  388. package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +28 -0
  389. package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +40 -0
  390. package/src/bundled-plugins/memory/dreaming.ts +4 -1
  391. package/src/bundled-plugins/memory/load-memory.ts +2 -4
  392. package/src/bundled-plugins/memory/memory-logger.ts +74 -2
  393. package/src/bundled-plugins/memory/transcript-preload.ts +103 -0
  394. package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
  395. package/src/bundled-plugins/operator/operator.ts +1 -1
  396. package/src/bundled-plugins/qa/index.ts +11 -0
  397. package/src/bundled-plugins/qa/qa.ts +160 -0
  398. package/src/bundled-plugins/qa/skills/qa-cli.ts +50 -0
  399. package/src/bundled-plugins/qa/skills/qa-general.ts +30 -0
  400. package/src/bundled-plugins/qa/skills/qa-http.ts +39 -0
  401. package/src/bundled-plugins/qa/skills/qa-pr.ts +51 -0
  402. package/src/bundled-plugins/qa/skills/qa-web.ts +49 -0
  403. package/src/bundled-plugins/security/index.ts +53 -34
  404. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  405. package/src/bundled-plugins/security/policies/private-surface-read.ts +166 -201
  406. package/src/channels/adapter-namespace.ts +13 -0
  407. package/src/channels/adapters/discord-bot-reference.ts +5 -4
  408. package/src/channels/adapters/discord-bot.ts +98 -5
  409. package/src/channels/adapters/discord-classify.ts +8 -3
  410. package/src/channels/adapters/discord.ts +29 -0
  411. package/src/channels/adapters/github/index.ts +16 -0
  412. package/src/channels/adapters/github/last-alive.ts +4 -16
  413. package/src/channels/adapters/slack-attachment-download.ts +14 -3
  414. package/src/channels/adapters/slack-bot-author-resolver.ts +4 -3
  415. package/src/channels/adapters/slack-bot-channel-resolver.ts +9 -6
  416. package/src/channels/adapters/slack-bot-classify.ts +1 -0
  417. package/src/channels/adapters/slack-bot-slash-commands.ts +3 -1
  418. package/src/channels/adapters/slack-bot.ts +299 -67
  419. package/src/channels/adapters/slack-classify.ts +1 -0
  420. package/src/channels/catch-up.ts +137 -0
  421. package/src/channels/continuation-willingness.ts +2 -2
  422. package/src/channels/continuity-types.ts +1 -0
  423. package/src/channels/engagement.ts +17 -1
  424. package/src/channels/github-false-receipt.ts +3 -3
  425. package/src/channels/github-rereview-guard.ts +9 -5
  426. package/src/channels/github-review-check.ts +5 -1
  427. package/src/channels/github-review-verdict-coordinator.ts +68 -2
  428. package/src/channels/github-token-bridge.ts +24 -0
  429. package/src/channels/last-alive.ts +34 -0
  430. package/src/channels/manager.ts +8 -1
  431. package/src/channels/router.ts +515 -243
  432. package/src/channels/session-handoff.fixture.ts +144 -0
  433. package/src/channels/session-handoff.ts +175 -0
  434. package/src/channels/session-search.ts +71 -0
  435. package/src/channels/subagent-completion-bridge.ts +3 -2
  436. package/src/channels/types.ts +12 -2
  437. package/src/cli/channel.ts +2 -3
  438. package/src/cli/hostd.ts +3 -0
  439. package/src/cli/init.ts +2 -3
  440. package/src/cli/model.ts +132 -3
  441. package/src/coding-agent/index.ts +7 -1
  442. package/src/coding-agent/omo-stream.ts +40 -0
  443. package/src/coding-agent/runner.ts +30 -8
  444. package/src/config/config.ts +126 -22
  445. package/src/config/model-overrides.ts +59 -0
  446. package/src/config/models-mutation.ts +185 -2
  447. package/src/config/providers-mutation.ts +12 -4
  448. package/src/config/providers.ts +69 -4
  449. package/src/container/start.ts +132 -5
  450. package/src/doctor/checks.ts +33 -22
  451. package/src/doctor/index.ts +48 -12
  452. package/src/doctor/operational-incidents.ts +16 -1
  453. package/src/doctor/plugin-bridge.ts +14 -1
  454. package/src/doctor/stage.ts +14 -0
  455. package/src/doctor/types.ts +6 -0
  456. package/src/eval/cell.ts +93 -0
  457. package/src/eval/config.ts +32 -0
  458. package/src/eval/dispatch.ts +67 -0
  459. package/src/eval/entry.ts +261 -0
  460. package/src/eval/kernel.ts +154 -0
  461. package/src/eval/process.ts +113 -0
  462. package/src/eval/protocol.ts +26 -0
  463. package/src/eval/redeclare.ts +174 -0
  464. package/src/eval/sandbox.ts +114 -0
  465. package/src/eval/tool.ts +98 -0
  466. package/src/eval/wire.ts +93 -0
  467. package/src/hostd/daemon.ts +13 -1
  468. package/src/init/auto-upgrade.ts +7 -1
  469. package/src/init/dockerfile.ts +57 -12
  470. package/src/init/index.ts +4 -3
  471. package/src/init/local-source-stamp.ts +68 -0
  472. package/src/init/models-dev.ts +4 -0
  473. package/src/init/validate-api-key.ts +3 -0
  474. package/src/operations/classify-tool-outcome.ts +1 -1
  475. package/src/permissions/builtins.ts +7 -0
  476. package/src/permissions/permissions.ts +18 -9
  477. package/src/permissions/resolve.ts +7 -1
  478. package/src/plugin/context.ts +2 -0
  479. package/src/plugin/core-tool-names.ts +6 -1
  480. package/src/plugin/hooks.ts +137 -0
  481. package/src/plugin/index.ts +6 -0
  482. package/src/plugin/manager.ts +4 -0
  483. package/src/plugin/types.ts +60 -0
  484. package/src/run/bundled-plugins.ts +6 -0
  485. package/src/run/index.ts +24 -14
  486. package/src/run/llm-fetch-observer.ts +12 -15
  487. package/src/sandbox/canonical-secrets.ts +4 -0
  488. package/src/sandbox/dev-source.ts +26 -0
  489. package/src/sandbox/env-exposure.ts +20 -0
  490. package/src/sandbox/hidden-paths.ts +16 -2
  491. package/src/secrets/storage.ts +13 -0
  492. package/src/server/index.ts +46 -11
  493. package/src/skills/typeclaw-channel-github/SKILL.md +8 -8
  494. package/src/skills/typeclaw-config/SKILL.md +57 -5
  495. package/src/skills/typeclaw-config/references/dockerfile.md +2 -2
  496. package/src/skills/typeclaw-github-contributing/SKILL.md +1 -1
  497. package/src/skills/typeclaw-monorepo/SKILL.md +1 -1
  498. package/src/skills/typeclaw-permissions/SKILL.md +7 -7
  499. package/src/skills/typeclaw-troubleshooting/SKILL.md +12 -1
  500. package/typeclaw.schema.json +488 -5
  501. package/src/bundled-plugins/doc-render/templates/lib.typ +0 -339
  502. package/src/bundled-plugins/github-cli-auth/gh-store.ts +0 -733
@@ -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'
@@ -34,24 +33,27 @@ import { SUBAGENT_OUTPUT_TOOL_NAME } from '@/agent/tools/subagent-output'
34
33
  import { promptPersistentTurnWithFallback } from '@/agent/turn-runner'
35
34
  import { type Command, type CommandPermission, type CommandResult, createCommandRegistry } from '@/commands'
36
35
  import { getConfig, resolveModel } from '@/config'
37
- import { CORE_PERMISSIONS, type PermissionService } from '@/permissions'
38
- import type { HookBus } from '@/plugin'
36
+ import { effectiveModels } from '@/config/model-overrides'
37
+ import { CORE_PERMISSIONS, type MatchableOrigin, type PermissionService } from '@/permissions'
38
+ import type { ChannelOutboundBeforeEvent, ChannelOutboundOrigin, HookBus } from '@/plugin'
39
39
  import { extractClaimCode } from '@/role-claim'
40
40
  import type { Stream } from '@/stream'
41
41
 
42
+ import { adapterNamespace } from './adapter-namespace'
42
43
  import { extractMentionedUserIds } from './adapters/mention-hints'
43
44
  import {
44
45
  BackgroundObligationStore,
45
46
  type BackgroundObligation,
46
47
  type BackgroundObligationRef,
47
48
  } from './background-obligations'
49
+ import { createInboundCatchUp, type ListMissedInbound } from './catch-up'
48
50
  import { formatChannelCommandHelp } from './commands'
49
51
  import { isQualifyingWorkResult } from './completion-claim'
50
52
  import { detectContinuationWillingness } from './continuation-willingness'
51
53
  import type { RecoveryFailure, RecoveryRecord } from './continuity-types'
52
54
  import { describeError } from './describe-error'
53
55
  import {
54
- countEffectiveHumans,
56
+ countEngagementHumans,
55
57
  decideEngagement,
56
58
  grantStickyForReplyTargets,
57
59
  isMultiHumanGroup,
@@ -109,6 +111,13 @@ import {
109
111
  type ReadCapability,
110
112
  type WriteCapability,
111
113
  } from './schema'
114
+ import { checkHandoffAccess, createSessionHandoff, type ChannelHandoffResult } from './session-handoff'
115
+ import {
116
+ createSessionSearch,
117
+ type SessionActivity,
118
+ type SessionSearchArgs,
119
+ type SessionSearchTarget,
120
+ } from './session-search'
112
121
  import type {
113
122
  ChannelHistoryMessage,
114
123
  ChannelKey,
@@ -243,6 +252,7 @@ export const SESSION_GC_INTERVAL_MS = 60 * 1000
243
252
  export const MAX_CHANNEL_SENDS_PER_TURN = 10
244
253
  export const ENGAGE_REACTION_EMOJI = 'eyes'
245
254
  export const CONTINUATION_REACTION_EMOJI = 'hourglass_flowing_sand'
255
+ export const QUEUED_REACTION_EMOJI = 'hourglass_flowing_sand'
246
256
  // Marks the triggering message of a turn that failed for a reason the user can
247
257
  // only answer by retrying, in place of a chat notice. Adapters that cannot
248
258
  // render it (GitHub's fixed set, reaction-less platforms) get the text notice.
@@ -394,7 +404,7 @@ export const EMPTY_TURN_RETRY_NUDGE = [
394
404
  // Reminder-only nudge for the stranded-toolUse-after-send retry. Distinct from
395
405
  // EMPTY_TURN_RETRY_NUDGE: that one diagnoses output-budget exhaustion and tells
396
406
  // the model to "answer directly", which makes a stranded investigation RE-RUN
397
- // its tools and strand again. Here the model already sent a `more_work_this_turn: true`
407
+ // its tools and strand again. Here the model already sent a `continue_after_reply: true`
398
408
  // status ack and did real tool work; the turn just ended on an unanswered
399
409
  // toolUse before final prose. The prior toolUse/toolResult entries are still in
400
410
  // this session's branch on the re-prompt, so the recovery is to STOP, read what
@@ -450,7 +460,7 @@ export const COLD_START_REPLY_NUDGE = [
450
460
  // both EMPTY_TURN_RETRY_NUDGE (which misdiagnoses a clean `stop` as output-budget
451
461
  // exhaustion and, per its own docstring, makes the model RE-RUN its tools and
452
462
  // strand again) and STRANDED_TOOLUSE_CONTINUATION_NUDGE (which assumes a
453
- // `more_work_this_turn: true` status reply already landed). Here NO send landed,
463
+ // `continue_after_reply: true` status reply already landed). Here NO send landed,
454
464
  // the model gathered real
455
465
  // tool results, then the final completion came back as a bare empty `stop` — the
456
466
  // Fireworks/gpt empty-completion degeneration. The recovery is to READ the results
@@ -478,7 +488,7 @@ export const EMPTY_STOP_AFTER_TOOL_WORK_NUDGE = [
478
488
  // is a one-shot correction offer, not recovery from no output.
479
489
  export const MAX_WILLINGNESS_NUDGES = 1
480
490
  // Injected when a reply that ended the turn (terminal-reply abort) promised to
481
- // keep working but omitted `more_work_this_turn: true`. Reminder-only, SYSTEM MESSAGE
491
+ // keep working but omitted `continue_after_reply: true`. Reminder-only, SYSTEM MESSAGE
482
492
  // framing so persona-rich models do not reply to the notice itself.
483
493
  // Leads with the DELIVERY imperative, mirroring SEND_WILLINGNESS_NUDGE below. An
484
494
  // earlier revision closed on a bare "If there is nothing left to do, reply with
@@ -493,13 +503,13 @@ export const WILLINGNESS_NUDGE = [
493
503
  '',
494
504
  'Your last reply promised the human you would keep working, but the turn ended',
495
505
  'right after sending — a successful channel reply ends the turn unless you set',
496
- '`more_work_this_turn: true` on it. This is an automated signal from the channel',
506
+ '`continue_after_reply: true` on it. This is an automated signal from the channel',
497
507
  'router, not a message from anyone in the chat. **Do not acknowledge or reply to',
498
508
  'this notice itself.**',
499
509
  '',
500
510
  'Someone is waiting on the result you just promised. Do the work now (fetch data,',
501
511
  'run a tool, spawn a subagent) and post what you find — and on any further status',
502
- 'reply that precedes more work this turn, set `more_work_this_turn: true`. If you',
512
+ 'reply that precedes more work this turn, set `continue_after_reply: true`. If you',
503
513
  'already did the work, post the conclusion you reached: having no work left is NOT',
504
514
  'the same as having nothing to report, and a promise that never lands reads to the',
505
515
  'human as being ignored.',
@@ -512,7 +522,7 @@ export const WILLINGNESS_NUDGE = [
512
522
  // did fresh work after it, then ended on an EMPTY `stop` leaf — the answer was
513
523
  // computed but never sent (the Kimi/Fireworks empty-completion flake). Distinct
514
524
  // from WILLINGNESS_NUDGE: that path is a `channel_reply` that ended the turn and
515
- // needs `more_work_this_turn: true`; this path is a `channel_send` (which never ends the
525
+ // needs `continue_after_reply: true`; this path is a `channel_send` (which never ends the
516
526
  // turn) whose follow-up degenerated, so the model just needs to emit the reply it
517
527
  // already worked out. Shares MAX_WILLINGNESS_NUDGES so a turn can't double-nudge.
518
528
  // Scopes NO_REPLY the same way WILLINGNESS_NUDGE does, and for the same reason:
@@ -550,38 +560,16 @@ export const SEND_RATE_WARN_THRESHOLD = 3
550
560
  export const OUTBOUND_FLOOD_ERROR = 'outbound message denied: content looks like a repeated-character flood'
551
561
 
552
562
  /**
553
- * Soft freshness boundary: the age of the last engaged inbound past which the
554
- * provider's server-side KV prompt-cache for this session's prefix is assumed
555
- * cold. Set to the LLM provider's KV-cache TTL (5 min) so a session reused
556
- * WITHIN this window is guaranteed a cache hit on the provider side.
557
- *
558
- * Reaching this boundary no longer forces an immediate rollover. Between the
559
- * soft boundary and SESSION_GRACE_HARD_TTL_MS, the live path defers to a
560
- * cost-aware grace decision (see `isGraceWorthReusing`): a session whose fixed
561
- * base context (rendered system prompt + injected memory + prefetched channel
562
- * context) still costs more to rebuild than its accumulated transcript is
563
- * reused for one more turn rather than torn down. This targets the common
564
- * channel shape — a human replying a few minutes past the cache TTL — where a
565
- * full cold-start rebuild of a large memory/index-mode base context dominates
566
- * the cost of carrying a modest transcript forward.
563
+ * Roll over only after more than 60 minutes without an engaged inbound.
564
+ * Continuity of an active conversation outweighs one cold prefix resend;
565
+ * compaction bounds the transcript carried by that resend.
567
566
  *
568
- * Unlike SESSION_IDLE_MS (which evicts the in-memory entry without rollover), a
569
- * rollover triggers a full tearDownLive + recreate on the next engaged inbound.
570
- * The old session's transcript is preserved on disk; only the in-memory live
571
- * entry and sessions.json pointer are replaced.
567
+ * SESSION_IDLE_MS (30 minutes) only evicts the in-memory entry: the next inbound
568
+ * within this freshness window rehydrates the same session file without rollover.
569
+ * A rollover tears down the live entry and replaces the sessions.json pointer;
570
+ * the old transcript remains on disk.
572
571
  */
573
- export const SESSION_FRESHNESS_TTL_MS = 5 * 60 * 1000
574
-
575
- /**
576
- * Hard ceiling on the cost-aware grace window. Past this age the live session is
577
- * rolled over unconditionally regardless of base-vs-transcript cost: the grace
578
- * decision only defers rollover, it never makes the session immortal. Bounding
579
- * grace at 2x the soft TTL keeps a never-quite-idle session from accumulating an
580
- * ever-growing, fully-uncached prefix (every turn past the soft boundary re-sends
581
- * the whole prefix at no provider-cache discount) and prevents grace from
582
- * silently becoming an unbounded TTL increase.
583
- */
584
- export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
572
+ export const SESSION_FRESHNESS_TTL_MS = 60 * 60 * 1000
585
573
 
586
574
  /**
587
575
  * Leak guard — NOT a freshness cap. A running background subagent pins its parent
@@ -605,37 +593,6 @@ export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
605
593
  */
606
594
  export const SESSION_CHILD_STUCK_BACKSTOP_MS = 6 * 60 * 60 * 1000
607
595
 
608
- /**
609
- * Cost-aware grace decision for the soft→hard TTL band. Returns true when reusing
610
- * the (now cache-cold) live session is cheaper than a fresh cold-start.
611
- *
612
- * After the soft TTL the provider prefix is cold either way, so the choice is:
613
- * - rollover: pay to rebuild the fixed base context (system prompt + memory +
614
- * prefetched context) plus a fresh first model call, OR
615
- * - reuse: re-send the cold base context PLUS the accumulated transcript.
616
- *
617
- * Rollover only wins once the transcript a reused session would carry forward
618
- * exceeds the base context a rollover would rebuild. We approximate both with the
619
- * session transcript file: `baseContextBytes` is its size captured right after
620
- * cold-start (the rendered prompt before any user turn), and the live delta is
621
- * the growth since. While `baseContextBytes > transcriptDeltaBytes`, the fixed
622
- * rebuild is the larger cost and grace is worth it. A `baseContextBytes` of 0
623
- * (no transcript path available) disables grace — fail closed to the prior
624
- * roll-over-at-soft-TTL behavior.
625
- */
626
- export function isGraceWorthReusing(baseContextBytes: number, transcriptDeltaBytes: number): boolean {
627
- if (baseContextBytes <= 0) return false
628
- return baseContextBytes > transcriptDeltaBytes
629
- }
630
-
631
- function defaultMeasureTranscriptBytes(path: string): number {
632
- try {
633
- return statSync(path).size
634
- } catch {
635
- return 0
636
- }
637
- }
638
-
639
596
  // Watchdog ceiling for ensureLive's full async chain (resolve names →
640
597
  // fetch membership → open session manager → persist mapping → prefetch
641
598
  // history). A legitimate cold-start completes in well under a second;
@@ -752,12 +709,17 @@ export type CreateSessionForChannel = (params: {
752
709
 
753
710
  export type ConfigForAdapter = (adapter: ChannelKey['adapter']) => ChannelAdapterConfig | undefined
754
711
 
712
+ export type { ChannelHandoffResult } from './session-handoff'
713
+
714
+ const CONVERSATION_ORIGIN_WINDOW_MS = 30 * 60_000
715
+
755
716
  type QueuedInbound = {
756
717
  inputId: string
757
718
  text: string
758
719
  referenceContext?: InboundReferenceContext
759
720
  attachments?: readonly InboundAttachment[]
760
721
  authorId: string
722
+ authorAdapter?: AdapterId
761
723
  authorName: string
762
724
  authorIsBot: boolean
763
725
  externalMessageId: string
@@ -777,6 +739,8 @@ type QueuedInbound = {
777
739
  ts: number
778
740
  githubReviewRound?: GithubReviewFollowupRound
779
741
  githubReviewThreadCloseout?: GithubReviewThreadCloseout
742
+ routingNote?: string
743
+ handoff?: true
780
744
  }
781
745
 
782
746
  type ObservedInbound = {
@@ -803,7 +767,7 @@ type ObservedInbound = {
803
767
  source: 'prefetch' | 'observed'
804
768
  }
805
769
 
806
- type TimedAttachment = { ts: number; attachment: InboundAttachment }
770
+ type TimedAttachment = { ts: number; attachment: InboundAttachment; current?: boolean }
807
771
 
808
772
  type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined }
809
773
 
@@ -867,6 +831,8 @@ type PendingReloadCoverage = {
867
831
  // Author context a completion-only wake needs for author-scoped role
868
832
  // resolution, exactly as the reloaded session would have restored it.
869
833
  lastTurnAuthorId: string | null
834
+ lastTurnAuthorAdapter: AdapterId
835
+ lastTurnHandoff: boolean
870
836
  lastTurnAuthorIds: string[]
871
837
  }
872
838
 
@@ -937,6 +903,10 @@ type LiveSession = {
937
903
  })
938
904
  | null
939
905
  githubReviewThreadCloseoutDecisionTurn: number | null
906
+ // When this session last resolved its review thread. A reply written before
907
+ // that resolution was already answered by it, so it must not re-arm the
908
+ // close-out obligation and force a duplicate reply or the canned fallback.
909
+ githubReviewThreadResolvedAt: { rootCommentId: string; at: number } | null
940
910
  // Round key of a close-out that arrived while the round was still pending
941
911
  // completion. Replayed once the round completes; see replayPendingRoundCloseouts.
942
912
  pendingGithubReviewRoundCloseout: string | null
@@ -949,18 +919,10 @@ type LiveSession = {
949
919
  // are empty. This turn-scoped snapshot, populated right after the splice
950
920
  // and cleared when the turn ends, is what the lookup reads so a freshly-
951
921
  // arrived attachment stays resolvable for the whole turn it belongs to.
952
- currentTurnAttachments: readonly InboundAttachment[]
953
- // Refs from an explicit channel_history look-back. A prior-turn attachment is
954
- // replayed to the model as a text placeholder but its ref is gone from every
955
- // turn-scoped queue above, so look_at/fetch can't resolve it; stashing the
956
- // fetched refs here makes the same `attachment_id: N` resolvable. MUST be
957
- // searched LAST so a live `#1` still wins over a historical `#1` (the
958
- // newest-first collision rule lookupInboundAttachment documents). Bounded,
959
- // never persisted, never exposes the ref to the model. historyTimedAttachments
960
- // is the ts-tagged source of truth (ordered oldest→newest, deduped by id);
961
- // historyAttachments is its flat projection consumed by the lookup helpers.
922
+ currentTurnAttachments: readonly TimedAttachment[]
923
+ // Message-local numbers may collide. Keep timestamped history refs so an
924
+ // observed old #1 cannot shadow a newer file discovered through history.
962
925
  historyTimedAttachments: readonly TimedAttachment[]
963
- historyAttachments: InboundAttachment[]
964
926
  draining: boolean
965
927
  // Every drain invocation still running, including the tail it executes after
966
928
  // `draining` flips back to false. `drain()` deliberately no-ops while a drain
@@ -986,14 +948,10 @@ type LiveSession = {
986
948
  // leaks a timer that fires past the turn's end.
987
949
  promptInFlight: boolean
988
950
  lastInboundAt: number
989
- // Transcript-file size (bytes) captured immediately after cold-start, before
990
- // any user turn — a proxy for the fixed base-context rebuild cost (rendered
991
- // system prompt + injected memory + prefetched channel context). Read by the
992
- // soft-TTL grace decision against the current transcript size to weigh reuse
993
- // vs rollover. 0 when no transcript path is available, which disables grace.
994
- baseContextBytes: number
951
+ recentMessages: SessionActivity[]
995
952
  firstUnprocessedAt: number
996
953
  currentTurnAuthorId: string | null
954
+ currentTurnAuthorAdapter: AdapterId
997
955
  currentTurnAuthorIds: Set<string>
998
956
  // Reaction target of the inbound that triggered THIS turn (the last item in
999
957
  // the drained batch, mirroring `currentTurnAuthorId`). Surfaced on the live
@@ -1012,6 +970,13 @@ type LiveSession = {
1012
970
  // and target cannot disagree. Reset with `currentTurnReactionRef` in the drain
1013
971
  // finally; preserved across reminder-only iterations exactly like it.
1014
972
  currentTurnExplicitlyAddressed: boolean
973
+ // True when THIS turn's batch carries a cross-session handoff inbound. The
974
+ // handoff loop guard: a handoff-started turn cannot hand off again.
975
+ currentTurnHandoff: boolean
976
+ // Whether the most recent inbound was private, for handoff context framing.
977
+ lastInboundIsDm: boolean
978
+ // Hint each recently visited conversation only once in this session.
979
+ originHintedKeys: Set<string>
1015
980
  // Typing-status anchor of the inbound that triggered THIS turn (last item in
1016
981
  // the drained batch, mirroring `currentTurnReactionRef`). Adapter-opaque ts
1017
982
  // carried only to the typing path; null when the triggering inbound supplied
@@ -1053,6 +1018,8 @@ type LiveSession = {
1053
1018
  // inserted into Set"), so a multi-author prior turn like alice→bob
1054
1019
  // restores `bob`, the same identity normal turns would have used.
1055
1020
  lastTurnAuthorId: string | null
1021
+ lastTurnAuthorAdapter: AdapterId
1022
+ lastTurnHandoff: boolean
1056
1023
  consecutiveAborts: number
1057
1024
  // Per-(chat:thread) count of bot messages sent without intervening user
1058
1025
  // input being rendered into the model's context. Reset at the top of each
@@ -1100,7 +1067,7 @@ type LiveSession = {
1100
1067
  // channel send landed this turn. `validateChannelTurn` compares it to the
1101
1068
  // turn-end leaf: a DIFFERENT assistant `stop` leaf means the model replied,
1102
1069
  // kept working, then ended with FRESH final prose it forgot to deliver
1103
- // (the `more_work_this_turn: true` progress-reply bug) — recover it. A leaf that still
1070
+ // (the `continue_after_reply: true` progress-reply bug) — recover it. A leaf that still
1104
1071
  // matches is narration the model emitted BEFORE/with the reply that already
1105
1072
  // landed, so it stays suppressed. Reset to null on every new prompt batch.
1106
1073
  lastSendLeafId: string | null
@@ -1190,7 +1157,7 @@ type LiveSession = {
1190
1157
  // nudge itself queues — same anti-reloop discipline as the empty-turn budget.
1191
1158
  willingnessNudges: number
1192
1159
  // Stashed by `installChannelReplyTerminalHook` after a successful
1193
- // `channel_reply` that omitted `more_work_this_turn: true`. Read once
1160
+ // `channel_reply` that omitted `continue_after_reply: true`. Read once
1194
1161
  // by `validateChannelTurn` to decide the continuation nudge. `turnSeq`-stamped
1195
1162
  // (like `skippedTurn`/`skipLockedSendTurn`) so a stale record from an earlier
1196
1163
  // turn can never trigger a nudge on a later one. `null` when no such reply
@@ -1204,7 +1171,7 @@ type LiveSession = {
1204
1171
  // assistant. Cleared on consumption, stop, or a fresh user turn.
1205
1172
  pendingTerminalReplyStop: { turnSeq: number; tokens: number } | null
1206
1173
  // Stamped by `installChannelReplyTerminalHook` when a successful `channel_reply`
1207
- // set `more_work_this_turn: true` — the machine-readable "I'll keep working this turn"
1174
+ // set `continue_after_reply: true` — the machine-readable "I'll keep working this turn"
1208
1175
  // promise. `validateChannelTurn` reads it to recover a turn that made that promise,
1209
1176
  // did more work, then ended on a fresh empty `stop` (dropped its conclusion) —
1210
1177
  // independent of what natural-language phrase the ack used, so a persona speaking
@@ -1271,7 +1238,7 @@ type LiveSession = {
1271
1238
  emptyTurnFallbackTurn: number | null
1272
1239
  // Set when a WILLINGNESS-ACK exhaustion path (empty_stop_after_continue_reply /
1273
1240
  // empty_stop_after_send_ack) would post EMPTY_TURN_FALLBACK_TEXT, but the model
1274
- // just made a machine-readable promise to keep working (`more_work_this_turn: true` /
1241
+ // just made a machine-readable promise to keep working (`continue_after_reply: true` /
1275
1242
  // willingness phrase) and did post-ack tool work. Rather than posting the scary
1276
1243
  // "I got stuck" notice synchronously at validateChannelTurn — BEFORE the drain
1277
1244
  // loop runs maybeContinueTodosChannel, which can re-prompt the same logical turn
@@ -1330,7 +1297,7 @@ type LiveSession = {
1330
1297
  // this logical turn. Unlike toolExecutionThisLogicalTurn, channel_reply and
1331
1298
  // todo/control calls cannot satisfy a later durable completion claim.
1332
1299
  qualifyingWorkThisLogicalTurn: boolean
1333
- // True while a successful `channel_reply({ more_work_this_turn: true })`
1300
+ // True while a successful `channel_reply({ continue_after_reply: true })`
1334
1301
  // promise remains unfulfilled in this LOGICAL turn. Unlike the per-iteration
1335
1302
  // `continueReplyTurn` stamp used by retry authorization and empty-stop
1336
1303
  // recovery, this survives reminder-only iterations so a provider failure
@@ -1343,7 +1310,7 @@ type LiveSession = {
1343
1310
  // True while the latest landed output accounted to this logical turn was a
1344
1311
  // continuation-willingness/status message ("I'll check and get back to you"):
1345
1312
  // the turn told the user more was coming without the machine-readable
1346
- // `more_work_this_turn` flag. A substantive send clears it; meta notices
1313
+ // `continue_after_reply` flag. A substantive send clears it; meta notices
1347
1314
  // (provider error, fallbacks) leave it. Together with
1348
1315
  // `promisedWorkOutstandingThisLogicalTurn` it marks promised unfinished work,
1349
1316
  // which explicit silence can never settle. Reset with the logical turn.
@@ -1466,8 +1433,13 @@ export type SendOptions = TransportSendOptions & {
1466
1433
  // set it explicitly because recovery prose fulfills promised work whereas
1467
1434
  // provider/fallback/control notices are meta output and must not.
1468
1435
  outputKind?: 'substantive' | 'status' | 'meta'
1436
+ // Runtime-owned provenance; never populated from model tool arguments.
1437
+ origin?: ChannelOutboundOrigin
1469
1438
  }
1470
1439
 
1440
+ export type EditMessageOptions = { origin?: ChannelOutboundOrigin }
1441
+ export type ChannelOutboundReviewer = (event: ChannelOutboundBeforeEvent) => Promise<{ text: string }>
1442
+
1471
1443
  export const DUPLICATE_SEND_ERROR =
1472
1444
  'Duplicate not sent. Do not call channel_send/channel_reply again this turn. ' +
1473
1445
  'End with NO_REPLY unless you have genuinely new, non-redundant information.'
@@ -1482,6 +1454,11 @@ export const SKIP_RESPONSE_LOCK_ERROR =
1482
1454
  'something to say, send it on the next turn.'
1483
1455
 
1484
1456
  export type ChannelRouter = {
1457
+ registerMissedInbound: (adapter: AdapterId, callback: ListMissedInbound) => void
1458
+ unregisterMissedInbound: (adapter: AdapterId, callback: ListMissedInbound) => void
1459
+ catchUp: (adapter: AdapterId) => Promise<void>
1460
+ disconnectCatchUp: (adapter: AdapterId) => void
1461
+ catchUpTargets: (adapter: AdapterId) => Promise<readonly ChannelKey[]>
1485
1462
  route: (event: InboundMessage, onAdmitted?: () => Promise<void>) => Promise<RouteReceipt>
1486
1463
  send: (msg: OutboundMessage, opts?: SendOptions) => Promise<SendResult>
1487
1464
  acceptBackgroundResponse: (args: {
@@ -1602,7 +1579,11 @@ export type ChannelRouter = {
1602
1579
  // send()'s flood/cap/dup/sticky guards.
1603
1580
  registerEditMessage: (adapter: ChannelKey['adapter'], cb: EditMessageCallback) => void
1604
1581
  unregisterEditMessage: (adapter: ChannelKey['adapter'], cb: EditMessageCallback) => void
1605
- editMessage: (req: EditMessageRequest) => Promise<EditMessageResult>
1582
+ editMessage: (req: EditMessageRequest, opts?: EditMessageOptions) => Promise<EditMessageResult>
1583
+ // Direct adapter control responses use the same transform without entering
1584
+ // send accounting, sticky engagement or turn-completion bookkeeping.
1585
+ reviewOutbound: (event: ChannelOutboundBeforeEvent) => Promise<string>
1586
+ hasOutboundReviewer: () => boolean
1606
1587
  registerFetchAttachment: (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback) => void
1607
1588
  unregisterFetchAttachment: (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback) => void
1608
1589
  fetchAttachment: (adapter: ChannelKey['adapter'], args: FetchAttachmentArgs) => Promise<FetchAttachmentResult>
@@ -1623,7 +1604,7 @@ export type ChannelRouter = {
1623
1604
  registerReviewSubmitter: (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter) => void
1624
1605
  unregisterReviewSubmitter: (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter) => void
1625
1606
  submitReview: (req: SubmitReviewRequest) => Promise<SubmitReviewResult>
1626
- lookupInboundAttachment: (args: ChannelKey & { id: number }) => InboundAttachment | null
1607
+ lookupInboundAttachment: (args: ChannelKey & { id: number; ref?: string }) => InboundAttachment | null
1627
1608
  listInboundAttachmentIds: (args: ChannelKey) => readonly number[]
1628
1609
  // Stash refs from a channel_history fetch so prior-turn attachments stay
1629
1610
  // resolvable by their placeholder id. Called by the channel_history tool
@@ -1657,6 +1638,12 @@ export type ChannelRouter = {
1657
1638
  // session was found and the reminder was queued, `no-live-session`
1658
1639
  // otherwise. Used by the subagent-completion bridge in
1659
1640
  // src/run/index.ts; safe for tests to call directly via a fake router.
1641
+ // Delegate work to the live session that owns `target` on any adapter instead of
1642
+ // posting there blind. Routed as a synthetic inbound authored by the source
1643
+ // turn's requester, so it queues behind any running turn and re-checks the
1644
+ // requester's target role without linking identities across platforms.
1645
+ handoff: (args: { fromSessionId: string; target: ChannelKey; text: string }) => Promise<ChannelHandoffResult>
1646
+ searchSessions: (args: SessionSearchArgs) => SessionSearchTarget[]
1660
1647
  injectSubagentCompletionReminder: (args: {
1661
1648
  parentSessionId: string
1662
1649
  subagent: string
@@ -1837,10 +1824,6 @@ export type CreateChannelRouterOptions = {
1837
1824
  // random/timer mutation. Production defaults remain Math.random and no hook.
1838
1825
  retryRandom?: () => number
1839
1826
  onRetryBackoffStart?: () => void
1840
- // Test seam: measure a transcript file's byte size for the soft-TTL grace
1841
- // decision. Defaults to a stat()-based reader returning 0 for a missing or
1842
- // unreadable file (grace then fails closed to roll-over-at-soft-TTL).
1843
- measureTranscriptBytes?: (path: string) => number
1844
1827
  // Test seam: the idle/todo continuation driver, invoked from
1845
1828
  // maybeContinueTodosChannel AFTER validateChannelTurn. Defaults to the real
1846
1829
  // runIdleContinuation. Injecting it lets a test deliver the continuation at the
@@ -1930,6 +1913,8 @@ export type CreateChannelRouterOptions = {
1930
1913
  workKey: string,
1931
1914
  reason: string,
1932
1915
  ) => Promise<{ matched: number; cancelled: number; failures: number }>
1916
+ reviewOutbound?: ChannelOutboundReviewer
1917
+ outboundReviewerActive?: () => boolean
1933
1918
  }
1934
1919
 
1935
1920
  export type RestartCommandContext = {
@@ -1984,7 +1969,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1984
1969
  const recoveryOutbox =
1985
1970
  options.recoveryOutbox ?? new RecoveryOutbox(options.agentDir, { epoch: backgroundObligations.epoch })
1986
1971
  void ready.catch((error) => logger.error(`[channels] inbound journal initialization failed: ${describeError(error)}`))
1987
- const measureTranscriptBytes = options.measureTranscriptBytes ?? defaultMeasureTranscriptBytes
1988
1972
  const ensureLiveTimeoutMs = options.ensureLiveTimeoutMs ?? ENSURE_LIVE_TIMEOUT_MS
1989
1973
  const handoffRetryRetentionMs = options.handoffRetryRetentionMs ?? RELOAD_HANDOFF_RETENTION_MS
1990
1974
  const handoffRetryItemLimit = options.handoffRetryItemLimit ?? MAX_PENDING_RELOAD_HANDOFF_ITEMS_PER_KEY
@@ -2412,22 +2396,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2412
2396
  if (live.draining) return false
2413
2397
  if (isPinnedByRunningChild(live.sessionId, live.keyId, 'stale-rollover')) return false
2414
2398
  if (idleMs <= SESSION_FRESHNESS_TTL_MS) return false
2415
- if (idleMs > SESSION_GRACE_HARD_TTL_MS) {
2416
- logger.info(`[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle, past grace cap)`)
2417
- return true
2418
- }
2419
- const transcriptPath = live.getTranscriptPath?.()
2420
- const transcriptBytes = transcriptPath !== undefined ? measureTranscriptBytes(transcriptPath) : 0
2421
- const transcriptDeltaBytes = Math.max(0, transcriptBytes - live.baseContextBytes)
2422
- if (isGraceWorthReusing(live.baseContextBytes, transcriptDeltaBytes)) {
2423
- logger.info(
2424
- `[channels] ${live.keyId}: grace-reuse (live: ${idleMs}ms idle, base=${live.baseContextBytes}B delta=${transcriptDeltaBytes}B)`,
2425
- )
2426
- return false
2427
- }
2428
- logger.info(
2429
- `[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle, base=${live.baseContextBytes}B delta=${transcriptDeltaBytes}B)`,
2430
- )
2399
+ logger.info(`[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle)`)
2431
2400
  return true
2432
2401
  }
2433
2402
 
@@ -2694,6 +2663,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2694
2663
  coverageDeferredParentSessionId: live.coverageDeferredParentSessionId,
2695
2664
  ...(live.turnAccountIdentity !== undefined ? { turnAccountIdentity: live.turnAccountIdentity } : {}),
2696
2665
  lastTurnAuthorId: live.lastTurnAuthorId,
2666
+ lastTurnAuthorAdapter: live.lastTurnAuthorAdapter,
2667
+ lastTurnHandoff: live.lastTurnHandoff,
2697
2668
  lastTurnAuthorIds: [...live.lastTurnAuthorIds],
2698
2669
  })
2699
2670
 
@@ -2938,6 +2909,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2938
2909
  if (coverage.turnAccountIdentity !== undefined) live.turnAccountIdentity = coverage.turnAccountIdentity
2939
2910
  if (live.lastTurnAuthorId === null && coverage.lastTurnAuthorId !== null) {
2940
2911
  live.lastTurnAuthorId = coverage.lastTurnAuthorId
2912
+ live.lastTurnAuthorAdapter = coverage.lastTurnAuthorAdapter
2913
+ live.lastTurnHandoff = coverage.lastTurnHandoff
2941
2914
  live.lastTurnAuthorIds = new Set(coverage.lastTurnAuthorIds)
2942
2915
  }
2943
2916
  }
@@ -2951,7 +2924,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2951
2924
  // Restart-resume only: force rehydration of this exact (sessionId,
2952
2925
  // sessionFile) and bypass stale-rollover, so the originating session's
2953
2926
  // `typeclaw.restart-self` entry is reopened rather than rolled into a fresh
2954
- // session (a restart easily outlasts SESSION_FRESHNESS_TTL_MS). The mapping
2927
+ // session, even if the restart outlasts SESSION_FRESHNESS_TTL_MS. The mapping
2955
2928
  // is persisted only through the normal success path below — no pre-mutation
2956
2929
  // — so a reopen failure leaves the durable mapping untouched.
2957
2930
  resumeTarget?: { sessionId: string; sessionFile: string },
@@ -2973,7 +2946,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2973
2946
  adoptPendingReloadHandoff(existing)
2974
2947
  return existing
2975
2948
  }
2976
- // Rollover decision (soft TTL → cost-aware grace → hard cap) lives in
2949
+ // The 60-minute idle rollover decision lives in
2977
2950
  // shouldRolloverLive, which also skips draining sessions so a mid-prompt
2978
2951
  // turn is never aborted by a follow-up's idle check (PR #359 incident).
2979
2952
  const idleMs = now() - existing.lastInboundAt
@@ -3218,7 +3191,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3218
3191
  keyId,
3219
3192
  room,
3220
3193
  session: created.session,
3221
- activeModelRef: resolveFallbackChain(getConfig().models, undefined)[0]!,
3194
+ activeModelRef: resolveFallbackChain(effectiveModels(getConfig(), origin), undefined)[0]!,
3222
3195
  turnThinkingDefault: created.session.thinkingLevel,
3223
3196
  lastQuestionSignal: null,
3224
3197
  pendingUserTurnSignal: null,
@@ -3240,6 +3213,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3240
3213
  deferred: true,
3241
3214
  },
3242
3215
  githubReviewThreadCloseoutDecisionTurn: null,
3216
+ githubReviewThreadResolvedAt: null,
3243
3217
  pendingGithubReviewRoundCloseout: null,
3244
3218
  promptQueue: [],
3245
3219
  pendingSystemReminders: [],
@@ -3252,7 +3226,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3252
3226
  contextBuffer: [],
3253
3227
  currentTurnAttachments: [],
3254
3228
  historyTimedAttachments: [],
3255
- historyAttachments: [],
3256
3229
  draining: false,
3257
3230
  activeDrains: new Set(),
3258
3231
  debounceTimer: null,
@@ -3263,12 +3236,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3263
3236
  typingEpoch: 0,
3264
3237
  promptInFlight: false,
3265
3238
  lastInboundAt: now(),
3266
- baseContextBytes: 0,
3267
3239
  firstUnprocessedAt: 0,
3268
3240
  currentTurnAuthorId: null,
3241
+ recentMessages: [],
3242
+ currentTurnAuthorAdapter: key.adapter,
3269
3243
  currentTurnAuthorIds: new Set(),
3270
3244
  currentTurnReactionRef: null,
3271
3245
  currentTurnExplicitlyAddressed: false,
3246
+ currentTurnHandoff: false,
3247
+ lastInboundIsDm: false,
3248
+ originHintedKeys: new Set(),
3272
3249
  currentTurnTypingThread: null,
3273
3250
  dirtyTypingThreads: new Set(),
3274
3251
  currentTurnEngageReactions: [],
@@ -3287,6 +3264,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3287
3264
  // stay in sync, so they are written in the same statement.
3288
3265
  lastTurnAuthorIds: triggeringAuthorId !== undefined ? new Set([triggeringAuthorId]) : new Set(),
3289
3266
  lastTurnAuthorId: triggeringAuthorId ?? null,
3267
+ lastTurnAuthorAdapter: key.adapter,
3268
+ lastTurnHandoff: false,
3290
3269
  consecutiveAborts: 0,
3291
3270
  consecutiveSends: new Map(),
3292
3271
  lastSentText: new Map(),
@@ -3454,15 +3433,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3454
3433
  liveSessions.set(keyId, live)
3455
3434
  }
3456
3435
 
3457
- // Snapshot the rendered base context size now, after prefetch and before
3458
- // any user turn, so the soft-TTL grace decision can later compare it
3459
- // against transcript growth. Only meaningful on cold-start (a rehydrated
3460
- // session's file already holds prior conversation, not a clean base).
3461
- const transcriptPathForBase = live.getTranscriptPath?.()
3462
- if (isColdStart && transcriptPathForBase !== undefined) {
3463
- live.baseContextBytes = measureTranscriptBytes(transcriptPathForBase)
3464
- }
3465
-
3466
3436
  if (!isLatestCreation()) {
3467
3437
  await unwindInstalledLive(keyId, live)
3468
3438
  throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
@@ -3499,8 +3469,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3499
3469
  ): Promise<void> => {
3500
3470
  const prefetch = adapterConfig.history.prefetch
3501
3471
  const isThread = live.key.thread !== null
3502
- const head = isThread ? prefetch.thread.head : 0
3503
- const tail = isThread ? prefetch.thread.tail : prefetch.channel.tail
3472
+ let head = isThread ? prefetch.thread.head : 0
3473
+ let tail = isThread ? prefetch.thread.tail : prefetch.channel.tail
3504
3474
  if (head === 0 && tail === 0) return
3505
3475
 
3506
3476
  // One fetch per cold start. We always pass the live thread when present so
@@ -3535,10 +3505,33 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3535
3505
  // "Recent context" and once in "Current message". Adapters typically
3536
3506
  // return the latest channel/thread messages, so this overlap is the
3537
3507
  // common case, not the edge case.
3538
- const filteredMessages =
3508
+ let filteredMessages =
3539
3509
  triggeringMessageId !== undefined
3540
3510
  ? result.messages.filter((m) => m.externalMessageId !== triggeringMessageId)
3541
3511
  : result.messages
3512
+ let fromParentChannel = false
3513
+
3514
+ // A thread rooted at the triggering message (a top-level mention the bot
3515
+ // answers in-thread) has no history of its own yet, so the thread fetch
3516
+ // seeds nothing and the agent starts blind to what was just said in the
3517
+ // channel, including its own recent posts. Seed from the channel tail.
3518
+ if (filteredMessages.length === 0 && isThread && live.key.thread === triggeringMessageId) {
3519
+ tail = prefetch.channel.tail
3520
+ if (tail === 0) return
3521
+ head = 0
3522
+ const channelResult = await fetchHistory(live.key.adapter, {
3523
+ chat: live.key.chat,
3524
+ thread: null,
3525
+ limit: tail + 1,
3526
+ prefetch: true,
3527
+ })
3528
+ if (!channelResult.ok) {
3529
+ logger.info(`[channels] ${live.keyId}: channel prefetch fallback skipped (${channelResult.error})`)
3530
+ return
3531
+ }
3532
+ filteredMessages = channelResult.messages.filter((m) => m.externalMessageId !== triggeringMessageId)
3533
+ fromParentChannel = true
3534
+ }
3542
3535
  if (filteredMessages.length === 0) return
3543
3536
 
3544
3537
  const seeded = sliceHeadTail(filteredMessages, head, tail)
@@ -3577,6 +3570,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3577
3570
  // normal. We push into contextBuffer (not promptQueue) because these are
3578
3571
  // background context for the model, not turns it must respond to.
3579
3572
  live.contextBuffer.push(...observed)
3573
+ // Persisted participants only include authors routed since the session went
3574
+ // live, so a cold-started thread would undercount humans who spoke earlier
3575
+ // and lose them once the context buffer drains. Record the thread's own
3576
+ // historical human speakers; parent-channel seeds are not thread members.
3577
+ if ((isThread || live.room?.kind === 'thread') && !fromParentChannel) {
3578
+ for (const item of observed) {
3579
+ if (item.authorIsBot || live.participants.some((p) => p.authorId === item.authorId)) continue
3580
+ live.participants = updateParticipants(live.participants, item.authorId, item.authorName, now(), false)
3581
+ }
3582
+ }
3580
3583
  logger.info(`[channels] ${live.keyId}: prefetched ${observed.length} context messages`)
3581
3584
  }
3582
3585
 
@@ -3739,12 +3742,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3739
3742
  // tools and `channel_send` must keep the follow-up so genuine multi-step turns
3740
3743
  // continue. A prior non-typeclaw `afterToolCall` (none today) is composed.
3741
3744
  //
3742
- // `channel_reply({ more_work_this_turn: true })` is the explicit opt-out: a
3745
+ // `channel_reply({ continue_after_reply: true })` is the explicit opt-out: a
3743
3746
  // mid-turn status reply ("working on it…") that the model follows with more
3744
3747
  // work this turn. The tool surfaces that intent as
3745
- // `details.more_work_this_turn === true`, and we keep the follow-up so the turn
3748
+ // `details.continue_after_reply === true`, and we keep the follow-up so the turn
3746
3749
  // proceeds. The kimi 32k loop only recurs when the model genuinely has nothing
3747
- // left to say after a reply, which `more_work_this_turn` asserts is not the
3750
+ // left to say after a reply, which `continue_after_reply` asserts is not the
3748
3751
  // case; Layer 2's maxTokens cap still bounds any misuse.
3749
3752
  // IDs are cache hints, never generation authority. Call only inside the lane.
3750
3753
  const resolveBackgroundCoverage = async (
@@ -3880,7 +3883,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3880
3883
  const details = context.result.details as
3881
3884
  | {
3882
3885
  ok?: unknown
3883
- more_work_this_turn?: unknown
3886
+ continue_after_reply?: unknown
3884
3887
  backgroundCoverage?: BackgroundObligationRef[]
3885
3888
  inboundCoverage?: InboundRef[]
3886
3889
  }
@@ -3895,11 +3898,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3895
3898
  live.qualifyingWorkThisLogicalTurn = true
3896
3899
  }
3897
3900
  const succeeded = context.toolCall.name === 'channel_reply' && !context.isError && details?.ok === true
3898
- const keepTurnAlive = details?.more_work_this_turn === true
3901
+ const keepTurnAlive = details?.continue_after_reply === true
3899
3902
  if (succeeded) {
3900
3903
  // This hook is authoritative for channel_reply semantics: the send path
3901
3904
  // cannot distinguish channel_reply from channel_send, but here the
3902
- // explicit more_work_this_turn flag tells us whether the delivered reply
3905
+ // explicit continue_after_reply flag tells us whether the delivered reply
3903
3906
  // renewed the promise or terminally fulfilled it.
3904
3907
  const text = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
3905
3908
  if (!keepTurnAlive && !promisesUnfinishedWork(live, text)) {
@@ -4377,6 +4380,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4377
4380
  ...(live.room?.parentChat !== undefined ? { parentChat: live.room.parentChat } : {}),
4378
4381
  ...(live.room?.parentChatName !== undefined ? { parentChatName: live.room.parentChatName } : {}),
4379
4382
  ...(live.currentTurnAuthorId !== null ? { lastInboundAuthorId: live.currentTurnAuthorId } : {}),
4383
+ ...(live.currentTurnAuthorAdapter !== live.key.adapter
4384
+ ? { lastInboundAuthorAdapter: live.currentTurnAuthorAdapter }
4385
+ : {}),
4380
4386
  ...(live.currentTurnReactionRef !== null ? { reactionRef: live.currentTurnReactionRef } : {}),
4381
4387
  participants: live.participants,
4382
4388
  ...(membership !== null ? { membership } : {}),
@@ -4834,7 +4840,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4834
4840
  }
4835
4841
 
4836
4842
  // The logical turn told the user more was coming and has not delivered it: a
4837
- // `more_work_this_turn: true` reply, or a landed status/continuation message
4843
+ // `continue_after_reply: true` reply, or a landed status/continuation message
4838
4844
  // that no substantive output followed. Silence cannot answer such a promise.
4839
4845
  const owesPromisedWork = (live: LiveSession): boolean =>
4840
4846
  live.promisedWorkOutstandingThisLogicalTurn || live.statusOutputOutstandingThisLogicalTurn
@@ -5412,6 +5418,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5412
5418
  // which skip this branch.
5413
5419
  live.pendingProviderError = null
5414
5420
  live.currentTurnAuthorId = batch[batch.length - 1]!.authorId
5421
+ live.currentTurnAuthorAdapter = batch[batch.length - 1]!.authorAdapter ?? live.key.adapter
5415
5422
  live.currentTurnAuthorIds = new Set(batch.map((m) => m.authorId))
5416
5423
  live.currentTurnReactionRef = batch[batch.length - 1]!.reactionRef ?? null
5417
5424
  const trigger = batch[batch.length - 1]!
@@ -5420,6 +5427,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5420
5427
  }
5421
5428
  live.currentTurnExplicitlyAddressed =
5422
5429
  trigger.isDm || trigger.isBotMention || trigger.replyToBotMessageId !== null
5430
+ live.currentTurnHandoff = batch.some((m) => m.handoff === true)
5423
5431
  live.currentTurnTypingThread = batch[batch.length - 1]!.typingThread ?? null
5424
5432
  live.currentTurnEngageReactions = batch.flatMap((m) =>
5425
5433
  m.engageReaction !== undefined ? [m.engageReaction] : [],
@@ -5427,7 +5435,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5427
5435
  live.consecutiveSends.clear()
5428
5436
  live.lastSentText.clear()
5429
5437
  live.lastSendLeafId = null
5430
- live.pendingQuoteCandidate = captureQuoteCandidate(live.key.adapter, batch, observed)
5438
+ live.pendingQuoteCandidate = captureQuoteCandidate(
5439
+ live.key.adapter,
5440
+ // A handoff inbound has no platform message to quote or reply to.
5441
+ batch.filter((m) => m.handoff !== true),
5442
+ observed,
5443
+ )
5431
5444
  // A real user batch starts a fresh logical turn → restore the full
5432
5445
  // empty-turn retry budget and drop any raised output-token budget left
5433
5446
  // over from a prior turn's length-retry. Reset here (batch.length > 0)
@@ -5439,18 +5452,43 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5439
5452
  live.emptyStopAfterToolWorkArmed = false
5440
5453
  live.willingnessNudges = 0
5441
5454
  live.logicalTurnStartedAt = now()
5442
- const stampedCloseout = batch.findLast((item) => item.githubReviewThreadCloseout !== undefined)
5455
+ const latestStampedCloseout = batch.findLast((item) => item.githubReviewThreadCloseout !== undefined)
5456
+ const resolvedAt = live.githubReviewThreadResolvedAt
5457
+ const alreadyResolved =
5458
+ latestStampedCloseout?.githubReviewThreadCloseout !== undefined &&
5459
+ resolvedAt !== null &&
5460
+ resolvedAt.rootCommentId === latestStampedCloseout.githubReviewThreadCloseout.rootCommentId &&
5461
+ latestStampedCloseout.ts > 0 &&
5462
+ latestStampedCloseout.ts <= resolvedAt.at
5463
+ if (alreadyResolved) {
5464
+ logger.info(
5465
+ `[channels] ${live.keyId} github_thread_closeout_already_resolved root=${resolvedAt?.rootCommentId} reply_ts=${latestStampedCloseout?.ts} resolved_at=${resolvedAt?.at}`,
5466
+ )
5467
+ }
5468
+ const stampedCloseout = alreadyResolved ? undefined : latestStampedCloseout
5443
5469
  const deferredCloseout =
5444
5470
  stampedCloseout?.githubReviewThreadCloseout === undefined &&
5445
5471
  live.githubReviewThreadCloseout !== null &&
5446
5472
  live.githubReviewThreadCloseout.deferred
5447
5473
  ? live.githubReviewThreadCloseout
5448
5474
  : null
5475
+ // A follow-up on a thread whose close-out is still open continues the
5476
+ // same obligation. Keep its start so a reviewer spawned for it before
5477
+ // this batch still holds the close-out instead of being treated as an
5478
+ // earlier turn's child and letting the canned fallback race its verdict.
5479
+ const openCloseout = live.githubReviewThreadCloseout
5480
+ const continuedStartedAt = (next: GithubReviewThreadCloseout): number =>
5481
+ openCloseout !== null &&
5482
+ openCloseout.workspace === next.workspace &&
5483
+ openCloseout.prNumber === next.prNumber &&
5484
+ openCloseout.rootCommentId === next.rootCommentId
5485
+ ? openCloseout.startedAt
5486
+ : live.logicalTurnStartedAt
5449
5487
  live.githubReviewThreadCloseout =
5450
5488
  stampedCloseout?.githubReviewThreadCloseout !== undefined
5451
5489
  ? {
5452
5490
  ...stampedCloseout.githubReviewThreadCloseout,
5453
- startedAt: live.logicalTurnStartedAt,
5491
+ startedAt: continuedStartedAt(stampedCloseout.githubReviewThreadCloseout),
5454
5492
  correctionAttempts: 0,
5455
5493
  deferred: false,
5456
5494
  }
@@ -5458,7 +5496,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5458
5496
  ? null
5459
5497
  : {
5460
5498
  ...deferredCloseout,
5461
- startedAt: live.logicalTurnStartedAt,
5499
+ startedAt: continuedStartedAt(deferredCloseout),
5462
5500
  correctionAttempts: 0,
5463
5501
  }
5464
5502
  if (stampedCloseout?.githubReviewThreadCloseout !== undefined) {
@@ -5504,6 +5542,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5504
5542
  // turn `batch[batch.length - 1]!.authorId` semantics) so a multi-
5505
5543
  // author prior turn like alice→bob restores `bob`, not alice.
5506
5544
  live.currentTurnAuthorId = live.lastTurnAuthorId
5545
+ live.currentTurnAuthorAdapter = live.lastTurnAuthorAdapter
5546
+ live.currentTurnHandoff = live.lastTurnHandoff
5507
5547
  live.currentTurnAuthorIds = new Set(live.lastTurnAuthorIds)
5508
5548
  } else {
5509
5549
  live.currentTurnEngageReactions = []
@@ -5583,7 +5623,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5583
5623
  live.promptInFlight = true
5584
5624
  try {
5585
5625
  const result = await promptPersistentTurnWithFallback({
5586
- refs: resolveFallbackChain(getConfig().models, undefined),
5626
+ refs: resolveFallbackChain(effectiveModels(getConfig(), live.originRef.current), undefined),
5587
5627
  currentModelRef: live.activeModelRef,
5588
5628
  session: live.session,
5589
5629
  text: promptText,
@@ -5762,6 +5802,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5762
5802
  live.lastTurnAuthorIds = new Set(live.currentTurnAuthorIds)
5763
5803
  if (live.currentTurnAuthorId !== null) {
5764
5804
  live.lastTurnAuthorId = live.currentTurnAuthorId
5805
+ live.lastTurnAuthorAdapter = live.currentTurnAuthorAdapter
5806
+ live.lastTurnHandoff = live.currentTurnHandoff
5765
5807
  }
5766
5808
  }
5767
5809
  } finally {
@@ -5770,6 +5812,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5770
5812
  live.currentTurnAuthorIds = new Set()
5771
5813
  live.currentTurnReactionRef = null
5772
5814
  live.currentTurnExplicitlyAddressed = false
5815
+ live.currentTurnHandoff = false
5773
5816
  live.currentTurnEngageReactions = []
5774
5817
  // Drop any still-held reactions if the loop exited without running the
5775
5818
  // per-turn finally (e.g. session destroyed mid-drain): never leave a
@@ -6021,7 +6064,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6021
6064
  )
6022
6065
  }
6023
6066
 
6024
- const route = async (event: InboundMessage, onAdmitted?: () => Promise<void>): Promise<RouteReceipt> => {
6067
+ const routeInbound = async (event: InboundMessage, onAdmitted?: () => Promise<void>): Promise<RouteReceipt> => {
6025
6068
  const adapterConfig = options.configForAdapter(event.adapter)
6026
6069
  if (!adapterConfig) return { kind: 'denied' }
6027
6070
 
@@ -6040,7 +6083,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6040
6083
  // Claims are accepted from any chat (DM, group, thread) because the
6041
6084
  // resulting match rule is platform-wide + author-scoped — see
6042
6085
  // src/role-claim/match-rule.ts.
6043
- if (claimHandler !== undefined && extractClaimCode(event.text) !== null) {
6086
+ // A handoff's text is delegated context, never control traffic: it must not
6087
+ // claim roles or run commands on the requester's behalf.
6088
+ if (event.handoff !== true && claimHandler !== undefined && extractClaimCode(event.text) !== null) {
6044
6089
  const outcome = await claimHandler({
6045
6090
  adapter: event.adapter,
6046
6091
  workspace: event.workspace,
@@ -6074,7 +6119,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6074
6119
 
6075
6120
  // Parse once, here, so the public-command fast path (below) and the
6076
6121
  // post-gate command block share one parse and lookup.
6077
- const parsedCommand = commands.parse(event.text)
6122
+ const parsedCommand = event.handoff === true ? null : commands.parse(event.text)
6078
6123
  const commandInfo = parsedCommand === null ? undefined : commands.get(parsedCommand.name)
6079
6124
 
6080
6125
  // Public-command fast path: a known command that is both ungated
@@ -6155,6 +6200,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6155
6200
  chat: event.chat,
6156
6201
  ...(event.room?.parentChat !== undefined ? { parentChat: event.room.parentChat } : {}),
6157
6202
  lastInboundAuthorId: event.authorId,
6203
+ ...(event.authorAdapter !== undefined ? { lastInboundAuthorAdapter: event.authorAdapter } : {}),
6158
6204
  },
6159
6205
  messageId: event.externalMessageId || undefined,
6160
6206
  eventKind: event.eventKind ?? 'message',
@@ -6184,15 +6230,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6184
6230
  let live = await ensureLive(key, event.externalMessageId, event.authorId, undefined, event.room, generation)
6185
6231
  live.room = event.room
6186
6232
 
6187
- const isNewAuthor = !live.participants.some((p) => p.authorId === event.authorId)
6188
- live.participants = updateParticipants(
6189
- live.participants,
6190
- event.authorId,
6191
- event.authorName,
6192
- now(),
6193
- event.authorIsBot,
6194
- )
6195
- void persistParticipants(live)
6233
+ const isNewAuthor = event.handoff !== true && !live.participants.some((p) => p.authorId === event.authorId)
6234
+ // A delegated note is not evidence that its author joined this conversation.
6235
+ if (event.handoff !== true) {
6236
+ live.participants = updateParticipants(
6237
+ live.participants,
6238
+ event.authorId,
6239
+ event.authorName,
6240
+ now(),
6241
+ event.authorIsBot,
6242
+ )
6243
+ void persistParticipants(live)
6244
+ live.recentMessages.push({ text: event.text.slice(0, 2000), at: now() })
6245
+ if (live.recentMessages.length > 20) live.recentMessages.shift()
6246
+ }
6196
6247
 
6197
6248
  // A previously-unseen author just spoke. The cached membership count
6198
6249
  // (from /members or history-derived) was computed without them, so
@@ -6213,7 +6264,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6213
6264
 
6214
6265
  const membership = await membershipForEngagement(live)
6215
6266
 
6216
- const effectiveHumans = countEffectiveHumans(live.participants, membership, now())
6267
+ const botInThread = hasBotParticipated(live)
6268
+ const effectiveHumans = countEngagementHumans(event, live.participants, membership, now(), botInThread)
6217
6269
  live.multiHumanGroup = isMultiHumanGroup(event.isDm, effectiveHumans)
6218
6270
 
6219
6271
  const decision: EngagementDecision = decideEngagement({
@@ -6225,7 +6277,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6225
6277
  participants: live.participants,
6226
6278
  membership,
6227
6279
  selfAliases: computeSelfAliases(),
6228
- botInThread: hasBotParticipated(live),
6280
+ botInThread,
6229
6281
  })
6230
6282
 
6231
6283
  if (decision === 'observe') {
@@ -6276,11 +6328,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6276
6328
  event.replyToBotMessageId === null &&
6277
6329
  !live.multiHumanGroup
6278
6330
 
6279
- const engageReaction = autoReactOnEngage(event)
6331
+ const engageReaction = autoReactOnEngage(event, live.draining)
6280
6332
 
6281
6333
  updateLoopGuard(live, event)
6282
6334
 
6283
- enqueue(live, event, engageReaction, admission.inputId)
6335
+ const originNote = event.handoff !== true ? takeConversationOriginNote(live, event) : undefined
6336
+ live.lastInboundIsDm = event.isDm
6337
+ enqueue(
6338
+ live,
6339
+ originNote !== undefined
6340
+ ? { ...event, routingNote: [event.routingNote, originNote].filter((n) => n !== undefined).join('\n') }
6341
+ : event,
6342
+ engageReaction,
6343
+ admission.inputId,
6344
+ )
6284
6345
 
6285
6346
  // Start showing "typing..." the moment we know we're going to engage,
6286
6347
  // so users see the indicator during the debounce window — not just
@@ -6299,6 +6360,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6299
6360
  })
6300
6361
  }
6301
6362
 
6363
+ const route = async (event: InboundMessage, onAdmitted?: () => Promise<void>): Promise<RouteReceipt> => {
6364
+ const receipt = await routeInbound(event, onAdmitted)
6365
+ if (receipt.kind === 'observed' || receipt.kind === 'control') catchUp.noteObserved(event)
6366
+ return receipt
6367
+ }
6368
+ const catchUp = createInboundCatchUp({ agentDir: options.agentDir, route, logger, now })
6369
+ const catchUpTargets = async (adapter: AdapterId): Promise<readonly ChannelKey[]> => {
6370
+ await ensureLoaded()
6371
+ return (mappings ?? []).filter((record) => record.adapter === adapter)
6372
+ }
6373
+
6302
6374
  const inboundAuthorOrigin = (event: InboundMessage): SessionOrigin => ({
6303
6375
  kind: 'channel',
6304
6376
  adapter: event.adapter,
@@ -6307,6 +6379,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6307
6379
  thread: event.thread,
6308
6380
  ...(event.room?.parentChat !== undefined ? { parentChat: event.room.parentChat } : {}),
6309
6381
  lastInboundAuthorId: event.authorId,
6382
+ ...(event.authorAdapter !== undefined ? { lastInboundAuthorAdapter: event.authorAdapter } : {}),
6310
6383
  })
6311
6384
 
6312
6385
  const isChannelRespondDenied = (event: InboundMessage): boolean =>
@@ -6401,6 +6474,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6401
6474
  ...(event.referenceContext !== undefined ? { referenceContext: event.referenceContext } : {}),
6402
6475
  ...(event.attachments !== undefined && event.attachments.length > 0 ? { attachments: event.attachments } : {}),
6403
6476
  authorId: event.authorId,
6477
+ ...(event.authorAdapter !== undefined ? { authorAdapter: event.authorAdapter } : {}),
6404
6478
  authorName: event.authorName,
6405
6479
  authorIsBot: event.authorIsBot,
6406
6480
  externalMessageId: event.externalMessageId,
@@ -6415,6 +6489,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6415
6489
  ...(event.githubReviewThreadCloseout !== undefined
6416
6490
  ? { githubReviewThreadCloseout: event.githubReviewThreadCloseout }
6417
6491
  : {}),
6492
+ ...(event.routingNote !== undefined ? { routingNote: event.routingNote } : {}),
6493
+ ...(event.handoff === true ? { handoff: true as const } : {}),
6418
6494
  receivedAt: now(),
6419
6495
  ts: event.ts,
6420
6496
  })
@@ -6616,15 +6692,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6616
6692
  // supporting reactions, a transient API error) can NEVER block engagement,
6617
6693
  // enqueueing, or the agent's actual reply. No reactionRef = nothing reactable
6618
6694
  // (synthetic inbounds, reaction-less adapters) = silent skip.
6619
- const autoReactOnEngage = (event: InboundMessage): WaitingReactionHandle | null => {
6620
- if (event.reactionRef === undefined || typingCapableAdapters.has(event.adapter)) return null
6695
+ //
6696
+ // A message queued behind an in-flight turn gets an :hourglass_flowing_sand:
6697
+ // even where typing renders: that indicator belongs to the running turn and
6698
+ // cannot tell the sender their message is waiting. GitHub's fixed reaction
6699
+ // set has no hourglass, so it keeps :eyes:.
6700
+ const autoReactOnEngage = (event: InboundMessage, queuedBehindTurn: boolean): WaitingReactionHandle | null => {
6701
+ if (event.reactionRef === undefined) return null
6702
+ if (!queuedBehindTurn && typingCapableAdapters.has(event.adapter)) return null
6621
6703
  return waitingReactions.acquire({
6622
6704
  adapter: event.adapter,
6623
6705
  workspace: event.workspace,
6624
6706
  chat: event.chat,
6625
6707
  thread: event.thread,
6626
6708
  reactionRef: event.reactionRef,
6627
- emoji: ENGAGE_REACTION_EMOJI,
6709
+ emoji: queuedBehindTurn && event.adapter !== 'github' ? QUEUED_REACTION_EMOJI : ENGAGE_REACTION_EMOJI,
6628
6710
  })
6629
6711
  }
6630
6712
 
@@ -6850,7 +6932,26 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6850
6932
  editMessageCallbacks.get(adapter)?.delete(cb)
6851
6933
  }
6852
6934
 
6853
- const editMessage = async (req: EditMessageRequest): Promise<EditMessageResult> => {
6935
+ const hasOutboundReviewer = (): boolean =>
6936
+ options.reviewOutbound !== undefined && (options.outboundReviewerActive?.() ?? true)
6937
+
6938
+ const reviewOutbound = async (event: ChannelOutboundBeforeEvent): Promise<string> => {
6939
+ if (!hasOutboundReviewer()) return event.text
6940
+ try {
6941
+ const result = await options.reviewOutbound!(event)
6942
+ // A transform cannot undo the normal reasoning/flood protections or
6943
+ // synthesize a caption on an attachment-only delivery.
6944
+ const text = normalizeSendText(result.text)
6945
+ if (event.text.trim().length === 0) return event.text
6946
+ if (text !== undefined && text.trim().length > 0 && checkOutboundFlood(text).ok) return text
6947
+ } catch {
6948
+ // Plugin failures are categorical: never log message-bearing errors.
6949
+ }
6950
+ logger.warn('[channels] outbound transform failed or returned invalid text; retaining original')
6951
+ return event.text
6952
+ }
6953
+
6954
+ const editMessage = async (req: EditMessageRequest, opts?: EditMessageOptions): Promise<EditMessageResult> => {
6854
6955
  // Strip leaked `<think>` blocks before the edit reaches any adapter, exactly
6855
6956
  // as the send path does via normalizeSendText — an edit is another way text
6856
6957
  // reaches the chat, so it must not become a hole that writes raw reasoning a
@@ -6860,7 +6961,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6860
6961
  if (normalized === undefined) {
6861
6962
  return { ok: false, error: 'message-edit-empty-after-normalization', code: 'not-found' }
6862
6963
  }
6863
- const normalizedReq = normalized === req.text ? req : { ...req, text: normalized }
6964
+ let normalizedReq = normalized === req.text ? req : { ...req, text: normalized }
6864
6965
  const callbacks = editMessageCallbacks.get(req.adapter)
6865
6966
  if (!callbacks || callbacks.size === 0) {
6866
6967
  return isWriteCapabilityUnavailable(req.adapter, 'message-edit')
@@ -6871,6 +6972,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6871
6972
  }
6872
6973
  : { ok: false, error: 'message-edit-not-supported', code: 'not-supported' }
6873
6974
  }
6975
+ const reviewed = hasOutboundReviewer()
6976
+ if (reviewed) {
6977
+ const text = await reviewOutbound({
6978
+ adapter: req.adapter,
6979
+ workspace: req.workspace,
6980
+ chat: req.chat,
6981
+ ...(req.thread != null ? { thread: req.thread } : {}),
6982
+ text: normalized,
6983
+ op: 'edit',
6984
+ messageId: req.messageId,
6985
+ source: 'tool',
6986
+ ...(opts?.origin ? { origin: opts.origin } : {}),
6987
+ })
6988
+ normalizedReq = { ...normalizedReq, text }
6989
+ }
6874
6990
  const snapshot = Array.from(callbacks)
6875
6991
  let lastError: EditMessageResult & { ok: false } = { ok: false, error: 'message-edit-not-supported' }
6876
6992
  for (const cb of snapshot) {
@@ -6880,7 +6996,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6880
6996
  fetchHistoryTimeoutMs,
6881
6997
  `[channels] ${req.adapter} edit message`,
6882
6998
  )
6883
- if (result.ok) return result
6999
+ if (result.ok) return reviewed ? { ...result, deliveredText: normalizedReq.text } : result
6884
7000
  lastError = result
6885
7001
  } catch (err) {
6886
7002
  logger.warn(`[channels] edit message threw for ${req.adapter}: ${describeError(err)}`)
@@ -7032,43 +7148,45 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7032
7148
  )
7033
7149
  }
7034
7150
 
7035
- const lookupInboundAttachment = (args: ChannelKey & { id: number }): InboundAttachment | null => {
7151
+ const lookupInboundAttachment = (args: ChannelKey & { id: number; ref?: string }): InboundAttachment | null => {
7036
7152
  const live = liveSessions.get(channelKeyId(args))
7037
7153
  if (live === undefined) return null
7038
- // Walk newest → oldest so that when an id collides across messages
7039
- // (e.g. two photos in the same session each labelled `#1`) the agent's
7040
- // `attachment_id: 1` always resolves to the CURRENT inbound's
7041
- // attachment. currentTurnAttachments holds the in-flight turn — the
7042
- // only place the about-to-be-viewed attachment lives once drain() has
7043
- // spliced promptQueue empty — and is therefore the freshest; promptQueue
7044
- // then holds any inbound that arrived mid-turn. Within each list,
7045
- // append-order maps to wall-clock order, so iterating in reverse gives
7046
- // recency.
7047
- const found = findAttachmentById(live.currentTurnAttachments, args.id)
7048
- if (found !== null) return found
7049
- const haystacks: ReadonlyArray<ReadonlyArray<{ attachments?: readonly InboundAttachment[] }>> = [
7050
- live.promptQueue,
7051
- live.contextBuffer,
7052
- ]
7053
- for (const haystack of haystacks) {
7054
- for (let i = haystack.length - 1; i >= 0; i--) {
7055
- const item = haystack[i]
7056
- const hit = item?.attachments?.find((attachment) => attachment.id === args.id)
7057
- if (hit !== undefined) return hit
7058
- }
7059
- }
7060
- return findAttachmentById(live.historyAttachments, args.id)
7154
+ const matches = (attachment: InboundAttachment) =>
7155
+ attachment.id === args.id && (args.ref === undefined || attachment.ref === args.ref)
7156
+ // An actual attachment on the in-flight request wins. Observed scrollback
7157
+ // in that same prompt is NOT the current request's attachment.
7158
+ for (let i = live.currentTurnAttachments.length - 1; i >= 0; i--) {
7159
+ const entry = live.currentTurnAttachments[i]!
7160
+ if (entry.current && matches(entry.attachment)) return entry.attachment
7161
+ }
7162
+ let newest: TimedAttachment | undefined
7163
+ for (const entries of [live.currentTurnAttachments, live.historyTimedAttachments]) {
7164
+ for (const entry of entries) {
7165
+ if (matches(entry.attachment) && (newest === undefined || entry.ts >= newest.ts)) newest = entry
7166
+ }
7167
+ }
7168
+ // Future arrivals must never retarget a tool call from an in-flight turn.
7169
+ if (!live.draining) {
7170
+ for (const item of [...live.contextBuffer, ...live.promptQueue]) {
7171
+ for (const attachment of item.attachments ?? []) {
7172
+ if (matches(attachment) && (newest === undefined || item.ts >= newest.ts))
7173
+ newest = { ts: item.ts, attachment }
7174
+ }
7175
+ }
7176
+ }
7177
+ return newest?.attachment ?? null
7061
7178
  }
7062
7179
 
7063
7180
  const listInboundAttachmentIds = (args: ChannelKey): readonly number[] => {
7064
7181
  const live = liveSessions.get(channelKeyId(args))
7065
7182
  if (live === undefined) return []
7066
7183
  const ids = new Set<number>()
7067
- for (const attachment of live.currentTurnAttachments) ids.add(attachment.id)
7068
- for (const item of [...live.promptQueue, ...live.contextBuffer]) {
7069
- for (const attachment of item.attachments ?? []) ids.add(attachment.id)
7184
+ for (const entry of live.currentTurnAttachments) ids.add(entry.attachment.id)
7185
+ if (!live.draining) {
7186
+ for (const item of [...live.promptQueue, ...live.contextBuffer])
7187
+ for (const attachment of item.attachments ?? []) ids.add(attachment.id)
7070
7188
  }
7071
- for (const attachment of live.historyAttachments) ids.add(attachment.id)
7189
+ for (const entry of live.historyTimedAttachments) ids.add(entry.attachment.id)
7072
7190
  return Array.from(ids).sort((a, b) => a - b)
7073
7191
  }
7074
7192
 
@@ -7079,23 +7197,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7079
7197
  (message.attachments ?? []).map((attachment) => ({ ts: message.ts, attachment })),
7080
7198
  )
7081
7199
  if (incoming.length === 0) return
7082
- // Order by message freshness, NOT append order: channel_history pages
7083
- // OLDER messages via nextCursor, so a later call can deliver an OLDER ref.
7084
- // findAttachmentById searches end-first, so the list MUST end with the
7085
- // freshest ref or an older paged `#1` would shadow a newer one. Dedupe by
7086
- // id keeping the freshest ts (a re-fetch of the same message is a no-op,
7087
- // not a duplicate), sort ascending by ts, then keep the freshest LIMIT so
7088
- // eviction drops the OLDEST refs, never newer ones.
7089
- const byId = new Map<number, TimedAttachment>()
7200
+ // Keep each distinct ref, not only the latest message-local number: an
7201
+ // explicit file_id must still select an older file from this conversation.
7202
+ const byRef = new Map<string, TimedAttachment>()
7090
7203
  for (const entry of [...live.historyTimedAttachments, ...incoming]) {
7091
- const existing = byId.get(entry.attachment.id)
7092
- if (existing === undefined || entry.ts >= existing.ts) byId.set(entry.attachment.id, entry)
7204
+ const key = `${entry.attachment.id}:${entry.attachment.ref}`
7205
+ const existing = byRef.get(key)
7206
+ if (existing === undefined || entry.ts >= existing.ts) byRef.set(key, entry)
7093
7207
  }
7094
- const sorted = Array.from(byId.values()).sort((a, b) => a.ts - b.ts)
7208
+ const sorted = Array.from(byRef.values()).sort((a, b) => a.ts - b.ts)
7095
7209
  const kept =
7096
7210
  sorted.length > HISTORY_ATTACHMENT_LIMIT ? sorted.slice(sorted.length - HISTORY_ATTACHMENT_LIMIT) : sorted
7097
7211
  live.historyTimedAttachments = kept
7098
- live.historyAttachments = kept.map((entry) => entry.attachment)
7099
7212
  }
7100
7213
 
7101
7214
  const send = async (msg: OutboundMessage, opts?: SendOptions): Promise<SendResult> => {
@@ -7122,9 +7235,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7122
7235
  // Recovery is a transport-only operation. Do not even look up the live
7123
7236
  // session: doing so would let a delayed notice alter a newer logical turn.
7124
7237
  if (opts?.accounting === 'recovery') {
7238
+ const reviewed = hasOutboundReviewer()
7239
+ if (reviewed) {
7240
+ const text = await reviewOutbound({
7241
+ adapter: msg.adapter,
7242
+ workspace: msg.workspace,
7243
+ chat: msg.chat,
7244
+ ...(msg.thread != null ? { thread: msg.thread } : {}),
7245
+ text: msg.text ?? '',
7246
+ op: 'send',
7247
+ source,
7248
+ outputKind: opts.outputKind ?? 'meta',
7249
+ ...(opts.origin ? { origin: opts.origin } : {}),
7250
+ })
7251
+ if (msg.text !== undefined) msg = { ...msg, text }
7252
+ }
7125
7253
  for (const callback of Array.from(callbacks)) {
7126
7254
  const result = await callback({ ...msg, sendOptions: opts })
7127
- if (result.ok) return result
7255
+ if (result.ok) return reviewed && msg.text !== undefined ? { ...result, deliveredText: msg.text } : result
7128
7256
  return result
7129
7257
  }
7130
7258
  return { ok: false, error: 'no recovery transport available', code: 'no-adapter' }
@@ -7309,7 +7437,27 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7309
7437
  let messageId: string | undefined
7310
7438
  let messageIds: readonly string[] | undefined
7311
7439
  let reactionRef: ReactionRef | undefined
7440
+ let deliveredText: string | undefined
7312
7441
  try {
7442
+ if (hasOutboundReviewer()) {
7443
+ const reviewed = await reviewOutbound({
7444
+ adapter: msg.adapter,
7445
+ workspace: msg.workspace,
7446
+ chat: msg.chat,
7447
+ ...(msg.thread != null ? { thread: msg.thread } : {}),
7448
+ text: msg.text ?? '',
7449
+ op: 'send',
7450
+ source,
7451
+ outputKind,
7452
+ ...(opts?.origin ? { origin: opts.origin } : {}),
7453
+ })
7454
+ // Admission, duplicate reservations and output-kind decisions stay based
7455
+ // on the authored text. A nondeterministic reviewer cannot evade them.
7456
+ if (msg.text !== undefined) {
7457
+ msg = { ...msg, text: reviewed }
7458
+ deliveredText = reviewed
7459
+ }
7460
+ }
7313
7461
  for (const cb of snapshot) {
7314
7462
  if (dependentLiveSend && !inboundJournal.health().available) {
7315
7463
  lastError = 'continuity persistence unavailable'
@@ -7392,7 +7540,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7392
7540
  // (d) provider-error, empty-turn-fallback, and control notices are
7393
7541
  // explicitly meta and preserve, so a warning can never self-clear.
7394
7542
  // The channel_reply afterToolCall hook above remains authoritative for its
7395
- // machine-readable more_work_this_turn flag.
7543
+ // machine-readable continue_after_reply flag.
7396
7544
  if (outputKind === 'substantive') {
7397
7545
  live.promisedWorkOutstandingThisLogicalTurn = false
7398
7546
  live.statusOutputOutstandingThisLogicalTurn = false
@@ -7458,11 +7606,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7458
7606
  ...(messageId !== undefined ? { messageId } : {}),
7459
7607
  ...(messageIds !== undefined ? { messageIds } : {}),
7460
7608
  ...(reactionRef !== undefined ? { reactionRef } : {}),
7609
+ ...(deliveredText !== undefined ? { deliveredText } : {}),
7461
7610
  }
7462
7611
  }
7463
7612
 
7464
7613
  // The turn ended via terminal channel_reply completion. If that reply promised to keep
7465
- // working but omitted `more_work_this_turn: true`, queue ONE reminder-only re-prompt so
7614
+ // working but omitted `continue_after_reply: true`, queue ONE reminder-only re-prompt so
7466
7615
  // the model gets a second chance to actually do it. The tool batch already
7467
7616
  // terminated (safe default preserved); this only adds an optional nudge. Bounded by
7468
7617
  // MAX_WILLINGNESS_NUDGES and gated on `promptQueue` being empty so a real
@@ -7548,6 +7697,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7548
7697
  live.skippedTurn = null
7549
7698
  armRetainedOutputAckIfEligible(live, successfulSendsBeforePrompt, true)
7550
7699
  logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
7700
+ // The model decided this turn owes the user nothing, so a provider failure
7701
+ // on the request after that decision lost nothing the user was waiting for.
7702
+ // A notice here would be a false alarm, typically stranded under the real
7703
+ // reply an earlier pass of the same logical turn already delivered.
7704
+ const pendingError = live.pendingProviderError
7705
+ if (pendingError !== null && pendingError.turnSeq === live.turnSeq) {
7706
+ live.pendingProviderError = null
7707
+ logger.warn(
7708
+ `[channels] ${live.keyId}: provider_error_notice_suppressed reason=explicit_skip_response notice="${pendingError.safeMessage}"`,
7709
+ )
7710
+ }
7711
+ // This session already resolved the thread and the model read the newer
7712
+ // reply and deliberately skipped it. Leaving a resolved thread resolved is
7713
+ // a close-out decision, so neither the reminder nor the "leaving it open"
7714
+ // fallback applies. A turn that ends silent without skip_response still owes one.
7715
+ const closeout = live.githubReviewThreadCloseout
7716
+ const resolvedAt = live.githubReviewThreadResolvedAt
7717
+ if (closeout !== null && resolvedAt !== null && resolvedAt.rootCommentId === closeout.rootCommentId) {
7718
+ clearGithubReviewThreadCloseout(live)
7719
+ live.githubReviewThreadCloseoutDecisionTurn = live.turnSeq
7720
+ logger.info(
7721
+ `[channels] ${live.keyId} github_thread_closeout_skipped_already_resolved pr=${closeout.prNumber} root=${closeout.rootCommentId}`,
7722
+ )
7723
+ }
7551
7724
  void dropContinuationReactions(live)
7552
7725
  return
7553
7726
  }
@@ -7628,10 +7801,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7628
7801
  return
7629
7802
  }
7630
7803
 
7631
- // A send landed this turn, but the model may have posted a `more_work_this_turn: true`
7804
+ // A send landed this turn, but the model may have posted a `continue_after_reply: true`
7632
7805
  // progress reply, kept working, then ENDED with its final answer as plain
7633
7806
  // prose — never calling a channel tool again. The terminal-reply abort fires
7634
- // only for a `channel_reply` WITHOUT `more_work_this_turn: true`, so that `stopReason:
7807
+ // only for a `channel_reply` WITHOUT `continue_after_reply: true`, so that `stopReason:
7635
7808
  // 'stop'` text leaf is left undelivered and unguarded (the false-receipt
7636
7809
  // guard is github-only). The discriminator is leaf IDENTITY: only when the
7637
7810
  // turn-end `stop` leaf is a DIFFERENT entry than the one in place at the last
@@ -7642,17 +7815,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7642
7815
  const terminalReplyCompletedThisTurn = live.lastTerminalReplyCompletion?.turnSeq === live.turnSeq
7643
7816
  maybeNudgeContinuationWillingness(live)
7644
7817
 
7645
- // A `channel_reply({ more_work_this_turn: true })` progress ack landed this turn (the
7818
+ // A `channel_reply({ continue_after_reply: true })` progress ack landed this turn (the
7646
7819
  // machine-readable "I'll keep working" promise — `continueReplyTurn` is stamped
7647
7820
  // by installChannelReplyTerminalHook), the model did more work, then ended on a
7648
7821
  // FRESH empty `stop` — dropping its conclusion. This is the SAME degeneration as
7649
- // the phrase-gated `channel_send` branch below, but keyed on the `more_work_this_turn: true`
7822
+ // the phrase-gated `channel_send` branch below, but keyed on the `continue_after_reply: true`
7650
7823
  // FLAG instead of a natural-language willingness phrase. The flag is the robust
7651
7824
  // signal: it fires regardless of the ack's language or register, closing the gap
7652
7825
  // where a persona speaking a phrasing outside the willingness table (e.g. casual
7653
7826
  // Korean "확인해볼게") stranded the user in silence. The `attemptMadeToolCall`
7654
7827
  // half ties the first trigger to real post-ack work; `willingnessNudges > 0`
7655
- // lets a retry that re-emitted `more_work_this_turn: true` and re-stranded spend the shared
7828
+ // lets a retry that re-emitted `continue_after_reply: true` and re-stranded spend the shared
7656
7829
  // budget toward the visible fallback instead of bailing silent. Same
7657
7830
  // MAX_WILLINGNESS_NUDGES bound, same empty-`promptQueue` gate (a coalesced live
7658
7831
  // inbound supersedes this turn's silence), and same nudge/fallback path as the
@@ -7740,7 +7913,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7740
7913
 
7741
7914
  const trailing = recoverableAssistantText(live.session)
7742
7915
  if (trailing === null || trailing.source !== 'leaf') {
7743
- // A `more_work_this_turn: true` status reply landed, then the turn stranded on an
7916
+ // A `continue_after_reply: true` status reply landed, then the turn stranded on an
7744
7917
  // unanswered `toolUse` (the post-tool follow-up never produced an
7745
7918
  // assistant message — aborted loop / cancelled stream). The promised
7746
7919
  // work never finished, so the user is left with a bare "checking now…"
@@ -7760,6 +7933,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7760
7933
  return
7761
7934
  }
7762
7935
  if (branchLeafEntry(live.session)?.id === live.lastSendLeafId) return
7936
+ // A fresh post-send prose leaf while this turn's background child is still
7937
+ // running is the model narrating its own spawn ("Researcher spawned, I'll
7938
+ // report back"), written as invisible console text, often in the tool
7939
+ // result's language rather than the user's. The ack already landed and the
7940
+ // child's completion turn owns the real answer, so do not post it.
7941
+ if (isAwaitingBackgroundChild(live, 'post_send_prose')) {
7942
+ logger.info(
7943
+ `[channels] ${live.keyId} post_send_prose_suppressed cause=awaiting_background_child text_len=${trailing.text.length}`,
7944
+ )
7945
+ return
7946
+ }
7763
7947
  }
7764
7948
 
7765
7949
  if (unfinishedToolUseWithoutReply) {
@@ -8083,6 +8267,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8083
8267
  // missing formal review on the model's behalf, and posting the unguarded ack
8084
8268
  // is worse than dropping it — the next inbound re-prompts the model, which
8085
8269
  // can then land the verdict properly.
8270
+ // Real leftover prose is still recovered while a background child runs (an
8271
+ // answer the model already wrote should land), but a lone identifier-shaped
8272
+ // ASCII token is model degeneration, not an answer: a bare `_RGCTX` once
8273
+ // landed as a public PR comment right after a reviewer spawn. The child's
8274
+ // completion turn owns the real reply, so drop it. Scoped to the awaiting
8275
+ // turn so ordinary recovery is untouched; non-Latin short replies never match.
8276
+ if (/^[A-Za-z0-9_]+$/.test(assistantText.trim()) && isAwaitingBackgroundChild(live, 'recovery_leaf')) {
8277
+ logger.info(
8278
+ `[channels] ${live.keyId} recovery_suppressed cause=awaiting_background_child text_len=${assistantText.length}`,
8279
+ )
8280
+ armSilentTurnAck(live, 'awaiting_background_child')
8281
+ return
8282
+ }
8283
+
8086
8284
  const recoveryBlock = await evaluateRecoveryReviewGuards(live, assistantText)
8087
8285
  if (recoveryBlock !== null) {
8088
8286
  logger.warn(
@@ -8141,7 +8339,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8141
8339
  chat: live.key.chat,
8142
8340
  thread: live.key.thread,
8143
8341
  text,
8144
- moreWorkThisTurn: false,
8342
+ continueAfterReply: false,
8145
8343
  resolveReviewThread: false,
8146
8344
  })
8147
8345
  if (falseReceipt.kind === 'block') return falseReceipt.reason
@@ -8153,7 +8351,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8153
8351
  thread: live.key.thread,
8154
8352
  text,
8155
8353
  wantsResolve: false,
8156
- moreWorkThisTurn: false,
8354
+ continueAfterReply: false,
8157
8355
  getReviewState: (req) => getReviewState(req),
8158
8356
  })
8159
8357
  if (rereview.block) return rereview.reason
@@ -8339,6 +8537,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8339
8537
 
8340
8538
  const stop = async (): Promise<void> => {
8341
8539
  closing = true
8540
+ await catchUp.stop()
8342
8541
  if (!options.inboundJournal) inboundJournal.cancelInitialization()
8343
8542
  unsubscribeJournalFailure()
8344
8543
  if (gcTimer) clearInterval(gcTimer)
@@ -8669,13 +8868,32 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8669
8868
  return { kind: 'unknown-command', name: lowered }
8670
8869
  }
8671
8870
 
8672
- const acceptBackgroundResponse: ChannelRouter['acceptBackgroundResponse'] = async (args) =>
8673
- backgroundObligations.withTargetLane(args.key, async () => {
8871
+ const acceptBackgroundResponse: ChannelRouter['acceptBackgroundResponse'] = async (args) => {
8872
+ // Freeze the authenticated live actor before entering the asynchronous lane.
8873
+ // Legacy callers without a live parent retain their supplied provenance.
8874
+ const live = liveSessions.get(channelKeyId(args.key))
8875
+ let principal: MatchableOrigin | undefined
8876
+ if (live !== undefined && !live.destroyed && live.sessionId === args.parentSessionId) {
8877
+ const authorId = live.currentTurnAuthorId ?? live.lastTurnAuthorId
8878
+ const authorAdapter =
8879
+ live.currentTurnAuthorId !== null ? live.currentTurnAuthorAdapter : live.lastTurnAuthorAdapter
8880
+ principal = {
8881
+ kind: 'channel',
8882
+ adapter: live.key.adapter,
8883
+ workspace: live.key.workspace,
8884
+ chat: live.key.chat,
8885
+ ...(live.room?.parentChat !== undefined ? { parentChat: live.room.parentChat } : {}),
8886
+ ...(authorId !== null ? { lastInboundAuthorId: authorId } : {}),
8887
+ ...(authorAdapter !== live.key.adapter ? { lastInboundAuthorAdapter: authorAdapter } : {}),
8888
+ }
8889
+ }
8890
+ return backgroundObligations.withTargetLane(args.key, async () => {
8674
8891
  await ready
8675
8892
  inboundJournal.assertAvailable()
8676
- const row = await backgroundObligations.accept(args)
8893
+ const row = await backgroundObligations.accept({ ...args, ...(principal !== undefined ? { principal } : {}) })
8677
8894
  return { obligationId: row.obligationId, generation: row.generation }
8678
8895
  })
8896
+ }
8679
8897
 
8680
8898
  const suppressUnstartedBackgroundResponse: ChannelRouter['suppressUnstartedBackgroundResponse'] = async (
8681
8899
  ref,
@@ -8837,6 +9055,52 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8837
9055
  return { kind: 'delivered', keyId: live.keyId }
8838
9056
  }
8839
9057
 
9058
+ // Only shared namespaces identify the same person across conversations.
9059
+ // Check the NEW inbound author, not the session's previous turn owner.
9060
+ const takeConversationOriginNote = (live: LiveSession, event: InboundMessage): string | undefined => {
9061
+ let origin: LiveSession | undefined
9062
+ for (const s of liveSessions.values()) {
9063
+ if (s === live || s.destroyed || adapterNamespace(s.key.adapter) !== adapterNamespace(event.adapter)) continue
9064
+ if (!options.configForAdapter(s.key.adapter)?.enabled) continue
9065
+ if (
9066
+ !s.participants.some(
9067
+ (p) => p.authorId === event.authorId && now() - p.lastMessageAt <= CONVERSATION_ORIGIN_WINDOW_MS,
9068
+ )
9069
+ )
9070
+ continue
9071
+ const access = checkHandoffAccess({
9072
+ source: {
9073
+ ...live,
9074
+ currentTurnAuthorId: event.authorId,
9075
+ currentTurnAuthorAdapter: event.adapter,
9076
+ currentTurnHandoff: false,
9077
+ lastTurnHandoff: false,
9078
+ },
9079
+ target: s,
9080
+ permissions,
9081
+ })
9082
+ if (!access.ok) continue
9083
+ if (origin === undefined || s.lastInboundAt > origin.lastInboundAt) origin = s
9084
+ }
9085
+ if (origin === undefined || live.originHintedKeys.has(origin.keyId)) return undefined
9086
+ live.originHintedKeys.add(origin.keyId)
9087
+ const k = origin.key
9088
+ const thread = k.thread !== null ? ` thread="${k.thread}"` : ''
9089
+ return (
9090
+ `[runtime note: this user was just talking with you in another conversation ` +
9091
+ `(adapter="${k.adapter}" workspace="${k.workspace}" chat="${k.chat}"${thread}). ` +
9092
+ 'If they ask you to continue there or to deliver a result there, use `channel_handoff` with that target ' +
9093
+ 'instead of `channel_send`, so the session that owns that conversation answers with its current context.]'
9094
+ )
9095
+ }
9096
+
9097
+ const handoff = createSessionHandoff({ sessions: liveSessions, permissions, route, logger, now })
9098
+ const searchSessions = createSessionSearch({
9099
+ sessions: liveSessions,
9100
+ permissions,
9101
+ configForAdapter: options.configForAdapter,
9102
+ })
9103
+
8840
9104
  const injectSubagentCompletionReminder = async (args: {
8841
9105
  parentSessionId: string
8842
9106
  subagent: string
@@ -8878,9 +9142,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8878
9142
  }
8879
9143
  // The exact parent session is gone. If the subagent was spawned from a
8880
9144
  // channel session, the conversation may have rolled over
8881
- // (SESSION_FRESHNESS_TTL_MS) or been idle-evicted onto a fresh sessionId
8882
- // for the same channel key while the subagent ran. Fall back to the live
8883
- // successor for that key so a finished review/result still surfaces
9145
+ // after 60 minutes idle (SESSION_FRESHNESS_TTL_MS), or been idle-evicted
9146
+ // and rehydrated for the same channel key while the subagent ran. Fall back
9147
+ // to the live successor for that key so a finished review/result still surfaces
8884
9148
  // instead of being silently dropped.
8885
9149
  if (args.channelKey !== undefined) {
8886
9150
  const targetKeyId = channelKeyId(args.channelKey)
@@ -9138,6 +9402,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9138
9402
  )
9139
9403
  if (live !== undefined) {
9140
9404
  live.githubReviewThreadCloseoutDecisionTurn = live.turnSeq
9405
+ if (args.decision === 'resolved' && args.thread !== null) {
9406
+ live.githubReviewThreadResolvedAt = { rootCommentId: args.thread, at: now() }
9407
+ }
9141
9408
  clearGithubReviewThreadCloseout(live)
9142
9409
  logger.info(
9143
9410
  `[channels] ${live.keyId} github_thread_closeout_decided decision=${args.decision} turn=${live.turnSeq}`,
@@ -9451,6 +9718,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9451
9718
  registerMembership,
9452
9719
  unregisterMembership,
9453
9720
  registerHistory,
9721
+ registerMissedInbound: catchUp.register,
9722
+ unregisterMissedInbound: catchUp.unregister,
9723
+ catchUp: catchUp.run,
9724
+ disconnectCatchUp: catchUp.disconnect,
9725
+ catchUpTargets,
9454
9726
  unregisterHistory,
9455
9727
  fetchHistory,
9456
9728
  registerMessageGet,
@@ -9462,6 +9734,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9462
9734
  registerEditMessage,
9463
9735
  unregisterEditMessage,
9464
9736
  editMessage,
9737
+ reviewOutbound,
9738
+ hasOutboundReviewer,
9465
9739
  registerFetchAttachment,
9466
9740
  unregisterFetchAttachment,
9467
9741
  fetchAttachment,
@@ -9488,6 +9762,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9488
9762
  hasOutstandingGithubReviewThreadCloseout,
9489
9763
  markTurnSkipped,
9490
9764
  clearSticky,
9765
+ handoff,
9766
+ searchSessions,
9491
9767
  reserveRestartHandoff,
9492
9768
  resumeRestartHandoff,
9493
9769
  stop,
@@ -9617,21 +9893,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9617
9893
  function collectTurnAttachments(
9618
9894
  observed: readonly ObservedInbound[],
9619
9895
  batch: readonly QueuedInbound[],
9620
- ): readonly InboundAttachment[] {
9621
- const out: InboundAttachment[] = []
9622
- for (const item of observed) out.push(...(item.attachments ?? []))
9623
- for (const item of batch) out.push(...(item.attachments ?? []))
9896
+ ): readonly TimedAttachment[] {
9897
+ const out: TimedAttachment[] = []
9898
+ for (const item of observed) for (const attachment of item.attachments ?? []) out.push({ ts: item.ts, attachment })
9899
+ const current = batch.at(-1)
9900
+ for (const item of batch)
9901
+ for (const attachment of item.attachments ?? []) out.push({ ts: item.ts, attachment, current: item === current })
9624
9902
  return out
9625
9903
  }
9626
9904
 
9627
- function findAttachmentById(attachments: readonly InboundAttachment[], id: number): InboundAttachment | null {
9628
- for (let i = attachments.length - 1; i >= 0; i--) {
9629
- const attachment = attachments[i]
9630
- if (attachment?.id === id) return attachment
9631
- }
9632
- return null
9633
- }
9634
-
9635
9905
  // Strips the platform's user/group-mention markup so a bare ping can be told
9636
9906
  // from a mention that also carries real text. Slack and Discord both encode
9637
9907
  // mentions as `<@id>` / `<@id|name>` (users) and `<!subteam^ID>` / `<!channel>`
@@ -9910,11 +10180,13 @@ function formatInboundPromptLines(
9910
10180
  authorIsBot: boolean
9911
10181
  text: string
9912
10182
  referenceContext?: InboundReferenceContext
10183
+ routingNote?: string
9913
10184
  },
9914
10185
  adapter: AdapterId,
9915
10186
  maxTextChars?: number,
9916
10187
  ): string {
9917
- const lines = inbound.referenceContext?.sources.map(renderQuoteAnchor) ?? []
10188
+ const lines = inbound.routingNote !== undefined ? [inbound.routingNote] : []
10189
+ lines.push(...(inbound.referenceContext?.sources.map(renderQuoteAnchor) ?? []))
9918
10190
  lines.push(
9919
10191
  formatAuthorLine(
9920
10192
  inbound.ts,
@@ -10506,7 +10778,7 @@ function assistantLeafStopReason(session: AgentSession): 'length' | 'error' | 'a
10506
10778
  // alongside its tool call and DID land a real send this turn (that trailing
10507
10779
  // `toolUse` is delivered narration, not a stranded promise — leave it alone).
10508
10780
  // Keys on the model having INTENDED to keep working with nothing yet said; used
10509
- // to re-prompt a turn that strands mid-work after a `more_work_this_turn: true` status
10781
+ // to re-prompt a turn that strands mid-work after a `continue_after_reply: true` status
10510
10782
  // reply instead of ending in silence.
10511
10783
  function leafIsStrandedToolUse(session: AgentSession): boolean {
10512
10784
  const leaf = branchLeafEntry(session)
@@ -10590,7 +10862,7 @@ function repairDanglingToolUseBranch(session: AgentSession, timestamp: number):
10590
10862
  // (the model did more work, then dropped its conclusion) from a legitimate
10591
10863
  // ack-then-stop where the model meant to wait for the user (leaf unchanged since
10592
10864
  // the send). The two willingness paths below layer their own promise-signal on top
10593
- // of this shape: `channel_reply({ more_work_this_turn: true })` via `continueReplyTurn`, and
10865
+ // of this shape: `channel_reply({ continue_after_reply: true })` via `continueReplyTurn`, and
10594
10866
  // `channel_send` acks via the willingness phrase table.
10595
10867
  function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
10596
10868
  const leaf = branchLeafEntry(live.session)
@@ -10600,10 +10872,10 @@ function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
10600
10872
  return leaf.id !== live.lastSendLeafId
10601
10873
  }
10602
10874
 
10603
- // The `channel_send` analogue of the `more_work_this_turn: true` recovery: the most recent
10875
+ // The `channel_send` analogue of the `continue_after_reply: true` recovery: the most recent
10604
10876
  // send to this target was a continuation-willingness ack (by phrase), then the
10605
10877
  // model produced a fresh empty stop. `channel_send` keeps the turn alive without a
10606
- // `more_work_this_turn: true` flag and stamps no semantic marker, so the phrase table is the
10878
+ // `continue_after_reply: true` flag and stamps no semantic marker, so the phrase table is the
10607
10879
  // only "I promised to keep working" signal available for that shape.
10608
10880
  function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
10609
10881
  if (!isFreshEmptyStopAfterSend(live)) return false