@cortex-agent/server 2026.8.3 → 2026.8.6

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 (224) hide show
  1. package/defaults/config/thread-templates/agents/benchmark-coder.json +2 -2
  2. package/defaults/config/thread-templates/agents/benchmark-fixer.json +17 -0
  3. package/defaults/config/thread-templates/agents/benchmark-reviewer.json +5 -5
  4. package/defaults/config/thread-templates/templates/benchmark-coder-review-fix.json +21 -0
  5. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +1 -0
  6. package/defaults/prompts/directives/benchmark-coder.md +1 -0
  7. package/defaults/prompts/directives/benchmark-fixer.md +1 -0
  8. package/defaults/prompts/directives/benchmark-reviewer.md +1 -0
  9. package/defaults/prompts/systemPrompts/benchmark-coder.md +1 -0
  10. package/defaults/prompts/systemPrompts/benchmark-fixer.md +1 -0
  11. package/defaults/prompts/systemPrompts/benchmark-reviewer.md +1 -0
  12. package/dist/agent-adapter/capabilities.d.ts +32 -1
  13. package/dist/agent-adapter/capabilities.js +39 -1
  14. package/dist/agent-adapter/claude/adapter.d.ts +15 -0
  15. package/dist/agent-adapter/claude/adapter.js +29 -7
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -2
  17. package/dist/agent-adapter/claude/spawn-args.js +29 -6
  18. package/dist/agent-adapter/index.js +11 -1
  19. package/dist/agent-adapter/normalize/tool-names.d.ts +4 -0
  20. package/dist/agent-adapter/normalize/tool-names.js +10 -0
  21. package/dist/agent-adapter/pi/adapter.d.ts +20 -8
  22. package/dist/agent-adapter/pi/adapter.js +130 -35
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +20 -53
  24. package/dist/agent-adapter/pi/agent-dir.js +48 -89
  25. package/dist/agent-adapter/pi/custom-catalog.d.ts +10 -0
  26. package/dist/agent-adapter/pi/custom-catalog.js +42 -0
  27. package/dist/agent-adapter/pi/defaults.d.ts +9 -0
  28. package/dist/agent-adapter/pi/defaults.js +14 -4
  29. package/dist/agent-adapter/pi/discovery.d.ts +1 -3
  30. package/dist/agent-adapter/pi/discovery.js +3 -15
  31. package/dist/agent-adapter/pi/event-parser.js +8 -0
  32. package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -0
  33. package/dist/agent-adapter/pi/mcp-bridge.js +31 -6
  34. package/dist/agent-adapter/pi/mcp-duration.d.ts +28 -0
  35. package/dist/agent-adapter/pi/mcp-duration.js +48 -0
  36. package/dist/agent-adapter/pi/policy-guard.d.ts +40 -0
  37. package/dist/agent-adapter/pi/policy-guard.js +111 -0
  38. package/dist/agent-adapter/pi/providers-config.d.ts +62 -0
  39. package/dist/agent-adapter/pi/providers-config.js +101 -0
  40. package/dist/agent-adapter/pi/quota-probe.d.ts +11 -0
  41. package/dist/agent-adapter/pi/quota-probe.js +36 -0
  42. package/dist/agent-adapter/pi/quota-sink.d.ts +25 -0
  43. package/dist/agent-adapter/pi/quota-sink.js +31 -0
  44. package/dist/agent-adapter/pi/session-files.d.ts +2 -0
  45. package/dist/agent-adapter/pi/session-files.js +19 -0
  46. package/dist/agent-adapter/pi/session-support.d.ts +14 -3
  47. package/dist/agent-adapter/pi/session-support.js +8 -0
  48. package/dist/agent-adapter/pi/spawn-args.d.ts +11 -1
  49. package/dist/agent-adapter/pi/spawn-args.js +13 -0
  50. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -2
  51. package/dist/agent-adapter/pi/tool-shims.js +32 -21
  52. package/dist/agent-adapter/pi/web-search.js +36 -8
  53. package/dist/agent-adapter/types.d.ts +14 -0
  54. package/dist/core/locales/en.d.ts +54 -1
  55. package/dist/core/locales/en.js +2 -0
  56. package/dist/core/locales/slices/commands.d.ts +12 -1
  57. package/dist/core/locales/slices/commands.js +24 -2
  58. package/dist/core/locales/slices/providers.d.ts +45 -0
  59. package/dist/core/locales/slices/providers.js +95 -0
  60. package/dist/core/locales/zh.js +2 -0
  61. package/dist/core/resilient-watch.d.ts +28 -0
  62. package/dist/core/resilient-watch.js +110 -0
  63. package/dist/core/settings.js +15 -20
  64. package/dist/core/types/agent-types.d.ts +6 -0
  65. package/dist/core/types/thread-types.d.ts +21 -3
  66. package/dist/core/utils.d.ts +21 -1
  67. package/dist/core/utils.js +37 -1
  68. package/dist/domain/agent-run/agent-run-cli.js +3 -1
  69. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
  70. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
  71. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
  72. package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
  73. package/dist/domain/agent-run/identity.d.ts +5 -0
  74. package/dist/domain/agent-run/identity.js +4 -1
  75. package/dist/domain/agent-run/journal.d.ts +3 -2
  76. package/dist/domain/agent-run/manifest.js +11 -4
  77. package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
  78. package/dist/domain/agent-run/pinned-node-process.js +9 -0
  79. package/dist/domain/agent-run/role-surface.d.ts +2 -2
  80. package/dist/domain/agent-run/role-surface.js +7 -3
  81. package/dist/domain/agent-run/run-config.d.ts +10 -1
  82. package/dist/domain/agent-run/run-config.js +57 -6
  83. package/dist/domain/agent-run/runner.js +149 -31
  84. package/dist/domain/agents/facade.d.ts +37 -122
  85. package/dist/domain/agents/facade.js +47 -115
  86. package/dist/domain/agents/spawn-config.d.ts +135 -0
  87. package/dist/domain/agents/spawn-config.js +121 -0
  88. package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
  89. package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
  90. package/dist/domain/benchmark/arm-schema.d.ts +43 -0
  91. package/dist/domain/benchmark/arm-schema.js +243 -0
  92. package/dist/domain/benchmark/capabilities.d.ts +4 -0
  93. package/dist/domain/benchmark/capabilities.js +54 -0
  94. package/dist/domain/benchmark/decimal-text.d.ts +27 -0
  95. package/dist/domain/benchmark/decimal-text.js +67 -0
  96. package/dist/domain/benchmark/lease-echo.d.ts +43 -0
  97. package/dist/domain/benchmark/lease-echo.js +56 -0
  98. package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
  99. package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
  100. package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
  101. package/dist/domain/benchmark/policy-compiler.js +680 -0
  102. package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
  103. package/dist/domain/benchmark/resolved-policy.js +195 -0
  104. package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
  105. package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
  106. package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
  107. package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
  108. package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
  109. package/dist/domain/benchmark/variant-proposal.js +42 -0
  110. package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
  111. package/dist/domain/benchmark/workspace-lease.js +272 -0
  112. package/dist/domain/costs/codex-quota.d.ts +29 -0
  113. package/dist/domain/costs/codex-quota.js +102 -0
  114. package/dist/domain/costs/cost-tracker.d.ts +48 -9
  115. package/dist/domain/costs/cost-tracker.js +74 -18
  116. package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
  117. package/dist/domain/costs/rate-limit-throttle.js +61 -6
  118. package/dist/domain/costs/resume-registry.d.ts +3 -1
  119. package/dist/domain/costs/resume-registry.js +10 -1
  120. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
  121. package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
  122. package/dist/domain/mcp/tools/cost.js +15 -6
  123. package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
  124. package/dist/domain/pi-providers/custom-provider-model.js +122 -0
  125. package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
  126. package/dist/domain/pi-providers/custom-provider-service.js +143 -0
  127. package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
  128. package/dist/domain/pi-providers/gateway-route-store.js +78 -0
  129. package/dist/domain/pi-providers/index.d.ts +4 -0
  130. package/dist/domain/pi-providers/index.js +8 -0
  131. package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
  132. package/dist/domain/pi-providers/models-json-store.js +77 -0
  133. package/dist/domain/remote/client-hot-reload.d.ts +9 -1
  134. package/dist/domain/remote/client-hot-reload.js +60 -12
  135. package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
  136. package/dist/domain/scheduling/jobs/_shared.js +11 -2
  137. package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
  138. package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
  139. package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
  140. package/dist/domain/sessions/session-lifecycle.js +20 -1
  141. package/dist/domain/system/install-cli.js +8 -3
  142. package/dist/domain/system/system-notice.d.ts +4 -1
  143. package/dist/domain/system/system-notice.js +6 -2
  144. package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
  145. package/dist/domain/tasks/dispatch-utils.js +24 -37
  146. package/dist/domain/threads/runner.d.ts +16 -1
  147. package/dist/domain/threads/runner.js +62 -8
  148. package/dist/domain/threads/template-loader.d.ts +5 -0
  149. package/dist/domain/threads/template-loader.js +120 -36
  150. package/dist/domain/threads/template-validate.d.ts +244 -0
  151. package/dist/domain/threads/template-validate.js +574 -0
  152. package/dist/domain/threads/template-validate.parity.d.ts +1 -0
  153. package/dist/domain/threads/template-validate.parity.js +47 -0
  154. package/dist/domain/threads/template-writer.d.ts +55 -0
  155. package/dist/domain/threads/template-writer.js +131 -0
  156. package/dist/domain/ui-service/app-router.d.ts +143 -1
  157. package/dist/domain/ui-service/app-router.js +29 -3
  158. package/dist/domain/ui-service/input-schemas.d.ts +228 -4
  159. package/dist/domain/ui-service/input-schemas.js +132 -1
  160. package/dist/domain/ui-service/mutate/config.d.ts +10 -1
  161. package/dist/domain/ui-service/mutate/config.js +45 -5
  162. package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
  163. package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
  164. package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
  165. package/dist/domain/ui-service/mutate/profiles.js +156 -0
  166. package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
  167. package/dist/domain/ui-service/mutate/schedules.js +53 -3
  168. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  169. package/dist/domain/ui-service/mutate/sessions.js +25 -1
  170. package/dist/domain/ui-service/mutate/system.d.ts +2 -1
  171. package/dist/domain/ui-service/mutate/system.js +17 -3
  172. package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
  173. package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
  174. package/dist/domain/ui-service/query/config.js +30 -0
  175. package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
  176. package/dist/domain/ui-service/query/custom-providers.js +13 -0
  177. package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
  178. package/dist/domain/ui-service/query/machine-detail.js +56 -0
  179. package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
  180. package/dist/domain/ui-service/query/machine-probe.js +136 -0
  181. package/dist/domain/ui-service/query/schedules.js +5 -0
  182. package/dist/domain/ui-service/query/sessions.js +8 -2
  183. package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
  184. package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
  185. package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
  186. package/dist/domain/ui-service/query/thread-templates.js +44 -7
  187. package/dist/domain/ui-service/types.d.ts +298 -7
  188. package/dist/domain/ui-service/ui-service.js +27 -3
  189. package/dist/entry/app.js +24 -3
  190. package/dist/entry/auth-cli.d.ts +4 -1
  191. package/dist/entry/auth-cli.js +10 -2
  192. package/dist/entry/cli-help.js +6 -2
  193. package/dist/entry/cli.js +2 -1
  194. package/dist/entry/daemon.d.ts +0 -11
  195. package/dist/entry/daemon.js +5 -49
  196. package/dist/entry/provider-cli.d.ts +16 -0
  197. package/dist/entry/provider-cli.js +203 -0
  198. package/dist/events/event-types.d.ts +2 -1
  199. package/dist/orchestration/agent-runner.js +3 -2
  200. package/dist/orchestration/routing/commands/cost.d.ts +8 -0
  201. package/dist/orchestration/routing/commands/cost.js +93 -21
  202. package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
  203. package/dist/orchestration/routing/commands/login-custom.js +89 -0
  204. package/dist/orchestration/routing/commands/login.d.ts +3 -0
  205. package/dist/orchestration/routing/commands/login.js +7 -0
  206. package/dist/orchestration/routing/message-router.js +48 -33
  207. package/dist/orchestration/routing/webhook.js +1 -1
  208. package/dist/orchestration/session-events.d.ts +2 -1
  209. package/dist/orchestration/session-events.js +1 -0
  210. package/dist/orchestration/thread-callback.js +1 -1
  211. package/dist/store/conversation-history-repo.d.ts +5 -1
  212. package/dist/store/conversation-history-repo.js +2 -1
  213. package/dist/store/cost-repo.d.ts +17 -0
  214. package/dist/store/cost-repo.js +47 -5
  215. package/dist/store/profile-repo.d.ts +0 -10
  216. package/dist/store/profile-repo.js +34 -56
  217. package/dist/store/session-registry-repo.d.ts +12 -0
  218. package/dist/store/session-registry-repo.js +16 -0
  219. package/package.json +1 -1
  220. package/web/dist/assets/index-DYMfaAi4.css +1 -0
  221. package/web/dist/assets/index-uOoZjGKa.js +141 -0
  222. package/web/dist/index.html +2 -2
  223. package/web/dist/assets/index-DrNx9R6c.js +0 -139
  224. package/web/dist/assets/index-zpf3OSKC.css +0 -1
@@ -3,8 +3,8 @@
3
3
  "description": "Benchmark Coder — implements a task directly in an isolated task workspace",
4
4
  "profile": "__active__",
5
5
  "persistSession": true,
6
- "directive": "You are the benchmark coder. Work directly in the current task workspace, implement only the requested change, and verify the affected behavior with targeted checks. Do not assume the workspace is a git repository.",
7
- "systemPrompt": "You are a code implementer operating in an isolated benchmark task workspace. Make the smallest correct change for the task and avoid unrelated refactors.",
6
+ "directive": "file:benchmark-coder.md",
7
+ "systemPrompt": "file:benchmark-coder.md",
8
8
  "entryStage": "implement",
9
9
  "stages": {
10
10
  "implement": {
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "benchmark-fixer",
3
+ "description": "Benchmark Fixer — independently audits the task-workspace implementation and directly fixes the blockers it finds",
4
+ "profile": "__active__",
5
+ "persistSession": true,
6
+ "directive": "file:benchmark-fixer.md",
7
+ "systemPrompt": "file:benchmark-fixer.md",
8
+ "entryStage": "auditFix",
9
+ "stages": {
10
+ "auditFix": {
11
+ "description": "Audit the implementation, fix confirmed blockers in place, and record the terminal review.",
12
+ "promptTemplate": "Original task:\n{{input}}\n\nRead {{artifactPath}} for the coder's implementation handoff, then inspect the current task workspace yourself and verify the implementation against the task. Re-check each candidate blocker against the workspace before acting on it. Fix every blocker you confirm, directly and in place, keeping each fix minimal and scoped to that blocker; run targeted verification for each behavior you change. Do not assume git, commits, or a repository-wide test command exists. When finished, append a terminal review to {{artifactPath}} listing each issue with its evidence and its disposition — fixed, or left open with the reason. If every blocker you found is now fixed and verified, end your message with the exact token [FIX-VERIFIED]; if any blocker remains open, do not write that token anywhere. This is the final stage: nothing runs after you."
13
+ }
14
+ },
15
+ "tools": "Bash,Read,Write,Edit,Glob,Grep,TodoWrite,Skill",
16
+ "mcpComposition": "none"
17
+ }
@@ -3,20 +3,20 @@
3
3
  "description": "Benchmark Reviewer — audits task-workspace changes without modifying them",
4
4
  "profile": "__active__",
5
5
  "persistSession": true,
6
- "directive": "You are the benchmark reviewer. Independently inspect the current task workspace and verify the implementation without modifying project files. Report only evidence-backed blockers.",
7
- "systemPrompt": "You are a read-only implementation auditor in an isolated benchmark task workspace. Inspect the implementation and run focused checks; write review findings only to the thread artifact.",
6
+ "directive": "file:benchmark-reviewer.md",
7
+ "systemPrompt": "file:benchmark-reviewer.md",
8
8
  "entryStage": "audit",
9
9
  "stages": {
10
10
  "audit": {
11
11
  "description": "Audit the first implementation and either approve it or identify blockers.",
12
- "promptTemplate": "Original task:\n{{input}}\n\nRead {{artifactPath}}, inspect the current task workspace, and run targeted verification for the changed behavior. Do not modify any workspace file. The only file you may write is {{artifactPath}}. Append a concise implementation audit with evidence. If the implementation satisfies the task, end with `[IMPL-APPROVED]`. Otherwise list only actionable blockers and do not include the approval token anywhere."
12
+ "promptTemplate": "Original task:\n{{input}}\n\nRead {{artifactPath}}, inspect the current task workspace, and run targeted verification for the changed behavior. Do not modify any workspace file and do not write any file. Report your concise implementation audit, with evidence, as your final message. If the implementation satisfies the task, end with `[IMPL-APPROVED]`. Otherwise list only actionable blockers and do not include the approval token anywhere."
13
13
  },
14
14
  "finalAudit": {
15
15
  "description": "Audit the retry and provide the terminal review.",
16
16
  "continuesSession": true,
17
- "promptTemplate": "Read the retry handoff in {{artifactPath}}, inspect the current task workspace again, and run targeted verification for the revised behavior. Do not modify any workspace file. The only file you may write is {{artifactPath}}. Append a final audit with evidence. If the implementation now satisfies the task, end with `[IMPL-APPROVED]`. Otherwise list the remaining blockers without the approval token; this is the final audit."
17
+ "promptTemplate": "Read the retry handoff in {{artifactPath}}, inspect the current task workspace again, and run targeted verification for the revised behavior. Do not modify any workspace file and do not write any file. Report your final audit, with evidence, as your final message. If the implementation now satisfies the task, end with `[IMPL-APPROVED]`. Otherwise list the remaining blockers without the approval token; this is the final audit."
18
18
  }
19
19
  },
20
- "tools": "Bash,Read,Write,Edit,Glob,Grep,TodoWrite,Skill",
20
+ "tools": "Bash,Read,Glob,Grep,TodoWrite,Skill",
21
21
  "mcpComposition": "none"
22
22
  }
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "benchmark-coder-review-fix",
3
+ "description": "Hook-free benchmark loop: coder implement, then an independent reviewer that audits and directly fixes blockers in the shared writable workspace",
4
+ "agents": [
5
+ "benchmark-coder",
6
+ "benchmark-fixer"
7
+ ],
8
+ "transitions": [
9
+ {
10
+ "from": "benchmark-coder:implement",
11
+ "to": "benchmark-fixer:auditFix",
12
+ "condition": {
13
+ "type": "always"
14
+ }
15
+ }
16
+ ],
17
+ "entryAgent": "benchmark-coder",
18
+ "entryStage": "implement",
19
+ "maxTotalSteps": 3,
20
+ "disableHooks": true
21
+ }
@@ -130,6 +130,7 @@ Config is directory-based (DR-0017 D6 Phase 2.5): entities live one-file-each un
130
130
  - **One-time migration:** on startup a legacy single file (with no directory yet) is split into per-entity files and the original is renamed `thread-templates.json.migrated-bak` (preserved, never deleted; idempotent).
131
131
  - **Defaults merge:** shipped defaults are a directory too, merged **per-file copy-if-missing** (never overwrites your files) so new default agents/templates/shells reach existing installs.
132
132
  - **Hot-reload:** each entity subdirectory (`agents/`, `templates/`, `shells/`) and the `prompts/` directory are watched via `fs.watch` (300ms debounce); reload is fail-soft (a malformed file is skipped, not the whole table).
133
+ - **Editing:** hand-edit the JSON, or use the desktop **Settings → Thread templates** editor, which validates before writing. Validation lives in `domain/threads/template-validate.ts` and the write path in `template-writer.ts`; errors block a save, warnings do not. Saving an agent re-validates every template that uses it — because the executor re-reads transitions and prompts on *every* step, a bad edit does not fail at launch, it stalls a live thread mid-flight. The editor also refuses to delete an entity that other templates still reference, and rejects a save made against a stale body hash. There is no rename (the filename is the identity) — duplicate, then delete.
133
134
 
134
135
  The two core entity kinds are `agents` (independent agent definitions) and `templates` (multi-agent pipelines, either full templates or shell bindings); `shells` are parameterized transition graphs the templates reuse.
135
136
 
@@ -0,0 +1 @@
1
+ You are the benchmark coder. Work directly in the current task workspace, implement only the requested change, and verify the affected behavior with targeted checks. Do not assume the workspace is a git repository.
@@ -0,0 +1 @@
1
+ You are the benchmark fixing reviewer. Independently inspect the current task workspace, verify the implementation against the task, and directly fix every blocker you can confirm with evidence. Work in place in the current workspace. Do not assume git, commits, a repository-wide test command, or any task-tracking system exists, and do not attempt to use one.
@@ -0,0 +1 @@
1
+ You are the benchmark reviewer. Independently inspect the current task workspace and verify the implementation without modifying project files. Report only evidence-backed blockers.
@@ -0,0 +1 @@
1
+ You are a code implementer operating in an isolated benchmark task workspace. Make the smallest correct change for the task and avoid unrelated refactors.
@@ -0,0 +1 @@
1
+ You are an implementation auditor operating in an isolated benchmark task workspace. You are the last stage of this pipeline: audit the implementation, and fix the blockers you confirm rather than reporting them. Keep every fix minimal and scoped to the blocker that motivated it. The workspace may not be a git repository and may have no repository-wide test command; verify only the behavior you changed.
@@ -0,0 +1 @@
1
+ You are a read-only implementation auditor in an isolated benchmark task workspace. Inspect the implementation and run focused checks; write no files and report review findings as your final message.
@@ -13,6 +13,37 @@ export declare enum Capability {
13
13
  StreamingDeltas = "streaming-deltas",
14
14
  /** Backend accepts a user message into a turn already in flight (no new turn opened).
15
15
  * Part of the shared capability vocabulary; declared by the backends that implement injection. */
16
- MidTurnInject = "mid-turn-inject"
16
+ MidTurnInject = "mid-turn-inject",
17
+ /** Backend's configured MCP tool timeout and progress handling permit a single tool call to run
18
+ * beyond the native default while staying bounded by the trial deadline. Benchmark arms require
19
+ * it: a blocking benchmark tool call must not be cut short by an SDK or CLI default. */
20
+ BenchmarkLongMcpCall = "benchmark-long-mcp-call"
17
21
  }
18
22
  export declare const CAPABILITIES_BY_BACKEND: Record<Backend, Set<Capability>>;
23
+ /** Who governs how long one MCP tool call may run, per backend. Which process owns the MCP client
24
+ * decides this, so it is declared per backend and never inferred: an empty allowlist would say
25
+ * "nothing verified yet" and "version is not the governing fact" in the same bytes. */
26
+ export type LongMcpCallVersionGovernance =
27
+ /** The backend's own CLI owns the MCP client and reads the per-call budget itself, so the exact
28
+ * version is evidence. Closed allowlist, never an ordering: an unknown, unorderable or malformed
29
+ * version is simply not a member. */
30
+ {
31
+ readonly governed_by: 'cli-version';
32
+ readonly verified_versions: readonly string[];
33
+ }
34
+ /** Cortex's own bridge is the MCP client, over an SDK pinned by our lockfile, so the backend
35
+ * binary's version governs nothing here and the cited proof governs instead. */
36
+ | {
37
+ readonly governed_by: 'cortex-bridge';
38
+ readonly proof: string;
39
+ };
40
+ export declare const LONG_MCP_CALL_VERSION_GOVERNANCE: {
41
+ readonly claude: {
42
+ readonly governed_by: "cli-version";
43
+ readonly verified_versions: readonly ["2.1.220 (Claude Code)"];
44
+ };
45
+ readonly pi: {
46
+ readonly governed_by: "cortex-bridge";
47
+ readonly proof: "tests/domain/agent-run/long-mcp-call-e2e.test.ts";
48
+ };
49
+ };
@@ -1,5 +1,5 @@
1
1
  // input: Backend type from types.ts
2
- // output: Capability enum and Claude/PI capability matrix
2
+ // output: Capability enum, Claude/PI capability matrix, long-MCP-call version governance
3
3
  // pos: Capability declaration matrix per backend
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  export var Capability;
@@ -18,6 +18,10 @@ export var Capability;
18
18
  /** Backend accepts a user message into a turn already in flight (no new turn opened).
19
19
  * Part of the shared capability vocabulary; declared by the backends that implement injection. */
20
20
  Capability["MidTurnInject"] = "mid-turn-inject";
21
+ /** Backend's configured MCP tool timeout and progress handling permit a single tool call to run
22
+ * beyond the native default while staying bounded by the trial deadline. Benchmark arms require
23
+ * it: a blocking benchmark tool call must not be cut short by an SDK or CLI default. */
24
+ Capability["BenchmarkLongMcpCall"] = "benchmark-long-mcp-call";
21
25
  })(Capability || (Capability = {}));
22
26
  // Claude: full native support (claude-bridge.ts wires all ten shared capabilities).
23
27
  // StreamingDeltas: `--include-partial-messages` token-level output.
@@ -36,6 +40,9 @@ const CLAUDE_CAPS = [
36
40
  Capability.StreamingDeltas,
37
41
  // Print mode accepts a user message written to stdin while a turn is in flight.
38
42
  Capability.MidTurnInject,
43
+ // The CLI itself owns the MCP client, and it reads MCP_TOOL_TIMEOUT from the environment as the
44
+ // per-call budget. See LONG_MCP_CALL_VERSION_GOVERNANCE for the read evidence.
45
+ Capability.BenchmarkLongMcpCall,
39
46
  ];
40
47
  // PI: per DR-0008 §5.1 capability matrix — --skill for Plugins, --system-prompt for SystemPromptOverride, tool-allowlist via adapter;
41
48
  // MCP enabled by mcp-bridge.ts extension (task 5754): auto-injected via --extension in PIAdapter.spawn();
@@ -54,8 +61,39 @@ const PI_CAPS = [
54
61
  Capability.SessionResume,
55
62
  Capability.StreamingDeltas,
56
63
  Capability.MidTurnInject,
64
+ // Admitted on measured evidence, not on the option shapes alone. PI's MCP calls are issued by the
65
+ // Cortex bridge, which now supplies explicit timeout / maxTotalTimeout / resetTimeoutOnProgress
66
+ // RequestOptions (`benchmarkCallOptions`, pi/mcp-duration.ts). An independently written suite held
67
+ // one real call through that bridge for 63324 ms of wall clock while a no-options control client
68
+ // on a second server was cut at the SDK's 60 s default; a second row ended a 90 s hold at ~9.6 s =
69
+ // remaining budget + the 6000 ms cleanup grace despite progress notifications resetting the
70
+ // per-call timeout, so the raised budget is still bounded by the trial deadline; a third proved
71
+ // cancellation reaching the server rather than orphaning the request. The governing proof is
72
+ // tests/domain/agent-run/long-mcp-call-e2e.test.ts — real wall clock, no fake timers.
73
+ Capability.BenchmarkLongMcpCall,
57
74
  ];
58
75
  export const CAPABILITIES_BY_BACKEND = {
59
76
  claude: new Set(CLAUDE_CAPS),
60
77
  pi: new Set(PI_CAPS),
61
78
  };
79
+ // Every backend declares its governance. Nothing here is a default: the compiler refuses a backend
80
+ // that is absent from this table, so a backend added later lands on the refusing branch until
81
+ // someone writes down which of the two facts is true of it and why.
82
+ //
83
+ // claude 2.1.220, admitted by reading the installed bundle: MCP_TOOL_TIMEOUT is read from
84
+ // process.env and becomes the per-call hard timeout when > 0 (unset default 1e8 ms), clamped to
85
+ // 2147483647 ms, so no ceiling lands below a trial deadline; the stdio idle timeout defaults to
86
+ // 1800000 ms and is itself clamped by that hard timeout.
87
+ //
88
+ // pi is exempt on measured evidence rather than on absence of evidence: with the bridge supplying
89
+ // explicit call options, one real call was held 63324 ms while a no-options control client on a
90
+ // second server was cut at the SDK's 60 s default, and a 90 s hold was still bounded by the trial
91
+ // deadline. Upgrading the `pi` binary cannot change that; changing the bridge or its pinned SDK can,
92
+ // which is why the proof names a suite rather than a release string.
93
+ export const LONG_MCP_CALL_VERSION_GOVERNANCE = {
94
+ claude: { governed_by: 'cli-version', verified_versions: ['2.1.220 (Claude Code)'] },
95
+ pi: {
96
+ governed_by: 'cortex-bridge',
97
+ proof: 'tests/domain/agent-run/long-mcp-call-e2e.test.ts',
98
+ },
99
+ };
@@ -1,3 +1,4 @@
1
+ import type { IdentityJsonValue } from '../../domain/agent-run/identity.js';
1
2
  import { Capability } from '../capabilities.js';
2
3
  import type { AgentAdapter, AgentCompactResult, AgentProcess, AgentProcessSpawner, AgentProcessSupervision, AgentSpawnConfig, Backend, ContinuationSink, InjectionAckSink, McpComposition, UserMessage } from '../types.js';
3
4
  import type { ContextUsage } from '../../core/types/agent-types.js';
@@ -34,6 +35,14 @@ interface ClaudeSessionOptions {
34
35
  captureTranscriptLogs?: boolean;
35
36
  preserveUnreportedAccounting?: boolean;
36
37
  processSpawner?: AgentProcessSpawner;
38
+ /** Absolute CLI path frozen by a trial policy; absent resolves `claude` from PATH. */
39
+ cliPath?: string;
40
+ /** Compiled benchmark policy guard; present replaces the ambient hook surface entirely. */
41
+ benchmarkPolicyGuard?: IdentityJsonValue;
42
+ /** Exact allowlisted child environment for a pinned trial. */
43
+ pinnedEnv?: NodeJS.ProcessEnv;
44
+ /** Absolute trial deadline the child's MCP call budget is derived from at each spawn. */
45
+ benchmarkDeadlineEpochMs?: number;
37
46
  /** Extra CLI options from profile (e.g. {"--thinking": "xhigh"}). */
38
47
  extraOption?: Record<string, string>;
39
48
  /** Thinking level from the profile's `thinking` field → `--effort <level>`. Absent → no flag. */
@@ -75,6 +84,12 @@ declare class ClaudeSession {
75
84
  private captureTranscriptLogs;
76
85
  private preserveUnreportedAccounting;
77
86
  private processSpawner;
87
+ private cliPath;
88
+ private benchmarkPolicyGuard;
89
+ private pinnedEnv;
90
+ /** The trial deadline as an instant. The MCP budget derived from it is not stored: every spawn
91
+ * recomputes it, so a resumed or restarted process never inherits a stale budget. */
92
+ private benchmarkDeadlineEpochMs;
78
93
  private supervision;
79
94
  private extraOption;
80
95
  private thinking;
@@ -25,10 +25,13 @@ import { BgTaskTracker, routeLine } from './bg-task-tracker.js';
25
25
  import { ClaudeContextUsageTracker } from './context-usage.js';
26
26
  import { resolveAutoCompactWindow } from './compact-window.js';
27
27
  const log = createLogger('claude-bridge');
28
- function spawnClaudeProcess(spawner, args, options) {
28
+ function spawnClaudeProcess(spawner, args, options, cliPath) {
29
+ // One resolved command for both branches: a supervised trial and a direct spawn cannot run
30
+ // different binaries (design §13 C2).
31
+ const command = cliPath ?? 'claude';
29
32
  if (spawner)
30
- return spawner('claude', args, options);
31
- return { process: spawn('claude', args, { ...options, stdio: ['pipe', 'pipe', 'pipe'] }) };
33
+ return spawner(command, args, options);
34
+ return { process: spawn(command, args, { ...options, stdio: ['pipe', 'pipe', 'pipe'] }) };
32
35
  }
33
36
  function tokenValue(value) {
34
37
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
@@ -66,6 +69,7 @@ function deriveClaudeSpawnOptions(fields) {
66
69
  mcpComposition: fields.mcpComposition,
67
70
  mcpConfigPaths: fields.mcpConfigPaths,
68
71
  disableHooks: fields.disableHooks,
72
+ benchmarkPolicyGuard: fields.benchmarkPolicyGuard,
69
73
  streamDeltas: fields.streamDeltas,
70
74
  };
71
75
  }
@@ -112,6 +116,12 @@ class ClaudeSession {
112
116
  captureTranscriptLogs;
113
117
  preserveUnreportedAccounting;
114
118
  processSpawner;
119
+ cliPath;
120
+ benchmarkPolicyGuard;
121
+ pinnedEnv;
122
+ /** The trial deadline as an instant. The MCP budget derived from it is not stored: every spawn
123
+ * recomputes it, so a resumed or restarted process never inherits a stale budget. */
124
+ benchmarkDeadlineEpochMs;
115
125
  supervision;
116
126
  extraOption;
117
127
  thinking;
@@ -156,8 +166,10 @@ class ClaudeSession {
156
166
  this.needsResume = options.needsResume;
157
167
  this.modelName = options.model || null;
158
168
  this.cwd = options.cwd ?? DATA_DIR;
159
- // Settings are read per session because the CLI reads project settings from its spawn cwd.
160
- this.contextUsageTracker = new ClaudeContextUsageTracker(this.modelName, resolveAutoCompactWindow(this.cwd));
169
+ // Settings are read per session because the CLI reads project settings from its spawn cwd. A
170
+ // pinned trial supplies its own config dir, so the session never falls through to the host's
171
+ // ambient CLAUDE_CONFIG_DIR / ~/.claude (design §13 A15).
172
+ this.contextUsageTracker = new ClaudeContextUsageTracker(this.modelName, resolveAutoCompactWindow(this.cwd, options.pinnedEnv?.CLAUDE_CONFIG_DIR));
161
173
  this.isUserInitiated = options.isUserInitiated || false;
162
174
  this.callbackSource = options.callbackSource || null;
163
175
  this.scheduleTaskId = options.scheduleTaskId || null;
@@ -176,6 +188,10 @@ class ClaudeSession {
176
188
  this.captureTranscriptLogs = options.captureTranscriptLogs !== false;
177
189
  this.preserveUnreportedAccounting = options.preserveUnreportedAccounting === true;
178
190
  this.processSpawner = options.processSpawner;
191
+ this.cliPath = options.cliPath;
192
+ this.benchmarkPolicyGuard = options.benchmarkPolicyGuard;
193
+ this.pinnedEnv = options.pinnedEnv;
194
+ this.benchmarkDeadlineEpochMs = options.benchmarkDeadlineEpochMs;
179
195
  this.extraOption = options.extraOption;
180
196
  this.thinking = options.thinking ?? null;
181
197
  this.context = options.context;
@@ -197,6 +213,7 @@ class ClaudeSession {
197
213
  mcpComposition: this.mcpComposition,
198
214
  mcpConfigPaths: this.mcpConfigPaths,
199
215
  disableHooks: this.disableHooks,
216
+ benchmarkPolicyGuard: this.benchmarkPolicyGuard,
200
217
  streamDeltas: this.streamDeltas,
201
218
  });
202
219
  }
@@ -277,7 +294,7 @@ class ClaudeSession {
277
294
  }
278
295
  }
279
296
  spawnProcess() {
280
- const env = buildClaudeEnv(this.channel, this.sessionId, this.callbackSource, this.scheduleTaskId, this.anthropicBaseUrl, this.extraEnv, this.context);
297
+ const env = buildClaudeEnv(this.channel, this.sessionId, this.callbackSource, this.scheduleTaskId, this.anthropicBaseUrl, this.extraEnv, this.context, this.pinnedEnv, this.benchmarkDeadlineEpochMs);
281
298
  const spawnOptions = this.toSpawnOptions();
282
299
  // Sessions that originate from Slack (channel carries the SlackAdapter `slack:` prefix) load the
283
300
  // cortex-slack MCP server so the agent can send files to Slack. Non-direct compositions suppress it.
@@ -293,7 +310,7 @@ class ClaudeSession {
293
310
  spawnOptions.isUserInitiated = this.isUserInitiated;
294
311
  const args = buildSpawnArgs(spawnOptions);
295
312
  log.info(`Spawning persistent process: ${this.sessionId.substring(0, 8)} ${this.needsResume ? '(resume)' : '(new)'}`);
296
- const spawned = spawnClaudeProcess(this.processSpawner, args, { cwd: this.cwd, env });
313
+ const spawned = spawnClaudeProcess(this.processSpawner, args, { cwd: this.cwd, env }, this.cliPath);
297
314
  this.proc = spawned.process;
298
315
  this.supervision = spawned.supervision;
299
316
  this.stderr = '';
@@ -1089,6 +1106,10 @@ function sessionOptionsFromSpawnConfig(config) {
1089
1106
  captureTranscriptLogs: config.captureTranscriptLogs,
1090
1107
  preserveUnreportedAccounting: config.preserveUnreportedAccounting,
1091
1108
  processSpawner: config.processSpawner,
1109
+ cliPath: config.cliPath,
1110
+ benchmarkPolicyGuard: config.benchmarkPolicyGuard,
1111
+ pinnedEnv: config.pinnedEnv,
1112
+ benchmarkDeadlineEpochMs: config.benchmarkDeadlineEpochMs,
1092
1113
  extraOption: config.extraOption,
1093
1114
  thinking: config.thinking ?? null,
1094
1115
  context: config.cortexContext,
@@ -1115,6 +1136,7 @@ function computeSpawnArgsForConfig(config) {
1115
1136
  mcpComposition: opts.mcpComposition ?? 'direct',
1116
1137
  mcpConfigPaths: opts.mcpConfigPaths,
1117
1138
  disableHooks: opts.disableHooks,
1139
+ benchmarkPolicyGuard: opts.benchmarkPolicyGuard,
1118
1140
  streamDeltas: opts.streamDeltas,
1119
1141
  });
1120
1142
  spawnOptions.isUserInitiated = config.isUserInitiated;
@@ -1,3 +1,4 @@
1
+ import type { IdentityJsonValue } from '../../domain/agent-run/identity.js';
1
2
  import type { McpComposition } from '../types.js';
2
3
  /**
3
4
  * Adapter mode selector. `print` (default) uses `-p` + stream-json; `tui` uses interactive TUI
@@ -18,8 +19,10 @@ export interface ClaudeSpawnOptions {
18
19
  mcpComposition?: McpComposition;
19
20
  /** Concrete MCP files supplied by a frozen one-shot run configuration. */
20
21
  mcpConfigPaths?: string[] | null;
21
- /** Omit all configured hooks for isolated one-shot execution. */
22
+ /** Omit all configured **ambient** hooks for isolated one-shot execution. */
22
23
  disableHooks?: boolean;
24
+ /** Compiled benchmark policy guard. Present makes the guard the entire hooks surface. */
25
+ benchmarkPolicyGuard?: IdentityJsonValue;
23
26
  /** Explicit partial-message policy; absent reads the daemon setting. */
24
27
  streamDeltas?: boolean;
25
28
  /** Layer the cortex-slack MCP server on top of the base config. Set by the adapter for sessions
@@ -73,4 +76,4 @@ export interface CortexAgentContext {
73
76
  taskProject?: string | null;
74
77
  taskGeneration?: string | null;
75
78
  }
76
- export declare function buildClaudeEnv(channel: string, sessionId: string, callbackSource?: string | null, scheduleTaskId?: string | null, anthropicBaseUrl?: string, extraEnv?: Record<string, string>, context?: CortexAgentContext): NodeJS.ProcessEnv;
79
+ export declare function buildClaudeEnv(channel: string, sessionId: string, callbackSource?: string | null, scheduleTaskId?: string | null, anthropicBaseUrl?: string, extraEnv?: Record<string, string>, context?: CortexAgentContext, pinnedEnv?: NodeJS.ProcessEnv, benchmarkDeadlineEpochMs?: number): NodeJS.ProcessEnv;
@@ -4,6 +4,9 @@
4
4
  // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { BENCHMARK_THREAD_MCP_CONFIG, CORE_MCP_CONFIG, DEFAULT_TOOLS, EMPTY_MCP_CONFIG, FEISHU_MCP_CONFIG, MANAGER_QA_MCP_CONFIG, MCP_CONFIG, SLACK_MCP_CONFIG, TASKS_MCP_CONFIG, THREAD_MCP_CONFIG, TUI_BRIDGE_TOOLS, TUI_MCP_CONFIG, TUI_STRIP_TOOLS, TUI_TOOLS, WEB_MCP_CONFIG, } from './defaults.js';
6
6
  import { getSettings } from '../../core/settings.js';
7
+ // The cleanup grace is one backend-neutral quantity: design §5.7 C3 defines the Claude budget as
8
+ // "the same quantity as P2", so a second copy of `1000 + 5000` here could only ever drift from it.
9
+ import { MCP_CLEANUP_GRACE_MS } from '../pi/mcp-duration.js';
7
10
  import { buildHooksSettings } from './hooks-builder.js';
8
11
  /** Token-level assistant streaming gate, read for each spawn argument build. */
9
12
  export function isStreamDeltasEnabled() {
@@ -100,8 +103,12 @@ export function buildSpawnArgs(options) {
100
103
  for (const [k, v] of Object.entries(options.extraOption))
101
104
  args.push(k, v);
102
105
  }
106
+ // A compiled benchmark guard is the whole hook surface: the ambient registry is never consulted,
107
+ // and `disableHooks` keeps its shipped meaning of "no AMBIENT hooks" (design §13 GT5, §6.5).
103
108
  const settings = {
104
- hooks: options.disableHooks ? {} : buildHooksSettings(options.tools),
109
+ hooks: options.benchmarkPolicyGuard !== undefined
110
+ ? options.benchmarkPolicyGuard
111
+ : (options.disableHooks ? {} : buildHooksSettings(options.tools)),
105
112
  };
106
113
  if (options.outputStyle)
107
114
  settings.outputStyle = options.outputStyle;
@@ -112,8 +119,11 @@ export function buildSpawnArgs(options) {
112
119
  args.push('--session-id', options.sessionId);
113
120
  return args;
114
121
  }
115
- export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskId, anthropicBaseUrl, extraEnv, context) {
116
- const env = { ...process.env };
122
+ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskId, anthropicBaseUrl, extraEnv, context, pinnedEnv, benchmarkDeadlineEpochMs) {
123
+ // Allowlist-first for a pinned trial: the child starts from the exact trial environment and
124
+ // inherits nothing from the host, so no denylist can leak a host credential or platform
125
+ // surface into the trial (design §13 C5/C7).
126
+ const env = pinnedEnv ? { ...pinnedEnv } : { ...process.env };
117
127
  delete env.CLAUDECODE;
118
128
  for (const key of Object.keys(env)) {
119
129
  if (key.startsWith('CLAUDE_CODE'))
@@ -131,9 +141,11 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
131
141
  env.CLAUDE_CODE_AUTO_CONNECT_IDE = 'false'; // no IDE auto-connect probe
132
142
  env.CLAUDE_CODE_DISABLE_POLICY_SKILLS = '1'; // skip system managed-skills dir (Cortex uses pluginDirs)
133
143
  env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE = '1'; // no title updates; also skips the title-gen Haiku call in -p
134
- env.SLACK_CHANNEL = channel;
135
- env.FEISHU_CHANNEL = channel;
136
- env.SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN;
144
+ if (!pinnedEnv) {
145
+ env.SLACK_CHANNEL = channel;
146
+ env.FEISHU_CHANNEL = channel;
147
+ env.SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN;
148
+ }
137
149
  // CORTEX_SESSION_ID is the stable Cortex tracking id (session-activity log routing + MCP context),
138
150
  // NOT the backend CLI's self-assigned session id. Falls back to the backend id when unset (threads).
139
151
  env.CORTEX_SESSION_ID = context?.trackSessionId ?? sessionId;
@@ -147,6 +159,17 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
147
159
  for (const [key, value] of Object.entries(extraEnv))
148
160
  env[key] = value;
149
161
  }
162
+ // The CLI owns the MCP client on this backend, so the only budget Cortex can supply is the pair it
163
+ // reads from its environment: `MCP_TOOL_TIMEOUT` per tool call and `MCP_TIMEOUT` for server
164
+ // startup. Both carry the remaining trial time plus the cleanup grace, so a benchmark call
165
+ // outlives the CLI's native default yet is still cut off with the trial rather than after it.
166
+ // Derived here, at the instant the child environment is built, and never carried as a stored
167
+ // duration; written after the `extraEnv` merge so an inherited value cannot raise the bound.
168
+ if (benchmarkDeadlineEpochMs !== undefined) {
169
+ const budgetMs = Math.max(0, benchmarkDeadlineEpochMs - Date.now()) + MCP_CLEANUP_GRACE_MS;
170
+ env.MCP_TOOL_TIMEOUT = String(budgetMs);
171
+ env.MCP_TIMEOUT = String(budgetMs);
172
+ }
150
173
  delete env.CORTEX_THREAD_ID;
151
174
  delete env.CORTEX_PROFILE;
152
175
  delete env.CORTEX_PROJECT;
@@ -4,12 +4,22 @@
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { ClaudeAdapter } from './claude/adapter.js';
6
6
  import { PIAdapter } from './pi/adapter.js';
7
+ import { ensureAuthVisible, USER_PI_MODELS_PATH } from './pi/agent-dir.js';
8
+ import { DEFAULT_SESSION_DIR, PI_AGENT_DIR } from './pi/defaults.js';
9
+ import { piProviderDiscovery } from './pi/discovery.js';
7
10
  export * from './types.js';
8
11
  export * from './capabilities.js';
9
12
  export * from './normalize/event-types.js';
10
13
  export * from './normalize/hooks.js';
11
14
  export * from './normalize/tool-names.js';
12
- const PI_ADAPTER = new PIAdapter();
15
+ // The daemon's PI collaborators are injected here rather than defaulted inside the adapter: the host
16
+ // PI home, its cached provider scan and its auth mirroring are exactly the ambient reaches design
17
+ // §13 A1/A6/A7 forbids a trial from touching, and this registry is the daemon-only owner of all three.
18
+ const PI_ADAPTER = new PIAdapter(undefined, DEFAULT_SESSION_DIR, piProviderDiscovery, {
19
+ agentDir: PI_AGENT_DIR,
20
+ prepareAgentDir: (agentDir) => ensureAuthVisible({ agentDir }),
21
+ userModelsPath: USER_PI_MODELS_PATH,
22
+ });
13
23
  const ADAPTERS = {
14
24
  claude: new ClaudeAdapter(),
15
25
  pi: PI_ADAPTER,
@@ -1,5 +1,9 @@
1
1
  import type { Backend } from '../types.js';
2
2
  export type CanonicalToolName = 'bash' | 'read' | 'write' | 'edit' | 'grep' | 'glob' | 'web_fetch' | 'web_search' | 'ask_user_question' | 'enter_plan_mode' | 'exit_plan_mode' | 'todo_write' | 'skill' | 'agent';
3
+ /** Every tool label a backend's own dispatch boundary answers to. Design §13.10 GS4 draws a
4
+ * benchmark policy guard's allow-list from exactly this namespace, so it is derived from the table
5
+ * the adapters already translate through rather than restated somewhere it can drift. */
6
+ export declare function nativeToolNames(backend: Backend): string[];
3
7
  /** Translate a backend-native tool name to canonical. MCP tools (mcp__ prefix) pass through unchanged. */
4
8
  export declare function toCanonical(backend: Backend, nativeName: string): CanonicalToolName | string | null;
5
9
  /** Translate a canonical name to the backend-native tool name. MCP tools pass through unchanged. Returns null if backend lacks the tool. */
@@ -50,6 +50,16 @@ function buildReverse(forward) {
50
50
  }
51
51
  return m;
52
52
  }
53
+ /** PI answers to these natively without owning a `NativeMap` entry, because the extension shim —
54
+ * not the name map — registers them (`pi/tool-shims.ts:227`, gated by `decide('agent', 'Agent')`). */
55
+ const PI_SHIM_ONLY_TOOLS = ['agent'];
56
+ /** Every tool label a backend's own dispatch boundary answers to. Design §13.10 GS4 draws a
57
+ * benchmark policy guard's allow-list from exactly this namespace, so it is derived from the table
58
+ * the adapters already translate through rather than restated somewhere it can drift. */
59
+ export function nativeToolNames(backend) {
60
+ const mapped = Object.values(FORWARD_BY_BACKEND[backend]).filter((name) => !!name);
61
+ return backend === 'pi' ? [...mapped, ...PI_SHIM_ONLY_TOOLS] : mapped;
62
+ }
53
63
  /** Translate a backend-native tool name to canonical. MCP tools (mcp__ prefix) pass through unchanged. */
54
64
  export function toCanonical(backend, nativeName) {
55
65
  if (nativeName.startsWith('mcp__'))
@@ -1,13 +1,20 @@
1
1
  import { Capability } from '../capabilities.js';
2
- import type { AgentAdapter, AgentSpawnConfig, Backend, McpComposition } from '../types.js';
3
- import { type PIProviderDiscovery } from './discovery.js';
2
+ import type { AgentAdapter, AgentSpawnConfig, Backend } from '../types.js';
3
+ import type { PIProviderDiscovery } from './discovery.js';
4
4
  import { type PIAgentProcess, type SpawnFn, type SwitchResult } from './session-support.js';
5
5
  export type { PIAgentProcess } from './session-support.js';
6
- type UnsupportedPiMcpComposition = Extract<McpComposition, 'none' | 'benchmark-thread-run'>;
7
- export declare class UnsupportedMcpCompositionError extends Error {
8
- readonly composition: UnsupportedPiMcpComposition;
9
- readonly name = "UnsupportedMcpCompositionError";
10
- constructor(composition: UnsupportedPiMcpComposition);
6
+ /** Collaborators the daemon owns and a trial replaces. Both are injected rather than defaulted so
7
+ * the host PI home and its auth mirroring are not reachable from this module (§13 A1, A6). */
8
+ export interface PIAdapterHooks {
9
+ /** `PI_CODING_AGENT_DIR` for every session this instance spawns (§13 P4). */
10
+ agentDir?: string;
11
+ /** Run before spawn with the resolved agent dir: the daemon mirrors the host credential here, a
12
+ * trial writes its dummy token. Never a module default (§13 A5/A6). */
13
+ prepareAgentDir?: (agentDir: string) => void;
14
+ /** The user's PI catalog (`~/.pi/agent/models.json`), source of user-defined provider
15
+ * definitions. Injected, never defaulted: reading the host PI home is exactly the ambient reach
16
+ * a trial must not have (§13 A1). Left unset, no custom provider is mirrored. */
17
+ userModelsPath?: string;
11
18
  }
12
19
  export declare class PIAdapter implements AgentAdapter {
13
20
  readonly backend: Backend;
@@ -17,9 +24,14 @@ export declare class PIAdapter implements AgentAdapter {
17
24
  private readonly providerDiscovery;
18
25
  private readonly configuredProviderOverrides;
19
26
  private readonly sessionPathRegistry;
27
+ /** Injected PI home, or undefined when the caller left it to the daemon default. */
28
+ private readonly configuredAgentDir;
29
+ private readonly prepareAgentDir;
30
+ /** Injected user catalog path, or undefined when this instance mirrors no custom provider. */
31
+ private readonly userModelsPath;
20
32
  /** sessionDir for the <sessionId>.jsonl path convention. Exposed for tests. */
21
33
  readonly sessionDir: string;
22
- constructor(spawner?: SpawnFn, sessionDir?: string, providerDiscovery?: PIProviderDiscovery);
34
+ constructor(spawner?: SpawnFn, sessionDir?: string, providerDiscovery?: PIProviderDiscovery, hooks?: PIAdapterHooks);
23
35
  private gatewayOverrides;
24
36
  spawn(config: AgentSpawnConfig): PIAgentProcess;
25
37
  /** Record the exact transcript path restored by rewind before the next resume spawn. */