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
@@ -7,11 +7,12 @@ import {
7
7
  DefaultResourceLoader,
8
8
  defineTool as definePiTool,
9
9
  SessionManager,
10
- } from '@mariozechner/pi-coding-agent'
11
- import type { AgentSession, ToolDefinition } from '@mariozechner/pi-coding-agent'
10
+ } from '@earendil-works/pi-coding-agent'
11
+ import type { AgentSession, ToolDefinition } from '@earendil-works/pi-coding-agent'
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,
@@ -39,7 +40,6 @@ import type { ReloadRegistry } from '@/reload'
39
40
  import { enterSubagentTmpScope, resolveHiddenPaths } from '@/sandbox'
40
41
  import type { Stream } from '@/stream'
41
42
 
42
- import { applyAdaptiveThinkingCompat } from './adaptive-thinking-compat'
43
43
  import { getAuthFor } from './auth'
44
44
  import { createCompactionSettingsManager } from './compaction'
45
45
  import { renderGitNudge } from './git-nudge'
@@ -58,16 +58,22 @@ import {
58
58
  zodToToolParameters,
59
59
  } from './plugin-tools'
60
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'
61
63
  import { createReloadTool } from './reload-tool'
62
64
  import type { RestartHandoffOrigin } from './restart-handoff'
63
65
  import type { SubagentBashPolicy } from './reviewer-bash-policy'
64
66
  import { loadSelf } from './self'
65
67
  import { SESSION_META_CUSTOM_TYPE, sessionMetaPayload } from './session-meta'
66
- 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'
67
74
  import type { CreateSessionForSubagent, SubagentCoalescer, SubagentRegistry } from './subagents'
68
75
  import {
69
- buildDefaultSystemPrompt,
70
- buildSlimSystemPrompt,
76
+ buildSystemPolicy,
71
77
  DEFAULT_SUBAGENT_ROSTER,
72
78
  renderRuntimeBlock,
73
79
  renderRuntimeNondisclosureRule,
@@ -103,6 +109,13 @@ export { renderTurnRoleAnchor, renderTurnTimeAnchor } from './system-prompt'
103
109
 
104
110
  type AgentSessionTools = NonNullable<Parameters<typeof createAgentSession>[0]>['tools']
105
111
 
112
+ // Pi AI 0.73.1 capped an unset output budget at 32K
113
+ // (pi-ai dist/providers/simple-options.js:4). Pi 0.87.1 instead defaults to
114
+ // the full model maximum before context clamping (dist/api/simple-options.js:17),
115
+ // so preserve the former safe default at the session boundary. Explicit budgets
116
+ // remain untouched for compaction and channel-specific output caps.
117
+ export const DEFAULT_MAX_OUTPUT_TOKENS = 32_000
118
+
106
119
  export type PluginSessionWiring = {
107
120
  registry: PluginRegistry
108
121
  hooks: HookBus
@@ -132,8 +145,12 @@ export type CreateSessionOptions = {
132
145
  stream?: Stream
133
146
  channelRouter?: ChannelRouter
134
147
  mcpManager?: McpManager
135
- // Bypass the file-based resource loader (IDENTITY.md, SOUL.md, MEMORY.md,
136
- // 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.
137
154
  systemPromptOverride?: string
138
155
  // Identifies the kind of session and (for channels) its addressing fields.
139
156
  // Rendered into the system prompt so the agent knows who's listening, where
@@ -276,7 +293,10 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
276
293
  // `refOverride` lets the model-fallback helper pin a specific entry from
277
294
  // the chain when it recreates a session after the previous ref failed.
278
295
  const activeRef: ModelRef = options.refOverride ?? resolved.ref
279
- const { authStorage, modelRegistry } = getAuthFor(providerForModelRef(activeRef))
296
+ // Provider auth owns both credentials and model resolution in Pi 0.87.
297
+ // Passing its ModelRuntime keeps every session request and compaction on the
298
+ // same configured provider runtime (sdk.d.ts:15-16; CHANGELOG 0.80.0).
299
+ const { modelRuntime } = await getAuthFor(providerForModelRef(activeRef))
280
300
  const sessionManager = options.sessionManager ?? SessionManager.inMemory()
281
301
 
282
302
  const materializedSkills =
@@ -320,13 +340,28 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
320
340
  let loopGuardTurnId = 0
321
341
  const getLoopGuardTurn = () => loopGuardTurnId
322
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
+ })
323
349
 
324
350
  // Subagent built-in tool refs resolve to `ToolDefinition`s (see
325
351
  // plugin-tools.ts). Their NAMES narrow the session via `tools:`; their wrapped
326
352
  // implementations arrive through `customTools` (either `builtinPiToolOverrides`
327
353
  // for pi coding builtins, or `customSystemTools` for typeclaw web tools).
328
- const resolvedSubagentBuiltins = options.pluginSubagent?.toolRefs
329
- ? 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
+ )
330
365
  : []
331
366
  const subagentBuiltinNames = resolvedSubagentBuiltins.map((t) => t.name)
332
367
  const subagentTypeclawToolDefinitions = resolvedSubagentBuiltins.filter((t) => !isPiCodingBuiltinName(t.name))
@@ -353,7 +388,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
353
388
  : undefined
354
389
  const sessionBudgetState = sessionBudget ? createBudgetState() : undefined
355
390
 
356
- // The session's tool-name allowlist (pi 0.73 `tools:` is names, not tools).
391
+ // The session's tool-name allowlist is authoritative: with an explicit list,
392
+ // pi activates only listed builtins and custom tools (sdk.d.ts:35-47).
357
393
  // A subagent narrows to its declared refs; a non-subagent caller passes its
358
394
  // own explicit list (e.g. look-at's `[]`); everyone else leaves it undefined
359
395
  // so pi's default builtins apply. Implementations arrive via `customTools`;
@@ -403,6 +439,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
403
439
  agentDir: options.plugins?.agentDir,
404
440
  parentSessionId: sessionManager.getSessionId(),
405
441
  getOrigin,
442
+ getSessionFile: () => sessionManager.getSessionFile(),
406
443
  permissions: options.permissions,
407
444
  stream: options.stream,
408
445
  allowBackgroundFromSubagent: options.allowBackgroundFromSubagent,
@@ -411,7 +448,10 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
411
448
  }),
412
449
  ]
413
450
  : [
414
- ...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
+ ),
415
455
  ...(options.mcpManager
416
456
  ? buildMcpDispatcherToolDefinitions(options.mcpManager, {
417
457
  permissions: options.permissions,
@@ -447,6 +487,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
447
487
  agentDir: options.plugins?.agentDir,
448
488
  parentSessionId: sessionManager.getSessionId(),
449
489
  getOrigin,
490
+ getSessionFile: () => sessionManager.getSessionFile(),
450
491
  permissions: options.permissions,
451
492
  stream: options.stream,
452
493
  coalescer: options.subagentCoalescer,
@@ -514,24 +555,50 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
514
555
  const thinkingLevel = resolveSessionThinkingLevel(getConfig().models, resolved, activeRef)
515
556
  const { session } = await createAgentSession({
516
557
  model,
558
+ modelRuntime,
517
559
  sessionManager,
518
560
  settingsManager: createCompactionSettingsManager(model),
519
- authStorage,
520
- modelRegistry,
521
561
  resourceLoader,
522
562
  noTools: 'builtin',
523
563
  tools: intendedActiveToolNames,
524
564
  customTools,
525
565
  ...(thinkingLevel ? { thinkingLevel } : {}),
526
566
  })
567
+
568
+ // Wrapping also means `agent.streamFunction !== streamSimple`, which puts pi's
569
+ // summarization auth on its lenient branch (agent-session.js:214-232): a
570
+ // failed compaction auth surfaces from the request rather than as pi's
571
+ // "Authentication failed … /login" message. Channel sessions already wrap
572
+ // this function, so every origin now behaves the same way.
573
+ const innerStreamFunction = session.agent.streamFunction
574
+ session.agent.streamFunction = async (requestModel, context, streamOptions) => {
575
+ const maxTokens =
576
+ streamOptions?.maxTokens ??
577
+ (requestModel.maxTokens > 0 ? Math.min(requestModel.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS) : undefined)
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
+ })
591
+ }
592
+
527
593
  // typeclaw owns retry/fallback in its turn drivers, so the SDK's own
528
594
  // same-model auto-retry must be OFF. Leaving it on races typeclaw's
529
595
  // soft-error capture: the SDK can silently recover a `stopReason:'error'` turn
530
596
  // while typeclaw has already latched the failure, reporting a recovered turn as
531
597
  // failed (and burning an unnecessary failover). Disabling it makes a soft error
532
598
  // a deterministic, typeclaw-owned signal. Compaction/context-overflow recovery
533
- // is independent (gated on compaction settings), so this does not disable those.
534
- ;(session as { setAutoRetryEnabled?: (enabled: boolean) => void }).setAutoRetryEnabled?.(false)
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.
601
+ session.setAutoRetryEnabled(false)
535
602
  const getAbortReason = () => abortHolder.reason
536
603
  const sessionWithAbortReason = Object.assign(session, { getAbortReason })
537
604
  const unsubLoopGuardTurn = attachLoopGuardTurnTracking(session.agent, () => {
@@ -553,12 +620,19 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
553
620
  }
554
621
  }
555
622
 
556
- // Same seam, one hook later: layer the adaptive-thinking rewrite over pi's
557
- // onPayload so Sonnet 5 / Fable 5 never receive the budget-based `thinking`
558
- // payload the pinned pi-ai 0.73.x emits for them (a hard 400 — see
559
- // adaptive-thinking-compat.ts). Covers every provider call path through the
560
- // agent, including model switches mid-session.
561
- applyAdaptiveThinkingCompat(session.agent)
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
+ })
562
636
 
563
637
  abortHolder.abort = (reason?: string) => {
564
638
  if (reason !== undefined) abortHolder.reason = reason
@@ -870,6 +944,7 @@ export function buildSubagentOrchestrationTools(opts: {
870
944
  agentDir: string | undefined
871
945
  parentSessionId: string
872
946
  getOrigin: () => SessionOrigin | undefined
947
+ getSessionFile?: () => string | undefined
873
948
  permissions: PermissionService | undefined
874
949
  stream: Stream | undefined
875
950
  allowBackgroundFromSubagent?: boolean
@@ -892,6 +967,10 @@ export function buildSubagentOrchestrationTools(opts: {
892
967
  agentDir: opts.agentDir,
893
968
  parentSessionId: opts.parentSessionId,
894
969
  getOrigin: opts.getOrigin,
970
+ ...(opts.getSessionFile !== undefined ? { getSessionFile: opts.getSessionFile } : {}),
971
+ ...(opts.channelRouter === undefined
972
+ ? {}
973
+ : { getAccountIdentity: opts.channelRouter.getRecoveryAccountIdentity, router: opts.channelRouter }),
895
974
  ...(opts.permissions ? { permissions: opts.permissions } : {}),
896
975
  ...(opts.stream ? { stream: opts.stream } : {}),
897
976
  ...(opts.allowBackgroundFromSubagent !== undefined
@@ -903,6 +982,7 @@ export function buildSubagentOrchestrationTools(opts: {
903
982
  liveRegistry: opts.liveRegistry,
904
983
  getOrigin: opts.getOrigin,
905
984
  callerSessionId: opts.parentSessionId,
985
+ ...(opts.channelRouter ? { router: opts.channelRouter } : {}),
906
986
  ...(opts.permissions ? { permissions: opts.permissions } : {}),
907
987
  }),
908
988
  createSubagentCancelTool({
@@ -947,8 +1027,11 @@ export function buildTodoTools(
947
1027
  return createTodoTools({ agentDir, getOrigin })
948
1028
  }
949
1029
 
950
- function buildCoreSystemTools(permissions: PermissionService | undefined): ToolDefinition[] {
951
- 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]
952
1035
  const byName = new Map(definitions.map((tool) => [tool.name, tool]))
953
1036
  if (byName.size !== definitions.length || byName.size !== CORE_SYSTEM_TOOL_NAMES.length) {
954
1037
  throw new Error('core system tool catalog does not match its registered definitions')
@@ -1085,31 +1168,31 @@ export type CreateResourceLoaderOptions = {
1085
1168
  mcpManager?: McpManager
1086
1169
  permissions?: PermissionService
1087
1170
  runtimeVersion?: string
1088
- // Public subagents whose names + `rosterDescription`s render the full-mode
1089
- // "## Subagent orchestration" roster. When omitted (no-registry callers, the
1090
- // debug dumper), the prompt falls back to `DEFAULT_SUBAGENT_ROSTER`. Threaded
1091
- // from `createSessionWithDispose`, where the merged registry is already in
1092
- // 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.
1093
1176
  subagentRegistry?: SubagentRegistry
1094
- // Explicit override for the prompt mode. When omitted, the mode is derived
1095
- // from `origin.kind`: cron + subagent → slim, tui + channel → full. Pass
1096
- // '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
1097
1180
  // useful; mostly an escape hatch for ad-hoc debugging).
1098
1181
  mode?: SystemPromptMode
1099
1182
  proactiveNextStepNudge?: boolean
1100
1183
  }
1101
1184
 
1102
- // Origins where the operator-facing DEFAULT_SYSTEM_PROMPT, git-nudge, and the
1103
- // agent-folder commit guidance carry their weight: there is a human reading
1104
- // the output, the agent is expected to maintain its folder over time, and
1105
- // conversational register matters. For everything else (cron fires, default
1106
- // subagents), the slim prompt is the right default — the origin block already
1107
- // 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.
1108
1191
  //
1109
1192
  // Exhaustive switch (not a boolean expression) so a future origin kind forces
1110
1193
  // the author to make an explicit full-or-slim decision at compile time. The
1111
1194
  // previous form silently defaulted new origins to slim, which would have
1112
- // stripped the operator-facing prompt from a new interactive surface by
1195
+ // stripped the interactive context from a new interactive surface by
1113
1196
  // accident.
1114
1197
  export function deriveSystemPromptMode(origin: SessionOrigin | undefined): SystemPromptMode {
1115
1198
  if (origin === undefined) return 'full'
@@ -1136,28 +1219,27 @@ export function deriveSystemPromptMode(origin: SessionOrigin | undefined): Syste
1136
1219
  // pipeline `createResourceLoader` uses, with no risk of drift if the
1137
1220
  // section order changes.
1138
1221
  //
1139
- // `mode` selects the base prompt:
1140
- // - 'full' (default) — DEFAULT_SYSTEM_PROMPT (~2155 tok of operator-facing
1141
- // guidance: agent folder layout, version-control rules, register matching,
1142
- // workspace boundary). Right choice for TUI and channel sessions where a
1143
- // human is reading the output and the agent maintains its folder.
1144
- // - 'slim' — SLIM_SYSTEM_PROMPT (~80 tok). Right choice for cron jobs and
1145
- // default subagents — unattended sessions where most of the operator
1146
- // guidance is irrelevant and the origin block already covers per-kind
1147
- // 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).
1148
1229
  export type SystemPromptMode = 'full' | 'slim'
1149
1230
 
1150
1231
  export type SystemPromptComposition = {
1151
1232
  mode?: SystemPromptMode
1152
1233
  // Whether the prompt discloses that the agent runs on TypeClaw. When false,
1153
- // the base prompt's opening is phrased generically and the `## Runtime`
1154
- // 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`.
1155
1237
  branding?: boolean
1156
1238
  self: string
1157
- // Pre-rendered full-mode orchestration roster (from `renderPublicSubagentRoster`).
1239
+ // Pre-rendered interactive-context roster (from `renderPublicSubagentRoster`).
1158
1240
  // Kept as a ready string so this composer stays pure and registry-free; the
1159
- // registry-aware caller renders it. Ignored in slim mode (no roster section).
1160
- // 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.
1161
1243
  subagentRoster?: string
1162
1244
  runtimeVersion?: string
1163
1245
  origin?: SessionOrigin
@@ -1175,12 +1257,19 @@ export type SystemPromptComposition = {
1175
1257
  // section changes (the provider's prompt cache hits up to the first byte
1176
1258
  // that differs).
1177
1259
  //
1178
- // 0. runtime block — most stable: only changes on typeclaw releases (rare).
1179
- // 1. origin block — stable across all sessions of the same kind.
1180
- // 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
1181
1270
  // memory/ after every turn, so the dirty-files list is empty most of
1182
1271
  // the time.
1183
- // 3. proactive next-step nudge — deterministic per model family.
1272
+ // 7. proactive next-step nudge — deterministic per model family.
1184
1273
  //
1185
1274
  // The wall-clock anchor that used to live here as `## Now` moved out
1186
1275
  // entirely. It is now injected into the user turn at each `session.prompt`
@@ -1188,20 +1277,23 @@ export type SystemPromptComposition = {
1188
1277
  // stamp reflects the moment of THIS turn, not session creation. Per-turn
1189
1278
  // injection costs zero cached bytes — the user turn is the non-cacheable
1190
1279
  // suffix anyway — and removes the staleness failure mode where a session
1191
- // 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.
1192
1285
  export function composeSystemPrompt(parts: SystemPromptComposition): string {
1193
1286
  const branding = parts.branding ?? true
1194
- const base =
1195
- parts.mode === 'slim'
1196
- ? buildSlimSystemPrompt(branding)
1197
- : buildDefaultSystemPrompt(parts.subagentRoster ?? DEFAULT_SUBAGENT_ROSTER, branding)
1198
- let prompt = `${base}\n\n${parts.self}`
1287
+ let prompt = `${buildSystemPolicy(branding)}\n\n${parts.self}`
1199
1288
  if (branding && parts.runtimeVersion !== undefined) {
1200
1289
  prompt = `${prompt}\n\n${renderRuntimeBlock(parts.runtimeVersion)}`
1201
1290
  }
1202
1291
  if (!branding) {
1203
1292
  prompt = `${prompt}\n\n${renderRuntimeNondisclosureRule()}`
1204
1293
  }
1294
+ if (parts.mode !== 'slim') {
1295
+ prompt = `${prompt}\n\n${renderInteractiveSessionContext(parts.subagentRoster ?? DEFAULT_SUBAGENT_ROSTER)}`
1296
+ }
1205
1297
  if (parts.origin !== undefined) {
1206
1298
  prompt = `${prompt}\n\n${renderSessionOrigin(parts.origin, Date.now(), parts.roleContext)}`
1207
1299
  }
@@ -1220,10 +1312,10 @@ export function composeSystemPrompt(parts: SystemPromptComposition): string {
1220
1312
  export async function createResourceLoader(options: CreateResourceLoaderOptions = {}): Promise<DefaultResourceLoader> {
1221
1313
  const agentDir = options.agentDir ?? process.cwd()
1222
1314
  const mode: SystemPromptMode = options.mode ?? deriveSystemPromptMode(options.origin)
1223
- // Slim mode (cron/subagent) has no orchestration section, so it never reads
1224
- // the roster. Skip rendering it there — `renderPublicSubagentRoster` throws on
1225
- // a public subagent with a missing/blank `rosterDescription`, and a slim
1226
- // 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.
1227
1319
  const subagentRoster =
1228
1320
  mode === 'slim'
1229
1321
  ? undefined
@@ -1231,10 +1323,7 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1231
1323
  ? renderPublicSubagentRoster(options.subagentRegistry)
1232
1324
  : DEFAULT_SUBAGENT_ROSTER
1233
1325
  const branding = getConfig().branding
1234
- const basePrompt =
1235
- mode === 'slim'
1236
- ? buildSlimSystemPrompt(branding)
1237
- : buildDefaultSystemPrompt(subagentRoster ?? DEFAULT_SUBAGENT_ROSTER, branding)
1326
+ const policy = buildSystemPolicy(branding)
1238
1327
 
1239
1328
  // Kick off the independent I/O paths concurrently. Sequential awaits
1240
1329
  // here used to be the dominant cold-start cost amplifier: loadSelf is 2
@@ -1269,25 +1358,24 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1269
1358
  let self = await selfPromise
1270
1359
 
1271
1360
  if (options.plugins) {
1272
- // The plugin hook receives the partially-assembled prompt (base + identity)
1273
- // so plugins can rewrite either section before the cache-suffix blocks are
1274
- // appended. The base reflects the resolved mode, so a slim cron session's
1275
- // plugin hook sees the slim base — plugins that read the base text get
1276
- // the same shape the agent will see.
1277
- 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}`
1278
1366
  const event = { prompt: preHook, sessionId: options.plugins.sessionId, agentDir, origin: options.origin }
1279
1367
  await options.plugins.hooks.runSessionPrompt(event)
1280
- // Recover `self` by stripping the leading base so the rest of the
1281
- // 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
1282
1370
  // well, the recovered `self` carries the full mutated remainder.
1283
- 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
1284
1372
  }
1285
1373
 
1286
1374
  const roleContext = options.origin !== undefined ? resolveRoleContext(options.origin, options.permissions) : undefined
1287
- // Slim mode skips git-nudge entirely: cron + subagent sessions are not the
1288
- // right actor to drive interactive commit decisions, and the operator-facing
1289
- // commit guidance the nudge points back to is itself excluded from the slim
1290
- // 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.
1291
1379
  const gitNudgeResult = await gitNudgeSettled
1292
1380
  const gitNudge = unwrapSettled(gitNudgeResult)
1293
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()
@@ -33,7 +33,7 @@
33
33
  // This is a read-only projection: it never mutates the persisted JSONL, so an
34
34
  // already-poisoned session becomes usable without destructive migration.
35
35
 
36
- import type { Message } from '@mariozechner/pi-ai'
36
+ import type { Message } from '@earendil-works/pi-ai'
37
37
 
38
38
  export type ReplaySanitizerStats = {
39
39
  droppedOrphans: number
@@ -1,4 +1,4 @@
1
- import type { Api, Model } from '@mariozechner/pi-ai'
1
+ import type { Api, Model } from '@earendil-works/pi-ai'
2
2
 
3
3
  import { providerForModelRef, type KnownModelRef, type KnownProviderId, type ModelRef } from '@/config/providers'
4
4
 
@@ -1,8 +1,8 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import { Type } from '@mariozechner/pi-ai'
4
- import type { ImageContent } from '@mariozechner/pi-ai'
5
- import { defineTool } from '@mariozechner/pi-coding-agent'
3
+ import { Type } from '@earendil-works/pi-ai'
4
+ import type { ImageContent } from '@earendil-works/pi-ai'
5
+ import { defineTool } from '@earendil-works/pi-coding-agent'
6
6
 
7
7
  import { createSessionWithDispose, type SessionOrigin } from '@/agent'
8
8
  import { readResponseBodyBounded } from '@/agent/network/response-body'
@@ -5,7 +5,7 @@ import { GUARD_IMAGE_READ_REDIRECT } from '@/bundled-plugins/guard/keys'
5
5
 
6
6
  export { GUARD_IMAGE_READ_REDIRECT } from '@/bundled-plugins/guard/keys'
7
7
 
8
- // Mirrors the IMAGE_MIME_TYPES set in @mariozechner/pi-coding-agent
8
+ // Mirrors the IMAGE_MIME_TYPES set in @earendil-works/pi-coding-agent
9
9
  // (dist/utils/mime.ts). Keeping the trigger surface aligned with the upstream
10
10
  // read tool's image-attachment behavior means we redirect on exactly the
11
11
  // extensions that would otherwise inject `{ type: 'image' }` content parts