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/init/index.ts CHANGED
@@ -29,7 +29,7 @@ import {
29
29
  } from '@/container'
30
30
  import { hooklessGitArgs } from '@/git/hookless'
31
31
  import { commitSystemFile } from '@/git/system-commit'
32
- import { createSecretsStoreForAgent, type Channels, type Secret, SecretsBackend } from '@/secrets'
32
+ import { type Channels, type Secret, SecretsBackend } from '@/secrets'
33
33
  import { hostLocaleIsCjk } from '@/shared/host-locale'
34
34
  import { isWindows } from '@/shared/platform'
35
35
  import { createTui } from '@/tui'
@@ -949,10 +949,10 @@ export async function writeSecrets(
949
949
  visionProviderId !== null &&
950
950
  KNOWN_PROVIDERS[visionProviderId].apiKeyEnv !== null
951
951
  if (wantsDefaultKey || wantsVisionKey) {
952
- const secretsStore = createSecretsStoreForAgent(join(root, 'secrets.json'))
953
- if (wantsDefaultKey) secretsStore.set(providerId, { type: 'api_key', key: apiKey! })
952
+ const backend = new SecretsBackend(join(root, 'secrets.json'))
953
+ if (wantsDefaultKey) backend.writeProviderCredentialSync(providerId, { type: 'api_key', key: { value: apiKey! } })
954
954
  if (wantsVisionKey) {
955
- secretsStore.set(visionProviderId, { type: 'api_key', key: visionApiKey! })
955
+ backend.writeProviderCredentialSync(visionProviderId, { type: 'api_key', key: { value: visionApiKey! } })
956
956
  }
957
957
  }
958
958
 
@@ -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
  //
@@ -1,5 +1,8 @@
1
1
  import { join } from 'node:path'
2
2
 
3
+ import type { AuthInteraction, AuthPrompt } from '@earendil-works/pi-ai'
4
+ import { ModelRuntime } from '@earendil-works/pi-coding-agent'
5
+
3
6
  import {
4
7
  KNOWN_PROVIDERS,
5
8
  providerForModelRef,
@@ -14,13 +17,14 @@ export type OAuthLoginResult = { ok: true } | { ok: false; reason: string }
14
17
  export type OAuthLoginRunner = (options: { cwd: string; model: ModelRef | string }) => Promise<OAuthLoginResult>
15
18
 
16
19
  // Wrap pi-ai's OAuth callbacks so the CLI doesn't have to know about the
17
- // upstream callback shape. The CLI sees four lifecycle events:
20
+ // upstream callback shape. The CLI sees five lifecycle events:
18
21
  // (1) onAuth(url) — print the URL the user must visit
19
22
  // (2) onProgress(message) — show waiting/finalizing status
20
- // (3) onPrompt(prompt) — ask the user for a manual code if the browser flow
23
+ // (3) onSelect(message, options) — choose a provider-defined option by ID
24
+ // (4) onPrompt(prompt) — ask the user for a manual code if the browser flow
21
25
  // can't reach the local callback server. Fires only after the local
22
26
  // server gave up (bind error -> waitForCode resolves null).
23
- // (4) onManualCodeInput() — concurrent paste input that RACES the local
27
+ // (5) onManualCodeInput() — concurrent paste input that RACES the local
24
28
  // callback server. Required for cross-device flows: pi-ai's openai-codex
25
29
  // OAuth hardcodes redirect_uri=http://localhost:1455/auth/callback, which
26
30
  // resolves to the *browser's* machine. When the user runs `typeclaw init`
@@ -32,11 +36,19 @@ export type OAuthLoginRunner = (options: { cwd: string; model: ModelRef | string
32
36
  // code first wins. parseAuthorizationInput on the upstream side accepts
33
37
  // the full redirect URL, the bare `code=...&state=...` query string, or
34
38
  // just the code value.
39
+ export type OAuthSelectOption = Extract<AuthPrompt, { type: 'select' }>['options'][number]
40
+
35
41
  export type OAuthCallbacks = {
36
42
  onAuth: (url: string, instructions?: string) => void
37
43
  onProgress?: (message: string) => void
38
- onPrompt: (message: string, placeholder?: string) => Promise<string | null>
39
- onManualCodeInput?: () => Promise<string>
44
+ onPrompt: (message: string, placeholder?: string, signal?: AbortSignal) => Promise<string | null>
45
+ onSecret: (message: string, placeholder?: string, signal?: AbortSignal) => Promise<string | null>
46
+ onSelect: (
47
+ message: string,
48
+ options: readonly OAuthSelectOption[],
49
+ signal?: AbortSignal,
50
+ ) => Promise<OAuthSelectOption['id'] | null>
51
+ onManualCodeInput?: (signal?: AbortSignal) => Promise<string>
40
52
  }
41
53
 
42
54
  // Default runner: real OAuth flow against pi-ai. Tests inject a stub to skip
@@ -52,19 +64,12 @@ export function makeOAuthLoginRunner(callbacks: OAuthCallbacks): OAuthLoginRunne
52
64
  }
53
65
 
54
66
  try {
55
- const secrets = createSecretsStoreForAgent(join(cwd, 'secrets.json'))
56
- await secrets.login(provider.oauthProviderId, {
57
- onAuth: (info) => callbacks.onAuth(info.url, info.instructions),
58
- onProgress: callbacks.onProgress,
59
- onPrompt: async (prompt) => {
60
- const value = await callbacks.onPrompt(prompt.message, prompt.placeholder)
61
- if (value === null) {
62
- throw new Error('Login cancelled by user')
63
- }
64
- return value
65
- },
66
- onManualCodeInput: callbacks.onManualCodeInput,
67
+ const modelRuntime = await ModelRuntime.create({
68
+ credentials: createSecretsStoreForAgent(join(cwd, 'secrets.json')),
69
+ modelsPath: null,
70
+ refreshOnCreate: false,
67
71
  })
72
+ await modelRuntime.login(provider.oauthProviderId, 'oauth', createOAuthInteraction(callbacks))
68
73
  return { ok: true }
69
74
  } catch (error) {
70
75
  return { ok: false, reason: error instanceof Error ? error.message : String(error) }
@@ -72,6 +77,41 @@ export function makeOAuthLoginRunner(callbacks: OAuthCallbacks): OAuthLoginRunne
72
77
  }
73
78
  }
74
79
 
80
+ // Isolate the pi 0.87 AuthInteraction adaptation so manual-code prompt
81
+ // cancellation and callback forwarding remain behavior-testable without a
82
+ // live provider login.
83
+ export function createOAuthInteraction(callbacks: OAuthCallbacks): AuthInteraction {
84
+ return {
85
+ notify: (event) => {
86
+ if (event.type === 'auth_url') callbacks.onAuth(event.url, event.instructions)
87
+ else if (event.type === 'progress') callbacks.onProgress?.(event.message)
88
+ else if (event.type === 'device_code') callbacks.onAuth(event.verificationUri, `Enter code ${event.userCode}`)
89
+ },
90
+ prompt: async (prompt) => {
91
+ if (prompt.type === 'select') {
92
+ const value = await callbacks.onSelect(prompt.message, prompt.options, prompt.signal)
93
+ // pi-ai 0.87 requires select prompts to resolve with an option ID
94
+ // (dist/auth/types.d.ts:153-155); reject stale/corrupt UI values as cancellation.
95
+ if (value === null || !prompt.options.some((option) => option.id === value)) {
96
+ throw new Error('Login cancelled by user')
97
+ }
98
+ return value
99
+ }
100
+ if (prompt.type === 'manual_code' && callbacks.onManualCodeInput) {
101
+ return await callbacks.onManualCodeInput(prompt.signal)
102
+ }
103
+ const callback = prompt.type === 'secret' ? callbacks.onSecret : callbacks.onPrompt
104
+ if (prompt.type === 'text' || prompt.type === 'secret' || prompt.type === 'manual_code') {
105
+ const value = await callback(prompt.message, prompt.placeholder, prompt.signal)
106
+ if (value === null) throw new Error('Login cancelled by user')
107
+ return value
108
+ }
109
+ const unknownPrompt: never = prompt
110
+ throw new Error(`Unsupported OAuth prompt type: ${unknownPrompt}`)
111
+ },
112
+ }
113
+ }
114
+
75
115
  // Test seam: lets unit tests assert "OAuth login was invoked with these
76
116
  // params" without spinning up a real secrets store / browser callback server.
77
117
  export type FakeOAuthLoginRunnerOptions = {
@@ -6,8 +6,8 @@ import {
6
6
  type Component,
7
7
  type Terminal,
8
8
  Text,
9
- TUI,
10
- } from '@mariozechner/pi-tui'
9
+ TuiMainScreen,
10
+ } from '@earendil-works/pi-tui'
11
11
 
12
12
  import { formatToolEnd, formatToolStart, formatUserPromptHistory } from '@/tui/format'
13
13
  import { armTerminalGuard } from '@/tui/terminal-guard'
@@ -41,7 +41,10 @@ export const MAX_LIVE_HISTORY_ENTRIES = 250
41
41
  export function createTranscriptView(opts: TranscriptViewOptions) {
42
42
  async function run(): Promise<TranscriptViewOutcome> {
43
43
  const terminal = (opts.createTerminal ?? (() => new ProcessTerminal()))()
44
- const tui = new TUI(terminal)
44
+ // pi-tui 0.87 exports TUI only as an interface; use its concrete
45
+ // main-screen renderer to preserve this viewer's scrollback behavior
46
+ // (dist/tui.d.ts:213-244, tui-main-screen.d.ts:11-12).
47
+ const tui = new TuiMainScreen(terminal)
45
48
 
46
49
  const status = new Text(statusLine('replay'), 0, 0)
47
50
  tui.addChild(new Text(header(opts.summary), 0, 0))
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
+ }
@@ -1,6 +1,6 @@
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 as defaultCreateSession } from '@/agent'
6
6
  import type { LiveSessionRegistry } from '@/agent/live-sessions'
@@ -185,8 +185,9 @@ export function buildChannelSessionFactory(deps: BuildChannelSessionFactoryDeps)
185
185
  // because pi-coding-agent prefixes filenames with an ISO timestamp at write
186
186
  // time that is not derivable from sessionId alone. Failure to reopen
187
187
  // (corruption, missing file, schema drift, or v2 mapping with no sessionFile)
188
- // falls back to a fresh session — matching the router's existing best-effort
189
- // durability for channel sessions.
188
+ // falls back to a fresh session. pi 0.87 preserves a non-empty invalid file
189
+ // rather than silently rewriting it, so the warning below explicitly says its
190
+ // history is unavailable while retaining the file for operator recovery.
190
191
  function tryReopenOrCreate(
191
192
  cwd: string,
192
193
  sessionDir: string,
@@ -234,7 +235,7 @@ function tryReopenOrCreate(
234
235
  return sessionManager
235
236
  } catch (err) {
236
237
  if (!errorChainHasCode(err, 'ENOENT')) {
237
- logger.warn('[channels] persisted session rehydrate failed; creating new')
238
+ logger.warn('[channels] persisted session history unavailable; creating new')
238
239
  }
239
240
  return SessionManager.create(cwd, sessionDir)
240
241
  }