typeclaw 0.51.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 (202) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +2 -0
  2. package/dist/types/agent/bash-sandbox.d.ts +4 -0
  3. package/dist/types/agent/index.d.ts +5 -0
  4. package/dist/types/agent/multimodal/look-at.d.ts +1 -1
  5. package/dist/types/agent/plugin-tools.d.ts +4 -0
  6. package/dist/types/agent/prompt-cache-key.d.ts +1 -0
  7. package/dist/types/agent/session-tail.d.ts +12 -0
  8. package/dist/types/agent/subagents.d.ts +5 -0
  9. package/dist/types/agent/system-prompt-composition.d.ts +1 -0
  10. package/dist/types/agent/system-prompt.d.ts +2 -0
  11. package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
  12. package/dist/types/agent/tools/channel-edit.d.ts +1 -1
  13. package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
  14. package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
  15. package/dist/types/agent/tools/channel-history.d.ts +1 -1
  16. package/dist/types/agent/tools/channel-react.d.ts +1 -1
  17. package/dist/types/agent/tools/channel-read.d.ts +10 -2
  18. package/dist/types/agent/tools/channel-reply.d.ts +1 -1
  19. package/dist/types/agent/tools/channel-send.d.ts +1 -1
  20. package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
  21. package/dist/types/agent/tools/grant-role.d.ts +1 -1
  22. package/dist/types/agent/tools/post-github-review.d.ts +1 -1
  23. package/dist/types/agent/tools/restart.d.ts +1 -1
  24. package/dist/types/agent/tools/skip-response.d.ts +1 -1
  25. package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
  26. package/dist/types/agent/tools/stream-snapshot.d.ts +1 -1
  27. package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
  28. package/dist/types/agent/tools/subagent-output.d.ts +1 -1
  29. package/dist/types/agent/tools/todo/index.d.ts +1 -1
  30. package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
  31. package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
  32. package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
  33. package/dist/types/agent/tools/websearch.d.ts +1 -1
  34. package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
  35. package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
  36. package/dist/types/channels/adapters/github/auth.d.ts +24 -0
  37. package/dist/types/channels/github-token-bridge.d.ts +4 -0
  38. package/dist/types/channels/lost-background-context.d.ts +2 -0
  39. package/dist/types/channels/persistence.d.ts +1 -0
  40. package/dist/types/channels/router.d.ts +5 -1
  41. package/dist/types/channels/types.d.ts +1 -0
  42. package/dist/types/coding-agent/tool.d.ts +1 -1
  43. package/dist/types/config/config.d.ts +20 -11
  44. package/dist/types/config/providers.d.ts +47 -0
  45. package/dist/types/eval/sandbox.d.ts +2 -0
  46. package/dist/types/git/resolve-identity.d.ts +2 -0
  47. package/dist/types/init/dockerfile.d.ts +1 -0
  48. package/dist/types/init/gitignore.d.ts +1 -1
  49. package/dist/types/permissions/builtins.d.ts +1 -0
  50. package/dist/types/plugin/types.d.ts +3 -0
  51. package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
  52. package/dist/types/sandbox/coding-agent.d.ts +1 -1
  53. package/dist/types/sandbox/dependency-bins.d.ts +1 -0
  54. package/dist/types/sandbox/dev-source.d.ts +2 -2
  55. package/dist/types/sandbox/hidden-paths.d.ts +1 -0
  56. package/dist/types/sandbox/index.d.ts +1 -1
  57. package/dist/types/sandbox/policy.d.ts +3 -0
  58. package/dist/types/typevault/cli-path.d.ts +2 -0
  59. package/dist/types/typevault/envelope-store.d.ts +11 -0
  60. package/dist/types/typevault/lifecycle.d.ts +13 -0
  61. package/dist/types/typevault/vault.d.ts +27 -0
  62. package/package.json +8 -7
  63. package/scripts/test.ts +252 -0
  64. package/src/agent/bash-sandbox-env.ts +33 -1
  65. package/src/agent/bash-sandbox.ts +20 -6
  66. package/src/agent/index.ts +120 -31
  67. package/src/agent/multimodal/look-at.ts +1 -1
  68. package/src/agent/plugin-tools.ts +35 -1
  69. package/src/agent/prompt-cache-key.ts +26 -3
  70. package/src/agent/session-origin.ts +39 -18
  71. package/src/agent/session-tail.ts +28 -0
  72. package/src/agent/subagents.ts +21 -2
  73. package/src/agent/system-prompt-composition.ts +18 -0
  74. package/src/agent/system-prompt.ts +39 -1
  75. package/src/agent/tool-error-remediation.ts +18 -3
  76. package/src/agent/tools/channel-disengage.ts +1 -1
  77. package/src/agent/tools/channel-edit.ts +1 -1
  78. package/src/agent/tools/channel-fetch-attachment.ts +1 -1
  79. package/src/agent/tools/channel-handoff.ts +3 -2
  80. package/src/agent/tools/channel-history.ts +2 -1
  81. package/src/agent/tools/channel-react.ts +1 -1
  82. package/src/agent/tools/channel-read.ts +36 -3
  83. package/src/agent/tools/channel-reply.ts +1 -1
  84. package/src/agent/tools/channel-send.ts +4 -3
  85. package/src/agent/tools/channel-session-search.ts +13 -4
  86. package/src/agent/tools/grant-role.ts +1 -1
  87. package/src/agent/tools/post-github-review.ts +1 -1
  88. package/src/agent/tools/restart.ts +1 -1
  89. package/src/agent/tools/skip-response.ts +1 -1
  90. package/src/agent/tools/spawn-subagent.ts +15 -1
  91. package/src/agent/tools/stream-snapshot.ts +1 -1
  92. package/src/agent/tools/subagent-cancel.ts +1 -1
  93. package/src/agent/tools/subagent-output.ts +1 -1
  94. package/src/agent/tools/todo/index.ts +1 -1
  95. package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
  96. package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
  97. package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
  98. package/src/agent/tools/webfetch/tool.ts +6 -5
  99. package/src/agent/tools/websearch.ts +1 -1
  100. package/src/browser/dockerfile.ts +1 -1
  101. package/src/browser/fill-secret.ts +92 -35
  102. package/src/browser/registry.ts +6 -6
  103. package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
  104. package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
  105. package/src/bundled-plugins/backup/index.ts +17 -2
  106. package/src/bundled-plugins/backup/runner.ts +37 -2
  107. package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
  108. package/src/bundled-plugins/browser-agent/index.ts +12 -5
  109. package/src/bundled-plugins/managed-browser/index.ts +25 -2
  110. package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
  111. package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
  112. package/src/bundled-plugins/memory/README.md +23 -2
  113. package/src/bundled-plugins/memory/append-fragment.ts +133 -0
  114. package/src/bundled-plugins/memory/append-tool.ts +80 -149
  115. package/src/bundled-plugins/memory/dreaming.ts +2 -0
  116. package/src/bundled-plugins/memory/index.ts +33 -6
  117. package/src/bundled-plugins/memory/memory-logger.ts +133 -11
  118. package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
  119. package/src/bundled-plugins/memory/remember-tool.ts +81 -0
  120. package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
  121. package/src/bundled-plugins/memory/search-tool.ts +58 -12
  122. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  123. package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
  124. package/src/bundled-plugins/memory/transcript-preload.ts +131 -26
  125. package/src/bundled-plugins/memory/transcript-view.ts +36 -0
  126. package/src/bundled-plugins/memory/watermark.ts +19 -10
  127. package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
  128. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
  129. package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
  130. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
  131. package/src/bundled-plugins/typevault/grants.ts +119 -0
  132. package/src/bundled-plugins/typevault/index.ts +152 -0
  133. package/src/bundled-plugins/typevault/request.ts +87 -0
  134. package/src/bundled-plugins/typevault/runtime.ts +45 -0
  135. package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
  136. package/src/channels/adapter-halt.ts +17 -0
  137. package/src/channels/adapters/github/history.ts +23 -2
  138. package/src/channels/adapters/github/inbound.ts +60 -1
  139. package/src/channels/adapters/github/index.ts +27 -5
  140. package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
  141. package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
  142. package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
  143. package/src/channels/adapters/kakaotalk-classify.ts +7 -9
  144. package/src/channels/adapters/kakaotalk-list.ts +62 -0
  145. package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
  146. package/src/channels/adapters/kakaotalk-membership.ts +27 -10
  147. package/src/channels/adapters/kakaotalk-mention.ts +61 -0
  148. package/src/channels/adapters/kakaotalk.ts +159 -125
  149. package/src/channels/adapters/teams-classify.ts +18 -8
  150. package/src/channels/github-token-bridge.ts +13 -0
  151. package/src/channels/lost-background-context.ts +46 -0
  152. package/src/channels/manager.ts +52 -3
  153. package/src/channels/persistence.ts +5 -0
  154. package/src/channels/router.ts +120 -21
  155. package/src/channels/schema.ts +1 -1
  156. package/src/channels/types.ts +3 -0
  157. package/src/coding-agent/tool.ts +1 -1
  158. package/src/config/config.ts +20 -1
  159. package/src/config/providers.ts +65 -0
  160. package/src/container/start.ts +15 -2
  161. package/src/doctor/channel-checks.ts +33 -0
  162. package/src/doctor/checks.ts +12 -2
  163. package/src/eval/sandbox.ts +3 -0
  164. package/src/eval/tool.ts +1 -0
  165. package/src/git/resolve-identity.ts +67 -2
  166. package/src/git/system-commit.ts +7 -0
  167. package/src/init/dockerfile.ts +5 -1
  168. package/src/init/gitignore.ts +3 -3
  169. package/src/init/index.ts +1 -0
  170. package/src/init/models-dev.ts +2 -0
  171. package/src/init/validate-api-key.ts +5 -0
  172. package/src/migrations/secrets-v1-to-v2.ts +2 -0
  173. package/src/permissions/builtins.ts +8 -0
  174. package/src/plugin/types.ts +6 -0
  175. package/src/run/bundled-plugins.ts +12 -0
  176. package/src/run/channel-session-factory.ts +3 -0
  177. package/src/run/index.ts +13 -2
  178. package/src/sandbox/build.ts +1 -0
  179. package/src/sandbox/canonical-secrets.ts +6 -0
  180. package/src/sandbox/dependency-bins.ts +13 -1
  181. package/src/sandbox/dev-source.ts +21 -12
  182. package/src/sandbox/hidden-paths.ts +1 -1
  183. package/src/sandbox/index.ts +1 -0
  184. package/src/sandbox/policy.ts +5 -0
  185. package/src/secrets/hydrate.ts +4 -1
  186. package/src/secrets/storage.ts +10 -1
  187. package/src/server/command-runner.ts +4 -0
  188. package/src/server/index.ts +8 -1
  189. package/src/skills/typeclaw-config/SKILL.md +16 -0
  190. package/src/skills/typeclaw-memory/SKILL.md +3 -1
  191. package/src/skills/typeclaw-permissions/SKILL.md +8 -8
  192. package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
  193. package/src/tunnels/active.ts +14 -0
  194. package/src/typevault/bash-cli.ts +18 -0
  195. package/src/typevault/cli-path.ts +11 -0
  196. package/src/typevault/envelope-helper.ts +17 -0
  197. package/src/typevault/envelope-store.ts +98 -0
  198. package/src/typevault/lifecycle.ts +132 -0
  199. package/src/typevault/prompt-tunnel.ts +33 -0
  200. package/src/typevault/redaction.ts +37 -0
  201. package/src/typevault/vault.ts +283 -0
  202. package/typeclaw.schema.json +40 -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'
@@ -25,7 +26,12 @@ import {
25
26
  import { config } from '@/config/config'
26
27
  import { registerEvalTool, EVAL_PROMPT_HINT } from '@/eval/tool'
27
28
 
28
- import { composeSystemPrompt, deriveSystemPromptMode, type SystemPromptMode } from './system-prompt-composition'
29
+ import {
30
+ composeSessionTail,
31
+ composeSystemPrompt,
32
+ deriveSystemPromptMode,
33
+ type SystemPromptMode,
34
+ } from './system-prompt-composition'
29
35
  export {
30
36
  composeSystemPrompt,
31
37
  deriveSystemPromptMode,
@@ -50,7 +56,7 @@ import type {
50
56
  import { createHookBus, materializeSkills } from '@/plugin'
51
57
  import { CORE_SYSTEM_TOOL_NAMES } from '@/plugin/core-tool-names'
52
58
  import type { ReloadRegistry } from '@/reload'
53
- import { enterSubagentTmpScope, resolveHiddenPaths } from '@/sandbox'
59
+ import { canSeePrivateSurface, enterSubagentTmpScope, resolveHiddenPaths } from '@/sandbox'
54
60
  import type { Stream } from '@/stream'
55
61
 
56
62
  import { getAuthFor } from './auth'
@@ -67,13 +73,14 @@ import { defaultOutputAllowance } from './output-allowance'
67
73
  import {
68
74
  buildBuiltinPiToolOverrides,
69
75
  isPiCodingBuiltinName,
76
+ resetSharedLoopGuardSession,
70
77
  resolveBuiltinToolRefs,
71
78
  wrapPluginTool,
72
79
  wrapSystemTool,
73
80
  zodToToolParameters,
74
81
  } from './plugin-tools'
75
82
  import { PROACTIVE_NEXT_STEP_NUDGE } from './proactive-next-step-nudge'
76
- import { promptCacheKeyForOrigin, withPromptCacheKey } from './prompt-cache-key'
83
+ import { promptCacheKeyForOrigin, sharedSessionIdForOrigin, withPromptCacheKey } from './prompt-cache-key'
77
84
  import { wrapTransformContextWithLocalFailureMarker } from './provider-error'
78
85
  import { createReloadTool } from './reload-tool'
79
86
  import type { RestartHandoffOrigin } from './restart-handoff'
@@ -81,6 +88,7 @@ import type { SubagentBashPolicy } from './reviewer-bash-policy'
81
88
  import { loadSelf } from './self'
82
89
  import { SESSION_META_CUSTOM_TYPE, sessionMetaPayload } from './session-meta'
83
90
  import { renderSessionOrigin, type SessionOrigin, type SessionRoleContext } from './session-origin'
91
+ import { appendSessionTail, persistedPromptHasInlineSessionTail } from './session-tail'
84
92
  import { SubagentCacheKeepalive } from './subagent-cache-keepalive'
85
93
  import type { CreateSessionForSubagent, SubagentCoalescer, SubagentRegistry } from './subagents'
86
94
  import {
@@ -89,6 +97,8 @@ import {
89
97
  renderRuntimeBlock,
90
98
  renderRuntimeNondisclosureRule,
91
99
  stripRuntimeIdentityProse,
100
+ USER_INTENT_RULE,
101
+ GOAL_OWNERSHIP_RULE,
92
102
  } from './system-prompt'
93
103
  import { attachToolNotFoundNudge } from './tool-not-found-nudge'
94
104
  import { createBudgetState, type ToolResultBudget, wrapToolDefinitionWithBudget } from './tool-result-budget'
@@ -98,7 +108,7 @@ import { createChannelFetchAttachmentTool, resolveInboxBaseDir } from './tools/c
98
108
  import { createChannelHandoffTool } from './tools/channel-handoff'
99
109
  import { createChannelHistoryTool } from './tools/channel-history'
100
110
  import { createChannelReactTool } from './tools/channel-react'
101
- import { createChannelReadTool } from './tools/channel-read'
111
+ import { type ChannelReadTarget, createChannelReadTool } from './tools/channel-read'
102
112
  import { createChannelReplyTool } from './tools/channel-reply'
103
113
  import { createChannelSendTool } from './tools/channel-send'
104
114
  import { createChannelSessionSearchTool } from './tools/channel-session-search'
@@ -141,6 +151,7 @@ export type PluginSubagentSelection = {
141
151
  toolRefs?: BuiltinToolRef[]
142
152
  customTools?: PluginTool<any>[]
143
153
  toolNamePrefix: string
154
+ pluginToolNames?: readonly string[]
144
155
  }
145
156
 
146
157
  // Mutable holder for the live session origin. Pass this when the origin
@@ -153,6 +164,7 @@ export type PluginSubagentSelection = {
153
164
  export type SessionOriginRef = { current: SessionOrigin | undefined }
154
165
 
155
166
  export type CreateSessionOptions = {
167
+ readonly getGithubSelf?: GetGithubSelf
156
168
  reloadRegistry?: ReloadRegistry
157
169
  sessionManager?: SessionManager
158
170
  stream?: Stream
@@ -262,7 +274,7 @@ export type CreateSessionOptions = {
262
274
  }
263
275
 
264
276
  export type CreateSessionResult = {
265
- session: AgentSession & { getAbortReason?: () => string | undefined }
277
+ session: AgentSession & { getAbortReason?: () => string | undefined; resetLoopGuard?: () => void }
266
278
  dispose: () => Promise<void>
267
279
  getAbortReason?: () => string | undefined
268
280
  }
@@ -371,16 +383,20 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
371
383
  : []
372
384
  const subagentBuiltinNames = resolvedSubagentBuiltins.map((t) => t.name)
373
385
  const subagentTypeclawToolDefinitions = resolvedSubagentBuiltins.filter((t) => !isPiCodingBuiltinName(t.name))
386
+ const registryTools = wrapRegistryTools(options.plugins, getOrigin, getAbort, getLoopGuardTurn, options.permissions)
374
387
  const pluginCustomTools = options.pluginSubagent
375
- ? wrapSubagentCustomTools(
376
- options.pluginSubagent,
377
- options.plugins,
378
- getOrigin,
379
- getAbort,
380
- getLoopGuardTurn,
381
- options.permissions,
382
- )
383
- : 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
384
400
 
385
401
  // Per-run budget state for the tool-result byte ceiling. Allocated once per
386
402
  // session creation and threaded into every wrapped tool so they share the
@@ -516,6 +532,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
516
532
  // unwrapped bash path. `wrapBuiltinToolDefinition` no-ops the optional
517
533
  // stages (plugin hooks, permissions, bashPolicy) when they are absent.
518
534
  const builtinPiToolOverrides = buildBuiltinPiToolOverrides({
535
+ getGithubSelf: options.getGithubSelf,
519
536
  agentDir: options.plugins?.agentDir ?? process.cwd(),
520
537
  sessionId: options.plugins?.sessionId ?? sessionManager.getSessionId(),
521
538
  hooks: options.plugins?.hooks ?? createHookBus(),
@@ -562,6 +579,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
562
579
  activeNames: intendedActiveToolNames,
563
580
  getActiveNames: () => activeSession?.getActiveToolNames() ?? intendedActiveToolNames,
564
581
  wrappers: {
582
+ getGithubSelf: options.getGithubSelf,
565
583
  agentDir: options.plugins?.agentDir ?? process.cwd(),
566
584
  sessionId: options.plugins?.sessionId ?? sessionManager.getSessionId(),
567
585
  hooks: options.plugins?.hooks ?? createHookBus(),
@@ -576,6 +594,11 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
576
594
  budgetState: sessionBudgetState,
577
595
  })
578
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())
579
602
  const resourceLoader =
580
603
  options.systemPromptOverride !== undefined
581
604
  ? await createOverrideResourceLoader(
@@ -593,6 +616,13 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
593
616
  ...(options.mcpManager !== undefined ? { mcpManager: options.mcpManager } : {}),
594
617
  ...(options.subagentRegistry !== undefined ? { subagentRegistry: options.subagentRegistry } : {}),
595
618
  ...(isOpenAiFamilyRef(activeRef) ? { proactiveNextStepNudge: true } : {}),
619
+ ...(detachSessionTail
620
+ ? {
621
+ onSessionTail: (tail: string) => {
622
+ sessionTail = tail
623
+ },
624
+ }
625
+ : {}),
596
626
  })
597
627
 
598
628
  const model = applyModelRuntimeOverrides(resolveModel(activeRef), activeRef)
@@ -643,20 +673,25 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
643
673
  const innerStreamFunction = session.agent.streamFunction
644
674
  session.agent.streamFunction = async (requestModel, context, streamOptions) => {
645
675
  const maxTokens = streamOptions?.maxTokens ?? defaultOutputAllowance(requestModel)
646
- const promptCacheKey = promptCacheKeyForOrigin(getOrigin())
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
+ }
647
686
  const onPayload = async (payload: unknown, payloadModel: typeof requestModel) => {
648
687
  const next = (await streamOptions?.onPayload?.(payload, payloadModel)) ?? payload
649
688
  const final = promptCacheKey === undefined ? next : withPromptCacheKey(next, promptCacheKey)
650
689
  if (streamOptions?.sessionId === session.sessionId) {
651
- cacheKeepalive?.capture(payloadModel, context, { ...streamOptions, maxTokens }, final)
690
+ cacheKeepalive?.capture(payloadModel, context, requestOptions, final)
652
691
  }
653
692
  return final
654
693
  }
655
- return await innerStreamFunction(requestModel, context, {
656
- ...streamOptions,
657
- maxTokens,
658
- onPayload,
659
- })
694
+ return await innerStreamFunction(requestModel, context, { ...requestOptions, onPayload })
660
695
  }
661
696
 
662
697
  // typeclaw owns retry/fallback in its turn drivers, so the SDK's own
@@ -669,7 +704,14 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
669
704
  // marked local failures are kept out of overflow recovery at the marker below.
670
705
  session.setAutoRetryEnabled(false)
671
706
  const getAbortReason = () => abortHolder.reason
672
- 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 })
673
715
  const unsubLoopGuardTurn = attachLoopGuardTurnTracking(session.agent, () => {
674
716
  loopGuardTurnId += 1
675
717
  })
@@ -697,7 +739,16 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
697
739
  // stay unwrapped: their failures can be genuine provider/auth failures.
698
740
  // Overflow recovery stays enabled; a local failure whose text would read as a
699
741
  // provider overflow is stamped with fixed text and its raw text is logged here.
700
- 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, {
701
752
  getProvider: () => session.agent.state.model?.provider,
702
753
  logWithheld: (line) =>
703
754
  console.error(`[agent] ${options.plugins?.sessionId ?? sessionManager.getSessionId()}: ${line}`),
@@ -905,6 +956,26 @@ export function buildChannelTools(
905
956
  ): ToolDefinition[] {
906
957
  if (!channelRouter) return []
907
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
+ }
908
979
  const getOutboundOrigin = (): ChannelOutboundOrigin | undefined => {
909
980
  const current = getOrigin ? getOrigin() : origin
910
981
  return current ? { kind: current.kind, ...(current.kind === 'cron' ? { jobId: current.jobId } : {}) } : undefined
@@ -936,7 +1007,13 @@ export function buildChannelTools(
936
1007
  if (origin.adapter === 'github' && sessionId !== undefined)
937
1008
  tools.push(createPostGithubReviewTool({ router: channelRouter, origin: channelOrigin, sessionId }))
938
1009
  tools.push(createChannelHistoryTool({ router: channelRouter, origin: channelOrigin }))
939
- 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
+ )
940
1017
  tools.push(
941
1018
  createChannelSendTool({
942
1019
  router: channelRouter,
@@ -979,7 +1056,7 @@ export function buildChannelTools(
979
1056
  }
980
1057
  } else {
981
1058
  tools.push(createChannelSendTool({ router: channelRouter, getOutboundOrigin }))
982
- tools.push(createChannelReadTool({ router: channelRouter }))
1059
+ tools.push(createChannelReadTool({ router: channelRouter, ...(canRead !== undefined ? { canRead } : {}) }))
983
1060
  tools.push(createChannelEditTool({ router: channelRouter, getOutboundOrigin }))
984
1061
  }
985
1062
  return tools
@@ -1236,11 +1313,12 @@ export async function createOverrideResourceLoader(
1236
1313
  runtimeVersion?: string,
1237
1314
  ): Promise<DefaultResourceLoader> {
1238
1315
  const branding = getConfig().branding
1316
+ const withRule = `${systemPrompt}\n\n${USER_INTENT_RULE}\n\n${GOAL_OWNERSHIP_RULE}`
1239
1317
  const withRuntime = branding
1240
1318
  ? runtimeVersion !== undefined
1241
- ? `${systemPrompt}\n\n${renderRuntimeBlock(runtimeVersion)}`
1242
- : systemPrompt
1243
- : `${stripRuntimeIdentityProse(systemPrompt)}\n\n${renderRuntimeNondisclosureRule()}`
1319
+ ? `${withRule}\n\n${renderRuntimeBlock(runtimeVersion)}`
1320
+ : withRule
1321
+ : `${stripRuntimeIdentityProse(withRule)}\n\n${renderRuntimeNondisclosureRule()}`
1244
1322
  const finalPrompt = withOrigin(withRuntime, origin, permissions)
1245
1323
  const loader = new DefaultResourceLoader({
1246
1324
  cwd: process.cwd(),
@@ -1273,6 +1351,9 @@ export type CreateResourceLoaderOptions = {
1273
1351
  mode?: SystemPromptMode
1274
1352
  proactiveNextStepNudge?: boolean
1275
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
1276
1357
  }
1277
1358
 
1278
1359
  export async function createResourceLoader(options: CreateResourceLoaderOptions = {}): Promise<DefaultResourceLoader> {
@@ -1351,16 +1432,24 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1351
1432
  mcpCatalog = renderMcpCatalog(options.mcpManager.listServers())
1352
1433
  }
1353
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
+ )
1354
1443
  const systemPrompt = composeSystemPrompt({
1355
1444
  mode,
1356
1445
  branding,
1357
1446
  self,
1358
1447
  subagentRoster,
1359
1448
  ...(options.runtimeVersion !== undefined ? { runtimeVersion: options.runtimeVersion } : {}),
1360
- ...(options.origin !== undefined ? { origin: options.origin } : {}),
1361
- ...(roleContext !== undefined ? { roleContext } : {}),
1449
+ ...(options.origin !== undefined && !detached ? { origin: options.origin } : {}),
1450
+ ...(roleContext !== undefined && !detached ? { roleContext } : {}),
1362
1451
  ...(mcpCatalog !== undefined ? { mcpCatalog } : {}),
1363
- gitNudge,
1452
+ gitNudge: detached ? '' : gitNudge,
1364
1453
  ...(options.evalEnabled ? { evalHint: EVAL_PROMPT_HINT } : {}),
1365
1454
  ...(options.proactiveNextStepNudge === true ? { proactiveNextStepNudge: PROACTIVE_NEXT_STEP_NUDGE } : {}),
1366
1455
  })
@@ -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'
@@ -19,6 +19,7 @@ import { Type } from 'typebox'
19
19
  import { z } from 'zod'
20
20
 
21
21
  import { ACKNOWLEDGE_GUARDS } from '@/bundled-plugins/guard/keys'
22
+ import type { GetGithubSelf } from '@/channels/github-token-bridge'
22
23
  import { readOomEvents, toolOomNote } from '@/container/oom-events'
23
24
  import { withToolOomPriorityCommand } from '@/container/tool-oom-priority'
24
25
  import {
@@ -57,6 +58,7 @@ import {
57
58
  import {
58
59
  prepareBashSandbox,
59
60
  type BashSandboxBoundary,
61
+ type BashSandboxReveal,
60
62
  type DeferredBashPreparation,
61
63
  type PreparedBashSandbox,
62
64
  } from './bash-sandbox'
@@ -97,6 +99,7 @@ let sharedLoopGuard: LoopGuard = createLoopGuard()
97
99
  export const TYPECLAW_INTERNAL_BASH_ENV = '__typeclawBashEnv'
98
100
  export const TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV = '__typeclawBashWithholdEnv'
99
101
  export const TYPECLAW_INTERNAL_BASH_PREPARE = '__typeclawBashPrepare'
102
+ export const TYPECLAW_INTERNAL_BASH_REVEAL = '__typeclawBashReveal'
100
103
 
101
104
  type BashEnvOverlay = Record<string, string>
102
105
  type BashEnvWithhold = string[]
@@ -132,6 +135,20 @@ function readBashEnvWithhold(args: Record<string, unknown>): BashEnvWithhold | u
132
135
  return names.length > 0 ? names : undefined
133
136
  }
134
137
 
138
+ function readBashReveal(args: Record<string, unknown>): BashSandboxReveal | undefined {
139
+ const raw = args[TYPECLAW_INTERNAL_BASH_REVEAL]
140
+ if (!Array.isArray(raw)) return undefined
141
+ const reveal: BashSandboxReveal = []
142
+ for (const entry of raw) {
143
+ if (entry === null || typeof entry !== 'object') continue
144
+ const { type, source, dest } = entry as Record<string, unknown>
145
+ if (typeof dest !== 'string') continue
146
+ if (type === 'tmpfs') reveal.push({ type, dest })
147
+ else if (type === 'ro-bind' && typeof source === 'string') reveal.push({ type, source, dest })
148
+ }
149
+ return reveal.length > 0 ? reveal : undefined
150
+ }
151
+
135
152
  function readBashPreparation(args: Record<string, unknown>): DeferredBashPreparation | undefined {
136
153
  const raw = args[TYPECLAW_INTERNAL_BASH_PREPARE]
137
154
  return typeof raw === 'function' ? (raw as DeferredBashPreparation) : undefined
@@ -280,6 +297,7 @@ export type WrapToolOptions = {
280
297
  }
281
298
 
282
299
  export type WrapSystemToolOptions = {
300
+ readonly getGithubSelf?: GetGithubSelf
283
301
  agentDir: string
284
302
  sessionId: string
285
303
  hooks: HookBus
@@ -336,7 +354,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
336
354
  label: opts.toolName,
337
355
  description: tool.description,
338
356
  parameters,
339
- async execute(toolCallId, params, signal) {
357
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
340
358
  const envelope = extractGuardAcknowledgements(params, opts.toolName, opts.guards ?? [])
341
359
  if (!envelope.ok) return errorResult(`invalid arguments: ${envelope.error}`)
342
360
 
@@ -347,6 +365,8 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
347
365
 
348
366
  const mutableArgs = validated.data as Record<string, unknown>
349
367
  const liveOrigin = opts.getOrigin?.()
368
+ // Plain Agent/direct invocations may have no extension context.
369
+ const entryId = ctx?.sessionManager?.getLeafId() ?? undefined
350
370
  const before: ToolBeforeEvent = {
351
371
  tool: opts.toolName,
352
372
  sessionId: opts.sessionId,
@@ -379,6 +399,8 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
379
399
  sessionId: opts.sessionId,
380
400
  agentDir: opts.agentDir,
381
401
  logger: opts.logger,
402
+ ...(liveOrigin === undefined ? {} : { origin: liveOrigin }),
403
+ ...(entryId === undefined ? {} : { entryId }),
382
404
  }
383
405
 
384
406
  let result: ToolResult | undefined
@@ -562,6 +584,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
562
584
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_ENV]
563
585
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV]
564
586
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_PREPARE]
587
+ delete mutableArgs[TYPECLAW_INTERNAL_BASH_REVEAL]
565
588
  const blockResult = await opts.hooks.runToolBefore(
566
589
  {
567
590
  tool: tool.name,
@@ -589,9 +612,11 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
589
612
  const bashEnvOverlay = readBashEnvOverlay(mutableArgs)
590
613
  const bashEnvWithhold = readBashEnvWithhold(mutableArgs)
591
614
  const bashPreparation = readBashPreparation(mutableArgs)
615
+ const bashReveal = readBashReveal(mutableArgs)
592
616
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_ENV]
593
617
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV]
594
618
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_PREPARE]
619
+ delete mutableArgs[TYPECLAW_INTERNAL_BASH_REVEAL]
595
620
  const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs, opts.getLoopGuardTurn?.(), opts.agentDir)
596
621
  if (loopGate.blockNow) {
597
622
  fireLoopAbort(opts.getAbort, 'loop_guard:block', opts.sessionId)
@@ -636,6 +661,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
636
661
  }
637
662
  if (typeof attemptArgs.command !== 'string') throw new SandboxPolicyError('bash command must be a string')
638
663
  preparedSandboxRuntime = await prepareBashSandbox({
664
+ getGithubSelf: opts.getGithubSelf,
639
665
  command: attemptArgs.command,
640
666
  permissions: opts.permissions,
641
667
  origin: liveOrigin,
@@ -644,6 +670,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
644
670
  envOverlay: bashEnvOverlay,
645
671
  envWithhold: bashEnvWithhold,
646
672
  deferredPreparation: bashPreparation,
673
+ reveal: bashReveal,
647
674
  boundary: sandboxBoundary,
648
675
  })
649
676
  attemptArgs.command = preparedSandboxRuntime.commandString
@@ -1088,6 +1115,13 @@ export function forgetSharedLoopGuardTool(sessionId: string, tool: string): void
1088
1115
  sharedLoopGuard.forgetTool(sessionId, tool)
1089
1116
  }
1090
1117
 
1118
+ // Drops a session's whole loop-guard history when a new user request starts
1119
+ // (see `attachLoopGuardUserRunTracking`), so per-request repetition is not
1120
+ // mistaken for a cycle that spans requests.
1121
+ export function resetSharedLoopGuardSession(sessionId: string): void {
1122
+ sharedLoopGuard.reset(sessionId)
1123
+ }
1124
+
1091
1125
  // Test-only seam: swaps the shared loop guard for a fresh instance so tests
1092
1126
  // that reuse sessionIds across cases don't see cross-test streak counts.
1093
1127
  // Production code never calls this; the guard's LRU bound handles
@@ -10,9 +10,7 @@ const PROMPT_CACHE_KEY_MAX_LENGTH = 64
10
10
  // session therefore landed on a cold machine and re-paid its whole ~10K-token
11
11
  // system+tools prefix even though sibling sessions of the same kind had just
12
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.
13
+ // name, whose prompts differ) lets those sessions share the warm prefix.
16
14
  export function promptCacheKeyForOrigin(origin: SessionOrigin | undefined): string | undefined {
17
15
  const key = unboundedPromptCacheKey(origin)
18
16
  return key === undefined ? undefined : Array.from(key).slice(0, PROMPT_CACHE_KEY_MAX_LENGTH).join('')
@@ -32,6 +30,31 @@ function unboundedPromptCacheKey(origin: SessionOrigin | undefined): string | un
32
30
  }
33
31
  }
34
32
 
33
+ // Providers route cache affinity by the stream `sessionId` pi turns into
34
+ // session-affinity headers (`session-id`, `x-session-affinity`, `x-affinity`, …)
35
+ // and default cache keys, so rewriting the body key alone does not reach a warm
36
+ // machine. On the ChatGPT Codex backend, a live probe of identical prefixes on
37
+ // fresh connections got 0% reuse with per-session ids and the same body key,
38
+ // and ~96% once the session id was shared. Short-lived subagent and system
39
+ // sessions therefore send their origin key as the session id on every
40
+ // provider, and each cron fire (a fresh session that repeats its job's prompt)
41
+ // shares one id per job. Long-lived tui/channel sessions keep their own id so
42
+ // one hot shared key cannot spill their long histories onto overflow machines.
43
+ // The id travels in HTTP headers, whose values must be Latin-1, so characters
44
+ // outside printable ASCII are percent-encoded. ASCII names stay identical to
45
+ // their body cache key.
46
+ export function sharedSessionIdForOrigin(origin: SessionOrigin | undefined): string | undefined {
47
+ const shared =
48
+ origin?.kind === 'subagent' || origin?.kind === 'system'
49
+ ? unboundedPromptCacheKey(origin)!
50
+ : origin?.kind === 'cron'
51
+ ? `typeclaw:cron:${origin.jobId}`
52
+ : undefined
53
+ if (shared === undefined) return undefined
54
+ const key = shared.replace(/[^\x20-\x7e]/gu, (char) => encodeURIComponent(char))
55
+ return key.slice(0, PROMPT_CACHE_KEY_MAX_LENGTH)
56
+ }
57
+
35
58
  // Rewrites only payloads that already carry a string `prompt_cache_key`, so
36
59
  // providers without the field and `cacheRetention: 'none'` (which omits it)
37
60
  // are left untouched.
@@ -123,13 +123,16 @@ export const PARTICIPANTS_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
123
123
  // - 'at-username' — Telegram: `@username` plain text. The numeric
124
124
  // `authorId` is NOT what gets mentioned; usernames are
125
125
  // a separate field that not every user has.
126
- // - 'alias' — KakaoTalk: type the bot's alias as plain text. The
127
- // adapter's classifier (`kakaotalk-classify.ts`) does
128
- // a substring match against configured aliases; there
129
- // is no in-band syntax to copy.
126
+ // - 'at-name' — KakaoTalk: `@DisplayName` plain text. The adapter
127
+ // turns `@` + a chat member's exact nickname into a
128
+ // native tag (`kakaotalk-mention.ts`); `authorId` is
129
+ // never part of the syntax.
130
+ // - 'alias' — Instagram/LINE/Teams: type the person's name as plain
131
+ // text. The classifiers substring-match configured
132
+ // aliases; there is no in-band syntax to copy.
130
133
  type PlatformInfo = {
131
134
  displayName: string
132
- mentionMode: 'angle-id' | 'at-username' | 'alias'
135
+ mentionMode: 'angle-id' | 'at-username' | 'at-name' | 'alias'
133
136
  // This platform has no rich-text rendering, so markdown markers appear
134
137
  // literally to users.
135
138
  plainTextOnly: boolean
@@ -231,7 +234,7 @@ const PLATFORM_INFO: Record<AdapterId, PlatformInfo> = {
231
234
  },
232
235
  kakaotalk: {
233
236
  displayName: 'KakaoTalk',
234
- mentionMode: 'alias',
237
+ mentionMode: 'at-name',
235
238
  plainTextOnly: true,
236
239
  supportsReactions: false,
237
240
  supportsAttachments: true,
@@ -299,7 +302,7 @@ export function renderInteractiveSessionContext(subagentRoster: string): string
299
302
  '- Broad search: spawn 2-5 `explorer`/`scout` workers in parallel, end your response, then collect each completion once. Use `scout` for narrow lookups and `researcher` for decomposed, multi-source, cross-validated synthesis. When the user *explicitly* asks to research or investigate, you MUST spawn `researcher`: answering from training memory or one inline `web_search` does not satisfy the request, and `scout`/`explorer` fan-out does not replace `researcher`.',
300
303
  '- Delegate the search, not the judgment. When an answer depends on reasoning across raw records — transactions, logs, messages, database rows — use `explorer` to locate them, then read or query the decisive records yourself before concluding. A subagent summary drops the cross-record patterns an answer usually hinges on (sequences, matching amounts, what stopped and what started), and a subagent that found nothing is not evidence that the records hold nothing.',
301
304
  '- Delegate-and-converse: for side-effectful or noisy work over ~30s, spawn one background subagent and stay responsive — `operator` for side effects, `scout` for a quick lookup, `researcher` for deep investigation, `planner` for risk-aware sequencing, `qa` to prove a PR, repo, or deployed product actually works by running it. Pass `profile: "deep"` only when the work needs stronger reasoning than the default tier.',
302
- '- Web browsing: never drive a browser yourself. Any task that needs a real browser — navigating, clicking, forms, logins, screenshots, JS-rendered pages — goes to `browser`. Plain lookups stay with `scout`/`web_fetch`.',
305
+ '- Web browsing: never drive a browser yourself. Any task that needs a real browser — navigating, clicking, forms, logins, screenshots, JS-rendered pages — goes to `browser`. Plain lookups stay with `scout`/`web_fetch`. The user cannot see that browser: it runs in the container, and your messages are their only window. When they need to see a page, have `browser` save a screenshot and send it as an attachment (describe it where attachments are unsupported); never say a page is open for them or ask them to check the browser. If `browser` declines the task itself (a refusal, not a site or technical blocker), spawn it once more with the same task and `profile: "default"` instead of arguing with it; if that also declines, tell the user plainly that the model refused.',
303
306
  '- Troubleshooting: after ~3 non-converging attempts at the same failure, stop and hand the loop to `operator` (background; `profile: "deep"` when genuinely hard) with the symptom, attempts, and success condition. Read `typeclaw-troubleshooting` before spawning.',
304
307
  "- Status: when asked about a running subagent, call `subagent_output({ task_id })` and report its `status_summary` — don't guess.",
305
308
  "- Don't fire more than 5 subagents per turn, spawn for known answers or single-file lookups, poll output in a loop, or ask research subagents to decide: they report; you decide. Most subagents are leaves; only `operator` and `reviewer` may delegate one level deeper.",
@@ -409,12 +412,14 @@ function describeTrigger(origin: SessionOrigin): string {
409
412
  }
410
413
  }
411
414
 
412
- function renderSubagentOrigin(origin: { subagent: string; parentSessionId: string }): string {
415
+ // The parent session id stays out of the prompt: sibling sessions of one
416
+ // subagent otherwise diverge here and cannot reuse each other's cached prefix.
417
+ function renderSubagentOrigin(origin: { subagent: string }): string {
413
418
  return [
414
419
  '## Session origin',
415
420
  '',
416
- `You are a \`${origin.subagent}\` subagent spawned by parent session`,
417
- `\`${origin.parentSessionId}\`. Stay narrowly within the task you were given.`,
421
+ `You are a \`${origin.subagent}\` subagent spawned by a parent session.`,
422
+ 'Stay narrowly within the task you were given.',
418
423
  'Return cleanly when done; do not sprawl into unrelated work.',
419
424
  ].join('\n')
420
425
  }
@@ -673,11 +678,12 @@ function renderChannelOrigin(
673
678
  '}',
674
679
  '```',
675
680
  '',
676
- 'When work belongs to ANOTHER conversation, first use `channel_session_search` to find its owning session,',
677
- 'then pass that target to `channel_handoff`. Search by conversation name, topic, or participant, across adapters.',
678
- "The owning session reads its current context and answers through its own account; don't read or post there",
679
- 'directly from this session. This applies to channels, threads, groups, and DMs regardless of where you started.',
680
- '`channel_send` is for an explicit direct post, not a substitute for handing ongoing work to its owner.',
681
+ 'ANOTHER conversation (channels, threads, groups, and DMs on any adapter):',
682
+ '- Read it directly with `channel_read` (`mode: "list"` finds chat ids). The runtime checks the current',
683
+ " speaker's permission; a denied read means this speaker may not see it, so don't post there for them either.",
684
+ '- To act there, prefer `channel_session_search` then `channel_handoff` (search by conversation name, topic, or',
685
+ ' participant), so its live owning session answers with current context. When the search finds no live session',
686
+ ' and the speaker may read that conversation, post there yourself with `channel_send`.',
681
687
  'If `channel_read` reports an access error with a handoff target, use it rather than asking the user to fix permissions.',
682
688
  '',
683
689
  ...renderResearchReportDeliveryGuidance(platformInfo),
@@ -776,6 +782,13 @@ function renderMentionGuidance(
776
782
  'If no `@username` is known, use display name; reply context carries it.',
777
783
  ...renderSelfMention(platformInfo, self),
778
784
  ]
785
+ case 'at-name':
786
+ return [
787
+ `To mention someone in your reply, write \`@\` followed by their exact ${platformInfo.displayName} display name,`,
788
+ `e.g. \`@${exampleName} hello\`; it becomes a native ${platformInfo.displayName} mention when that name belongs to a chat member.`,
789
+ 'Display names are in the participants block. Any `<@id>` marker is inbound-only typeclaw convention;',
790
+ `do not echo them back as outbound mentions or ${platformInfo.displayName} renders them literally.`,
791
+ ]
779
792
  case 'alias':
780
793
  return [
781
794
  `${platformInfo.displayName} has no in-band mention syntax. To address someone, just type their display name as plain text;`,
@@ -790,9 +803,9 @@ function renderMentionGuidance(
790
803
  // id, so a message addressed to its own id reads as "addressed to someone
791
804
  // else" and it wrongly skips the turn (issue: skipped_by_tool "Message
792
805
  // addressed to @U…, not to <name>"). This line closes that gap by stating
793
- // the bot's own addressing token explicitly. Empty for the alias platform
794
- // (KakaoTalk has no in-band mention token to recognize) and when identity
795
- // has not resolved yet — both fall through to "omit the line".
806
+ // the bot's own addressing token explicitly. Empty for the at-name and alias
807
+ // platforms (no id-shaped token to recognize; KakaoTalk tags by display name)
808
+ // and when identity has not resolved yet — all fall through to "omit the line".
796
809
  function renderSelfMention(platformInfo: PlatformInfo, self: ChannelSelfIdentity | undefined): string[] {
797
810
  if (self === undefined) return []
798
811
  switch (platformInfo.mentionMode) {
@@ -805,6 +818,7 @@ function renderSelfMention(platformInfo: PlatformInfo, self: ChannelSelfIdentity
805
818
  'contains your id, it is addressed to YOU — do not skip it as "addressed to another user".',
806
819
  ]
807
820
  }
821
+ case 'at-name':
808
822
  case 'at-username': {
809
823
  if (self.username === undefined || self.username === '') return []
810
824
  return [
@@ -894,6 +908,7 @@ function renderParticipantAddressing(p: ChannelParticipant, platformInfo: Platfo
894
908
  case 'angle-id':
895
909
  return `<@${p.authorId}> (${p.authorName})`
896
910
  case 'at-username':
911
+ case 'at-name':
897
912
  case 'alias':
898
913
  return `${p.authorName} (${p.authorId})`
899
914
  }
@@ -920,6 +935,12 @@ function renderParticipantsTrailing(platformInfo: PlatformInfo): string[] {
920
935
  `${platformInfo.displayName} usernames are a SEPARATE field from numeric \`authorId\`, and`,
921
936
  'not every user has one. The list is recent context, not a directory.',
922
937
  ]
938
+ case 'at-name':
939
+ return [
940
+ "If a current sender isn't listed, mention them as `@` + their display name.",
941
+ '`authorId` is reference only and must not be echoed back.',
942
+ 'The list is recent context, not a directory.',
943
+ ]
923
944
  case 'alias':
924
945
  return [
925
946
  "If a current sender isn't listed, address by display name as plain text.",