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
@@ -12,6 +12,7 @@ import type { AgentSession, ToolDefinition } from '@earendil-works/pi-coding-age
12
12
 
13
13
  import type { ChannelRouter } from '@/channels/router'
14
14
  import type { ReactionRef } from '@/channels/types'
15
+ import { createCodingAgentTool } from '@/coding-agent/tool'
15
16
  import {
16
17
  getConfig,
17
18
  resolveModel,
@@ -57,16 +58,22 @@ import {
57
58
  zodToToolParameters,
58
59
  } from './plugin-tools'
59
60
  import { PROACTIVE_NEXT_STEP_NUDGE } from './proactive-next-step-nudge'
61
+ import { promptCacheKeyForOrigin, withPromptCacheKey } from './prompt-cache-key'
62
+ import { wrapTransformContextWithLocalFailureMarker } from './provider-error'
60
63
  import { createReloadTool } from './reload-tool'
61
64
  import type { RestartHandoffOrigin } from './restart-handoff'
62
65
  import type { SubagentBashPolicy } from './reviewer-bash-policy'
63
66
  import { loadSelf } from './self'
64
67
  import { SESSION_META_CUSTOM_TYPE, sessionMetaPayload } from './session-meta'
65
- import { renderSessionOrigin, type SessionOrigin, type SessionRoleContext } from './session-origin'
68
+ import {
69
+ renderInteractiveSessionContext,
70
+ renderSessionOrigin,
71
+ type SessionOrigin,
72
+ type SessionRoleContext,
73
+ } from './session-origin'
66
74
  import type { CreateSessionForSubagent, SubagentCoalescer, SubagentRegistry } from './subagents'
67
75
  import {
68
- buildDefaultSystemPrompt,
69
- buildSlimSystemPrompt,
76
+ buildSystemPolicy,
70
77
  DEFAULT_SUBAGENT_ROSTER,
71
78
  renderRuntimeBlock,
72
79
  renderRuntimeNondisclosureRule,
@@ -138,8 +145,12 @@ export type CreateSessionOptions = {
138
145
  stream?: Stream
139
146
  channelRouter?: ChannelRouter
140
147
  mcpManager?: McpManager
141
- // Bypass the file-based resource loader (IDENTITY.md, SOUL.md, MEMORY.md,
142
- // memory/, bundled skills) and use this string verbatim as the system prompt.
148
+ // Replace TypeClaw's standard composition with this string: the shared
149
+ // policy, IDENTITY.md/SOUL.md, the interactive context, and the skill paths
150
+ // TypeClaw adds (bundled, plugin, `.agents/skills/`, `memory/skills/`) are
151
+ // not injected. Runtime metadata and the origin block are still appended,
152
+ // and pi's own default discovery still runs, so project context files such
153
+ // as AGENTS.md still reach the final system message.
143
154
  systemPromptOverride?: string
144
155
  // Identifies the kind of session and (for channels) its addressing fields.
145
156
  // Rendered into the system prompt so the agent knows who's listening, where
@@ -329,13 +340,28 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
329
340
  let loopGuardTurnId = 0
330
341
  const getLoopGuardTurn = () => loopGuardTurnId
331
342
  const guards = buildInternalGuards(options.plugins?.agentDir ?? process.cwd())
343
+ const codingTool = createCodingAgentTool({
344
+ agentDir: options.plugins?.agentDir ?? process.cwd(),
345
+ sessionId: options.plugins?.sessionId ?? sessionManager.getSessionId(),
346
+ getOrigin,
347
+ permissions: options.permissions ?? noopPermissionService,
348
+ })
332
349
 
333
350
  // Subagent built-in tool refs resolve to `ToolDefinition`s (see
334
351
  // plugin-tools.ts). Their NAMES narrow the session via `tools:`; their wrapped
335
352
  // implementations arrive through `customTools` (either `builtinPiToolOverrides`
336
353
  // for pi coding builtins, or `customSystemTools` for typeclaw web tools).
337
- const resolvedSubagentBuiltins = options.pluginSubagent?.toolRefs
338
- ? resolveBuiltinToolRefs(options.pluginSubagent.toolRefs, options.plugins?.agentDir ?? process.cwd())
354
+ const declaredRefs = options.pluginSubagent?.toolRefs
355
+ const writeCapable =
356
+ declaredRefs?.some((ref) => ref.__builtinTool === 'bash') &&
357
+ declaredRefs.some((ref) => ref.__builtinTool === 'write' || ref.__builtinTool === 'edit') &&
358
+ options.bashPolicy === undefined
359
+ const resolvedSubagentBuiltins = declaredRefs
360
+ ? resolveBuiltinToolRefs(
361
+ declaredRefs.filter((ref) => ref.__builtinTool !== 'coding_agent' || writeCapable),
362
+ options.plugins?.agentDir ?? process.cwd(),
363
+ new Map([['coding_agent', codingTool]]),
364
+ )
339
365
  : []
340
366
  const subagentBuiltinNames = resolvedSubagentBuiltins.map((t) => t.name)
341
367
  const subagentTypeclawToolDefinitions = resolvedSubagentBuiltins.filter((t) => !isPiCodingBuiltinName(t.name))
@@ -413,6 +439,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
413
439
  agentDir: options.plugins?.agentDir,
414
440
  parentSessionId: sessionManager.getSessionId(),
415
441
  getOrigin,
442
+ getSessionFile: () => sessionManager.getSessionFile(),
416
443
  permissions: options.permissions,
417
444
  stream: options.stream,
418
445
  allowBackgroundFromSubagent: options.allowBackgroundFromSubagent,
@@ -421,7 +448,10 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
421
448
  }),
422
449
  ]
423
450
  : [
424
- ...buildCoreSystemTools(options.permissions),
451
+ ...buildCoreSystemTools(options.permissions, codingTool).filter(
452
+ (tool) =>
453
+ tool.name !== 'coding_agent' || options.tools === undefined || options.tools.includes('coding_agent'),
454
+ ),
425
455
  ...(options.mcpManager
426
456
  ? buildMcpDispatcherToolDefinitions(options.mcpManager, {
427
457
  permissions: options.permissions,
@@ -457,6 +487,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
457
487
  agentDir: options.plugins?.agentDir,
458
488
  parentSessionId: sessionManager.getSessionId(),
459
489
  getOrigin,
490
+ getSessionFile: () => sessionManager.getSessionFile(),
460
491
  permissions: options.permissions,
461
492
  stream: options.stream,
462
493
  coalescer: options.subagentCoalescer,
@@ -544,7 +575,19 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
544
575
  const maxTokens =
545
576
  streamOptions?.maxTokens ??
546
577
  (requestModel.maxTokens > 0 ? Math.min(requestModel.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS) : undefined)
547
- return await innerStreamFunction(requestModel, context, { ...streamOptions, maxTokens })
578
+ const promptCacheKey = promptCacheKeyForOrigin(getOrigin())
579
+ const onPayload =
580
+ promptCacheKey === undefined
581
+ ? streamOptions?.onPayload
582
+ : async (payload: unknown, payloadModel: typeof requestModel) => {
583
+ const next = (await streamOptions?.onPayload?.(payload, payloadModel)) ?? payload
584
+ return withPromptCacheKey(next, promptCacheKey)
585
+ }
586
+ return await innerStreamFunction(requestModel, context, {
587
+ ...streamOptions,
588
+ maxTokens,
589
+ ...(onPayload ? { onPayload } : {}),
590
+ })
548
591
  }
549
592
 
550
593
  // typeclaw owns retry/fallback in its turn drivers, so the SDK's own
@@ -553,7 +596,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
553
596
  // while typeclaw has already latched the failure, reporting a recovered turn as
554
597
  // failed (and burning an unnecessary failover). Disabling it makes a soft error
555
598
  // a deterministic, typeclaw-owned signal. Compaction/context-overflow recovery
556
- // is independent (gated on compaction settings), so this does not disable those.
599
+ // is independent (gated on compaction settings), so this does not disable those;
600
+ // marked local failures are kept out of overflow recovery at the marker below.
557
601
  session.setAutoRetryEnabled(false)
558
602
  const getAbortReason = () => abortHolder.reason
559
603
  const sessionWithAbortReason = Object.assign(session, { getAbortReason })
@@ -576,6 +620,20 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
576
620
  }
577
621
  }
578
622
 
623
+ // pi turns a throw from context preparation into the same `stopReason:'error'`
624
+ // message a provider failure produces, with only the error text kept, so the
625
+ // origin has to be stamped where it is thrown. Installed last so it is the
626
+ // outermost layer over pi's extension `context` pass (which clones the
627
+ // messages) and its forced-prompt projection. getApiKey and streamFunction
628
+ // stay unwrapped: their failures can be genuine provider/auth failures.
629
+ // Overflow recovery stays enabled; a local failure whose text would read as a
630
+ // provider overflow is stamped with fixed text and its raw text is logged here.
631
+ session.agent.transformContext = wrapTransformContextWithLocalFailureMarker(session.agent.transformContext, {
632
+ getProvider: () => session.agent.state.model?.provider,
633
+ logWithheld: (line) =>
634
+ console.error(`[agent] ${options.plugins?.sessionId ?? sessionManager.getSessionId()}: ${line}`),
635
+ })
636
+
579
637
  abortHolder.abort = (reason?: string) => {
580
638
  if (reason !== undefined) abortHolder.reason = reason
581
639
  if (session.agent.signal?.aborted !== true) session.agent.abort()
@@ -886,6 +944,7 @@ export function buildSubagentOrchestrationTools(opts: {
886
944
  agentDir: string | undefined
887
945
  parentSessionId: string
888
946
  getOrigin: () => SessionOrigin | undefined
947
+ getSessionFile?: () => string | undefined
889
948
  permissions: PermissionService | undefined
890
949
  stream: Stream | undefined
891
950
  allowBackgroundFromSubagent?: boolean
@@ -908,6 +967,10 @@ export function buildSubagentOrchestrationTools(opts: {
908
967
  agentDir: opts.agentDir,
909
968
  parentSessionId: opts.parentSessionId,
910
969
  getOrigin: opts.getOrigin,
970
+ ...(opts.getSessionFile !== undefined ? { getSessionFile: opts.getSessionFile } : {}),
971
+ ...(opts.channelRouter === undefined
972
+ ? {}
973
+ : { getAccountIdentity: opts.channelRouter.getRecoveryAccountIdentity, router: opts.channelRouter }),
911
974
  ...(opts.permissions ? { permissions: opts.permissions } : {}),
912
975
  ...(opts.stream ? { stream: opts.stream } : {}),
913
976
  ...(opts.allowBackgroundFromSubagent !== undefined
@@ -919,6 +982,7 @@ export function buildSubagentOrchestrationTools(opts: {
919
982
  liveRegistry: opts.liveRegistry,
920
983
  getOrigin: opts.getOrigin,
921
984
  callerSessionId: opts.parentSessionId,
985
+ ...(opts.channelRouter ? { router: opts.channelRouter } : {}),
922
986
  ...(opts.permissions ? { permissions: opts.permissions } : {}),
923
987
  }),
924
988
  createSubagentCancelTool({
@@ -963,8 +1027,11 @@ export function buildTodoTools(
963
1027
  return createTodoTools({ agentDir, getOrigin })
964
1028
  }
965
1029
 
966
- function buildCoreSystemTools(permissions: PermissionService | undefined): ToolDefinition[] {
967
- const definitions = [webSearchTool, webFetchTool, createLookAtTool(permissions)]
1030
+ function buildCoreSystemTools(
1031
+ permissions: PermissionService | undefined,
1032
+ codingTool: ToolDefinition,
1033
+ ): ToolDefinition[] {
1034
+ const definitions = [webSearchTool, webFetchTool, createLookAtTool(permissions), codingTool]
968
1035
  const byName = new Map(definitions.map((tool) => [tool.name, tool]))
969
1036
  if (byName.size !== definitions.length || byName.size !== CORE_SYSTEM_TOOL_NAMES.length) {
970
1037
  throw new Error('core system tool catalog does not match its registered definitions')
@@ -1101,31 +1168,31 @@ export type CreateResourceLoaderOptions = {
1101
1168
  mcpManager?: McpManager
1102
1169
  permissions?: PermissionService
1103
1170
  runtimeVersion?: string
1104
- // Public subagents whose names + `rosterDescription`s render the full-mode
1105
- // "## Subagent orchestration" roster. When omitted (no-registry callers, the
1106
- // debug dumper), the prompt falls back to `DEFAULT_SUBAGENT_ROSTER`. Threaded
1107
- // from `createSessionWithDispose`, where the merged registry is already in
1108
- // scope.
1171
+ // Public subagents whose names + `rosterDescription`s render the roster in
1172
+ // the full-mode interactive context. When omitted (registry-free callers,
1173
+ // the debug dumper), the context falls back to `DEFAULT_SUBAGENT_ROSTER`.
1174
+ // Threaded from `createSessionWithDispose`, where the merged registry is
1175
+ // already in scope.
1109
1176
  subagentRegistry?: SubagentRegistry
1110
- // Explicit override for the prompt mode. When omitted, the mode is derived
1111
- // from `origin.kind`: cron + subagent → slim, tui + channel → full. Pass
1112
- // 'full' to force the heavy prompt even on an unattended origin (rarely
1177
+ // Explicit override for the session-context mode. When omitted, the mode is
1178
+ // derived from `origin.kind`. It never changes the shared policy; pass
1179
+ // 'full' to add the interactive context to an unattended origin (rarely
1113
1180
  // useful; mostly an escape hatch for ad-hoc debugging).
1114
1181
  mode?: SystemPromptMode
1115
1182
  proactiveNextStepNudge?: boolean
1116
1183
  }
1117
1184
 
1118
- // Origins where the operator-facing DEFAULT_SYSTEM_PROMPT, git-nudge, and the
1119
- // agent-folder commit guidance carry their weight: there is a human reading
1120
- // the output, the agent is expected to maintain its folder over time, and
1121
- // conversational register matters. For everything else (cron fires, default
1122
- // subagents), the slim prompt is the right default — the origin block already
1123
- // names the unattended context and tells the agent what's expected of it.
1185
+ // Origins with a conversation partner waiting on the reply get the full-mode
1186
+ // session context: the interactive orchestration context with the live public
1187
+ // roster, the MCP catalog, and the git nudge. Unattended origins (cron fires,
1188
+ // default subagents, system processes) skip that context and the roster/git/MCP
1189
+ // work it needs — their origin block already says what is expected. Every
1190
+ // origin gets the same shared policy either way.
1124
1191
  //
1125
1192
  // Exhaustive switch (not a boolean expression) so a future origin kind forces
1126
1193
  // the author to make an explicit full-or-slim decision at compile time. The
1127
1194
  // previous form silently defaulted new origins to slim, which would have
1128
- // stripped the operator-facing prompt from a new interactive surface by
1195
+ // stripped the interactive context from a new interactive surface by
1129
1196
  // accident.
1130
1197
  export function deriveSystemPromptMode(origin: SessionOrigin | undefined): SystemPromptMode {
1131
1198
  if (origin === undefined) return 'full'
@@ -1152,28 +1219,27 @@ export function deriveSystemPromptMode(origin: SessionOrigin | undefined): Syste
1152
1219
  // pipeline `createResourceLoader` uses, with no risk of drift if the
1153
1220
  // section order changes.
1154
1221
  //
1155
- // `mode` selects the base prompt:
1156
- // - 'full' (default) — DEFAULT_SYSTEM_PROMPT (~2155 tok of operator-facing
1157
- // guidance: agent folder layout, version-control rules, register matching,
1158
- // workspace boundary). Right choice for TUI and channel sessions where a
1159
- // human is reading the output and the agent maintains its folder.
1160
- // - 'slim' — SLIM_SYSTEM_PROMPT (~80 tok). Right choice for cron jobs and
1161
- // default subagents — unattended sessions where most of the operator
1162
- // guidance is irrelevant and the origin block already covers per-kind
1163
- // specifics (no human, side effects via tools, narrow scope).
1222
+ // `mode` selects only the optional session context, never the policy: every
1223
+ // standard session starts with `buildSystemPolicy(branding)`.
1224
+ // - 'full' (default) — TUI, channel, and origin-less sessions: appends the
1225
+ // interactive context (`renderInteractiveSessionContext`) with the roster.
1226
+ // - 'slim' — cron, default subagents, system processes: no interactive
1227
+ // context; the origin block covers per-kind specifics (no human, side
1228
+ // effects via tools, narrow scope).
1164
1229
  export type SystemPromptMode = 'full' | 'slim'
1165
1230
 
1166
1231
  export type SystemPromptComposition = {
1167
1232
  mode?: SystemPromptMode
1168
1233
  // Whether the prompt discloses that the agent runs on TypeClaw. When false,
1169
- // the base prompt's opening is phrased generically and the `## Runtime`
1170
- // version block is dropped. Defaults to true. Mirrors `config.branding`.
1234
+ // the policy's opening is phrased generically, the `## Runtime` version
1235
+ // block is dropped, and the runtime-disclosure rule is appended. Defaults to
1236
+ // true. Mirrors `config.branding`.
1171
1237
  branding?: boolean
1172
1238
  self: string
1173
- // Pre-rendered full-mode orchestration roster (from `renderPublicSubagentRoster`).
1239
+ // Pre-rendered interactive-context roster (from `renderPublicSubagentRoster`).
1174
1240
  // Kept as a ready string so this composer stays pure and registry-free; the
1175
- // registry-aware caller renders it. Ignored in slim mode (no roster section).
1176
- // Falls back to `DEFAULT_SUBAGENT_ROSTER` when omitted.
1241
+ // registry-aware caller renders it. Ignored in slim mode (no interactive
1242
+ // context). Falls back to `DEFAULT_SUBAGENT_ROSTER` when omitted.
1177
1243
  subagentRoster?: string
1178
1244
  runtimeVersion?: string
1179
1245
  origin?: SessionOrigin
@@ -1191,12 +1257,19 @@ export type SystemPromptComposition = {
1191
1257
  // section changes (the provider's prompt cache hits up to the first byte
1192
1258
  // that differs).
1193
1259
  //
1194
- // 0. runtime block — most stable: only changes on typeclaw releases (rare).
1195
- // 1. origin block — stable across all sessions of the same kind.
1196
- // 2. gitNudge — rare changes; agent folders force-commit sessions/ and
1260
+ // 0. shared policy — identical for every standard session of an agent.
1261
+ // 1. self — IDENTITY.md + SOUL.md (plus any plugin `session.prompt` append).
1262
+ // 2. runtime block (or the runtime-disclosure rule when branding is off) —
1263
+ // only changes on typeclaw releases.
1264
+ // 3. interactive context (full mode) — stable per agent registry, so it
1265
+ // precedes the per-session origin block.
1266
+ // 4. origin block + role — stable across sessions of the same kind; channel
1267
+ // origins carry per-conversation details.
1268
+ // 5. MCP catalog — changes when servers connect or disconnect.
1269
+ // 6. gitNudge — rare changes; agent folders force-commit sessions/ and
1197
1270
  // memory/ after every turn, so the dirty-files list is empty most of
1198
1271
  // the time.
1199
- // 3. proactive next-step nudge — deterministic per model family.
1272
+ // 7. proactive next-step nudge — deterministic per model family.
1200
1273
  //
1201
1274
  // The wall-clock anchor that used to live here as `## Now` moved out
1202
1275
  // entirely. It is now injected into the user turn at each `session.prompt`
@@ -1204,20 +1277,23 @@ export type SystemPromptComposition = {
1204
1277
  // stamp reflects the moment of THIS turn, not session creation. Per-turn
1205
1278
  // injection costs zero cached bytes — the user turn is the non-cacheable
1206
1279
  // suffix anyway — and removes the staleness failure mode where a session
1207
- // opened Friday answered "today is Friday" on Thursday.
1280
+ // opened Friday answered "today is Friday" on Thursday. Retrieved memory and
1281
+ // the live channel role ride in the user turn for the same reason.
1282
+ //
1283
+ // pi appends project context (AGENTS.md), the skill catalog, and the cwd
1284
+ // after this preamble when it builds the final system message.
1208
1285
  export function composeSystemPrompt(parts: SystemPromptComposition): string {
1209
1286
  const branding = parts.branding ?? true
1210
- const base =
1211
- parts.mode === 'slim'
1212
- ? buildSlimSystemPrompt(branding)
1213
- : buildDefaultSystemPrompt(parts.subagentRoster ?? DEFAULT_SUBAGENT_ROSTER, branding)
1214
- let prompt = `${base}\n\n${parts.self}`
1287
+ let prompt = `${buildSystemPolicy(branding)}\n\n${parts.self}`
1215
1288
  if (branding && parts.runtimeVersion !== undefined) {
1216
1289
  prompt = `${prompt}\n\n${renderRuntimeBlock(parts.runtimeVersion)}`
1217
1290
  }
1218
1291
  if (!branding) {
1219
1292
  prompt = `${prompt}\n\n${renderRuntimeNondisclosureRule()}`
1220
1293
  }
1294
+ if (parts.mode !== 'slim') {
1295
+ prompt = `${prompt}\n\n${renderInteractiveSessionContext(parts.subagentRoster ?? DEFAULT_SUBAGENT_ROSTER)}`
1296
+ }
1221
1297
  if (parts.origin !== undefined) {
1222
1298
  prompt = `${prompt}\n\n${renderSessionOrigin(parts.origin, Date.now(), parts.roleContext)}`
1223
1299
  }
@@ -1236,10 +1312,10 @@ export function composeSystemPrompt(parts: SystemPromptComposition): string {
1236
1312
  export async function createResourceLoader(options: CreateResourceLoaderOptions = {}): Promise<DefaultResourceLoader> {
1237
1313
  const agentDir = options.agentDir ?? process.cwd()
1238
1314
  const mode: SystemPromptMode = options.mode ?? deriveSystemPromptMode(options.origin)
1239
- // Slim mode (cron/subagent) has no orchestration section, so it never reads
1240
- // the roster. Skip rendering it there — `renderPublicSubagentRoster` throws on
1241
- // a public subagent with a missing/blank `rosterDescription`, and a slim
1242
- // session must not fail on a roster it will never show.
1315
+ // Slim mode (cron/subagent/system) has no interactive context, so it never
1316
+ // reads the roster. Skip rendering it there — `renderPublicSubagentRoster`
1317
+ // throws on a public subagent with a missing/blank `rosterDescription`, and
1318
+ // a slim session must not fail on a roster it will never show.
1243
1319
  const subagentRoster =
1244
1320
  mode === 'slim'
1245
1321
  ? undefined
@@ -1247,10 +1323,7 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1247
1323
  ? renderPublicSubagentRoster(options.subagentRegistry)
1248
1324
  : DEFAULT_SUBAGENT_ROSTER
1249
1325
  const branding = getConfig().branding
1250
- const basePrompt =
1251
- mode === 'slim'
1252
- ? buildSlimSystemPrompt(branding)
1253
- : buildDefaultSystemPrompt(subagentRoster ?? DEFAULT_SUBAGENT_ROSTER, branding)
1326
+ const policy = buildSystemPolicy(branding)
1254
1327
 
1255
1328
  // Kick off the independent I/O paths concurrently. Sequential awaits
1256
1329
  // here used to be the dominant cold-start cost amplifier: loadSelf is 2
@@ -1285,25 +1358,24 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1285
1358
  let self = await selfPromise
1286
1359
 
1287
1360
  if (options.plugins) {
1288
- // The plugin hook receives the partially-assembled prompt (base + identity)
1289
- // so plugins can rewrite either section before the cache-suffix blocks are
1290
- // appended. The base reflects the resolved mode, so a slim cron session's
1291
- // plugin hook sees the slim base — plugins that read the base text get
1292
- // the same shape the agent will see.
1293
- const preHook = `${basePrompt}\n\n${self}`
1361
+ // The plugin hook receives the partially-assembled prompt (shared policy +
1362
+ // identity) so plugins can rewrite either section before the session
1363
+ // context and cache-suffix blocks are appended. Every standard origin
1364
+ // hands the hook the same policy text.
1365
+ const preHook = `${policy}\n\n${self}`
1294
1366
  const event = { prompt: preHook, sessionId: options.plugins.sessionId, agentDir, origin: options.origin }
1295
1367
  await options.plugins.hooks.runSessionPrompt(event)
1296
- // Recover `self` by stripping the leading base so the rest of the
1297
- // composition stays section-shaped. If a plugin rewrote the base prompt as
1368
+ // Recover `self` by stripping the leading policy so the rest of the
1369
+ // composition stays section-shaped. If a plugin rewrote the policy as
1298
1370
  // well, the recovered `self` carries the full mutated remainder.
1299
- self = event.prompt.startsWith(`${basePrompt}\n\n`) ? event.prompt.slice(basePrompt.length + 2) : event.prompt
1371
+ self = event.prompt.startsWith(`${policy}\n\n`) ? event.prompt.slice(policy.length + 2) : event.prompt
1300
1372
  }
1301
1373
 
1302
1374
  const roleContext = options.origin !== undefined ? resolveRoleContext(options.origin, options.permissions) : undefined
1303
- // Slim mode skips git-nudge entirely: cron + subagent sessions are not the
1304
- // right actor to drive interactive commit decisions, and the operator-facing
1305
- // commit guidance the nudge points back to is itself excluded from the slim
1306
- // base prompt.
1375
+ // Slim mode skips git-nudge entirely: cron, subagent, and system sessions
1376
+ // are not the right actor to drive commit decisions about dirty files they
1377
+ // did not touch. The shared policy's commit rules still cover their own
1378
+ // changes.
1307
1379
  const gitNudgeResult = await gitNudgeSettled
1308
1380
  const gitNudge = unwrapSettled(gitNudgeResult)
1309
1381
 
@@ -5,8 +5,8 @@ export type LiveAgentSession = {
5
5
  sessionId: string
6
6
  session: Pick<AgentSession, 'subscribe'>
7
7
  // Surfaced by the inspect picker for sessions not yet on disk: pi-coding-agent
8
- // defers the first .jsonl write until the first assistant message, so without
9
- // these a mid-reply session is invisible. Optional so subscribe-only test
8
+ // defers the first .jsonl write until the first user message, so without
9
+ // these a session that has not been prompted yet is invisible. Optional so subscribe-only test
10
10
  // harnesses can still register `{ sessionId, session }`; live-listing skips
11
11
  // entries lacking an origin.
12
12
  origin?: MinimalSessionOrigin
@@ -287,6 +287,7 @@ export class LiveSubagentRegistry {
287
287
  }
288
288
 
289
289
  clear(): void {
290
+ // Shutdown must not erase evidence of children that have not terminated.
290
291
  this.entries.clear()
291
292
  this.events.clear()
292
293
  this.capturedFinalMessages.clear()
@@ -4,6 +4,7 @@ import { join, relative, sep } from 'node:path'
4
4
 
5
5
  import {
6
6
  createBashToolDefinition as piCreateBashToolDefinition,
7
+ createLocalBashOperations,
7
8
  createEditToolDefinition as piCreateEditToolDefinition,
8
9
  createFindToolDefinition as piCreateFindToolDefinition,
9
10
  createGrepToolDefinition as piCreateGrepToolDefinition,
@@ -19,6 +20,8 @@ import { z } from 'zod'
19
20
 
20
21
  import { ACKNOWLEDGE_GUARDS } from '@/bundled-plugins/guard/keys'
21
22
  import { config, getSandboxWritablePathSpecs } from '@/config/config'
23
+ import { readOomEvents, toolOomNote } from '@/container/oom-events'
24
+ import { withToolOomPriorityCommand } from '@/container/tool-oom-priority'
22
25
  import { readEnvFile } from '@/init/env-file'
23
26
  import {
24
27
  classifyToolOutcome,
@@ -136,6 +139,7 @@ type BashSpawnEnvContext = {
136
139
  // that appears in process.env between policy build and spawn stays out of the
137
140
  // sandbox (closes the inherit TOCTOU).
138
141
  sandboxSpawnEnv?: Record<string, string>
142
+ oomNote?: string
139
143
  }
140
144
 
141
145
  const bashEnvStore = new AsyncLocalStorage<BashSpawnEnvContext | undefined>()
@@ -164,8 +168,9 @@ function readBashPreparation(args: Record<string, unknown>): DeferredBashPrepara
164
168
 
165
169
  function bashSpawnHookWithOverlay(context: BashSpawnContext): BashSpawnContext {
166
170
  const store = bashEnvStore.getStore()
167
- if (store?.sandboxSpawnEnv !== undefined) return { ...context, env: { ...store.sandboxSpawnEnv } }
168
- return { ...context, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay, store?.withhold) }
171
+ const command = withToolOomPriorityCommand(context.command)
172
+ if (store?.sandboxSpawnEnv !== undefined) return { ...context, command, env: { ...store.sandboxSpawnEnv } }
173
+ return { ...context, command, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay, store?.withhold) }
169
174
  }
170
175
 
171
176
  export function sanitizeBashSpawnEnvironment(
@@ -204,14 +209,33 @@ function createPiBuiltinToolDefinition(name: PiBuiltinToolName, cwd: string): To
204
209
  switch (name) {
205
210
  case 'read':
206
211
  return piCreateReadToolDefinition(cwd)
207
- case 'bash':
212
+ case 'bash': {
213
+ const operations = createLocalBashOperations()
208
214
  return piCreateBashToolDefinition(cwd, {
209
- // Pi 0.87 assumes a non-empty ExtensionContext when session metadata is
210
- // enabled (tools/bash.js:122-143). TypeClaw owns the bash environment
211
- // boundary, so disable Pi metadata rather than bypassing the spawn hook.
215
+ // TypeClaw owns the bash environment boundary, so disable Pi session
216
+ // metadata rather than bypassing the spawn hook. Bracket the real
217
+ // process at the operation boundary: only there can memory.events be
218
+ // read before spawn and after exit (Pi 0.99 reports a signal-killed
219
+ // shell as 128+signal, so a SIGKILLed shell surfaces as 137 too).
212
220
  exposeSessionEnvironment: false,
213
221
  spawnHook: bashSpawnHookWithOverlay,
222
+ operations: {
223
+ async exec(command, dir, options) {
224
+ const before = readOomEvents()
225
+ const result = await operations.exec(command, dir, options)
226
+ const note =
227
+ result.exitCode === null
228
+ ? null
229
+ : toolOomNote(before, result.exitCode, 'bash', { log: (line) => console.warn(line) })
230
+ if (note !== null) {
231
+ const context = bashEnvStore.getStore()
232
+ if (context !== undefined) context.oomNote = note
233
+ }
234
+ return result
235
+ },
236
+ },
214
237
  })
238
+ }
215
239
  case 'edit':
216
240
  return piCreateEditToolDefinition(cwd)
217
241
  case 'write':
@@ -249,11 +273,17 @@ function isTypeclawToolName(name: string): name is TypeclawToolName {
249
273
  return name in TYPECLAW_TOOL_DEFINITION_MAP
250
274
  }
251
275
 
252
- export function resolveBuiltinToolRefs(refs: BuiltinToolRef[], cwd: string): ToolDefinition<any, any, any>[] {
276
+ export function resolveBuiltinToolRefs(
277
+ refs: BuiltinToolRef[],
278
+ cwd: string,
279
+ contextTools: ReadonlyMap<string, ToolDefinition<any, any, any>> = new Map(),
280
+ ): ToolDefinition<any, any, any>[] {
253
281
  return refs.map((ref) => {
254
282
  const name = ref.__builtinTool
255
283
  if (isPiBuiltinToolName(name)) return createPiBuiltinToolDefinition(name, cwd)
256
284
  if (isTypeclawToolName(name)) return TYPECLAW_TOOL_DEFINITION_MAP[name]
285
+ const contextual = contextTools.get(name)
286
+ if (contextual) return contextual
257
287
  throw new Error(`unknown built-in tool ref: ${name}`)
258
288
  })
259
289
  }
@@ -639,6 +669,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
639
669
  cleanupError = undefined
640
670
  sandboxedRealProcSucceeded = false
641
671
  const attemptArgs = { ...originalArgs }
672
+ let spawnEnvContext: BashSpawnEnvContext | undefined
642
673
  try {
643
674
  if (tool.name === 'bash') {
644
675
  if (opts.permissions === undefined) {
@@ -678,7 +709,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
678
709
  signal,
679
710
  })
680
711
  await preparedSandboxRuntime?.verify()
681
- const spawnEnvContext: BashSpawnEnvContext | undefined =
712
+ spawnEnvContext =
682
713
  bashEnvOverlay !== undefined ||
683
714
  bashEnvWithhold !== undefined ||
684
715
  preparedSandboxRuntime?.spawnEnv !== undefined
@@ -689,17 +720,28 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
689
720
  ? { sandboxSpawnEnv: preparedSandboxRuntime.spawnEnv }
690
721
  : {}),
691
722
  }
692
- : undefined
693
- rawResult = await bashEnvStore.run(spawnEnvContext, () =>
723
+ : tool.name === 'bash'
724
+ ? {}
725
+ : undefined
726
+ const executed = await bashEnvStore.run(spawnEnvContext, () =>
694
727
  tool.execute(toolCallId, attemptArgs as Static<TParams>, signal, onUpdate, ctx),
695
728
  )
729
+ // Pi 0.99 bash returns a nonzero exit as an `isError` result whose text
730
+ // is the message 0.87 threw (tools/bash.js). This wrapper returns only
731
+ // content/details, so rethrow to keep the failure on the error path
732
+ // (remediation, incident repair, sandbox note, model-facing isError).
733
+ if (executed.isError === true) {
734
+ throw new Error(executed.content.map((part) => (part.type === 'text' ? part.text : '')).join('\n'))
735
+ }
736
+ rawResult = executed
696
737
  const originalCommand = originalArgs.command
697
738
  sandboxedRealProcSucceeded =
698
739
  preparedSandboxRuntime !== undefined &&
699
740
  typeof originalCommand === 'string' &&
700
741
  (opts.realProcDependencyCheck ?? commandNeedsRealProc)(originalCommand)
701
742
  } catch (error) {
702
- executionError = error
743
+ executionError =
744
+ spawnEnvContext?.oomNote === undefined ? error : appendErrorText(error, spawnEnvContext.oomNote)
703
745
  } finally {
704
746
  const cleanup = [pinnedFiles?.cleanup(), preparedSandboxRuntime?.cleanup()].filter(
705
747
  (task): task is Promise<void> => task !== undefined,
@@ -0,0 +1,42 @@
1
+ import type { SessionOrigin } from './session-origin'
2
+
3
+ // Mirrors pi-ai's OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH, which pi applies before
4
+ // `onPayload` runs, so a replaced key must be bounded here too. Truncation can
5
+ // only merge two long-named origins into one cache bucket, which is harmless.
6
+ const PROMPT_CACHE_KEY_MAX_LENGTH = 64
7
+
8
+ // pi defaults OpenAI's `prompt_cache_key` to the session id, and OpenAI routes
9
+ // requests to cache machines by that key. Every new subagent/cron/channel
10
+ // session therefore landed on a cold machine and re-paid its whole ~10K-token
11
+ // system+tools prefix even though sibling sessions of the same kind had just
12
+ // sent the identical prefix. Keying by origin kind (and subagent/component
13
+ // name, whose prompts differ) lets those sessions share the warm prefix. Only
14
+ // the body key changes: pi still uses the session id for the Codex websocket
15
+ // session cache and request headers.
16
+ export function promptCacheKeyForOrigin(origin: SessionOrigin | undefined): string | undefined {
17
+ const key = unboundedPromptCacheKey(origin)
18
+ return key === undefined ? undefined : Array.from(key).slice(0, PROMPT_CACHE_KEY_MAX_LENGTH).join('')
19
+ }
20
+
21
+ function unboundedPromptCacheKey(origin: SessionOrigin | undefined): string | undefined {
22
+ if (origin === undefined) return undefined
23
+ switch (origin.kind) {
24
+ case 'subagent':
25
+ return `typeclaw:subagent:${origin.subagent}`
26
+ case 'system':
27
+ return `typeclaw:system:${origin.component}`
28
+ case 'tui':
29
+ case 'cron':
30
+ case 'channel':
31
+ return `typeclaw:${origin.kind}`
32
+ }
33
+ }
34
+
35
+ // Rewrites only payloads that already carry a string `prompt_cache_key`, so
36
+ // providers without the field and `cacheRetention: 'none'` (which omits it)
37
+ // are left untouched.
38
+ export function withPromptCacheKey(payload: unknown, key: string): unknown {
39
+ if (typeof payload !== 'object' || payload === null) return payload
40
+ if (typeof (payload as { prompt_cache_key?: unknown }).prompt_cache_key !== 'string') return payload
41
+ return { ...payload, prompt_cache_key: key }
42
+ }