typeclaw 0.50.0 → 0.52.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 (258) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +17 -0
  2. package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
  3. package/dist/types/agent/bash-sandbox.d.ts +98 -0
  4. package/dist/types/agent/compaction.d.ts +4 -4
  5. package/dist/types/agent/idle-compaction.d.ts +1 -0
  6. package/dist/types/agent/index.d.ts +10 -17
  7. package/dist/types/agent/multimodal/look-at.d.ts +1 -1
  8. package/dist/types/agent/output-allowance.d.ts +4 -0
  9. package/dist/types/agent/plugin-tools.d.ts +8 -75
  10. package/dist/types/agent/prompt-cache-key.d.ts +1 -0
  11. package/dist/types/agent/session-tail.d.ts +12 -0
  12. package/dist/types/agent/subagents.d.ts +5 -0
  13. package/dist/types/agent/system-prompt-composition.d.ts +18 -0
  14. package/dist/types/agent/system-prompt.d.ts +2 -0
  15. package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
  16. package/dist/types/agent/tools/channel-edit.d.ts +1 -1
  17. package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
  18. package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
  19. package/dist/types/agent/tools/channel-history.d.ts +1 -1
  20. package/dist/types/agent/tools/channel-react.d.ts +1 -1
  21. package/dist/types/agent/tools/channel-read.d.ts +10 -2
  22. package/dist/types/agent/tools/channel-reply.d.ts +1 -1
  23. package/dist/types/agent/tools/channel-send.d.ts +1 -1
  24. package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
  25. package/dist/types/agent/tools/ddg.d.ts +9 -0
  26. package/dist/types/agent/tools/grant-role.d.ts +1 -1
  27. package/dist/types/agent/tools/post-github-review.d.ts +1 -1
  28. package/dist/types/agent/tools/restart.d.ts +1 -1
  29. package/dist/types/agent/tools/skip-response.d.ts +1 -1
  30. package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
  31. package/dist/types/agent/tools/stream-snapshot.d.ts +2 -2
  32. package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
  33. package/dist/types/agent/tools/subagent-output.d.ts +1 -1
  34. package/dist/types/agent/tools/todo/index.d.ts +1 -1
  35. package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
  36. package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
  37. package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
  38. package/dist/types/agent/tools/websearch.d.ts +1 -1
  39. package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
  40. package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
  41. package/dist/types/channels/adapters/github/auth.d.ts +24 -0
  42. package/dist/types/channels/github-review-check.d.ts +1 -1
  43. package/dist/types/channels/github-token-bridge.d.ts +4 -0
  44. package/dist/types/channels/lost-background-context.d.ts +2 -0
  45. package/dist/types/channels/persistence.d.ts +1 -0
  46. package/dist/types/channels/router.d.ts +16 -50
  47. package/dist/types/channels/types.d.ts +1 -0
  48. package/dist/types/coding-agent/tool.d.ts +1 -1
  49. package/dist/types/config/config.d.ts +22 -0
  50. package/dist/types/config/providers.d.ts +50 -1
  51. package/dist/types/container/start.d.ts +1 -0
  52. package/dist/types/eval/cell.d.ts +26 -0
  53. package/dist/types/eval/config.d.ts +19 -0
  54. package/dist/types/eval/dispatch.d.ts +7 -0
  55. package/dist/types/eval/kernel.d.ts +28 -0
  56. package/dist/types/eval/process.d.ts +23 -0
  57. package/dist/types/eval/protocol.d.ts +34 -0
  58. package/dist/types/eval/sandbox.d.ts +12 -0
  59. package/dist/types/eval/tool.d.ts +17 -0
  60. package/dist/types/eval/wire.d.ts +33 -0
  61. package/dist/types/git/resolve-identity.d.ts +2 -0
  62. package/dist/types/init/dockerfile.d.ts +1 -0
  63. package/dist/types/init/gitignore.d.ts +1 -1
  64. package/dist/types/permissions/builtins.d.ts +1 -0
  65. package/dist/types/plugin/types.d.ts +3 -0
  66. package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
  67. package/dist/types/sandbox/coding-agent.d.ts +1 -1
  68. package/dist/types/sandbox/dependency-bins.d.ts +1 -0
  69. package/dist/types/sandbox/dev-source.d.ts +2 -2
  70. package/dist/types/sandbox/env-exposure.d.ts +2 -0
  71. package/dist/types/sandbox/hidden-paths.d.ts +1 -0
  72. package/dist/types/sandbox/index.d.ts +1 -1
  73. package/dist/types/sandbox/policy.d.ts +3 -0
  74. package/dist/types/typevault/cli-path.d.ts +2 -0
  75. package/dist/types/typevault/envelope-store.d.ts +11 -0
  76. package/dist/types/typevault/lifecycle.d.ts +13 -0
  77. package/dist/types/typevault/vault.d.ts +27 -0
  78. package/package.json +8 -7
  79. package/scripts/test.ts +252 -0
  80. package/src/agent/bash-sandbox-env.ts +136 -0
  81. package/src/agent/bash-sandbox-proc.ts +70 -0
  82. package/src/agent/bash-sandbox.ts +239 -0
  83. package/src/agent/compaction.ts +22 -10
  84. package/src/agent/idle-compaction.ts +7 -3
  85. package/src/agent/index.ts +185 -187
  86. package/src/agent/multimodal/look-at.ts +1 -1
  87. package/src/agent/output-allowance.ts +7 -0
  88. package/src/agent/plugin-tools.ts +64 -380
  89. package/src/agent/prompt-cache-key.ts +26 -3
  90. package/src/agent/session-origin.ts +41 -19
  91. package/src/agent/session-tail.ts +28 -0
  92. package/src/agent/subagent-completion-reminder.ts +2 -2
  93. package/src/agent/subagents.ts +21 -2
  94. package/src/agent/system-prompt-composition.ts +159 -0
  95. package/src/agent/system-prompt.ts +43 -5
  96. package/src/agent/todo/scope.ts +1 -1
  97. package/src/agent/tool-error-remediation.ts +18 -3
  98. package/src/agent/tools/channel-disengage.ts +1 -1
  99. package/src/agent/tools/channel-edit.ts +1 -1
  100. package/src/agent/tools/channel-fetch-attachment.ts +1 -1
  101. package/src/agent/tools/channel-handoff.ts +3 -2
  102. package/src/agent/tools/channel-history.ts +2 -1
  103. package/src/agent/tools/channel-react.ts +1 -1
  104. package/src/agent/tools/channel-read.ts +36 -3
  105. package/src/agent/tools/channel-reply.ts +1 -1
  106. package/src/agent/tools/channel-send.ts +4 -3
  107. package/src/agent/tools/channel-session-search.ts +13 -4
  108. package/src/agent/tools/ddg.ts +71 -11
  109. package/src/agent/tools/grant-role.ts +1 -1
  110. package/src/agent/tools/post-github-review.ts +1 -1
  111. package/src/agent/tools/restart.ts +1 -1
  112. package/src/agent/tools/skip-response.ts +1 -1
  113. package/src/agent/tools/spawn-subagent.ts +15 -1
  114. package/src/agent/tools/stream-snapshot.ts +1 -1
  115. package/src/agent/tools/subagent-cancel.ts +1 -1
  116. package/src/agent/tools/subagent-output.ts +1 -1
  117. package/src/agent/tools/todo/index.ts +1 -1
  118. package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
  119. package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
  120. package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
  121. package/src/agent/tools/webfetch/tool.ts +6 -5
  122. package/src/agent/tools/websearch.ts +1 -1
  123. package/src/agent/tools-without-local-file-operands.ts +4 -0
  124. package/src/browser/dockerfile.ts +1 -1
  125. package/src/browser/fill-secret.ts +364 -0
  126. package/src/browser/registry.ts +6 -6
  127. package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
  128. package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
  129. package/src/bundled-plugins/backup/index.ts +17 -2
  130. package/src/bundled-plugins/backup/runner.ts +37 -2
  131. package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
  132. package/src/bundled-plugins/browser-agent/index.ts +12 -5
  133. package/src/bundled-plugins/explorer/explorer.ts +1 -1
  134. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
  135. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
  136. package/src/bundled-plugins/github-cli-auth/index.ts +10 -1
  137. package/src/bundled-plugins/managed-browser/index.ts +130 -2
  138. package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
  139. package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
  140. package/src/bundled-plugins/memory/README.md +23 -2
  141. package/src/bundled-plugins/memory/append-fragment.ts +133 -0
  142. package/src/bundled-plugins/memory/append-tool.ts +80 -149
  143. package/src/bundled-plugins/memory/dreaming.ts +6 -1
  144. package/src/bundled-plugins/memory/index.ts +33 -6
  145. package/src/bundled-plugins/memory/load-memory.ts +2 -4
  146. package/src/bundled-plugins/memory/memory-logger.ts +200 -6
  147. package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
  148. package/src/bundled-plugins/memory/remember-tool.ts +81 -0
  149. package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
  150. package/src/bundled-plugins/memory/search-tool.ts +58 -12
  151. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  152. package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
  153. package/src/bundled-plugins/memory/transcript-preload.ts +208 -0
  154. package/src/bundled-plugins/memory/transcript-view.ts +36 -0
  155. package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
  156. package/src/bundled-plugins/memory/watermark.ts +19 -10
  157. package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
  158. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
  159. package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
  160. package/src/bundled-plugins/security/policies/private-surface-read.ts +166 -201
  161. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
  162. package/src/bundled-plugins/typevault/grants.ts +119 -0
  163. package/src/bundled-plugins/typevault/index.ts +152 -0
  164. package/src/bundled-plugins/typevault/request.ts +87 -0
  165. package/src/bundled-plugins/typevault/runtime.ts +45 -0
  166. package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
  167. package/src/channels/adapter-halt.ts +17 -0
  168. package/src/channels/adapters/discord-bot-reference.ts +5 -4
  169. package/src/channels/adapters/discord-bot.ts +1 -0
  170. package/src/channels/adapters/discord-classify.ts +8 -3
  171. package/src/channels/adapters/discord.ts +29 -0
  172. package/src/channels/adapters/github/history.ts +23 -2
  173. package/src/channels/adapters/github/inbound.ts +60 -1
  174. package/src/channels/adapters/github/index.ts +27 -5
  175. package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
  176. package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
  177. package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
  178. package/src/channels/adapters/kakaotalk-classify.ts +7 -9
  179. package/src/channels/adapters/kakaotalk-list.ts +62 -0
  180. package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
  181. package/src/channels/adapters/kakaotalk-membership.ts +27 -10
  182. package/src/channels/adapters/kakaotalk-mention.ts +61 -0
  183. package/src/channels/adapters/kakaotalk.ts +159 -125
  184. package/src/channels/adapters/teams-classify.ts +18 -8
  185. package/src/channels/github-review-check.ts +5 -1
  186. package/src/channels/github-review-verdict-coordinator.ts +68 -2
  187. package/src/channels/github-token-bridge.ts +13 -0
  188. package/src/channels/lost-background-context.ts +46 -0
  189. package/src/channels/manager.ts +52 -3
  190. package/src/channels/persistence.ts +5 -0
  191. package/src/channels/router.ts +208 -128
  192. package/src/channels/schema.ts +1 -1
  193. package/src/channels/subagent-completion-bridge.ts +3 -2
  194. package/src/channels/types.ts +3 -0
  195. package/src/cli/hostd.ts +3 -0
  196. package/src/coding-agent/tool.ts +1 -1
  197. package/src/config/config.ts +35 -1
  198. package/src/config/providers.ts +75 -4
  199. package/src/container/start.ts +52 -3
  200. package/src/doctor/channel-checks.ts +33 -0
  201. package/src/doctor/checks.ts +37 -18
  202. package/src/doctor/index.ts +48 -12
  203. package/src/doctor/operational-incidents.ts +16 -1
  204. package/src/doctor/plugin-bridge.ts +14 -1
  205. package/src/doctor/stage.ts +14 -0
  206. package/src/doctor/types.ts +6 -0
  207. package/src/eval/cell.ts +93 -0
  208. package/src/eval/config.ts +32 -0
  209. package/src/eval/dispatch.ts +67 -0
  210. package/src/eval/entry.ts +261 -0
  211. package/src/eval/kernel.ts +154 -0
  212. package/src/eval/process.ts +113 -0
  213. package/src/eval/protocol.ts +26 -0
  214. package/src/eval/redeclare.ts +174 -0
  215. package/src/eval/sandbox.ts +117 -0
  216. package/src/eval/tool.ts +99 -0
  217. package/src/eval/wire.ts +93 -0
  218. package/src/git/resolve-identity.ts +67 -2
  219. package/src/git/system-commit.ts +7 -0
  220. package/src/init/dockerfile.ts +5 -1
  221. package/src/init/gitignore.ts +3 -3
  222. package/src/init/index.ts +1 -0
  223. package/src/init/models-dev.ts +2 -0
  224. package/src/init/validate-api-key.ts +5 -0
  225. package/src/migrations/secrets-v1-to-v2.ts +2 -0
  226. package/src/operations/classify-tool-outcome.ts +1 -1
  227. package/src/permissions/builtins.ts +8 -0
  228. package/src/plugin/core-tool-names.ts +6 -1
  229. package/src/plugin/types.ts +6 -0
  230. package/src/run/bundled-plugins.ts +12 -0
  231. package/src/run/channel-session-factory.ts +3 -0
  232. package/src/run/index.ts +13 -2
  233. package/src/sandbox/build.ts +1 -0
  234. package/src/sandbox/canonical-secrets.ts +6 -0
  235. package/src/sandbox/dependency-bins.ts +13 -1
  236. package/src/sandbox/dev-source.ts +21 -12
  237. package/src/sandbox/env-exposure.ts +20 -0
  238. package/src/sandbox/hidden-paths.ts +1 -1
  239. package/src/sandbox/index.ts +1 -0
  240. package/src/sandbox/policy.ts +5 -0
  241. package/src/secrets/hydrate.ts +4 -1
  242. package/src/secrets/storage.ts +10 -1
  243. package/src/server/command-runner.ts +4 -0
  244. package/src/server/index.ts +54 -12
  245. package/src/skills/typeclaw-config/SKILL.md +36 -2
  246. package/src/skills/typeclaw-memory/SKILL.md +3 -1
  247. package/src/skills/typeclaw-permissions/SKILL.md +8 -8
  248. package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
  249. package/src/tunnels/active.ts +14 -0
  250. package/src/typevault/bash-cli.ts +18 -0
  251. package/src/typevault/cli-path.ts +11 -0
  252. package/src/typevault/envelope-helper.ts +17 -0
  253. package/src/typevault/envelope-store.ts +98 -0
  254. package/src/typevault/lifecycle.ts +132 -0
  255. package/src/typevault/prompt-tunnel.ts +33 -0
  256. package/src/typevault/redaction.ts +37 -0
  257. package/src/typevault/vault.ts +283 -0
  258. package/typeclaw.schema.json +92 -10
@@ -11,6 +11,7 @@ import {
11
11
  import type { AgentSession, ToolDefinition } from '@earendil-works/pi-coding-agent'
12
12
 
13
13
  import { adapterNamespace } from '@/channels/adapter-namespace'
14
+ import type { GetGithubSelf } from '@/channels/github-token-bridge'
14
15
  import type { ChannelRouter } from '@/channels/router'
15
16
  import type { ReactionRef } from '@/channels/types'
16
17
  import { createCodingAgentTool } from '@/coding-agent/tool'
@@ -22,6 +23,21 @@ import {
22
23
  type ResolvedProfile,
23
24
  type ThinkingLevel,
24
25
  } from '@/config'
26
+ import { config } from '@/config/config'
27
+ import { registerEvalTool, EVAL_PROMPT_HINT } from '@/eval/tool'
28
+
29
+ import {
30
+ composeSessionTail,
31
+ composeSystemPrompt,
32
+ deriveSystemPromptMode,
33
+ type SystemPromptMode,
34
+ } from './system-prompt-composition'
35
+ export {
36
+ composeSystemPrompt,
37
+ deriveSystemPromptMode,
38
+ type SystemPromptMode,
39
+ type SystemPromptComposition,
40
+ } from './system-prompt-composition'
25
41
  import { effectiveModels } from '@/config/model-overrides'
26
42
  import { defaultThinkingLevelForRef, isOpenAiFamilyRef, providerForModelRef, type ModelRef } from '@/config/providers'
27
43
  import { renderMcpCatalog } from '@/mcp/catalog'
@@ -40,7 +56,7 @@ import type {
40
56
  import { createHookBus, materializeSkills } from '@/plugin'
41
57
  import { CORE_SYSTEM_TOOL_NAMES } from '@/plugin/core-tool-names'
42
58
  import type { ReloadRegistry } from '@/reload'
43
- import { enterSubagentTmpScope, resolveHiddenPaths } from '@/sandbox'
59
+ import { canSeePrivateSurface, enterSubagentTmpScope, resolveHiddenPaths } from '@/sandbox'
44
60
  import type { Stream } from '@/stream'
45
61
 
46
62
  import { getAuthFor } from './auth'
@@ -53,28 +69,26 @@ import type { LiveSubagentRegistry } from './live-subagents'
53
69
  import { sanitizeMessagesForLlmReplay } from './llm-replay-sanitizer'
54
70
  import { applyModelRuntimeOverrides } from './model-overrides'
55
71
  import { createChannelLookAtTool, createLookAtTool } from './multimodal'
72
+ import { defaultOutputAllowance } from './output-allowance'
56
73
  import {
57
74
  buildBuiltinPiToolOverrides,
58
75
  isPiCodingBuiltinName,
76
+ resetSharedLoopGuardSession,
59
77
  resolveBuiltinToolRefs,
60
78
  wrapPluginTool,
61
79
  wrapSystemTool,
62
80
  zodToToolParameters,
63
81
  } from './plugin-tools'
64
82
  import { PROACTIVE_NEXT_STEP_NUDGE } from './proactive-next-step-nudge'
65
- import { promptCacheKeyForOrigin, withPromptCacheKey } from './prompt-cache-key'
83
+ import { promptCacheKeyForOrigin, sharedSessionIdForOrigin, withPromptCacheKey } from './prompt-cache-key'
66
84
  import { wrapTransformContextWithLocalFailureMarker } from './provider-error'
67
85
  import { createReloadTool } from './reload-tool'
68
86
  import type { RestartHandoffOrigin } from './restart-handoff'
69
87
  import type { SubagentBashPolicy } from './reviewer-bash-policy'
70
88
  import { loadSelf } from './self'
71
89
  import { SESSION_META_CUSTOM_TYPE, sessionMetaPayload } from './session-meta'
72
- import {
73
- renderInteractiveSessionContext,
74
- renderSessionOrigin,
75
- type SessionOrigin,
76
- type SessionRoleContext,
77
- } from './session-origin'
90
+ import { renderSessionOrigin, type SessionOrigin, type SessionRoleContext } from './session-origin'
91
+ import { appendSessionTail, persistedPromptHasInlineSessionTail } from './session-tail'
78
92
  import { SubagentCacheKeepalive } from './subagent-cache-keepalive'
79
93
  import type { CreateSessionForSubagent, SubagentCoalescer, SubagentRegistry } from './subagents'
80
94
  import {
@@ -83,6 +97,8 @@ import {
83
97
  renderRuntimeBlock,
84
98
  renderRuntimeNondisclosureRule,
85
99
  stripRuntimeIdentityProse,
100
+ USER_INTENT_RULE,
101
+ GOAL_OWNERSHIP_RULE,
86
102
  } from './system-prompt'
87
103
  import { attachToolNotFoundNudge } from './tool-not-found-nudge'
88
104
  import { createBudgetState, type ToolResultBudget, wrapToolDefinitionWithBudget } from './tool-result-budget'
@@ -92,7 +108,7 @@ import { createChannelFetchAttachmentTool, resolveInboxBaseDir } from './tools/c
92
108
  import { createChannelHandoffTool } from './tools/channel-handoff'
93
109
  import { createChannelHistoryTool } from './tools/channel-history'
94
110
  import { createChannelReactTool } from './tools/channel-react'
95
- import { createChannelReadTool } from './tools/channel-read'
111
+ import { type ChannelReadTarget, createChannelReadTool } from './tools/channel-read'
96
112
  import { createChannelReplyTool } from './tools/channel-reply'
97
113
  import { createChannelSendTool } from './tools/channel-send'
98
114
  import { createChannelSessionSearchTool } from './tools/channel-session-search'
@@ -121,7 +137,7 @@ type AgentSessionTools = NonNullable<Parameters<typeof createAgentSession>[0]>['
121
137
  // the full model maximum before context clamping (dist/api/simple-options.js:17),
122
138
  // so preserve the former safe default at the session boundary. Explicit budgets
123
139
  // remain untouched for compaction and channel-specific output caps.
124
- export const DEFAULT_MAX_OUTPUT_TOKENS = 32_000
140
+ export { DEFAULT_MAX_OUTPUT_TOKENS } from './output-allowance'
125
141
 
126
142
  export type PluginSessionWiring = {
127
143
  registry: PluginRegistry
@@ -135,6 +151,7 @@ export type PluginSubagentSelection = {
135
151
  toolRefs?: BuiltinToolRef[]
136
152
  customTools?: PluginTool<any>[]
137
153
  toolNamePrefix: string
154
+ pluginToolNames?: readonly string[]
138
155
  }
139
156
 
140
157
  // Mutable holder for the live session origin. Pass this when the origin
@@ -147,6 +164,7 @@ export type PluginSubagentSelection = {
147
164
  export type SessionOriginRef = { current: SessionOrigin | undefined }
148
165
 
149
166
  export type CreateSessionOptions = {
167
+ readonly getGithubSelf?: GetGithubSelf
150
168
  reloadRegistry?: ReloadRegistry
151
169
  sessionManager?: SessionManager
152
170
  stream?: Stream
@@ -256,7 +274,7 @@ export type CreateSessionOptions = {
256
274
  }
257
275
 
258
276
  export type CreateSessionResult = {
259
- session: AgentSession & { getAbortReason?: () => string | undefined }
277
+ session: AgentSession & { getAbortReason?: () => string | undefined; resetLoopGuard?: () => void }
260
278
  dispose: () => Promise<void>
261
279
  getAbortReason?: () => string | undefined
262
280
  }
@@ -328,24 +346,6 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
328
346
  )
329
347
  : null
330
348
 
331
- const resourceLoader =
332
- options.systemPromptOverride !== undefined
333
- ? await createOverrideResourceLoader(
334
- options.systemPromptOverride,
335
- options.origin,
336
- options.permissions,
337
- options.runtimeVersion,
338
- )
339
- : await createResourceLoader({
340
- ...(options.plugins ? { plugins: options.plugins, materializedSkills } : {}),
341
- ...(options.origin ? { origin: options.origin } : {}),
342
- ...(options.permissions ? { permissions: options.permissions } : {}),
343
- ...(options.runtimeVersion !== undefined ? { runtimeVersion: options.runtimeVersion } : {}),
344
- ...(options.mcpManager !== undefined ? { mcpManager: options.mcpManager } : {}),
345
- ...(options.subagentRegistry !== undefined ? { subagentRegistry: options.subagentRegistry } : {}),
346
- ...(isOpenAiFamilyRef(activeRef) ? { proactiveNextStepNudge: true } : {}),
347
- })
348
-
349
349
  const getOrigin: () => SessionOrigin | undefined =
350
350
  options.originRef !== undefined ? () => options.originRef!.current : () => options.origin
351
351
 
@@ -383,16 +383,20 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
383
383
  : []
384
384
  const subagentBuiltinNames = resolvedSubagentBuiltins.map((t) => t.name)
385
385
  const subagentTypeclawToolDefinitions = resolvedSubagentBuiltins.filter((t) => !isPiCodingBuiltinName(t.name))
386
+ const registryTools = wrapRegistryTools(options.plugins, getOrigin, getAbort, getLoopGuardTurn, options.permissions)
386
387
  const pluginCustomTools = options.pluginSubagent
387
- ? wrapSubagentCustomTools(
388
- options.pluginSubagent,
389
- options.plugins,
390
- getOrigin,
391
- getAbort,
392
- getLoopGuardTurn,
393
- options.permissions,
394
- )
395
- : wrapRegistryTools(options.plugins, getOrigin, getAbort, getLoopGuardTurn, options.permissions)
388
+ ? [
389
+ ...wrapSubagentCustomTools(
390
+ options.pluginSubagent,
391
+ options.plugins,
392
+ getOrigin,
393
+ getAbort,
394
+ getLoopGuardTurn,
395
+ options.permissions,
396
+ ),
397
+ ...registryTools.filter((tool) => options.pluginSubagent?.pluginToolNames?.includes(tool.name) === true),
398
+ ]
399
+ : registryTools
396
400
 
397
401
  // Per-run budget state for the tool-result byte ceiling. Allocated once per
398
402
  // session creation and threaded into every wrapped tool so they share the
@@ -528,6 +532,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
528
532
  // unwrapped bash path. `wrapBuiltinToolDefinition` no-ops the optional
529
533
  // stages (plugin hooks, permissions, bashPolicy) when they are absent.
530
534
  const builtinPiToolOverrides = buildBuiltinPiToolOverrides({
535
+ getGithubSelf: options.getGithubSelf,
531
536
  agentDir: options.plugins?.agentDir ?? process.cwd(),
532
537
  sessionId: options.plugins?.sessionId ?? sessionManager.getSessionId(),
533
538
  hooks: options.plugins?.hooks ?? createHookBus(),
@@ -567,15 +572,70 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
567
572
  ...new Set([...builtinActiveNames, ...[...wrappedCustomSystemTools, ...pluginCustomTools].map((t) => t.name)]),
568
573
  ]
569
574
 
575
+ let activeSession: AgentSession | undefined
576
+ const evalRuntime = registerEvalTool({
577
+ settings: config.eval,
578
+ tools: customTools,
579
+ activeNames: intendedActiveToolNames,
580
+ getActiveNames: () => activeSession?.getActiveToolNames() ?? intendedActiveToolNames,
581
+ wrappers: {
582
+ getGithubSelf: options.getGithubSelf,
583
+ agentDir: options.plugins?.agentDir ?? process.cwd(),
584
+ sessionId: options.plugins?.sessionId ?? sessionManager.getSessionId(),
585
+ hooks: options.plugins?.hooks ?? createHookBus(),
586
+ guards,
587
+ getOrigin,
588
+ getAbort,
589
+ getLoopGuardTurn,
590
+ permissions: options.permissions ?? noopPermissionService,
591
+ bashPolicy: options.bashPolicy,
592
+ },
593
+ budget: sessionBudget,
594
+ budgetState: sessionBudgetState,
595
+ })
596
+
597
+ // New sessions render their origin/role/git suffix after pi's sections at
598
+ // request time (see session-tail.ts); a resumed session keeps the layout its
599
+ // persisted prompt already has.
600
+ let sessionTail = ''
601
+ const detachSessionTail = !persistedPromptHasInlineSessionTail(sessionManager.getEntries())
602
+ const resourceLoader =
603
+ options.systemPromptOverride !== undefined
604
+ ? await createOverrideResourceLoader(
605
+ options.systemPromptOverride + (evalRuntime ? `\n\n${EVAL_PROMPT_HINT}` : ''),
606
+ options.origin,
607
+ options.permissions,
608
+ options.runtimeVersion,
609
+ )
610
+ : await createResourceLoader({
611
+ evalEnabled: evalRuntime !== undefined,
612
+ ...(options.plugins ? { plugins: options.plugins, materializedSkills } : {}),
613
+ ...(options.origin ? { origin: options.origin } : {}),
614
+ ...(options.permissions ? { permissions: options.permissions } : {}),
615
+ ...(options.runtimeVersion !== undefined ? { runtimeVersion: options.runtimeVersion } : {}),
616
+ ...(options.mcpManager !== undefined ? { mcpManager: options.mcpManager } : {}),
617
+ ...(options.subagentRegistry !== undefined ? { subagentRegistry: options.subagentRegistry } : {}),
618
+ ...(isOpenAiFamilyRef(activeRef) ? { proactiveNextStepNudge: true } : {}),
619
+ ...(detachSessionTail
620
+ ? {
621
+ onSessionTail: (tail: string) => {
622
+ sessionTail = tail
623
+ },
624
+ }
625
+ : {}),
626
+ })
627
+
570
628
  const model = applyModelRuntimeOverrides(resolveModel(activeRef), activeRef)
571
629
  // Read live so a reloaded `models` lands on the next session without a
572
630
  // container restart.
573
631
  const thinkingLevel = resolveSessionThinkingLevel(models, resolved, activeRef, options.thinkingLevel)
632
+ // Read per session like `models`, so a reloaded ceiling applies to new sessions.
633
+ const maxCompactionTriggerTokens = getConfig().compaction.maxTriggerTokens
574
634
  const { session } = await createAgentSession({
575
635
  model,
576
636
  modelRuntime,
577
637
  sessionManager,
578
- settingsManager: createCompactionSettingsManager(model),
638
+ settingsManager: createCompactionSettingsManager(model, maxCompactionTriggerTokens),
579
639
  resourceLoader,
580
640
  noTools: 'builtin',
581
641
  tools: intendedActiveToolNames,
@@ -584,6 +644,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
584
644
  })
585
645
  // Pi's general warmer also runs without background children. TypeClaw owns
586
646
  // the narrower idle-parent policy and never persists synthetic ping results.
647
+ activeSession = session
587
648
  session.setCacheWarmingMode('off')
588
649
  const cacheKeepalive = options.liveSubagentRegistry
589
650
  ? new SubagentCacheKeepalive(
@@ -598,6 +659,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
598
659
  })
599
660
  const innerDispose = session.dispose.bind(session)
600
661
  session.dispose = () => {
662
+ void evalRuntime?.dispose()
601
663
  cacheKeepalive?.close()
602
664
  unsubCacheKeepalive()
603
665
  innerDispose()
@@ -610,23 +672,26 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
610
672
  // this function, so every origin now behaves the same way.
611
673
  const innerStreamFunction = session.agent.streamFunction
612
674
  session.agent.streamFunction = async (requestModel, context, streamOptions) => {
613
- const maxTokens =
614
- streamOptions?.maxTokens ??
615
- (requestModel.maxTokens > 0 ? Math.min(requestModel.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS) : undefined)
616
- const promptCacheKey = promptCacheKeyForOrigin(getOrigin())
675
+ const maxTokens = streamOptions?.maxTokens ?? defaultOutputAllowance(requestModel)
676
+ const origin = getOrigin()
677
+ const promptCacheKey = promptCacheKeyForOrigin(origin)
678
+ const sharedSessionId = sharedSessionIdForOrigin(origin)
679
+ const requestOptions = {
680
+ ...streamOptions,
681
+ ...(sharedSessionId !== undefined && streamOptions?.sessionId !== undefined
682
+ ? { sessionId: sharedSessionId }
683
+ : {}),
684
+ maxTokens,
685
+ }
617
686
  const onPayload = async (payload: unknown, payloadModel: typeof requestModel) => {
618
687
  const next = (await streamOptions?.onPayload?.(payload, payloadModel)) ?? payload
619
688
  const final = promptCacheKey === undefined ? next : withPromptCacheKey(next, promptCacheKey)
620
689
  if (streamOptions?.sessionId === session.sessionId) {
621
- cacheKeepalive?.capture(payloadModel, context, { ...streamOptions, maxTokens }, final)
690
+ cacheKeepalive?.capture(payloadModel, context, requestOptions, final)
622
691
  }
623
692
  return final
624
693
  }
625
- return await innerStreamFunction(requestModel, context, {
626
- ...streamOptions,
627
- maxTokens,
628
- onPayload,
629
- })
694
+ return await innerStreamFunction(requestModel, context, { ...requestOptions, onPayload })
630
695
  }
631
696
 
632
697
  // typeclaw owns retry/fallback in its turn drivers, so the SDK's own
@@ -639,7 +704,14 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
639
704
  // marked local failures are kept out of overflow recovery at the marker below.
640
705
  session.setAutoRetryEnabled(false)
641
706
  const getAbortReason = () => abortHolder.reason
642
- const sessionWithAbortReason = Object.assign(session, { getAbortReason })
707
+ // The loop guard detects a model cycling inside one request. Repeating work
708
+ // across separate user messages (e.g. appending each reported workout set to
709
+ // the same log file) is progress, so turn drivers call this when a real user
710
+ // request starts. Runtime retries and reminders of the same request must not,
711
+ // or an aborted cycle could clear itself by being retried.
712
+ const loopGuardSessionId = options.plugins?.sessionId ?? sessionManager.getSessionId()
713
+ const resetLoopGuard = () => resetSharedLoopGuardSession(loopGuardSessionId)
714
+ const sessionWithAbortReason = Object.assign(session, { getAbortReason, resetLoopGuard })
643
715
  const unsubLoopGuardTurn = attachLoopGuardTurnTracking(session.agent, () => {
644
716
  loopGuardTurnId += 1
645
717
  })
@@ -667,7 +739,16 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
667
739
  // stay unwrapped: their failures can be genuine provider/auth failures.
668
740
  // Overflow recovery stays enabled; a local failure whose text would read as a
669
741
  // provider overflow is stamped with fixed text and its raw text is logged here.
670
- session.agent.transformContext = wrapTransformContextWithLocalFailureMarker(session.agent.transformContext, {
742
+ const innerTransformContext = session.agent.transformContext
743
+ const transformWithSessionTail: typeof innerTransformContext =
744
+ sessionTail === ''
745
+ ? innerTransformContext
746
+ : async (messages, signal) =>
747
+ appendSessionTail(
748
+ innerTransformContext ? await innerTransformContext(messages, signal) : messages,
749
+ sessionTail,
750
+ )
751
+ session.agent.transformContext = wrapTransformContextWithLocalFailureMarker(transformWithSessionTail, {
671
752
  getProvider: () => session.agent.state.model?.provider,
672
753
  logWithheld: (line) =>
673
754
  console.error(`[agent] ${options.plugins?.sessionId ?? sessionManager.getSessionId()}: ${line}`),
@@ -683,7 +764,10 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
683
764
  const unsubToolNudge = attachToolNotFoundNudge(session, intendedActiveToolNames)
684
765
  // An applied idle summary replaces the prefix the keepalive captured;
685
766
  // replaying the old one would only refresh a cache no turn will read.
686
- const stopIdleCompaction = attachIdleCompaction(session, { onApplied: () => cacheKeepalive?.invalidate() })
767
+ const stopIdleCompaction = attachIdleCompaction(session, {
768
+ maxTriggerTokens: maxCompactionTriggerTokens,
769
+ onApplied: () => cacheKeepalive?.invalidate(),
770
+ })
687
771
 
688
772
  // Registered only once creation can no longer fail, so a rejected creation
689
773
  // leaves no scope entry behind; tools resolve the scope lazily at call time.
@@ -695,6 +779,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
695
779
  )
696
780
  : undefined
697
781
  const dispose = async () => {
782
+ await evalRuntime?.dispose()
698
783
  stopIdleCompaction()
699
784
  cacheKeepalive?.close()
700
785
  unsubCacheKeepalive()
@@ -871,6 +956,26 @@ export function buildChannelTools(
871
956
  ): ToolDefinition[] {
872
957
  if (!channelRouter) return []
873
958
  const tools: ToolDefinition[] = []
959
+ // Another conversation's live history is the same exposure as its transcript
960
+ // under sessions/, so it takes the same tier. Checked per call against the
961
+ // live turn origin: one channel session serves speakers with different roles.
962
+ const canRead =
963
+ permissions === undefined
964
+ ? undefined
965
+ : (target: ChannelReadTarget): boolean => {
966
+ const live = getOrigin?.() ?? origin
967
+ const sameConversation =
968
+ live?.kind === 'channel' &&
969
+ target.chat !== undefined &&
970
+ adapterNamespace(live.adapter) === adapterNamespace(target.adapter) &&
971
+ live.workspace === target.workspace &&
972
+ live.chat === target.chat &&
973
+ // Some adapters address the read by `thread ?? chat` (a Discord
974
+ // thread is its own channel id), so any other thread could point
975
+ // anywhere the agent can see; only this session's own is exempt.
976
+ (target.thread === undefined || target.thread === live.thread)
977
+ return sameConversation || canSeePrivateSurface(permissions, live)
978
+ }
874
979
  const getOutboundOrigin = (): ChannelOutboundOrigin | undefined => {
875
980
  const current = getOrigin ? getOrigin() : origin
876
981
  return current ? { kind: current.kind, ...(current.kind === 'cron' ? { jobId: current.jobId } : {}) } : undefined
@@ -902,7 +1007,13 @@ export function buildChannelTools(
902
1007
  if (origin.adapter === 'github' && sessionId !== undefined)
903
1008
  tools.push(createPostGithubReviewTool({ router: channelRouter, origin: channelOrigin, sessionId }))
904
1009
  tools.push(createChannelHistoryTool({ router: channelRouter, origin: channelOrigin }))
905
- tools.push(createChannelReadTool({ router: channelRouter, ...(sessionId !== undefined ? { sessionId } : {}) }))
1010
+ tools.push(
1011
+ createChannelReadTool({
1012
+ router: channelRouter,
1013
+ ...(sessionId !== undefined ? { sessionId } : {}),
1014
+ ...(canRead !== undefined ? { canRead } : {}),
1015
+ }),
1016
+ )
906
1017
  tools.push(
907
1018
  createChannelSendTool({
908
1019
  router: channelRouter,
@@ -945,7 +1056,7 @@ export function buildChannelTools(
945
1056
  }
946
1057
  } else {
947
1058
  tools.push(createChannelSendTool({ router: channelRouter, getOutboundOrigin }))
948
- tools.push(createChannelReadTool({ router: channelRouter }))
1059
+ tools.push(createChannelReadTool({ router: channelRouter, ...(canRead !== undefined ? { canRead } : {}) }))
949
1060
  tools.push(createChannelEditTool({ router: channelRouter, getOutboundOrigin }))
950
1061
  }
951
1062
  return tools
@@ -1202,11 +1313,12 @@ export async function createOverrideResourceLoader(
1202
1313
  runtimeVersion?: string,
1203
1314
  ): Promise<DefaultResourceLoader> {
1204
1315
  const branding = getConfig().branding
1316
+ const withRule = `${systemPrompt}\n\n${USER_INTENT_RULE}\n\n${GOAL_OWNERSHIP_RULE}`
1205
1317
  const withRuntime = branding
1206
1318
  ? runtimeVersion !== undefined
1207
- ? `${systemPrompt}\n\n${renderRuntimeBlock(runtimeVersion)}`
1208
- : systemPrompt
1209
- : `${stripRuntimeIdentityProse(systemPrompt)}\n\n${renderRuntimeNondisclosureRule()}`
1319
+ ? `${withRule}\n\n${renderRuntimeBlock(runtimeVersion)}`
1320
+ : withRule
1321
+ : `${stripRuntimeIdentityProse(withRule)}\n\n${renderRuntimeNondisclosureRule()}`
1210
1322
  const finalPrompt = withOrigin(withRuntime, origin, permissions)
1211
1323
  const loader = new DefaultResourceLoader({
1212
1324
  cwd: process.cwd(),
@@ -1238,133 +1350,10 @@ export type CreateResourceLoaderOptions = {
1238
1350
  // useful; mostly an escape hatch for ad-hoc debugging).
1239
1351
  mode?: SystemPromptMode
1240
1352
  proactiveNextStepNudge?: boolean
1241
- }
1242
-
1243
- // Origins with a conversation partner waiting on the reply get the full-mode
1244
- // session context: the interactive orchestration context with the live public
1245
- // roster, the MCP catalog, and the git nudge. Unattended origins (cron fires,
1246
- // default subagents, system processes) skip that context and the roster/git/MCP
1247
- // work it needs — their origin block already says what is expected. Every
1248
- // origin gets the same shared policy either way.
1249
- //
1250
- // Exhaustive switch (not a boolean expression) so a future origin kind forces
1251
- // the author to make an explicit full-or-slim decision at compile time. The
1252
- // previous form silently defaulted new origins to slim, which would have
1253
- // stripped the interactive context from a new interactive surface by
1254
- // accident.
1255
- export function deriveSystemPromptMode(origin: SessionOrigin | undefined): SystemPromptMode {
1256
- if (origin === undefined) return 'full'
1257
- switch (origin.kind) {
1258
- case 'tui':
1259
- case 'channel':
1260
- return 'full'
1261
- case 'cron':
1262
- case 'subagent':
1263
- case 'system':
1264
- return 'slim'
1265
- default: {
1266
- const _exhaustive: never = origin
1267
- void _exhaustive
1268
- return 'full'
1269
- }
1270
- }
1271
- }
1272
-
1273
- // Pure inputs for `composeSystemPrompt`. Each field maps 1:1 to a rendered
1274
- // section of the prompt; callers that don't want a section pass `undefined`
1275
- // (or `''` for `gitNudge`). Extracted so the debug dumper in
1276
- // `scripts/dump-system-prompt.ts` can reuse the exact same composition
1277
- // pipeline `createResourceLoader` uses, with no risk of drift if the
1278
- // section order changes.
1279
- //
1280
- // `mode` selects only the optional session context, never the policy: every
1281
- // standard session starts with `buildSystemPolicy(branding)`.
1282
- // - 'full' (default) — TUI, channel, and origin-less sessions: appends the
1283
- // interactive context (`renderInteractiveSessionContext`) with the roster.
1284
- // - 'slim' — cron, default subagents, system processes: no interactive
1285
- // context; the origin block covers per-kind specifics (no human, side
1286
- // effects via tools, narrow scope).
1287
- export type SystemPromptMode = 'full' | 'slim'
1288
-
1289
- export type SystemPromptComposition = {
1290
- mode?: SystemPromptMode
1291
- // Whether the prompt discloses that the agent runs on TypeClaw. When false,
1292
- // the policy's opening is phrased generically, the `## Runtime` version
1293
- // block is dropped, and the runtime-disclosure rule is appended. Defaults to
1294
- // true. Mirrors `config.branding`.
1295
- branding?: boolean
1296
- self: string
1297
- // Pre-rendered interactive-context roster (from `renderPublicSubagentRoster`).
1298
- // Kept as a ready string so this composer stays pure and registry-free; the
1299
- // registry-aware caller renders it. Ignored in slim mode (no interactive
1300
- // context). Falls back to `DEFAULT_SUBAGENT_ROSTER` when omitted.
1301
- subagentRoster?: string
1302
- runtimeVersion?: string
1303
- origin?: SessionOrigin
1304
- roleContext?: SessionRoleContext
1305
- mcpCatalog?: string
1306
- gitNudge: string
1307
- proactiveNextStepNudge?: string
1308
- }
1309
-
1310
- // Section-order contract for the system prompt. Kept as a pure string→string
1311
- // transform so it can be exercised without disk, plugin runtime, or auth.
1312
- //
1313
- // Cache-suffix ordering: least-volatile sections first, most-volatile last.
1314
- // This minimises the number of cached prompt bytes invalidated when a
1315
- // section changes (the provider's prompt cache hits up to the first byte
1316
- // that differs).
1317
- //
1318
- // 0. shared policy — identical for every standard session of an agent.
1319
- // 1. self — IDENTITY.md + SOUL.md (plus any plugin `session.prompt` append).
1320
- // 2. runtime block (or the runtime-disclosure rule when branding is off) —
1321
- // only changes on typeclaw releases.
1322
- // 3. interactive context (full mode) — stable per agent registry, so it
1323
- // precedes the per-session origin block.
1324
- // 4. origin block + role — stable across sessions of the same kind; channel
1325
- // origins carry per-conversation details.
1326
- // 5. MCP catalog — changes when servers connect or disconnect.
1327
- // 6. gitNudge — rare changes; agent folders force-commit sessions/ and
1328
- // memory/ after every turn, so the dirty-files list is empty most of
1329
- // the time.
1330
- // 7. proactive next-step nudge — deterministic per model family.
1331
- //
1332
- // The wall-clock anchor that used to live here as `## Now` moved out
1333
- // entirely. It is now injected into the user turn at each `session.prompt`
1334
- // site via `renderTurnTimeAnchor` (src/agent/system-prompt.ts) so the
1335
- // stamp reflects the moment of THIS turn, not session creation. Per-turn
1336
- // injection costs zero cached bytes — the user turn is the non-cacheable
1337
- // suffix anyway — and removes the staleness failure mode where a session
1338
- // opened Friday answered "today is Friday" on Thursday. Retrieved memory and
1339
- // the live channel role ride in the user turn for the same reason.
1340
- //
1341
- // pi appends project context (AGENTS.md), the skill catalog, and the cwd
1342
- // after this preamble when it builds the final system message.
1343
- export function composeSystemPrompt(parts: SystemPromptComposition): string {
1344
- const branding = parts.branding ?? true
1345
- let prompt = `${buildSystemPolicy(branding)}\n\n${parts.self}`
1346
- if (branding && parts.runtimeVersion !== undefined) {
1347
- prompt = `${prompt}\n\n${renderRuntimeBlock(parts.runtimeVersion)}`
1348
- }
1349
- if (!branding) {
1350
- prompt = `${prompt}\n\n${renderRuntimeNondisclosureRule()}`
1351
- }
1352
- if (parts.mode !== 'slim') {
1353
- prompt = `${prompt}\n\n${renderInteractiveSessionContext(parts.subagentRoster ?? DEFAULT_SUBAGENT_ROSTER)}`
1354
- }
1355
- if (parts.origin !== undefined) {
1356
- prompt = `${prompt}\n\n${renderSessionOrigin(parts.origin, Date.now(), parts.roleContext)}`
1357
- }
1358
- if (parts.mcpCatalog !== undefined && parts.mcpCatalog !== '') {
1359
- prompt = `${prompt}\n\n${parts.mcpCatalog}`
1360
- }
1361
- if (parts.gitNudge !== '') {
1362
- prompt = `${prompt}\n\n${parts.gitNudge}`
1363
- }
1364
- if (parts.proactiveNextStepNudge !== undefined && parts.proactiveNextStepNudge !== '') {
1365
- prompt = `${prompt}\n\n${parts.proactiveNextStepNudge}`
1366
- }
1367
- return prompt
1353
+ evalEnabled?: boolean
1354
+ // When set, the origin/role/git suffix is left out of the preamble and handed
1355
+ // here instead, for the session to append after pi's sections.
1356
+ onSessionTail?: (tail: string) => void
1368
1357
  }
1369
1358
 
1370
1359
  export async function createResourceLoader(options: CreateResourceLoaderOptions = {}): Promise<DefaultResourceLoader> {
@@ -1443,16 +1432,25 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1443
1432
  mcpCatalog = renderMcpCatalog(options.mcpManager.listServers())
1444
1433
  }
1445
1434
 
1435
+ const detached = options.onSessionTail !== undefined
1436
+ options.onSessionTail?.(
1437
+ composeSessionTail({
1438
+ ...(options.origin !== undefined ? { origin: options.origin } : {}),
1439
+ ...(roleContext !== undefined ? { roleContext } : {}),
1440
+ gitNudge,
1441
+ }),
1442
+ )
1446
1443
  const systemPrompt = composeSystemPrompt({
1447
1444
  mode,
1448
1445
  branding,
1449
1446
  self,
1450
1447
  subagentRoster,
1451
1448
  ...(options.runtimeVersion !== undefined ? { runtimeVersion: options.runtimeVersion } : {}),
1452
- ...(options.origin !== undefined ? { origin: options.origin } : {}),
1453
- ...(roleContext !== undefined ? { roleContext } : {}),
1449
+ ...(options.origin !== undefined && !detached ? { origin: options.origin } : {}),
1450
+ ...(roleContext !== undefined && !detached ? { roleContext } : {}),
1454
1451
  ...(mcpCatalog !== undefined ? { mcpCatalog } : {}),
1455
- gitNudge,
1452
+ gitNudge: detached ? '' : gitNudge,
1453
+ ...(options.evalEnabled ? { evalHint: EVAL_PROMPT_HINT } : {}),
1456
1454
  ...(options.proactiveNextStepNudge === true ? { proactiveNextStepNudge: PROACTIVE_NEXT_STEP_NUDGE } : {}),
1457
1455
  })
1458
1456
 
@@ -1,8 +1,8 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import { Type } from '@earendil-works/pi-ai'
4
3
  import type { ImageContent } from '@earendil-works/pi-ai'
5
4
  import { defineTool } from '@earendil-works/pi-coding-agent'
5
+ import { Type } from 'typebox'
6
6
 
7
7
  import { createSessionWithDispose, type SessionOrigin } from '@/agent'
8
8
  import { readResponseBodyBounded } from '@/agent/network/response-body'
@@ -0,0 +1,7 @@
1
+ export const DEFAULT_MAX_OUTPUT_TOKENS = 32_000
2
+
3
+ // The output cap every session request sends when the caller set none.
4
+ // Undefined leaves the provider's own default in place.
5
+ export function defaultOutputAllowance(model: { maxTokens: number }): number | undefined {
6
+ return model.maxTokens > 0 ? Math.min(model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS) : undefined
7
+ }