typeclaw 0.48.12 → 0.49.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 (213) hide show
  1. package/package.json +6 -3
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/attention-escalation.ts +8 -5
  4. package/src/agent/auth-reloadable.ts +2 -3
  5. package/src/agent/auth.ts +59 -79
  6. package/src/agent/compaction.ts +2 -2
  7. package/src/agent/index.ts +173 -85
  8. package/src/agent/live-sessions.ts +2 -2
  9. package/src/agent/live-subagents.ts +1 -0
  10. package/src/agent/llm-replay-sanitizer.ts +1 -1
  11. package/src/agent/model-overrides.ts +1 -1
  12. package/src/agent/multimodal/look-at.ts +3 -3
  13. package/src/agent/multimodal/read-redirect.ts +1 -1
  14. package/src/agent/plugin-tools.ts +76 -39
  15. package/src/agent/prompt-cache-key.ts +42 -0
  16. package/src/agent/provider-error.ts +179 -10
  17. package/src/agent/reload-tool.ts +1 -1
  18. package/src/agent/restart-handoff/index.ts +7 -14
  19. package/src/agent/reviewer-activity.ts +68 -0
  20. package/src/agent/session-origin.ts +33 -0
  21. package/src/agent/subagents.ts +14 -2
  22. package/src/agent/system-prompt.ts +68 -202
  23. package/src/agent/todo/continuation-policy.ts +12 -4
  24. package/src/agent/tool-error-remediation.ts +1 -1
  25. package/src/agent/tool-file-safety.ts +113 -14
  26. package/src/agent/tool-not-found-nudge.ts +1 -1
  27. package/src/agent/tool-result-budget.ts +2 -2
  28. package/src/agent/tools/channel-disengage.ts +2 -2
  29. package/src/agent/tools/channel-edit.ts +2 -2
  30. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  31. package/src/agent/tools/channel-history-render.ts +2 -1
  32. package/src/agent/tools/channel-history.ts +2 -2
  33. package/src/agent/tools/channel-react.ts +2 -2
  34. package/src/agent/tools/channel-read.ts +2 -2
  35. package/src/agent/tools/channel-reply.ts +25 -7
  36. package/src/agent/tools/channel-send.ts +51 -9
  37. package/src/agent/tools/curl-impersonate.ts +11 -2
  38. package/src/agent/tools/grant-role.ts +2 -2
  39. package/src/agent/tools/post-github-review.ts +79 -17
  40. package/src/agent/tools/restart.ts +2 -2
  41. package/src/agent/tools/skip-response.ts +4 -4
  42. package/src/agent/tools/spawn-subagent.ts +165 -14
  43. package/src/agent/tools/stream-snapshot.ts +2 -2
  44. package/src/agent/tools/subagent-cancel.ts +2 -2
  45. package/src/agent/tools/subagent-output.ts +10 -2
  46. package/src/agent/tools/todo/index.ts +2 -2
  47. package/src/agent/tools/webfetch/tool.ts +2 -2
  48. package/src/agent/tools/websearch.ts +2 -2
  49. package/src/bundled-plugins/backup/README.md +10 -9
  50. package/src/bundled-plugins/backup/runner.ts +140 -58
  51. package/src/bundled-plugins/backup/subagents.ts +58 -26
  52. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  53. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  54. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  55. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  56. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  57. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  58. package/src/bundled-plugins/operator/operator.ts +15 -4
  59. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  60. package/src/bundled-plugins/security/index.ts +50 -2
  61. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  62. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/discord-bot.ts +122 -67
  64. package/src/channels/adapters/discord-reactions.ts +18 -0
  65. package/src/channels/adapters/discord.ts +114 -8
  66. package/src/channels/adapters/github/inbound.ts +103 -8
  67. package/src/channels/adapters/github/index.ts +251 -19
  68. package/src/channels/adapters/github/last-alive.ts +27 -0
  69. package/src/channels/adapters/github/outbound.ts +54 -18
  70. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  71. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  72. package/src/channels/adapters/github/reactions.ts +100 -0
  73. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  74. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  75. package/src/channels/adapters/github/recovery.ts +106 -0
  76. package/src/channels/adapters/github/review-check.ts +510 -0
  77. package/src/channels/adapters/github/review-submitter.ts +34 -2
  78. package/src/channels/adapters/instagram.ts +32 -14
  79. package/src/channels/adapters/kakaotalk.ts +22 -7
  80. package/src/channels/adapters/line.ts +18 -3
  81. package/src/channels/adapters/outbound-account.ts +20 -0
  82. package/src/channels/adapters/own-reactions.ts +66 -0
  83. package/src/channels/adapters/recovery-correlation.ts +214 -0
  84. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  85. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  86. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  87. package/src/channels/adapters/slack-bot.ts +125 -57
  88. package/src/channels/adapters/slack-classify.ts +25 -4
  89. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  90. package/src/channels/adapters/slack-reactions.ts +18 -0
  91. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  92. package/src/channels/adapters/slack.ts +48 -3
  93. package/src/channels/adapters/teams.ts +14 -4
  94. package/src/channels/adapters/telegram-bot.ts +56 -10
  95. package/src/channels/adapters/webex-bot.ts +12 -2
  96. package/src/channels/adapters/webex.ts +12 -2
  97. package/src/channels/background-handoff.ts +434 -0
  98. package/src/channels/background-obligations.ts +893 -0
  99. package/src/channels/continuity-types.ts +271 -0
  100. package/src/channels/github-review-check.ts +598 -0
  101. package/src/channels/github-review-turn-ledger.ts +102 -28
  102. package/src/channels/github-review-verdict-coordinator.ts +96 -13
  103. package/src/channels/github-token-bridge.ts +11 -5
  104. package/src/channels/inbound-journal.ts +1738 -0
  105. package/src/channels/index.ts +6 -1
  106. package/src/channels/manager.ts +17 -7
  107. package/src/channels/recovery-dispatcher.ts +264 -0
  108. package/src/channels/recovery-notice.ts +94 -0
  109. package/src/channels/recovery-outbox.ts +459 -0
  110. package/src/channels/router.ts +2582 -633
  111. package/src/channels/schema.ts +8 -1
  112. package/src/channels/subagent-completion-bridge.ts +17 -14
  113. package/src/channels/types.ts +121 -16
  114. package/src/channels/waiting-reactions.ts +664 -0
  115. package/src/cli/compose.ts +7 -4
  116. package/src/cli/hostd.ts +49 -3
  117. package/src/cli/inspect.ts +11 -14
  118. package/src/cli/model.ts +7 -5
  119. package/src/cli/oauth-callbacks.ts +38 -23
  120. package/src/coding-agent/broker-body.ts +38 -0
  121. package/src/coding-agent/broker.ts +290 -0
  122. package/src/coding-agent/claude.ts +95 -0
  123. package/src/coding-agent/codex.ts +104 -0
  124. package/src/coding-agent/index.ts +506 -0
  125. package/src/coding-agent/omo-state.ts +69 -0
  126. package/src/coding-agent/omo-stream.ts +98 -0
  127. package/src/coding-agent/omo.ts +192 -0
  128. package/src/coding-agent/runner.ts +263 -0
  129. package/src/coding-agent/tool.ts +62 -0
  130. package/src/coding-agent/worktree.ts +355 -0
  131. package/src/compose/restart.ts +10 -3
  132. package/src/compose/start.ts +20 -3
  133. package/src/config/config.ts +70 -26
  134. package/src/config/providers.ts +278 -50
  135. package/src/container/exit-reason.ts +44 -0
  136. package/src/container/index.ts +5 -0
  137. package/src/container/log-archive.ts +51 -13
  138. package/src/container/memory-limit.ts +1 -1
  139. package/src/container/memory-oversubscription.ts +36 -6
  140. package/src/container/oom-events.ts +86 -0
  141. package/src/container/restart.ts +2 -0
  142. package/src/container/shared.ts +8 -1
  143. package/src/container/start.ts +25 -13
  144. package/src/container/stop.ts +6 -2
  145. package/src/container/tool-oom-priority.ts +32 -0
  146. package/src/cron/consumer.ts +10 -4
  147. package/src/cron/reloadable.ts +23 -2
  148. package/src/doctor/checks.ts +14 -2
  149. package/src/hostd/daemon.ts +20 -10
  150. package/src/hostd/spawn.ts +106 -5
  151. package/src/hostd/version.ts +20 -0
  152. package/src/hostd/watchdog.ts +241 -0
  153. package/src/init/dockerfile.ts +57 -592
  154. package/src/init/index.ts +6 -7
  155. package/src/init/oauth-login.ts +57 -17
  156. package/src/inspect/transcript-view.ts +6 -3
  157. package/src/mcp/client.ts +3 -1
  158. package/src/operations/classify-tool-outcome.ts +45 -1
  159. package/src/operations/incidents.ts +10 -5
  160. package/src/plugin/core-tool-names.ts +1 -1
  161. package/src/plugin/define.ts +1 -0
  162. package/src/plugin/index.ts +1 -0
  163. package/src/plugin/types.ts +6 -1
  164. package/src/run/background-handoff-boot.ts +86 -0
  165. package/src/run/channel-session-factory.ts +5 -4
  166. package/src/run/index.ts +93 -93
  167. package/src/run/resource-sample.ts +19 -0
  168. package/src/sandbox/build.ts +4 -0
  169. package/src/sandbox/coding-agent.ts +214 -0
  170. package/src/sandbox/policy.ts +1 -0
  171. package/src/sandbox/runtime-private.ts +4 -1
  172. package/src/secrets/coding-agent-auth.ts +97 -0
  173. package/src/secrets/index.ts +0 -16
  174. package/src/secrets/refresh-provider-oauth.ts +30 -76
  175. package/src/secrets/schema.ts +3 -4
  176. package/src/secrets/storage.ts +133 -234
  177. package/src/server/command-runner.ts +6 -2
  178. package/src/server/index.ts +102 -41
  179. package/src/sessions/index.ts +1 -1
  180. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  181. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  182. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  183. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  184. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  185. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  186. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  187. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  188. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  189. package/src/skills/typeclaw-config/SKILL.md +24 -24
  190. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  191. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  192. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  193. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  194. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  195. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  196. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  197. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  198. package/src/skills/typeclaw-plugins/SKILL.md +20 -20
  199. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  200. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  201. package/src/tui/index.ts +5 -3
  202. package/src/tui/theme.ts +1 -1
  203. package/typeclaw.schema.json +44 -2
  204. package/src/agent/adaptive-thinking-compat.ts +0 -79
  205. package/src/secrets/claude-credentials-json.ts +0 -129
  206. package/src/secrets/codex-auth-json.ts +0 -102
  207. package/src/secrets/export-claude-credentials-file.ts +0 -270
  208. package/src/secrets/export-codex-auth-file.ts +0 -250
  209. package/src/secrets/oauth-xai.ts +0 -348
  210. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  211. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  212. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  213. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
package/src/run/index.ts CHANGED
@@ -1,13 +1,12 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import { SessionManager } from '@mariozechner/pi-coding-agent'
3
+ import { SessionManager } from '@earendil-works/pi-coding-agent'
4
4
 
5
5
  import { createSession, createSessionWithDispose } from '@/agent'
6
6
  import { createProviderAuthReloadable } from '@/agent/auth-reloadable'
7
7
  import { LiveSessionRegistry } from '@/agent/live-sessions'
8
8
  import { LiveSubagentRegistry, newestRunningBackgroundChildStartedAt } from '@/agent/live-subagents'
9
9
  import { requestContainerRestart } from '@/agent/restart'
10
- import { consumeRestartHandoff } from '@/agent/restart-handoff'
11
10
  import { sessionMetaPayload } from '@/agent/session-meta'
12
11
  import type { SessionOrigin } from '@/agent/session-origin'
13
12
  import {
@@ -34,13 +33,20 @@ import {
34
33
  createGithubTokenBridge,
35
34
  createPrVerdictActivityBridge,
36
35
  createSubagentCompletionBridge,
36
+ setReviewCoverageCapture,
37
37
  setReviewObserver,
38
38
  setReviewOutputObserver,
39
39
  type ChannelManager,
40
40
  type PrVerdictActivityBridge,
41
41
  type SubagentCompletionBridge,
42
42
  } from '@/channels'
43
+ import { LegacyBackgroundHandoffReader } from '@/channels/background-handoff'
44
+ import { BackgroundObligationStore } from '@/channels/background-obligations'
45
+ import { InboundJournal } from '@/channels/inbound-journal'
46
+ import { RecoveryDispatcher } from '@/channels/recovery-dispatcher'
47
+ import { RecoveryOutbox } from '@/channels/recovery-outbox'
43
48
  import { createTunnelBridge, type TunnelBridge } from '@/channels/tunnel-bridge'
49
+ import { retainCodingAgentService } from '@/coding-agent'
44
50
  import { createConfigReloadable, getConfig, loadConfigBundleSync, reloadConfig, withDefaultPlugins } from '@/config'
45
51
  import {
46
52
  type CountStore,
@@ -66,13 +72,7 @@ import type { CronHandlerContext } from '@/plugin/types'
66
72
  import { createContainerBroker, publishForwardResult, subscribeForwardRequest } from '@/portbroker'
67
73
  import { formatChannelReloadSummary, ReloadRegistry, type ReloadAllResult, type ReloadContext } from '@/reload'
68
74
  import { createClaimController } from '@/role-claim'
69
- import {
70
- exportClaudeCredentialsFileForAgent,
71
- exportCodexAuthFileForAgent,
72
- exportGithubCliStoreForAgent,
73
- hydrateChannelEnvFromSecrets,
74
- refreshProviderOAuthForAgent,
75
- } from '@/secrets'
75
+ import { exportGithubCliStoreForAgent, hydrateChannelEnvFromSecrets, refreshProviderOAuthForAgent } from '@/secrets'
76
76
  import { createServer, type Server } from '@/server'
77
77
  import {
78
78
  createCommandRunner,
@@ -86,6 +86,7 @@ import { createStream, type Stream } from '@/stream'
86
86
  import { createTui as createTuiDefault, type TuiOptions } from '@/tui'
87
87
  import { createTunnelManager, type TunnelManager, type TunnelManagerOptions } from '@/tunnels'
88
88
 
89
+ import { bootChannelRestartGreeting, bootBackgroundObligations } from './background-handoff-boot'
89
90
  import { BUNDLED_PLUGINS } from './bundled-plugins'
90
91
  import { buildChannelSessionFactory } from './channel-session-factory'
91
92
  import { installFatalGuard } from './fatal-guard'
@@ -128,10 +129,7 @@ export type StartAgentOptions = {
128
129
  // over the real env + <cwd>/secrets.json. Injectable so tests can supply a
129
130
  // fake secrets provider without touching process.env.
130
131
  caps?: RuntimeCapabilities
131
- // Boot credential exporters are injectable so ordering tests can prove they
132
- // observe secrets only after the awaited provider-OAuth refresh settles.
133
- exportCodexAuthFile?: typeof exportCodexAuthFileForAgent
134
- exportClaudeCredentialsFile?: typeof exportClaudeCredentialsFileForAgent
132
+ // The GitHub CLI exporter observes secrets only after the boot refresh settles.
135
133
  exportGithubCliStore?: typeof exportGithubCliStoreForAgent
136
134
  // Boot-time proactive provider-OAuth refresh. Injectable so a test can supply
137
135
  // a refresh that holds the real secrets lock on a gate, proving the boot
@@ -200,8 +198,6 @@ async function startAgentRuntime(
200
198
  createChannelManager: createChannelManagerFor = createChannelManager,
201
199
  createTunnelManager: createTunnelManagerFor = createTunnelManager,
202
200
  caps = createRuntimeCapabilities(process.env, join(cwd, 'secrets.json')),
203
- exportCodexAuthFile = exportCodexAuthFileForAgent,
204
- exportClaudeCredentialsFile = exportClaudeCredentialsFileForAgent,
205
201
  exportGithubCliStore = exportGithubCliStoreForAgent,
206
202
  refreshProviderOAuth = refreshProviderOAuthForAgent,
207
203
  startResourceSampler: startResourceSamplerFor = startResourceSampler,
@@ -408,49 +404,25 @@ async function startAgentRuntime(
408
404
  // log. Channel-adapter OAuth already has host-side renewal crons; this is the
409
405
  // provider-OAuth equivalent.
410
406
  //
411
- // MUST be awaited, and MUST run before the credential-file exporters below
407
+ // MUST be awaited, and MUST run before the GitHub CLI store exporter below
412
408
  // and the first session-producing consumer (subagentConsumer.start /
413
- // cronConsumer.start / channelManager.start / the websocket server). The SDK
414
- // refresh holds SecretsBackend's async file lock across its network request;
415
- // getAuthFor()'s synchronous lock read gives up after ~200ms and
416
- // process.exit(1)s on ELOCKED. Fire-and-forget here would let a slow refresh
417
- // still own the lock when an exporter or consumer reads secrets — worse than
418
- // the lazy path. Awaiting behind this barrier guarantees no synchronous auth
419
- // reader exists while the refresh owns the lock. Never throws (the wrapper
420
- // swallows and logs), so a probe failure can't block boot; a refresh that
421
- // hangs on a wedged network hangs the first turn today anyway.
409
+ // cronConsumer.start / channelManager.start / the websocket server). The
410
+ // refresh holds SecretsBackend's file lock across its network request
411
+ // (`CredentialStore.modify`), while the synchronous readers the exporter and
412
+ // channel hydration use give up after ~200ms and throw ELOCKED.
413
+ // Fire-and-forget here would let a slow refresh still own the lock when an
414
+ // exporter or consumer reads secrets — worse than the lazy path. Awaiting
415
+ // behind this barrier guarantees no synchronous reader races the refresh.
416
+ // Never throws (the wrapper swallows and logs), so a probe failure can't block
417
+ // boot; a refresh that hangs on a wedged network hangs the first turn anyway.
422
418
  await refreshProviderOAuth({
423
419
  agentDir: cwd,
424
420
  log: (message) => console.warn(message),
425
421
  })
426
422
 
427
- // When the user has `docker.file.codexCli: true` AND a typeclaw-managed
428
- // openai-codex OAuth credential in secrets.json, write ~/.codex/auth.json
429
- // so the Codex CLI in the container can run without a second login. This runs
430
- // after the awaited boot refresh so the fresh ephemeral HOME receives the
431
- // refreshed token, never the stale pre-refresh value. The exporter is
432
- // failure-tolerant by design: any error (gate miss, fs error, corrupt file)
433
- // returns a non-fatal result and the agent boot continues. See
434
- // src/secrets/export-codex-auth-file.ts for the newer-wins compare that
435
- // prevents clobbering Codex CLI's in-place token refreshes.
436
- exportCodexAuthFile({
437
- agentDir: cwd,
438
- codexCliEnabled: cwdConfig.docker.file.codexCli,
439
- log: (message) => console.warn(message),
440
- })
441
-
442
- // Same shape as the codex exporter above, gated on `docker.file.claudeCode`
443
- // and `secrets.json#providers.anthropic`. It likewise runs after the boot
444
- // refresh, then writes ~/.claude/.credentials.json so the Claude Code CLI in
445
- // the container can run without the user pasting a CLAUDE_CODE_OAUTH_TOKEN.
446
- // See src/secrets/export-claude-credentials-file.ts for the newer-wins compare
447
- // that prevents clobbering Claude Code's in-place token refreshes, and the
448
- // read-merge-write that preserves any mcpOAuth state in the file.
449
- exportClaudeCredentialsFile({
450
- agentDir: cwd,
451
- claudeCodeEnabled: cwdConfig.docker.file.claudeCode,
452
- log: (message) => console.warn(message),
453
- })
423
+ // Coding credentials stay in the runtime; neither CLI receives an exported profile.
424
+ const stopCodingAgents = retainCodingAgentService(cwd)
425
+ registerBootCleanup(stopCodingAgents)
454
426
 
455
427
  const githubCliExport = exportGithubCliStore({
456
428
  agentDir: cwd,
@@ -478,15 +450,38 @@ async function startAgentRuntime(
478
450
  },
479
451
  })
480
452
 
453
+ const legacyBackgroundHandoffs = new LegacyBackgroundHandoffReader(cwd, {
454
+ onError: (error) => console.warn(`[run] legacy background upgrade failed: ${error}`),
455
+ })
456
+ const backgroundObligations = new BackgroundObligationStore(cwd, {
457
+ epoch: legacyBackgroundHandoffs.processEpoch,
458
+ onError: (error) => console.warn(`[run] background continuity failed: ${error}`),
459
+ })
481
460
  const liveSubagentRegistry = new LiveSubagentRegistry()
482
461
  const subagentCoalescer = new SubagentCoalescer()
483
462
  const liveSessionRegistry = new LiveSessionRegistry()
484
463
 
464
+ const recoveryOutbox = new RecoveryOutbox(cwd, {
465
+ epoch: backgroundObligations.epoch,
466
+ onError: (error) => console.warn(`[run] recovery outbox failed: ${error}`),
467
+ })
468
+ const inboundJournal = new InboundJournal(cwd, {
469
+ backgroundObligations,
470
+ onError: (error) => console.warn(`[run] inbound continuity recovery blocked: ${error}`),
471
+ })
472
+ registerBootCleanup(() => inboundJournal.close())
473
+ let recoveryDispatcher: RecoveryDispatcher | undefined
485
474
  const channelManager = createChannelManagerFor({
486
475
  agentDir: cwd,
476
+ backgroundObligations,
477
+ inboundJournal,
478
+ recoveryOutbox,
487
479
  secretsProvider: caps.secrets,
488
480
  channelsConfigRef: () => getConfig().channels,
489
481
  aliasesRef: () => getConfig().alias,
482
+ onRecoveryReady: () => {
483
+ void recoveryDispatcher?.wake().catch((error) => console.warn(`[run] recovery wake failed: ${error}`))
484
+ },
490
485
  tunnelUrlForChannel: (name) => resolveTunnelUrlForChannel(name, tunnelManager),
491
486
  tunnelConfiguredForChannel: (name) => isTunnelConfiguredForChannel(name),
492
487
  createSessionForChannel: buildChannelSessionFactory({
@@ -514,11 +509,6 @@ async function startAgentRuntime(
514
509
  stream,
515
510
  newestRunningChildSubagentStartedAt: (sessionId) =>
516
511
  newestRunningBackgroundChildStartedAt(liveSubagentRegistry.list({ parentSessionId: sessionId })),
517
- listRunningBackgroundSubagentNames: (sessionId) =>
518
- liveSubagentRegistry
519
- .list({ parentSessionId: sessionId })
520
- .filter((child) => child.status === 'running' && child.background === true)
521
- .map((child) => child.subagentName),
522
512
  cancelRunningSubagentsByWorkKey: (workKey, reason) => liveSubagentRegistry.cancelRunningByWorkKey(workKey, reason),
523
513
  onReload: async () => {
524
514
  const { results } = await reloadAllNonDestructive()
@@ -889,16 +879,20 @@ async function startAgentRuntime(
889
879
  // empty-turn fallback is suppressed: the review IS the turn's output, but it goes
890
880
  // through the GitHub API, not the channel send path. In-process router call — no
891
881
  // stream fan-out, since this is the recording session's own bookkeeping.
892
- setReviewOutputObserver((output) => {
893
- channelManager.router.noteGithubReviewOutput(output)
894
- })
882
+ setReviewCoverageCapture(async (sessionId) => ({
883
+ expectedAccountIdentity: await channelManager.router.captureTurnAccountIdentity?.(sessionId, 'github'),
884
+ inboundCoverage: (await channelManager.router.captureInboundResultCoverage?.(sessionId)) ?? [],
885
+ backgroundCoverage: (await channelManager.router.captureBackgroundResultCoverage?.(sessionId)) ?? [],
886
+ }))
887
+ registerBootCleanup(() => setReviewCoverageCapture(null))
888
+ setReviewOutputObserver((output) => channelManager.router.noteGithubReviewOutput(output).then(() => {}))
895
889
  registerBootCleanup(() => setReviewOutputObserver(null))
896
890
 
897
891
  // Registered before channels so its cache clear lands before any channel
898
892
  // session teardown observes it. secrets.json provider credentials are not
899
893
  // part of the typeclaw.json config diff, so a rotated key takes effect on
900
894
  // `typeclaw reload` only via this dedicated scope. Live sessions captured
901
- // their AuthStorage at creation, so teardown recreates them with fresh auth.
895
+ // their ModelRuntime at creation, so teardown recreates them with fresh auth.
902
896
  reloadRegistry.register(
903
897
  createProviderAuthReloadable({
904
898
  onProviderAuthChanged: () => channelManager.router.tearDownAllLive(),
@@ -907,36 +901,38 @@ async function startAgentRuntime(
907
901
 
908
902
  reloadRegistry.register(createChannelsReloadable({ manager: channelManager }))
909
903
 
910
- // Two-phase channel restart-resume around adapter startup, to close the race
911
- // where an adapter starts receiving before the resume claims the handoff:
912
- // 1. Claim the channel handoff and RESERVE the originating key BEFORE
913
- // channelManager.start(). The reservation installs a per-key gate, so an
914
- // inbound that arrives the instant an adapter connects coalesces onto the
915
- // resume instead of stale-rolling the mapping or creating a rival session.
916
- // 2. start() the adapters (registers outbound callbacks the wake reply needs).
917
- // 3. resume() the reservation: reopen the exact session and enqueue the wake
918
- // — skipped automatically if a real inbound already coalesced in (2)→(3).
919
- // Claims ONLY channel handoffs; tui handoffs are left on disk (peek-then-delete
920
- // never removes an unclaimed handoff) for the websocket open handler to claim.
921
- // Best-effort throughout: any failure leaves the todo to resume on the next inbound.
922
- let restartReservation: ReturnType<typeof channelManager.router.reserveRestartHandoff> = null
923
- try {
924
- const handoff = await consumeRestartHandoff(cwd, { accept: (h) => h.origin.kind === 'channel' })
925
- if (handoff !== null) restartReservation = channelManager.router.reserveRestartHandoff(handoff)
926
- } catch (err) {
927
- console.warn(`[run] channel restart-resume reserve failed: ${err instanceof Error ? err.message : err}`)
928
- }
929
-
930
904
  registerBootCleanup(() => channelManager.stop())
931
- await channelManager.start()
932
-
933
- if (restartReservation !== null) {
934
- try {
935
- await restartReservation.resume()
936
- } catch (err) {
937
- console.warn(`[run] channel restart-resume failed: ${err instanceof Error ? err.message : err}`)
938
- }
905
+ recoveryDispatcher = new RecoveryDispatcher(recoveryOutbox, channelManager.router, {
906
+ onError: (error) => console.warn(`[run] recovery dispatch failed: ${error}`),
907
+ backgroundObligations,
908
+ inboundJournal,
909
+ })
910
+ registerBootCleanup(() => recoveryDispatcher?.stop())
911
+ try {
912
+ // Attempted before adapters start or the dispatcher wakes; failure does not block either.
913
+ await bootBackgroundObligations({
914
+ inboundJournal,
915
+ obligations: backgroundObligations,
916
+ outbox: recoveryOutbox,
917
+ inventory: legacyBackgroundHandoffs,
918
+ })
919
+ } catch (error) {
920
+ // Keep the operator/adapter surface and verified inventory-only notices alive;
921
+ // the helper has already frozen dependent background progress.
922
+ console.warn(`[run] continuity blocked pending operator repair: ${error}`)
939
923
  }
924
+ // Growth-driven compaction runs on the journal's own writer queue once boot recovery has been
925
+ // attempted. A frozen journal is never rewritten; `inboundJournal.close()` (shutdown or
926
+ // boot-failure cleanup) stops maintenance and waits for a compaction already in progress.
927
+ inboundJournal.startMaintenance()
928
+ await bootChannelRestartGreeting({
929
+ agentDir: cwd,
930
+ router: channelManager.router,
931
+ configured: (key) => getConfig().channels[key.adapter] !== undefined,
932
+ startAdapters: () => channelManager.start(),
933
+ onError: (error) => console.warn(`[run] channel restart-resume failed: ${error}`),
934
+ })
935
+ await recoveryDispatcher.wake()
940
936
 
941
937
  // Captured separately from setSpawnSubagent so both the plugin context and
942
938
  // the plugin-command runner can dispatch through the same path. The setter
@@ -1107,10 +1103,18 @@ async function startAgentRuntime(
1107
1103
  subagentCompletionBridge.stop()
1108
1104
  prVerdictActivityBridge.stop()
1109
1105
  setReviewObserver(null)
1106
+ setReviewCoverageCapture(null)
1107
+ setReviewOutputObserver(null)
1108
+ await stopCodingAgents()
1110
1109
  await tunnelManager.stop()
1110
+ await recoveryDispatcher?.stop()
1111
1111
  await channelManager.stop()
1112
1112
  await mcpManager?.closeAll()
1113
1113
  } finally {
1114
+ await inboundJournal.close().catch((error) => console.warn(`[run] inbound continuity close failed: ${error}`))
1115
+ await backgroundObligations
1116
+ .flush()
1117
+ .catch((error) => console.warn(`[run] background continuity flush failed: ${error}`))
1114
1118
  await pluginsLoaded.disposePlugins()
1115
1119
  disposeProcessGlobals()
1116
1120
  }
@@ -1133,10 +1137,6 @@ async function startAgentRuntime(
1133
1137
  forceExit.unref()
1134
1138
  void (async () => {
1135
1139
  if (containerName !== undefined) {
1136
- // Persist the interrupted-subagent handoff BEFORE markRestartAbortForAllLive
1137
- // aborts the sessions and stop() tears them down — both read the same live
1138
- // set this write depends on.
1139
- await channelManager.router.writeInterruptedSubagentHandoff().catch(() => undefined)
1140
1140
  await markRestartAbortPendingForOrigin(cwd, { kind: 'tui', sessionId: 'tui' }).catch(() => undefined)
1141
1141
  await channelManager.router.markRestartAbortForAllLive().catch(() => undefined)
1142
1142
  }
@@ -1,5 +1,7 @@
1
1
  import { readdirSync, readFileSync, statfsSync } from 'node:fs'
2
2
 
3
+ import { readOomEvents, unclaimedOomEvents, type OomEventsReader } from '@/container/oom-events'
4
+
3
5
  const BYTES_PER_MB = 1024 * 1024
4
6
 
5
7
  export type ResourceSample = {
@@ -140,6 +142,7 @@ export type ResourceSamplerOptions = {
140
142
  collect?: () => ResourceSample
141
143
  emit?: (line: string) => void
142
144
  now?: () => number
145
+ readOomEvents?: OomEventsReader
143
146
  }
144
147
 
145
148
  // Returns a stop function rather than running forever so the caller owns the
@@ -150,10 +153,26 @@ export function startResourceSampler(options: ResourceSamplerOptions = {}): () =
150
153
  const collect = options.collect ?? (() => collectResourceSample())
151
154
  const emit = options.emit ?? ((line: string) => console.info(line))
152
155
  const now = options.now ?? (() => Date.now())
156
+ const readEvents = options.readOomEvents ?? readOomEvents
157
+ let previousOomEvents = readEvents()
153
158
 
154
159
  let watermark: SampleWatermark | null = null
155
160
  const tick = (): void => {
156
161
  try {
162
+ const currentOomEvents = readEvents()
163
+ if (currentOomEvents !== null) {
164
+ const events = previousOomEvents === null ? null : unclaimedOomEvents(previousOomEvents, currentOomEvents)
165
+ previousOomEvents = currentOomEvents
166
+ if (events !== null) {
167
+ const pressure = events.reachedLimit
168
+ ? 'container reached its memory limit'
169
+ : 'no container memory-limit event recorded (possible Docker VM/ancestor pressure)'
170
+ emit(
171
+ `[resource] OOM kill observed (oom_kill ${events.from}→${events.to}); runtime survived — a subprocess was killed; ${pressure}` +
172
+ (events.claimed.length === 0 ? '' : `; claimed by ${events.claimed.join(', ')}`),
173
+ )
174
+ }
175
+ }
157
176
  const sample = collect()
158
177
  const at = now()
159
178
  if (!shouldEmitSample(watermark, sample, at)) return
@@ -278,6 +278,10 @@ function appendMount(argv: string[], mount: SandboxMount): void {
278
278
  case 'bind':
279
279
  argv.push('--bind', mount.source, mount.dest)
280
280
  return
281
+ case 'ro-bind-fd':
282
+ case 'bind-fd':
283
+ argv.push(`--${mount.type}`, String(mount.fd), mount.dest)
284
+ return
281
285
  case 'tmpfs':
282
286
  argv.push('--tmpfs', mount.dest)
283
287
  return
@@ -0,0 +1,214 @@
1
+ import { lstat, realpath } from 'node:fs/promises'
2
+ import { join, posix, resolve } from 'node:path'
3
+
4
+ import { createAndOpenAnchoredDirectory } from '@/agent/tool-file-safety'
5
+ import { config } from '@/config/config'
6
+
7
+ import { canMountRealProc, ensureBwrapAvailable, getProcBindSafetyVerdict } from './availability'
8
+ import { buildSandboxedCommand, type SandboxedCommand } from './build'
9
+ import {
10
+ CANONICAL_AGENT_SECRET_DIRS,
11
+ CANONICAL_AGENT_SECRET_FILES,
12
+ CANONICAL_HOME_SECRET_DIRS,
13
+ CANONICAL_HOME_SECRET_FILES,
14
+ } from './canonical-secrets'
15
+ import { verifyHiddenMaskTargets } from './hidden-paths'
16
+ import { DEFAULT_SANDBOX_ENV, type SandboxMount, type SandboxPolicy, type SandboxProcStrategy } from './policy'
17
+ import { formatCommand } from './quote'
18
+ import { CANONICAL_AGENT_RUNTIME_PRIVATE_FILES } from './runtime-private'
19
+
20
+ export const CODING_SOURCE = '/typeclaw-coding-source'
21
+ export const CODING_MASK_DIRS = [
22
+ ...CANONICAL_AGENT_SECRET_DIRS,
23
+ // Repository-scoped Claude/Codex settings are executable project context,
24
+ // not the runtime HOME profiles (HOME is never mounted). Mask their auth files.
25
+ ...CANONICAL_HOME_SECRET_DIRS.filter((dir) => dir !== '.claude' && dir !== '.codex'),
26
+ '.typeclaw',
27
+ ] as const
28
+ export const CODING_MASK_FILES = [
29
+ ...CANONICAL_AGENT_SECRET_FILES,
30
+ ...CANONICAL_HOME_SECRET_FILES,
31
+ ...CANONICAL_AGENT_RUNTIME_PRIVATE_FILES,
32
+ '.claude/.credentials.json',
33
+ '.codex/auth.json',
34
+ ] as const
35
+
36
+ export function codingSourceMaskDirs(source: string, taskRoot: string): readonly string[] {
37
+ return source === resolve(taskRoot, '../../..') ? [...CODING_MASK_DIRS, 'workspace'] : CODING_MASK_DIRS
38
+ }
39
+
40
+ export type CodingSandboxOptions = {
41
+ readonly source: string
42
+ readonly taskRoot: string
43
+ readonly mode: 'code' | 'plan' | 'snapshot'
44
+ readonly cwd: string
45
+ readonly env?: Record<string, string>
46
+ readonly engine?: 'claude' | 'codex' | 'omo'
47
+ }
48
+
49
+ export async function assertCodingDirectory(path: string): Promise<void> {
50
+ const absolute = resolve(path)
51
+ if ((await realpath(absolute)) !== absolute || !(await lstat(absolute)).isDirectory()) {
52
+ throw new Error('Coding task directory is a symlink or changed identity.')
53
+ }
54
+ }
55
+
56
+ export async function codingSandboxPolicy(
57
+ options: CodingSandboxOptions,
58
+ proc: SandboxProcStrategy,
59
+ ): Promise<SandboxPolicy> {
60
+ await assertCodingDirectory(options.source)
61
+ await assertCodingDirectory(options.taskRoot)
62
+ // Keep the canonical alias checks: unmounting the write directory must not
63
+ // admit a pre-existing credential hardlink into otherwise visible Git/task data.
64
+ const dirs: string[] = []
65
+ const files: string[] = []
66
+ for (const name of new Set([...codingSourceMaskDirs(options.source, options.taskRoot), ...CODING_MASK_FILES])) {
67
+ const path = join(options.source, name)
68
+ const stat = await lstat(path).catch((error: unknown) => {
69
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
70
+ throw error
71
+ })
72
+ if (!stat) continue
73
+ if (stat.isSymbolicLink() || (!stat.isDirectory() && (!stat.isFile() || stat.nlink !== 1))) {
74
+ throw new Error('Source has an unsafe canonical mask target.')
75
+ }
76
+ if (stat.isDirectory()) dirs.push(path)
77
+ else files.push(path)
78
+ }
79
+ await verifyHiddenMaskTargets({ dirs, files })
80
+ const sourceGit = join(options.source, '.git')
81
+ if (options.mode === 'snapshot') {
82
+ await assertCodingDirectory(sourceGit)
83
+ }
84
+ const configMasks: string[] = []
85
+ if (options.engine === 'omo') {
86
+ // Only these ancestors are visible through the task bind. Other host
87
+ // ancestors (including the real HOME) are absent in the empty sandbox root.
88
+ for (const directory of [options.taskRoot, join(options.taskRoot, 'worktree')]) {
89
+ const omo = join(directory, '.omo')
90
+ const stat = await lstat(omo).catch((error: unknown) => {
91
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
92
+ throw error
93
+ })
94
+ if (!stat) continue
95
+ await assertCodingDirectory(omo)
96
+ for (const name of ['omo.json', 'omo.jsonc']) {
97
+ const file = join(omo, name)
98
+ const target = await lstat(file).catch((error: unknown) => {
99
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
100
+ throw error
101
+ })
102
+ if (!target) continue
103
+ if (!target.isFile() || target.nlink !== 1) throw new Error('Unsafe OmO project configuration operand.')
104
+ configMasks.push(file)
105
+ }
106
+ }
107
+ }
108
+ return {
109
+ cwd: options.cwd,
110
+ proc,
111
+ network: 'inherit',
112
+ env: { set: options.env ?? {} },
113
+ ...(configMasks.length ? { masks: { files: configMasks } } : {}),
114
+ mounts: [
115
+ // Never bind the live source worktree: credential rotation can create
116
+ // arbitrary siblings and replace masked inodes there during an invocation.
117
+ // Only snapshot bootstrap needs source Git metadata, not its parent.
118
+ ...(options.mode === 'snapshot'
119
+ ? [{ type: 'ro-bind' as const, source: sourceGit, dest: posix.join(CODING_SOURCE, '.git') }]
120
+ : []),
121
+ { type: 'bind', source: options.taskRoot, dest: options.taskRoot },
122
+ ...(options.mode === 'plan'
123
+ ? [
124
+ { type: 'ro-bind' as const, source: join(options.taskRoot, 'git'), dest: join(options.taskRoot, 'git') },
125
+ {
126
+ type: 'ro-bind' as const,
127
+ source: join(options.taskRoot, 'worktree'),
128
+ dest: join(options.taskRoot, 'worktree'),
129
+ },
130
+ ]
131
+ : []),
132
+ ],
133
+ }
134
+ }
135
+
136
+ export async function prepareCodingCommand(
137
+ argv: readonly string[],
138
+ options: CodingSandboxOptions,
139
+ ): Promise<SandboxedCommand & { extraFiles: Array<number | 'ignore'>; cleanup(): Promise<void> }> {
140
+ await ensureBwrapAvailable()
141
+ fdBindSupport ??= supportsFdBinds()
142
+ if (!(await fdBindSupport)) {
143
+ throw new Error(
144
+ 'Coding delegation requires bwrap --bind-fd support. Rebuild the TypeClaw container image; ordinary bash is unaffected.',
145
+ )
146
+ }
147
+ const proc =
148
+ config.sandbox.realProc && (await canMountRealProc())
149
+ ? 'real-proc'
150
+ : (await getProcBindSafetyVerdict()) === 'safe'
151
+ ? 'proc-bind'
152
+ : undefined
153
+ if (!proc)
154
+ throw new Error(
155
+ 'Coding delegation requires a verified safe /proc sandbox. Fix the container user-namespace policy and retry.',
156
+ )
157
+ const policy = await codingSandboxPolicy(options, proc)
158
+ const capabilities: Record<string, string> = {}
159
+ const settings = { ...options.env }
160
+ for (const name of ['ANTHROPIC_AUTH_TOKEN', 'TYPECLAW_CODING_AGENT_CAPABILITY']) {
161
+ const value = settings[name]
162
+ if (value) {
163
+ capabilities[name] = value
164
+ delete settings[name]
165
+ }
166
+ }
167
+ // Capabilities travel in the explicit environment, never visible process argv.
168
+ policy.env = { set: settings, inherit: Object.keys(capabilities) }
169
+ const opened: Awaited<ReturnType<typeof createAndOpenAnchoredDirectory>>[] = []
170
+ // buildSandboxedCommand reserves descriptors starting at 3 for file masks.
171
+ // Keep anchored bind descriptors above them: shell mask redirects must never
172
+ // replace the task/source directory handles before bwrap consumes them.
173
+ const extraFiles: Array<number | 'ignore'> = (policy.masks?.files ?? []).map(() => 'ignore')
174
+ try {
175
+ const mounts: SandboxMount[] = []
176
+ // Native FD binds verify inode identity after mounting AND consume the FD.
177
+ // A plain bind of /proc/self/fd/N does neither: it resolves the path and
178
+ // leaves a directory handle capable of bypassing masks in the final child.
179
+ for (const mount of policy.mounts ?? []) {
180
+ if (mount.type !== 'bind' && mount.type !== 'ro-bind') {
181
+ mounts.push(mount)
182
+ continue
183
+ }
184
+ const file = await createAndOpenAnchoredDirectory(mount.source, false)
185
+ opened.push(file)
186
+ mounts.push({
187
+ type: mount.type === 'bind' ? 'bind-fd' : 'ro-bind-fd',
188
+ fd: 3 + extraFiles.length,
189
+ dest: mount.dest,
190
+ })
191
+ extraFiles.push(file.fd)
192
+ }
193
+ policy.mounts = mounts
194
+ const built = buildSandboxedCommand(`exec ${formatCommand([...argv])}`, policy)
195
+ return {
196
+ ...built,
197
+ spawnEnv: { ...built.spawnEnv, ...capabilities },
198
+ extraFiles,
199
+ cleanup: async () => {
200
+ await Promise.all(opened.map((file) => file.close()))
201
+ },
202
+ }
203
+ } catch (error) {
204
+ await Promise.all(opened.map((file) => file.close()))
205
+ throw error
206
+ }
207
+ }
208
+
209
+ let fdBindSupport: Promise<boolean> | undefined
210
+ async function supportsFdBinds(): Promise<boolean> {
211
+ const child = Bun.spawn(['bwrap', '--help'], { env: DEFAULT_SANDBOX_ENV, stdout: 'pipe', stderr: 'ignore' })
212
+ const help = await new Response(child.stdout).text()
213
+ return (await child.exited) === 0 && help.includes('--bind-fd') && help.includes('--ro-bind-fd')
214
+ }
@@ -1,6 +1,7 @@
1
1
  export type SandboxMount =
2
2
  | { type: 'ro-bind'; source: string; dest: string }
3
3
  | { type: 'bind'; source: string; dest: string }
4
+ | { type: 'ro-bind-fd' | 'bind-fd'; fd: number; dest: string }
4
5
  | { type: 'tmpfs'; dest: string }
5
6
  | { type: 'dev'; dest: string }
6
7
 
@@ -1,4 +1,7 @@
1
1
  // Runtime-owned operational state is private to TypeClaw, but is not a
2
2
  // credential. Keep this category separate from canonical-secrets so security
3
3
  // diagnostics never mislabel incident metadata as secret material.
4
- export const CANONICAL_AGENT_RUNTIME_PRIVATE_FILES = ['.typeclaw/incidents.json'] as const
4
+ export const CANONICAL_AGENT_RUNTIME_PRIVATE_FILES = [
5
+ '.typeclaw/incidents.json',
6
+ '.typeclaw/coding-agent-tasks.json',
7
+ ] as const