typeclaw 0.48.13 → 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 (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
package/src/init/index.ts CHANGED
@@ -1003,9 +1003,8 @@ export async function readExistingProviderApiKey(root: string, providerId: Known
1003
1003
  // shaped, or the access token is absent/blank.
1004
1004
  //
1005
1005
  // The token lives under `access` — pi-ai's secrets.json shape (`{ type:
1006
- // 'oauth', access, refresh, expires, accountId }`), the same field
1007
- // `export-codex-auth-file.ts` reads. NOT `access_token`: that key belongs to
1008
- // the unrelated `~/.codex/auth.json` export (`{ tokens: { access_token } }`).
1006
+ // 'oauth', access, refresh, expires, accountId }`). NOT `access_token`, which
1007
+ // belongs to the native Codex auth.json format that TypeClaw no longer exports.
1009
1008
  // Reading `access_token` here silently returned false for every real
1010
1009
  // credential, re-running the browser login on resume instead of reusing it.
1011
1010
  //
package/src/mcp/client.ts CHANGED
@@ -7,6 +7,7 @@ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'
7
7
  import { CallToolResultSchema, type CallToolResult, type ListToolsRequest } from '@modelcontextprotocol/sdk/types.js'
8
8
 
9
9
  import type { McpServer } from '@/config/config'
10
+ import { withToolOomPriorityArgv } from '@/container/tool-oom-priority'
10
11
  import type { ToolFileOperands } from '@/plugin'
11
12
  import { resolveSecret } from '@/secrets/resolve'
12
13
 
@@ -207,7 +208,8 @@ export function createTransport(
207
208
  authProvider?: OAuthClientProvider,
208
209
  ): Transport {
209
210
  if (server.command) {
210
- return new StdioClientTransport({ command: server.command, args: server.args, env: resolveServerEnv(server, env) })
211
+ const [command = server.command, ...args] = withToolOomPriorityArgv([server.command, ...server.args])
212
+ return new StdioClientTransport({ command, args, env: resolveServerEnv(server, env) })
211
213
  }
212
214
  const url = new URL(requiredUrl(server))
213
215
  return authProvider === undefined
@@ -1,11 +1,17 @@
1
1
  import { isSecretShapedToken } from '@/bundled-plugins/memory/secret-detector'
2
2
 
3
+ export type BuiltinSearchBin = 'rg' | 'fd'
4
+
3
5
  export type OperationalIncidentFact =
4
6
  | { kind: 'bash-command-not-found'; bin: string }
5
7
  | { kind: 'declared-skill-bin-unresolved'; bin: string }
6
8
  | { kind: 'sandbox-proc-unavailable' }
9
+ | { kind: 'builtin-search-bin-unavailable'; bin: BuiltinSearchBin }
7
10
 
8
- export type OperationalIncidentResolutionSignal = 'successful-bin' | 'successful-sandbox-real-proc'
11
+ export type OperationalIncidentResolutionSignal =
12
+ | 'successful-bin'
13
+ | 'successful-sandbox-real-proc'
14
+ | 'successful-builtin-search-tool'
9
15
 
10
16
  export type OperationalIncidentSuccessInput = {
11
17
  tool: string
@@ -17,6 +23,7 @@ export const OPERATIONAL_INCIDENT_RESOLUTION_SIGNAL_BY_KIND = {
17
23
  'bash-command-not-found': 'successful-bin',
18
24
  'declared-skill-bin-unresolved': 'successful-bin',
19
25
  'sandbox-proc-unavailable': 'successful-sandbox-real-proc',
26
+ 'builtin-search-bin-unavailable': 'successful-builtin-search-tool',
20
27
  } as const satisfies Record<OperationalIncidentFact['kind'], OperationalIncidentResolutionSignal>
21
28
 
22
29
  export class DeclaredSkillBinUnresolvedError extends Error {
@@ -32,10 +39,30 @@ const COMMAND_NOT_FOUND = new RegExp(
32
39
  `^(?:/bin/bash: |bash: line [1-9][0-9]{0,5}: )(${SAFE_BIN}): command not found\\n(?:\\n){1,2}Command exited with code 127$`,
33
40
  )
34
41
 
42
+ // Pi's grep/find reject with these fixed literals when `ensureTool` returns no
43
+ // rg/fd path (pi packages/coding-agent/src/core/tools/{grep,find}.ts; published
44
+ // dist/core/tools/{grep,find}.js, identical in 0.87.1, 0.99.2, and 1.0.0).
45
+ // Classification accepts the literal alone or followed by the exact `: `
46
+ // separator and untrusted context. Context is never parsed or persisted; the
47
+ // bin comes only from the closed grep->rg/find->fd tool mapping. This contract
48
+ // needs no unreleased Pi format. Wording drift stays an ordinary tool failure;
49
+ // re-verify the literals and default-operations invariant on every Pi bump.
50
+ const BUILTIN_SEARCH_TOOLS = {
51
+ grep: { bin: 'rg', unavailable: 'ripgrep (rg) is not available and could not be downloaded' },
52
+ find: { bin: 'fd', unavailable: 'fd is not available and could not be downloaded' },
53
+ } as const satisfies Record<string, { bin: BuiltinSearchBin; unavailable: string }>
54
+
35
55
  export function classifyToolOutcome(input: { tool: string; error: unknown }): OperationalIncidentFact | null {
36
56
  if (input.error instanceof DeclaredSkillBinUnresolvedError && isSafeBin(input.error.bin)) {
37
57
  return { kind: 'declared-skill-bin-unresolved', bin: input.error.bin }
38
58
  }
59
+ const searchTool = builtinSearchTool(input.tool)
60
+ if (searchTool !== undefined) {
61
+ if (!(input.error instanceof Error)) return null
62
+ const { message } = input.error
63
+ const unavailable = message === searchTool.unavailable || message.startsWith(`${searchTool.unavailable}: `)
64
+ return unavailable ? { kind: 'builtin-search-bin-unavailable', bin: searchTool.bin } : null
65
+ }
39
66
  if (input.tool !== 'bash' || !(input.error instanceof Error)) return null
40
67
  if (input.error.name === 'SandboxDegradedProcError') return { kind: 'sandbox-proc-unavailable' }
41
68
 
@@ -47,6 +74,12 @@ export function classifyToolOutcome(input: { tool: string; error: unknown }): Op
47
74
  export function deriveOperationalIncidentFactsForSuccess(
48
75
  input: OperationalIncidentSuccessInput,
49
76
  ): OperationalIncidentFact[] {
77
+ // TypeClaw builds grep/find without custom operations (createPiBuiltinToolDefinition),
78
+ // so a successful pi grep/find run proves `ensureTool` returned an rg/fd path.
79
+ // Passing a custom `operations.glob` to find would bypass fd and break this proof.
80
+ // Bash `rg`/`fd` runs never count: they use the sandbox PATH, not pi's tool bin.
81
+ const searchTool = builtinSearchTool(input.tool)
82
+ if (searchTool !== undefined) return [{ kind: 'builtin-search-bin-unavailable', bin: searchTool.bin }]
50
83
  if (input.tool !== 'bash') return []
51
84
  const command = input.args.command
52
85
  if (typeof command !== 'string') return []
@@ -64,6 +97,17 @@ function bashCommandNotFoundFact(bin: string): OperationalIncidentFact | null {
64
97
  return isSafeBin(bin) ? { kind: 'bash-command-not-found', bin } : null
65
98
  }
66
99
 
100
+ function builtinSearchTool(tool: string): (typeof BUILTIN_SEARCH_TOOLS)[keyof typeof BUILTIN_SEARCH_TOOLS] | undefined {
101
+ switch (tool) {
102
+ case 'grep':
103
+ return BUILTIN_SEARCH_TOOLS.grep
104
+ case 'find':
105
+ return BUILTIN_SEARCH_TOOLS.find
106
+ default:
107
+ return undefined
108
+ }
109
+ }
110
+
67
111
  function successfulBinFacts(bin: string): OperationalIncidentFact[] {
68
112
  if (!isSafeBin(bin)) return []
69
113
  return [
@@ -40,11 +40,16 @@ export function incidentsPath(agentDir: string): string {
40
40
  }
41
41
 
42
42
  export function fingerprintIncident(fact: OperationalIncidentFact): string {
43
- if (fact.kind === 'sandbox-proc-unavailable') return 'sandbox:proc-unavailable'
44
- const bin = normalizeBin(fact.bin)
45
- return fact.kind === 'bash-command-not-found'
46
- ? `bash:command-not-found:${bin}`
47
- : `skill-bin:declared-but-unresolved:${bin}`
43
+ switch (fact.kind) {
44
+ case 'sandbox-proc-unavailable':
45
+ return 'sandbox:proc-unavailable'
46
+ case 'bash-command-not-found':
47
+ return `bash:command-not-found:${normalizeBin(fact.bin)}`
48
+ case 'declared-skill-bin-unresolved':
49
+ return `skill-bin:declared-but-unresolved:${normalizeBin(fact.bin)}`
50
+ case 'builtin-search-bin-unavailable':
51
+ return `builtin-search:bin-unavailable:${fact.bin}`
52
+ }
48
53
  }
49
54
 
50
55
  export function deriveMechanicallyVerifiedIncidentFingerprints(input: OperationalIncidentSuccessInput): Set<string> {
@@ -10,6 +10,6 @@ export const PI_BUILTIN_TOOL_NAMES: readonly PiBuiltinToolName[] = [
10
10
  'ls',
11
11
  ]
12
12
 
13
- export const CORE_SYSTEM_TOOL_NAMES = ['web_search', 'web_fetch', 'look_at'] as const
13
+ export const CORE_SYSTEM_TOOL_NAMES = ['web_search', 'web_fetch', 'look_at', 'coding_agent'] as const
14
14
 
15
15
  export const CORE_TOOL_NAMES: ReadonlySet<string> = new Set([...PI_BUILTIN_TOOL_NAMES, ...CORE_SYSTEM_TOOL_NAMES])
@@ -80,3 +80,4 @@ export const findTool: BuiltinToolRef = { __builtinTool: 'find' }
80
80
  export const lsTool: BuiltinToolRef = { __builtinTool: 'ls' }
81
81
  export const webSearchTool: BuiltinToolRef = { __builtinTool: 'web_search' }
82
82
  export const webFetchTool: BuiltinToolRef = { __builtinTool: 'web_fetch' }
83
+ export const codingAgentTool: BuiltinToolRef = { __builtinTool: 'coding_agent' }
@@ -1,5 +1,6 @@
1
1
  export {
2
2
  bashTool,
3
+ codingAgentTool,
3
4
  defineCommand,
4
5
  definePlugin,
5
6
  defineSubagent,
@@ -54,7 +54,12 @@ export type SubagentContext<P = unknown> = {
54
54
  payload: P
55
55
  }
56
56
 
57
- export type RunSession = (override?: { userPrompt?: string }) => Promise<void>
57
+ export type RunSession = (override?: {
58
+ userPrompt?: string
59
+ // Called after a completed run with the terminal assistant text, or null
60
+ // after an empty terminal response or provider failure. No block projection.
61
+ onFinalMessage?: (message: string | null) => void
62
+ }) => Promise<void>
58
63
 
59
64
  // The plugin-author-facing subagent declaration. Differs from
60
65
  // `@/agent/subagents`'s `Subagent` only in the shape of `tools`/`customTools`:
@@ -0,0 +1,86 @@
1
+ import { consumeRestartHandoff } from '@/agent/restart-handoff'
2
+ import type { LegacyBackgroundHandoffReader } from '@/channels/background-handoff'
3
+ import type { BackgroundObligationStore } from '@/channels/background-obligations'
4
+ import type { InboundJournal } from '@/channels/inbound-journal'
5
+ import { loadChannelSessions } from '@/channels/persistence'
6
+ import type { RecoveryOutbox } from '@/channels/recovery-outbox'
7
+ import type { ChannelRouter, RestartReservation } from '@/channels/router'
8
+ import { channelKeyId, type ChannelKey } from '@/channels/types'
9
+
10
+ /**
11
+ * Transfer interrupted source authority at boot, before adapters or the dispatcher run; never replay work.
12
+ * Committed mixed decisions are repaired first, issued transfers re-import unchanged, inbound-seeded
13
+ * partitions absorb their compatible children, and only then do legacy inventory and unmatched
14
+ * children take their independent notices. A failure freezes dependent background progress
15
+ * (apparently valid child JSON is not proof of independence from an unreadable journal) and is
16
+ * rethrown; the caller keeps adapters running and dependent notices fail closed at dispatch.
17
+ */
18
+ export async function bootBackgroundObligations(options: {
19
+ inboundJournal: InboundJournal
20
+ obligations: BackgroundObligationStore
21
+ outbox: RecoveryOutbox
22
+ inventory: LegacyBackgroundHandoffReader
23
+ }): Promise<void> {
24
+ try {
25
+ await options.inboundJournal.initialize()
26
+ await options.inboundJournal.repair()
27
+ await options.inboundJournal.importOldEpoch(options.outbox)
28
+ await options.obligations.migrateLegacy(options.inventory, options.outbox)
29
+ await options.obligations.importOldEpoch(options.outbox)
30
+ } catch (error) {
31
+ options.obligations.setFrozen(error)
32
+ throw error
33
+ }
34
+ }
35
+
36
+ /** Ordinary #291 restart greetings retain their reservation/TTL behavior. */
37
+ export async function bootChannelRestartGreeting(options: {
38
+ agentDir: string
39
+ router: Pick<ChannelRouter, 'reserveRestartHandoff'>
40
+ configured: (key: ChannelKey) => boolean
41
+ startAdapters: () => Promise<void>
42
+ onError: (error: unknown) => void
43
+ }): Promise<void> {
44
+ const report = (error: unknown): void => {
45
+ try {
46
+ options.onError(error)
47
+ } catch {
48
+ // Reporting must not strand a greeting reservation.
49
+ }
50
+ }
51
+ let reservation: RestartReservation | null = null
52
+ try {
53
+ const explicit = await consumeRestartHandoff(options.agentDir, {
54
+ accept: (handoff) => handoff.origin.kind === 'channel',
55
+ })
56
+ if (explicit?.origin.kind === 'channel') {
57
+ try {
58
+ const originalKey = explicit.origin.key
59
+ const mappings = await loadChannelSessions(options.agentDir)
60
+ if (
61
+ options.configured(originalKey) &&
62
+ mappings.some(
63
+ (mapping) =>
64
+ channelKeyId(mapping) === channelKeyId(originalKey) &&
65
+ mapping.sessionId === explicit.originatingSessionId,
66
+ )
67
+ ) {
68
+ const { interruptedSubagents: _coveredLostWork, ...greeting } = explicit
69
+ reservation = options.router.reserveRestartHandoff(greeting)
70
+ }
71
+ } catch (error) {
72
+ report(error)
73
+ }
74
+ }
75
+ await options.startAdapters()
76
+ if (reservation) {
77
+ try {
78
+ await reservation.resume()
79
+ } catch (error) {
80
+ report(error)
81
+ }
82
+ }
83
+ } finally {
84
+ reservation?.release()
85
+ }
86
+ }
package/src/run/index.ts CHANGED
@@ -7,7 +7,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,11 +404,11 @@ 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
409
  // cronConsumer.start / channelManager.start / the websocket server). The
414
410
  // refresh holds SecretsBackend's file lock across its network request
415
- // (`CredentialStore.modify`), while the synchronous readers the exporters and
411
+ // (`CredentialStore.modify`), while the synchronous readers the exporter and
416
412
  // channel hydration use give up after ~200ms and throw ELOCKED.
417
413
  // Fire-and-forget here would let a slow refresh still own the lock when an
418
414
  // exporter or consumer reads secrets — worse than the lazy path. Awaiting
@@ -424,33 +420,9 @@ async function startAgentRuntime(
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,9 +879,13 @@ 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
@@ -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