@zergai/ztc 0.26.2-dev.202611210149 → 0.26.4-dev.202611231953

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 (275) hide show
  1. package/README.md +590 -28
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/zmux-linux-x64 +0 -0
  4. package/bin/ztc-audio-darwin-arm64 +0 -0
  5. package/bin/ztc-capture-darwin-arm64 +0 -0
  6. package/bin/ztc-tui-darwin-arm64 +0 -0
  7. package/bin/ztc-tui-linux-x64 +0 -0
  8. package/bin/zterm-darwin-arm64 +2 -2
  9. package/dist/App.js +18 -1
  10. package/dist/agent/agent.d.ts +25 -1
  11. package/dist/agent/agent.js +26 -1
  12. package/dist/agent/attached_images.d.ts +58 -0
  13. package/dist/agent/attached_images.js +145 -0
  14. package/dist/agent/backends/anthropic.d.ts +14 -0
  15. package/dist/agent/backends/anthropic.js +49 -2
  16. package/dist/agent/backends/codex_app_server.d.ts +3 -1
  17. package/dist/agent/backends/codex_app_server.js +9 -6
  18. package/dist/agent/backends/codex_auth.js +3 -0
  19. package/dist/agent/backends/gemini.js +3 -0
  20. package/dist/agent/backends/host_effort_policy.js +14 -2
  21. package/dist/agent/backends/http_error.d.ts +17 -0
  22. package/dist/agent/backends/http_error.js +50 -1
  23. package/dist/agent/backends/index.js +2 -1
  24. package/dist/agent/backends/model_redirect.d.ts +47 -0
  25. package/dist/agent/backends/model_redirect.js +97 -0
  26. package/dist/agent/backends/openai_compatible.js +5 -0
  27. package/dist/agent/backends/openai_responses.d.ts +9 -1
  28. package/dist/agent/backends/openai_responses.js +21 -12
  29. package/dist/agent/backends/prompt_cache.d.ts +8 -0
  30. package/dist/agent/backends/prompt_cache.js +10 -0
  31. package/dist/agent/backends/provider_ids.d.ts +1 -1
  32. package/dist/agent/backends/provider_ids.js +1 -1
  33. package/dist/agent/backends/types.d.ts +8 -0
  34. package/dist/agent/backends/zerg-api.js +5 -1
  35. package/dist/agent/backends/zrouter_stream.d.ts +75 -9
  36. package/dist/agent/backends/zrouter_stream.js +250 -49
  37. package/dist/agent/commands/config.js +51 -4
  38. package/dist/agent/commands/connect.js +20 -0
  39. package/dist/agent/commands/credential_status.js +5 -3
  40. package/dist/agent/commands/debug.js +3 -0
  41. package/dist/agent/commands/diff.js +9 -5
  42. package/dist/agent/commands/emulation.js +7 -1
  43. package/dist/agent/commands/inbox.js +4 -3
  44. package/dist/agent/commands/mcp.js +3 -0
  45. package/dist/agent/commands/models.js +20 -3
  46. package/dist/agent/commands/permissions.js +16 -2
  47. package/dist/agent/commands/provider_selection.js +13 -6
  48. package/dist/agent/commands/settings.js +15 -4
  49. package/dist/agent/commands/status.js +23 -1
  50. package/dist/agent/commands/types.d.ts +34 -3
  51. package/dist/agent/commands/update.d.ts +2 -1
  52. package/dist/agent/commands/update.js +8 -3
  53. package/dist/agent/commands/zerg.d.ts +6 -0
  54. package/dist/agent/commands/zerg.js +152 -28
  55. package/dist/agent/commands/ztc_pane.js +8 -5
  56. package/dist/agent/factory.js +22 -4
  57. package/dist/agent/request_encoder.js +11 -2
  58. package/dist/agent/runtime/command_jobs.js +16 -1
  59. package/dist/agent/runtime/command_panes.js +4 -1
  60. package/dist/agent/runtime/execution_context.d.ts +8 -1
  61. package/dist/agent/runtime/execution_context.js +8 -2
  62. package/dist/agent/runtime/policy.d.ts +66 -5
  63. package/dist/agent/runtime/policy.js +161 -33
  64. package/dist/agent/runtime/remote_broker_transport.d.ts +7 -0
  65. package/dist/agent/runtime/remote_broker_transport.js +33 -3
  66. package/dist/agent/runtime/remote_resource_errors.d.ts +7 -0
  67. package/dist/agent/runtime/remote_resource_errors.js +10 -0
  68. package/dist/agent/runtime/remote_resources.d.ts +1 -1
  69. package/dist/agent/runtime/remote_resources.js +7 -3
  70. package/dist/agent/runtime/source_verification.js +15 -12
  71. package/dist/agent/runtime/tool_runtime.js +165 -58
  72. package/dist/agent/runtime/verifier_capture.d.ts +1 -1
  73. package/dist/agent/runtime/verifier_capture.js +6 -0
  74. package/dist/agent/runtime/work_base.js +46 -14
  75. package/dist/agent/tools/adaptation.js +29 -12
  76. package/dist/agent/tools/apply_patch.js +62 -5
  77. package/dist/agent/tools/background.js +2 -0
  78. package/dist/agent/tools/benchmark_cpu.js +2 -0
  79. package/dist/agent/tools/bus_message.d.ts +4 -2
  80. package/dist/agent/tools/bus_message.js +21 -3
  81. package/dist/agent/tools/delegate.js +2 -0
  82. package/dist/agent/tools/file.d.ts +12 -1
  83. package/dist/agent/tools/file.js +92 -11
  84. package/dist/agent/tools/lsp.d.ts +12 -0
  85. package/dist/agent/tools/lsp.js +61 -5
  86. package/dist/agent/tools/pane.js +20 -45
  87. package/dist/agent/tools/project_context.js +5 -2
  88. package/dist/agent/tools/routine.js +20 -4
  89. package/dist/agent/tools/screenshot.d.ts +8 -0
  90. package/dist/agent/tools/screenshot.js +39 -25
  91. package/dist/agent/tools/search.js +31 -3
  92. package/dist/agent/tools/shell.js +7 -1
  93. package/dist/agent/tools/supervision.js +6 -0
  94. package/dist/agent/tools/types.d.ts +18 -0
  95. package/dist/agent/tools/zerg.js +15 -19
  96. package/dist/agent/tools/ztc_command.d.ts +15 -4
  97. package/dist/agent/tools/ztc_command.js +48 -34
  98. package/dist/app/agent_runner.js +8 -6
  99. package/dist/app/conversation_compaction.d.ts +6 -3
  100. package/dist/app/conversation_compaction.js +6 -3
  101. package/dist/app/tool_callbacks.js +1 -0
  102. package/dist/audio/sfx.js +6 -0
  103. package/dist/batch/worktree.js +22 -10
  104. package/dist/board/client.js +2 -1
  105. package/dist/cli_main.d.ts +1 -0
  106. package/dist/cli_main.js +141 -45
  107. package/dist/cli_ratatui.d.ts +49 -4
  108. package/dist/cli_ratatui.js +355 -79
  109. package/dist/conductor_branch.js +4 -1
  110. package/dist/config/host_credentials.d.ts +157 -0
  111. package/dist/config/host_credentials.js +589 -0
  112. package/dist/config/model_pin.d.ts +111 -0
  113. package/dist/config/model_pin.js +182 -0
  114. package/dist/config/own_state_files.d.ts +35 -0
  115. package/dist/config/own_state_files.js +161 -0
  116. package/dist/config/permission_pin.d.ts +148 -0
  117. package/dist/config/permission_pin.js +203 -0
  118. package/dist/config/permissions.d.ts +9 -2
  119. package/dist/config/permissions.js +14 -3
  120. package/dist/config/platform_login.d.ts +72 -0
  121. package/dist/config/platform_login.js +111 -0
  122. package/dist/config/profile_limits.d.ts +34 -0
  123. package/dist/config/profile_limits.js +66 -0
  124. package/dist/config/provider_api_key_env.js +3 -2
  125. package/dist/config/provider_models.d.ts +6 -1
  126. package/dist/config/provider_models.js +38 -11
  127. package/dist/config/repo_config.d.ts +22 -0
  128. package/dist/config/repo_config.js +77 -3
  129. package/dist/config/router_runtime_grant.d.ts +53 -0
  130. package/dist/config/router_runtime_grant.js +131 -0
  131. package/dist/config/settings_merge.d.ts +22 -0
  132. package/dist/config/settings_merge.js +75 -0
  133. package/dist/config/types.d.ts +8 -0
  134. package/dist/config.d.ts +334 -4
  135. package/dist/config.js +1024 -41
  136. package/dist/context/project_intelligence.d.ts +11 -2
  137. package/dist/context/project_intelligence.js +38 -15
  138. package/dist/desktop/daily/desktop_wiring.js +8 -6
  139. package/dist/desktop/daily/native_pane_launcher.js +2 -1
  140. package/dist/desktop/daily/native_tool.d.ts +1 -1
  141. package/dist/desktop/daily/native_tool.js +4 -3
  142. package/dist/desktop/daily/process_identity.js +10 -2
  143. package/dist/desktop/daily/source_baseline.js +4 -3
  144. package/dist/diagnostics/native_terminal_benchmark.js +3 -2
  145. package/dist/diagnostics/session_export.js +27 -14
  146. package/dist/embedded/anempa_runtime.js +3 -3
  147. package/dist/embedded/gameboy_runtime.js +5 -4
  148. package/dist/embedded/zergpod_runtime.js +5 -4
  149. package/dist/emulation/catalog.js +6 -1
  150. package/dist/emulation/tool_adapters.js +13 -3
  151. package/dist/environment/store.js +5 -4
  152. package/dist/extension_discovery.d.ts +12 -2
  153. package/dist/extension_discovery.js +52 -7
  154. package/dist/headless.d.ts +8 -0
  155. package/dist/headless.js +52 -13
  156. package/dist/headless_cli.js +16 -1
  157. package/dist/headless_workflow_trigger.js +1 -1
  158. package/dist/hooks/dispatcher.d.ts +8 -0
  159. package/dist/hooks/dispatcher.js +22 -2
  160. package/dist/hooks/lifecycle.d.ts +6 -0
  161. package/dist/hooks/lifecycle.js +1 -0
  162. package/dist/hooks/program_files.d.ts +10 -0
  163. package/dist/hooks/program_files.js +175 -0
  164. package/dist/hooks/runner.d.ts +11 -1
  165. package/dist/hooks/runner.js +112 -11
  166. package/dist/hooks/types.d.ts +2 -0
  167. package/dist/host_credentials_startup.d.ts +6 -0
  168. package/dist/host_credentials_startup.js +17 -0
  169. package/dist/instance_registry.d.ts +6 -2
  170. package/dist/instance_registry.js +9 -15
  171. package/dist/intake/format.d.ts +6 -0
  172. package/dist/intake/format.js +9 -0
  173. package/dist/intake/notifications.js +2 -1
  174. package/dist/lsp/manager.d.ts +1 -1
  175. package/dist/lsp/manager.js +4 -5
  176. package/dist/mcp/client.d.ts +2 -0
  177. package/dist/mcp/client.js +116 -18
  178. package/dist/mcp/registry.d.ts +12 -0
  179. package/dist/mcp/registry.js +15 -1
  180. package/dist/modes/handlers.js +14 -5
  181. package/dist/panes/agent_cli.d.ts +23 -1
  182. package/dist/panes/agent_cli.js +96 -1
  183. package/dist/panes/agent_panes.d.ts +27 -4
  184. package/dist/panes/agent_panes.js +73 -11
  185. package/dist/panes/editor_program.d.ts +8 -0
  186. package/dist/panes/editor_program.js +25 -0
  187. package/dist/panes/motsi.d.ts +11 -1
  188. package/dist/panes/motsi.js +14 -1
  189. package/dist/panes/pane_registry.d.ts +28 -1
  190. package/dist/panes/pane_registry.js +25 -0
  191. package/dist/panes/worker_route.js +5 -3
  192. package/dist/panes/ztc_launch.d.ts +8 -0
  193. package/dist/panes/ztc_launch.js +26 -1
  194. package/dist/profile_baseline.js +2 -0
  195. package/dist/router_auth.d.ts +8 -3
  196. package/dist/router_auth.js +34 -2
  197. package/dist/runtime_info.js +56 -38
  198. package/dist/session.js +12 -2
  199. package/dist/shannon/runtime.js +13 -1
  200. package/dist/simulation/domains/loader.d.ts +2 -1
  201. package/dist/simulation/domains/loader.js +19 -2
  202. package/dist/simulation/living/context.d.ts +8 -8
  203. package/dist/simulation/living/types.d.ts +2 -2
  204. package/dist/simulation/memory/embedding.d.ts +2 -1
  205. package/dist/simulation/memory/embedding.js +25 -6
  206. package/dist/terminal_attach.js +2 -1
  207. package/dist/types.d.ts +21 -0
  208. package/dist/ui/ratatui/headless_pane_manager.d.ts +12 -6
  209. package/dist/ui/ratatui/headless_pane_manager.js +65 -21
  210. package/dist/ui/ratatui/ipc_path.d.ts +41 -2
  211. package/dist/ui/ratatui/ipc_path.js +164 -5
  212. package/dist/ui/ratatui/pane_credential_broker.d.ts +17 -4
  213. package/dist/ui/ratatui/pane_credential_broker.js +23 -5
  214. package/dist/ui/ratatui/pane_relay.d.ts +74 -0
  215. package/dist/ui/ratatui/pane_relay.js +188 -13
  216. package/dist/ui/ratatui/process.d.ts +15 -1
  217. package/dist/ui/ratatui/process.js +129 -163
  218. package/dist/ui/ratatui/protocol.d.ts +11 -1
  219. package/dist/ui/ratatui/protocol.js +6 -0
  220. package/dist/ui/ratatui/ztc_launch_trust.d.ts +87 -0
  221. package/dist/ui/ratatui/ztc_launch_trust.js +249 -0
  222. package/dist/utils/admitted_open.d.ts +40 -0
  223. package/dist/utils/admitted_open.js +111 -0
  224. package/dist/utils/clipboard.js +2 -1
  225. package/dist/utils/computer_native.js +12 -56
  226. package/dist/utils/dictation.js +15 -12
  227. package/dist/utils/dictation_native.js +17 -60
  228. package/dist/utils/git_probe_options.d.ts +28 -0
  229. package/dist/utils/git_probe_options.js +30 -0
  230. package/dist/utils/git_program_files.d.ts +145 -0
  231. package/dist/utils/git_program_files.js +1282 -0
  232. package/dist/utils/git_repository_programs.d.ts +13 -0
  233. package/dist/utils/git_repository_programs.js +38 -0
  234. package/dist/utils/host_shell.js +2 -1
  235. package/dist/utils/idle_compaction.js +8 -1
  236. package/dist/utils/image_fit.d.ts +4 -1
  237. package/dist/utils/image_fit.js +6 -2
  238. package/dist/utils/image_preview.js +3 -2
  239. package/dist/utils/mirror_media.d.ts +22 -4
  240. package/dist/utils/mirror_media.js +87 -86
  241. package/dist/utils/ml_native.js +11 -56
  242. package/dist/utils/native_install.d.ts +55 -0
  243. package/dist/utils/native_install.js +107 -0
  244. package/dist/utils/open_url.js +2 -0
  245. package/dist/utils/process_end.d.ts +16 -0
  246. package/dist/utils/process_end.js +73 -0
  247. package/dist/utils/router_catalog.js +9 -2
  248. package/dist/utils/sandbox.d.ts +64 -1
  249. package/dist/utils/sandbox.js +397 -89
  250. package/dist/utils/shell.js +31 -12
  251. package/dist/utils/subprocess_env.d.ts +218 -2
  252. package/dist/utils/subprocess_env.js +429 -11
  253. package/dist/utils/system_ps.d.ts +5 -0
  254. package/dist/utils/system_ps.js +30 -0
  255. package/dist/utils/tts.js +5 -0
  256. package/dist/utils/tts_native.js +13 -60
  257. package/dist/utils/zlicky_overlay.js +17 -50
  258. package/dist/utils/ztc_own_state.d.ts +58 -0
  259. package/dist/utils/ztc_own_state.js +236 -0
  260. package/dist/web/mirror_authenticator.d.ts +67 -6
  261. package/dist/web/mirror_authenticator.js +131 -22
  262. package/dist/web/mirror_stream.d.ts +54 -10
  263. package/dist/web/mirror_stream.js +379 -92
  264. package/dist/web/observer_query_redaction.js +53 -13
  265. package/dist/web/observer_secret_redaction.d.ts +59 -0
  266. package/dist/web/observer_secret_redaction.js +714 -0
  267. package/dist/web/pane_credentials.d.ts +20 -2
  268. package/dist/web/pane_credentials.js +58 -5
  269. package/dist/worker/executor.js +3 -1
  270. package/dist/workspace_collision.js +19 -15
  271. package/dist/zerg/local_zerg_launches.d.ts +27 -0
  272. package/dist/zerg/local_zerg_launches.js +198 -0
  273. package/dist/zlm-embed.mjs +6257 -2791
  274. package/npm-shrinkwrap.json +1 -1
  275. package/package.json +42 -15
@@ -29,12 +29,14 @@ export interface BusTransport {
29
29
  * the time (MIRROR): the one it started with, or the one /mirror start started, whose bus its panes' mirror clients
30
30
  * rejoin; never one /mirror stop stopped, whose bus is gone. It says what the mirror did with the message, as /bus/send
31
31
  * answers a pane. While it runs none, OFF_BUS gets the message, which the owner types into the panes it is for, and it
32
- * says nothing.
32
+ * says what OFF_BUS says: nothing, or a refusal. Either way the message goes to agents alone, as a pane's own does: a
33
+ * shell or a command pane, which would run it as a command, is refused (not_an_agent). A message that is a pane control
34
+ * command ({"__ztc_cmd":...}), which a pane takes from Main as its owner's, is refused before it goes anywhere.
33
35
  *
34
36
  * NAME is what Main is called as each message leaves: the name its pane goes by, which list_panes and the pane's header
35
37
  * give it, "Main" or the one /rename gave it, so an agent that reads the message can answer Main by it.
36
38
  */
37
- export declare function overseerBusTransport(mirror: () => MirrorStreamServer | null, offBus: (message: BusMessage) => void, name?: () => string): BusTransport;
39
+ export declare function overseerBusTransport(mirror: () => MirrorStreamServer | null, offBus: (message: BusMessage) => BusSendResult | void, name?: () => string): BusTransport;
38
40
  export declare function setBusTransport(transport: BusTransport): void;
39
41
  export declare function clearBusTransport(): void;
40
42
  export declare function getBusTransport(): BusTransport | null;
@@ -22,12 +22,26 @@ function heldAnswer(sent, to, answers) {
22
22
  return null;
23
23
  return answers ? `${sent.notice} Its answer comes back to you as a message from pane ${to}.` : sent.notice;
24
24
  }
25
+ /**
26
+ * Whether TEXT is, or reads after its leading blanks as, a pane control command ({"__ztc_cmd":...}): what the ZTC that
27
+ * runs the workspace sends a pane to change its model or effort, or to answer its question or hook, which a pane takes
28
+ * from bus member 0 and from its parent's stdin as its owner's.
29
+ */
30
+ function isPaneControlLine(text) {
31
+ return text.trimStart().startsWith('{"__ztc_cmd":');
32
+ }
33
+ /** What Main's agent is told of a message that is a pane control command: refused, nothing sent. */
34
+ const PANE_CONTROL_REFUSAL = { ok: false, status: 400, code: 'control_command',
35
+ error: 'A message can\'t be a pane control command ({"__ztc_cmd":...}): only the ZTC that runs this workspace sends those, '
36
+ + 'never its agent. Say it in words.' };
25
37
  /**
26
38
  * The bus transport of the ZTC that runs the bus (Main, bus member 0). It sends as Main through the mirror it runs at
27
39
  * the time (MIRROR): the one it started with, or the one /mirror start started, whose bus its panes' mirror clients
28
40
  * rejoin; never one /mirror stop stopped, whose bus is gone. It says what the mirror did with the message, as /bus/send
29
41
  * answers a pane. While it runs none, OFF_BUS gets the message, which the owner types into the panes it is for, and it
30
- * says nothing.
42
+ * says what OFF_BUS says: nothing, or a refusal. Either way the message goes to agents alone, as a pane's own does: a
43
+ * shell or a command pane, which would run it as a command, is refused (not_an_agent). A message that is a pane control
44
+ * command ({"__ztc_cmd":...}), which a pane takes from Main as its owner's, is refused before it goes anywhere.
31
45
  *
32
46
  * NAME is what Main is called as each message leaves: the name its pane goes by, which list_panes and the pane's header
33
47
  * give it, "Main" or the one /rename gave it, so an agent that reads the message can answer Main by it.
@@ -35,11 +49,15 @@ function heldAnswer(sent, to, answers) {
35
49
  export function overseerBusTransport(mirror, offBus, name = () => 'Main') {
36
50
  return {
37
51
  sendBusMessage: (to, text, type = 'ztc_message') => {
52
+ // Main's agent speaks as Main, bus member 0, as the ZTC that runs the workspace sends its panes their control
53
+ // commands: a message that is one is no message of its agent's, and goes nowhere.
54
+ if (isPaneControlLine(text))
55
+ return PANE_CONTROL_REFUSAL;
38
56
  const message = { id: randomUUID(), from: { id: 0, name: name() }, to, type, text };
39
57
  const server = mirror();
40
58
  if (server)
41
- return server.busSendResult(server.deliverBusMessage(message), to);
42
- offBus(message);
59
+ return server.busSendResult(server.deliverBusMessage(message, { agentsOnly: true }), to);
60
+ return offBus(message);
43
61
  },
44
62
  getPaneId() { return 0; },
45
63
  getPaneName() { return name(); },
@@ -29,6 +29,8 @@ function workerBrief(task, context, toolContext) {
29
29
  ].join('\n\n');
30
30
  }
31
31
  export const delegateTaskTool = {
32
+ // Its workers run their commands through run_command, under this agent's policy (see Tool.confinedCommands).
33
+ confinedCommands: true,
32
34
  capabilities: [ToolCapability.FILE_READ, ToolCapability.SHELL_EXEC],
33
35
  definition: {
34
36
  name: 'delegate_task',
@@ -1,4 +1,5 @@
1
1
  import { Tool, ToolContext } from './types.js';
2
+ import { type OpenAdmission } from '../../utils/admitted_open.js';
2
3
  export declare function resolvePath(path: string, context?: ToolContext): string;
3
4
  /**
4
5
  * A tool's `path` argument as the policy judged it: a string. Another value is refused, never turned into a path:
@@ -8,6 +9,14 @@ export declare function stringPathArgument(args: Record<string, unknown>, tool:
8
9
  /** The path the runtime's write admission checks for a resolved tool path: in Docker mode, relative to the
9
10
  * container's working directory, as the host policy sees a relative `path` there. */
10
11
  export declare function writeAdmissionPath(path: string): string;
12
+ /**
13
+ * How a file tool opens the paths an agent names under a profile that limits it: checking after the open that it holds
14
+ * the file the policy admitted (utils/admitted_open.ts), with the runtime's admission of the real path, and that the
15
+ * file is not one of ZTC's own under another name, a hard link into its config, approvals or sessions, which the
16
+ * policy's check of the path cannot see (utils/ztc_own_state.ts). Undefined where it opens them as before: under any
17
+ * other profile, in Docker mode, and on Windows, which has no O_NOFOLLOW.
18
+ */
19
+ export declare function openAdmission(context: ToolContext | undefined, label?: string): OpenAdmission | undefined;
11
20
  /**
12
21
  * Admit a write of `path` once more, inside its path lock and just before the write: the filesystem may have changed
13
22
  * since dispatch (a directory swapped for a symlink that leads out).
@@ -34,7 +43,9 @@ export declare function readRawFile(path: string): Promise<string>;
34
43
  */
35
44
  export declare function updateFileAtomic(path: string, mutate: (content: string) => string,
36
45
  /** Runs inside the lock before the read: the caller's last admission of the write. */
37
- admit?: () => Promise<void>): Promise<{
46
+ admit?: () => Promise<void>,
47
+ /** Under a profile that limits the agent (openAdmission): read and write only what the policy admitted. */
48
+ admission?: OpenAdmission): Promise<{
38
49
  before: string;
39
50
  after: string;
40
51
  sha256: string;
@@ -1,8 +1,9 @@
1
- import { readFile, readdir, stat } from 'fs/promises';
1
+ import { readFile, readdir, realpath, stat } from 'fs/promises';
2
2
  import { basename, dirname, resolve, posix } from 'path';
3
3
  import { homedir } from 'os';
4
4
  import { createHash, randomBytes } from 'crypto';
5
5
  import { exec } from 'child_process';
6
+ import { buildUserSubprocessEnv } from '../../utils/subprocess_env.js';
6
7
  import { promisify } from 'util';
7
8
  import { ToolCapability } from '../runtime/capabilities.js';
8
9
  import { buildSimpleDiff, buildSimpleDiffMeta } from '../../utils/diff.js';
@@ -12,6 +13,10 @@ import { writeFileAtomic } from '../../utils/atomic_write.js';
12
13
  import { withPathLock } from '../../utils/path_lock.js';
13
14
  import { imageType } from '../../session_media.js';
14
15
  import { fitImage, IMAGE_MAX_PX } from '../../utils/image_fit.js';
16
+ import { profileLimitsAgent } from '../../config/profile_limits.js';
17
+ import { ztcOwnStateHoldingForRead, ztcOwnStateLinkCheck } from '../../utils/ztc_own_state.js';
18
+ import { readAdmittedFile, realFolderPath, writeAdmittedFileAtomic } from '../../utils/admitted_open.js';
19
+ import { canonicalPath } from '../../utils/canonical_path.js';
15
20
  const execAsync = promisify(exec);
16
21
  // Docker execution mode - mirrors shell.ts
17
22
  const DOCKER_CONTAINER = process.env.ZTC_DOCKER_CONTAINER;
@@ -27,7 +32,7 @@ function shellEscape(str) {
27
32
  */
28
33
  async function dockerExec(command) {
29
34
  const fullCmd = `docker exec ${DOCKER_CONTAINER} bash -c ${shellEscape(command)}`;
30
- return execAsync(fullCmd, { maxBuffer: 10 * 1024 * 1024 });
35
+ return execAsync(fullCmd, { maxBuffer: 10 * 1024 * 1024, env: buildUserSubprocessEnv() });
31
36
  }
32
37
  async function dockerWriteAtomic(path, content) {
33
38
  const b64Content = Buffer.from(content).toString('base64');
@@ -151,6 +156,35 @@ async function filePathTarget(args, context) {
151
156
  return [];
152
157
  return [{ path: writeAdmissionPath(resolvePath(String(args.path), context)), label: String(args.path) }];
153
158
  }
159
+ /**
160
+ * How a file tool opens the paths an agent names under a profile that limits it: checking after the open that it holds
161
+ * the file the policy admitted (utils/admitted_open.ts), with the runtime's admission of the real path, and that the
162
+ * file is not one of ZTC's own under another name, a hard link into its config, approvals or sessions, which the
163
+ * policy's check of the path cannot see (utils/ztc_own_state.ts). Undefined where it opens them as before: under any
164
+ * other profile, in Docker mode, and on Windows, which has no O_NOFOLLOW.
165
+ */
166
+ export function openAdmission(context, label) {
167
+ if (DOCKER_CONTAINER || process.platform === 'win32'
168
+ || !profileLimitsAgent(context?.commandPolicy?.profile, context?.commandPolicy?.sandbox))
169
+ return undefined;
170
+ const ownStateLink = ztcOwnStateLinkCheck();
171
+ return {
172
+ read: path => context?.admitReads?.([path]),
173
+ write: path => context?.admitWrites?.([{ path, label: label ?? path }]),
174
+ identity: async (path, file) => {
175
+ const holding = await ownStateLink(file);
176
+ if (holding !== null) {
177
+ throw new Error(`Permission denied: ${path} is a hard link to a file in ZTC's own state (${holding}), `
178
+ + 'which no profile that limits the agent reaches');
179
+ }
180
+ },
181
+ };
182
+ }
183
+ /** Whether ERROR says a path is not there (a file not made yet, or a folder of it that is a file). */
184
+ function missing(error) {
185
+ const code = error.code;
186
+ return code === 'ENOENT' || code === 'ENOTDIR';
187
+ }
154
188
  /**
155
189
  * Admit a write of `path` once more, inside its path lock and just before the write: the filesystem may have changed
156
190
  * since dispatch (a directory swapped for a symlink that leads out).
@@ -226,17 +260,27 @@ export const readFileTool = {
226
260
  let size;
227
261
  // Number text content for the model; leave hex/base64 dumps as raw blobs.
228
262
  let numberize = true;
263
+ // Under a profile that limits the agent: only the file the policy admitted, checked after the open.
264
+ const admission = openAdmission(context);
265
+ let admitted;
229
266
  try {
230
267
  if (DOCKER_CONTAINER) {
231
268
  const { stdout: sizeOut } = await dockerExec(`stat -c %s ${shellEscape(path)} 2>/dev/null || stat -f %z ${shellEscape(path)}`);
232
269
  size = parseInt(sizeOut.trim(), 10) || 0;
233
270
  }
271
+ else if (admission) {
272
+ const opened = await readAdmittedFile(path, admission, { maxBytes: READ_FILE_MAX_BYTES, tooLarge: bytes => new Error(sizeGuardError(bytes)) });
273
+ admitted = opened.data;
274
+ size = opened.size;
275
+ }
234
276
  else {
235
277
  const stats = await stat(path);
236
278
  size = stats.size;
237
279
  }
238
280
  }
239
281
  catch (err) {
282
+ if (err.message.startsWith('File too large to read'))
283
+ throw err;
240
284
  throw new Error(`Failed to read file: ${err.message}`);
241
285
  }
242
286
  if (size > READ_FILE_MAX_BYTES) {
@@ -250,7 +294,7 @@ export const readFileTool = {
250
294
  size = content.length;
251
295
  }
252
296
  else {
253
- const raw = await readFile(path);
297
+ const raw = admitted ?? await readFile(path);
254
298
  numberize = expectsText;
255
299
  // An image file is returned as an image, the envelope screenshots use,
256
300
  // so the model sees it and the transcript draws it. An explicit
@@ -420,6 +464,28 @@ export const writeFileTool = {
420
464
  const { mkdir } = await import('fs/promises');
421
465
  const written = await withPathLock(path, async () => {
422
466
  await admitLockedWrite(path, String(args.path), context);
467
+ // Under a profile that limits the agent: read and write only the files the policy admitted, in the folder the
468
+ // path's parent really is, checked after each open (utils/admitted_open.ts).
469
+ const admission = openAdmission(context, String(args.path));
470
+ if (admission) {
471
+ await mkdir(canonicalPath(dirname(path)), { recursive: true });
472
+ const target = await realFolderPath(path);
473
+ let before = '';
474
+ try {
475
+ before = (await readAdmittedFile(target, admission, { admit: 'write' })).data.toString('utf-8');
476
+ }
477
+ catch (error) {
478
+ if (!missing(error))
479
+ throw error;
480
+ }
481
+ const intended = append ? before + content : content;
482
+ const placed = await writeAdmittedFileAtomic(target, intended, admission);
483
+ const onDisk = (await readAdmittedFile(placed, admission, { admit: 'write' })).data.toString('utf-8');
484
+ if (onDisk !== intended) {
485
+ throw new Error(`write_file: verification failed for ${path}: content on disk does not match the intended result`);
486
+ }
487
+ return { before, after: intended };
488
+ }
423
489
  await mkdir(dirname(path), { recursive: true });
424
490
  let before = '';
425
491
  try {
@@ -524,13 +590,19 @@ function parseBooleanFlag(value) {
524
590
  */
525
591
  export async function updateFileAtomic(path, mutate,
526
592
  /** Runs inside the lock before the read: the caller's last admission of the write. */
527
- admit) {
593
+ admit,
594
+ /** Under a profile that limits the agent (openAdmission): read and write only what the policy admitted. */
595
+ admission) {
528
596
  return withPathLock(path, async () => {
529
597
  await admit?.();
530
- const before = await readRawFile(path);
598
+ // The file in the folder the path's parent really is, opened and replaced only as the policy admitted it.
599
+ const target = admission ? await realFolderPath(path) : path;
600
+ const read = async (file) => admission
601
+ ? (await readAdmittedFile(file, admission, { admit: 'write' })).data.toString('utf-8') : readRawFile(file);
602
+ const before = await read(target);
531
603
  const after = mutate(before);
532
- await writeRawFile(path, after);
533
- const onDisk = await readRawFile(path);
604
+ const placed = admission ? await writeAdmittedFileAtomic(target, after, admission) : (await writeRawFile(path, after), path);
605
+ const onDisk = await read(placed);
534
606
  if (onDisk !== after) {
535
607
  throw new Error(`file write verification failed for ${path}: content on disk does not match the intended result `
536
608
  + `(expected sha256 ${sha256(after)}, found ${sha256(onDisk)}). Another writer may have modified the file; `
@@ -578,7 +650,7 @@ export const editFileTool = {
578
650
  let after;
579
651
  let digest;
580
652
  try {
581
- const updated = await updateFileAtomic(path, content => applyExactReplace(content, args.old_string, args.new_string, replaceAll), () => admitLockedWrite(path, String(args.path), context));
653
+ const updated = await updateFileAtomic(path, content => applyExactReplace(content, args.old_string, args.new_string, replaceAll), () => admitLockedWrite(path, String(args.path), context), openAdmission(context, String(args.path)));
582
654
  before = updated.before;
583
655
  after = updated.after;
584
656
  digest = updated.sha256;
@@ -672,7 +744,8 @@ export const listDirectoryTool = {
672
744
  throw new Error(`Failed to list directory: ${err.message}`);
673
745
  }
674
746
  }
675
- // Local mode: use fs
747
+ // Local mode: use fs. Under a profile that limits the agent, a recursive listing does not go into ZTC's own state.
748
+ const ownStateHidden = profileLimitsAgent(context?.commandPolicy?.profile, context?.commandPolicy?.sandbox);
676
749
  let truncated = false;
677
750
  let totalEntries = 0;
678
751
  async function listDir(dir, depth = 0) {
@@ -694,7 +767,8 @@ export const listDirectoryTool = {
694
767
  const s = await stat(entryPath);
695
768
  info.size = s.size;
696
769
  }
697
- if (recursive && entry.isDirectory() && !entry.name.startsWith('.')) {
770
+ if (recursive && entry.isDirectory() && !entry.name.startsWith('.')
771
+ && !(ownStateHidden && ztcOwnStateHoldingForRead(entryPath) !== null)) {
698
772
  info.children = await listDir(entryPath, depth + 1);
699
773
  }
700
774
  results.push(info);
@@ -702,7 +776,14 @@ export const listDirectoryTool = {
702
776
  return results;
703
777
  }
704
778
  try {
705
- const entries = await listDir(path);
779
+ // Under a profile that limits the agent: the folder the policy admitted, which the path must still lead to after.
780
+ const admission = openAdmission(context);
781
+ const listed = admission ? await realpath(path) : path;
782
+ admission?.read(listed);
783
+ const entries = await listDir(listed);
784
+ if (admission && await realpath(path).catch(() => null) !== listed) {
785
+ throw new Error(`${path} changed while ZTC listed it (a link in it now leads elsewhere); nothing was listed`);
786
+ }
706
787
  return JSON.stringify({ path, entries, total_entries: totalEntries, truncated });
707
788
  }
708
789
  catch (err) {
@@ -5,6 +5,18 @@
5
5
  * for precise code navigation and analysis.
6
6
  */
7
7
  import { Tool } from './types.js';
8
+ import type { Policy } from '../runtime/policy.js';
9
+ /**
10
+ * Stops the language servers the LSP tools started (shutdownLSPManager) where PERMISSIONS, those the agent is built under
11
+ * again (POLICY), differ from the ones it was last built under and don't admit those tools without asking anyone. A
12
+ * language server keeps running the workspace's code outside any OS sandbox, rebuilding it as it changes: one started
13
+ * under trusted ran on after a switch to workspace_autonomous, which starts no program of the agent's outside its
14
+ * sandbox, while the agent's sandboxed commands could change what it built next (the reviewer's recheck, 2026-11-23). The
15
+ * next LSP call a later profile admits starts one again. The agent built again under the same permissions (a /model
16
+ * switch, a /cd) keeps the servers: one the person approved under permissions that ask stopped at every such build (the
17
+ * reviewer's recheck of round 2, 2026-11-23).
18
+ */
19
+ export declare function stopLanguageServersUnlessAdmitted(policy: Policy, permissions: string): void;
8
20
  export declare const gotoDefinitionTool: Tool;
9
21
  export declare const findReferencesTool: Tool;
10
22
  export declare const hoverTool: Tool;
@@ -5,7 +5,54 @@
5
5
  * for precise code navigation and analysis.
6
6
  */
7
7
  import { resolve } from 'path';
8
- import { getLSPManager, LSP_SERVERS, DiagnosticSeverity } from '../../lsp/index.js';
8
+ import { ToolCapability } from '../runtime/capabilities.js';
9
+ import { getLSPManager, shutdownLSPManager, LSP_SERVERS, DiagnosticSeverity } from '../../lsp/index.js';
10
+ /**
11
+ * What each LSP tool declares. It reads the file it names, which the runtime admits as read_file's path (admittedFile),
12
+ * and it starts a language server, which runs the workspace's code (a crate's build script and proc macros, a project's
13
+ * plugins) outside any OS sandbox (src/lsp/client.ts): a program of the workspace's choosing, not ZTC's. So a profile
14
+ * that runs no command, writes nothing, or runs the agent's commands only inside an OS sandbox neither offers nor admits
15
+ * these tools (startsProgramsOutsideSandbox), and one that asks before each command asks. Declaring none let a pinned
16
+ * hosted thread's diagnostics call run a build.rs that wrote outside its workspace (the reviewer's probe, 2026-11-22).
17
+ */
18
+ function lspCapabilities() {
19
+ return [ToolCapability.FILE_READ, ToolCapability.SHELL_EXEC];
20
+ }
21
+ /** The permissions the agent was last built under (stopLanguageServersUnlessAdmitted), as its caller spells them. */
22
+ let languageServersBuiltUnder;
23
+ /**
24
+ * Stops the language servers the LSP tools started (shutdownLSPManager) where PERMISSIONS, those the agent is built under
25
+ * again (POLICY), differ from the ones it was last built under and don't admit those tools without asking anyone. A
26
+ * language server keeps running the workspace's code outside any OS sandbox, rebuilding it as it changes: one started
27
+ * under trusted ran on after a switch to workspace_autonomous, which starts no program of the agent's outside its
28
+ * sandbox, while the agent's sandboxed commands could change what it built next (the reviewer's recheck, 2026-11-23). The
29
+ * next LSP call a later profile admits starts one again. The agent built again under the same permissions (a /model
30
+ * switch, a /cd) keeps the servers: one the person approved under permissions that ask stopped at every such build (the
31
+ * reviewer's recheck of round 2, 2026-11-23).
32
+ */
33
+ export function stopLanguageServersUnlessAdmitted(policy, permissions) {
34
+ if (permissions === languageServersBuiltUnder)
35
+ return;
36
+ languageServersBuiltUnder = permissions;
37
+ const decision = policy.evaluateTool({ name: 'lsp_status', args: {}, capabilities: lspCapabilities() });
38
+ if (decision.allowed && decision.approvalRequired !== true)
39
+ return;
40
+ void shutdownLSPManager().catch(() => { });
41
+ }
42
+ /** FILE resolved against the agent's folder, once the runtime admits reading it (ToolContext.admitReads), or it throws. */
43
+ function admittedFile(file, context, cwd) {
44
+ const filePath = resolve(cwd, file);
45
+ context?.admitReads?.([filePath]);
46
+ return filePath;
47
+ }
48
+ /**
49
+ * The file a call of TOOL_NAME names, resolved as its execution resolves it (Tool.readPaths): the runtime admits it as
50
+ * read_file's path before anyone is asked about the call, so a profile that asks first (ask_before_mutation,
51
+ * tests_allowed) refuses a file outside its roots without asking.
52
+ */
53
+ function lspReadPaths(toolName) {
54
+ return (args, context) => [resolve(context?.cwd || process.cwd(), requireStringArg(args, 'file', toolName))];
55
+ }
9
56
  function requireStringArg(args, name, toolName) {
10
57
  const value = args[name];
11
58
  if (typeof value !== 'string' || value.trim().length === 0) {
@@ -25,6 +72,8 @@ function requirePositiveIntegerArg(args, name, toolName) {
25
72
  // Goto Definition Tool
26
73
  // ============================================================================
27
74
  export const gotoDefinitionTool = {
75
+ capabilities: lspCapabilities(),
76
+ readPaths: lspReadPaths('goto_definition'),
28
77
  definition: {
29
78
  name: 'goto_definition',
30
79
  description: `Find where a symbol is defined using the Language Server Protocol.
@@ -56,7 +105,7 @@ Supported languages: Rust, TypeScript/JavaScript, Python, C/C++, Go`,
56
105
  const file = requireStringArg(args, 'file', 'goto_definition');
57
106
  const line = requirePositiveIntegerArg(args, 'line', 'goto_definition');
58
107
  const column = requirePositiveIntegerArg(args, 'column', 'goto_definition');
59
- const filePath = resolve(cwd, file);
108
+ const filePath = admittedFile(file, context, cwd);
60
109
  try {
61
110
  const manager = getLSPManager(cwd);
62
111
  const locations = await manager.gotoDefinition(filePath, line, column);
@@ -91,6 +140,8 @@ Supported languages: Rust, TypeScript/JavaScript, Python, C/C++, Go`,
91
140
  // Find References Tool
92
141
  // ============================================================================
93
142
  export const findReferencesTool = {
143
+ capabilities: lspCapabilities(),
144
+ readPaths: lspReadPaths('find_references'),
94
145
  definition: {
95
146
  name: 'find_references',
96
147
  description: `Find all references to a symbol using the Language Server Protocol.
@@ -122,7 +173,7 @@ Supported languages: Rust, TypeScript/JavaScript, Python, C/C++, Go`,
122
173
  const file = requireStringArg(args, 'file', 'find_references');
123
174
  const line = requirePositiveIntegerArg(args, 'line', 'find_references');
124
175
  const column = requirePositiveIntegerArg(args, 'column', 'find_references');
125
- const filePath = resolve(cwd, file);
176
+ const filePath = admittedFile(file, context, cwd);
126
177
  try {
127
178
  const manager = getLSPManager(cwd);
128
179
  const locations = await manager.findReferences(filePath, line, column);
@@ -157,6 +208,8 @@ Supported languages: Rust, TypeScript/JavaScript, Python, C/C++, Go`,
157
208
  // Hover Tool
158
209
  // ============================================================================
159
210
  export const hoverTool = {
211
+ capabilities: lspCapabilities(),
212
+ readPaths: lspReadPaths('hover'),
160
213
  definition: {
161
214
  name: 'hover',
162
215
  description: `Get type information and documentation for a symbol at a position.
@@ -187,7 +240,7 @@ Supported languages: Rust, TypeScript/JavaScript, Python, C/C++, Go`,
187
240
  const file = requireStringArg(args, 'file', 'hover');
188
241
  const line = requirePositiveIntegerArg(args, 'line', 'hover');
189
242
  const column = requirePositiveIntegerArg(args, 'column', 'hover');
190
- const filePath = resolve(cwd, file);
243
+ const filePath = admittedFile(file, context, cwd);
191
244
  try {
192
245
  const manager = getLSPManager(cwd);
193
246
  const hoverInfo = await manager.hover(filePath, line, column);
@@ -229,6 +282,8 @@ function severityToString(severity) {
229
282
  }
230
283
  }
231
284
  export const diagnosticsTool = {
285
+ capabilities: lspCapabilities(),
286
+ readPaths: lspReadPaths('diagnostics'),
232
287
  definition: {
233
288
  name: 'diagnostics',
234
289
  description: `Get compiler errors, warnings, and other diagnostics for a file.
@@ -249,7 +304,7 @@ Supported languages: Rust, TypeScript/JavaScript, Python, C/C++, Go`,
249
304
  execute: async (args, context) => {
250
305
  const cwd = context?.cwd || process.cwd();
251
306
  const file = requireStringArg(args, 'file', 'diagnostics');
252
- const filePath = resolve(cwd, file);
307
+ const filePath = admittedFile(file, context, cwd);
253
308
  try {
254
309
  const manager = getLSPManager(cwd);
255
310
  const diagnostics = await manager.getDiagnostics(filePath);
@@ -293,6 +348,7 @@ Supported languages: Rust, TypeScript/JavaScript, Python, C/C++, Go`,
293
348
  // LSP Status Tool
294
349
  // ============================================================================
295
350
  export const lspStatusTool = {
351
+ capabilities: lspCapabilities(),
296
352
  definition: {
297
353
  name: 'lsp_status',
298
354
  description: `Check the status of language servers.
@@ -1,4 +1,5 @@
1
1
  import { configStore } from '../../config.js';
2
+ import { permissionPinChildEnv } from '../../config/permission_pin.js';
2
3
  import { isRetiredModel, isRetiredProvider, retiredProviderMessage, ROUTE_AWAITS_A_CHOICE } from '../../config/retired_routes.js';
3
4
  /**
4
5
  * Terminal pane management tools for zmux mode.
@@ -9,18 +10,18 @@ import { isRetiredModel, isRetiredProvider, retiredProviderMessage, ROUTE_AWAITS
9
10
  */
10
11
  import { randomUUID } from 'node:crypto';
11
12
  import { ToolCapability } from '../runtime/capabilities.js';
12
- import { existsSync } from 'fs';
13
- import { basename, isAbsolute, resolve } from 'path';
14
- import { isRatatuiBinaryAvailable } from '../../ui/ratatui/process.js';
13
+ import { basename } from 'path';
14
+ import { isRatatuiBinaryAvailable, ztcPaneRendererMissing } from '../../ui/ratatui/process.js';
15
+ import { CHILD_ZTC_SCRIPT_RE, resolveChildZtcEntrypoint } from '../../ui/ratatui/ztc_launch_trust.js';
15
16
  import { CAPABILITY_PANE_DELIVERY_ACK } from '../../ui/ratatui/protocol.js';
16
17
  import { paneReadRefusal } from '../../ui/ratatui/screen_privacy.js';
17
18
  import { generateSessionId } from '../../session.js';
18
19
  import { isPaneProvider, resolveModelAndProvider } from '../../panes/model_catalog.js';
19
- import { buildZtcPaneLaunchCommand, createZtcLaunchSpec } from '../../panes/ztc_launch.js';
20
+ import { buildZtcPaneLaunchCommand, createZtcLaunchSpec, ztcPaneRoutingRefusal } from '../../panes/ztc_launch.js';
20
21
  import { PANE_TASK_AS_MESSAGE_ENV } from '../../panes/initial_input.js';
21
22
  import { keylessZtcPaneRoute, ztcPaneSignInNeeded } from '../../panes/worker_route.js';
22
23
  import { newPaneRoute } from '../commands/runtime_model.js';
23
- import { buildUserSubprocessEnvOverrides } from '../../utils/subprocess_env.js';
24
+ import { buildUserSubprocessEnvOverrides, hostRouterGrantBlank, hostRouterGrantDiscovery } from '../../utils/subprocess_env.js';
24
25
  export { resolveModelAndProvider };
25
26
  // --- Callback-based TUI process access ---
26
27
  let tuiProcessRef = null;
@@ -351,45 +352,6 @@ function shortTitle(prefix, value, maxLength = 44) {
351
352
  ? `${combined.slice(0, maxLength - 3)}...`
352
353
  : combined;
353
354
  }
354
- const CHILD_ZTC_SCRIPT_RE = /(^|[\\/])cli_(main|ratatui)\.(js|ts)$/;
355
- const PROCESS_START_CWD = process.cwd();
356
- function resolveChildZtcEntrypoint() {
357
- const override = process.env.ZTC_CHILD_ENTRYPOINT?.trim();
358
- if (override) {
359
- const resolved = resolve(override);
360
- if (existsSync(resolved)) {
361
- return resolved;
362
- }
363
- }
364
- const currentEntrypoint = process.argv[1] || '';
365
- if (currentEntrypoint && CHILD_ZTC_SCRIPT_RE.test(currentEntrypoint)) {
366
- if (isAbsolute(currentEntrypoint)) {
367
- return currentEntrypoint;
368
- }
369
- const roots = [
370
- PROCESS_START_CWD,
371
- process.env.INIT_CWD,
372
- process.env.PWD,
373
- process.cwd(),
374
- ].filter((value) => !!value);
375
- for (const root of roots) {
376
- const candidate = resolve(root, currentEntrypoint);
377
- if (existsSync(candidate)) {
378
- return candidate;
379
- }
380
- }
381
- }
382
- const candidates = [
383
- resolve(process.cwd(), 'src', 'cli_main.ts'),
384
- resolve(process.cwd(), 'dist', 'cli_main.js'),
385
- ];
386
- for (const candidate of candidates) {
387
- if (existsSync(candidate)) {
388
- return candidate;
389
- }
390
- }
391
- return null;
392
- }
393
355
  function filterChildZtcArgs(args) {
394
356
  const skipFlags = new Set([
395
357
  '--desktop',
@@ -469,6 +431,14 @@ export function withChildZtcFlags(args, flags) {
469
431
  export function childZtcPaneEnv() {
470
432
  const env = {
471
433
  ZTC_PARENT_PID: String(process.pid),
434
+ // The renderer that starts the pane holds this process's environment: the pane keeps a host's Router runtime grant
435
+ // that takes effect, which it routes on as this process does, and gets none that doesn't. With the grant, it imports
436
+ // no plugin from where an agent writes (hostRouterGrantDiscovery).
437
+ ...hostRouterGrantBlank(),
438
+ ...hostRouterGrantDiscovery(),
439
+ // Under the host's pin of the permission settings the pane pins its own, whatever this process's environment says
440
+ // now (config/permission_pin.ts).
441
+ ...permissionPinChildEnv(configStore.permissionsPinned()),
472
442
  };
473
443
  if (process.env.ZTC_MIRROR_PORT) {
474
444
  env.ZTC_MIRROR_PORT = process.env.ZTC_MIRROR_PORT;
@@ -500,7 +470,7 @@ function isLegacyChildZtcLaunch(command, args) {
500
470
  }
501
471
  export function buildChildZtcPaneLaunch(extraArgs = [], childSessionId = generateSessionId(), options) {
502
472
  if (!isRatatuiBinaryAvailable()) {
503
- return new Error('Error: ZTC child panes require the Rust ztc-tui binary. Build it with `cd packages/ztc-tui && cargo build --release`.');
473
+ return new Error(`Error: ${ztcPaneRendererMissing()}`);
504
474
  }
505
475
  const scriptPath = options?.entrypoint || resolveChildZtcEntrypoint() || '';
506
476
  if (!scriptPath) {
@@ -801,6 +771,11 @@ export const createZtcPaneTool = {
801
771
  // A child on a provider this run's own --provider didn't choose would choose it for a waiting profile.
802
772
  if (configStore.routeAwaitingChoice(provider) !== undefined)
803
773
  return `Error: ${ROUTE_AWAITS_A_CHOICE}`;
774
+ // A pane runs on its provider's routing: one off the routing ZTC_LLM_AUTH_MODE pins (a local login under zrouter)
775
+ // opens nothing. One a --provider among extra_args names is refused as its launch is built.
776
+ const offRouting = ztcPaneRoutingRefusal(provider);
777
+ if (offRouting)
778
+ return `Error: No ZTC pane was opened: ${offRouting}`;
804
779
  const started = configStore.getNewPaneRoute();
805
780
  const routed = newPaneRoute(configStore, { ...started, provider, model: model ?? started.model }).routed;
806
781
  if (!routed && !configStore.getApiKey(provider)) {
@@ -1,5 +1,8 @@
1
1
  import { indexProjectContext, queryProjectContext, PROJECT_CONTEXT_INDEX_PATH } from '../../context/project_intelligence.js';
2
+ import { ownStateLinkGuard } from '../../utils/ztc_own_state.js';
2
3
  import { ToolCapability } from '../runtime/capabilities.js';
4
+ /** Under a profile that limits the agent, no file the index reads is one of ZTC's own under another name (a hard link). */
5
+ const readOptions = (context) => ({ ownStateLink: ownStateLinkGuard(context.commandPolicy) });
3
6
  const pathParameters = {
4
7
  path: { type: 'string', enum: [PROJECT_CONTEXT_INDEX_PATH], description: 'The project-local index file.' },
5
8
  paths: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 16, description: 'Explicit project-relative source paths; also bounds live source checks.' },
@@ -23,7 +26,7 @@ export const indexProjectContextTool = {
23
26
  execute: async (args, context) => {
24
27
  if (!context)
25
28
  throw new TypeError('Project context requires an execution context');
26
- return JSON.stringify(await indexProjectContext(context.cwd, paths(args)));
29
+ return JSON.stringify(await indexProjectContext(context.cwd, paths(args), readOptions(context)));
27
30
  },
28
31
  };
29
32
  export const queryProjectContextTool = {
@@ -40,6 +43,6 @@ export const queryProjectContextTool = {
40
43
  throw new TypeError('Project context requires an execution context');
41
44
  if (typeof args.query !== 'string')
42
45
  throw new TypeError('Project context query must be text');
43
- return JSON.stringify(await queryProjectContext(context.cwd, args.query, paths(args)));
46
+ return JSON.stringify(await queryProjectContext(context.cwd, args.query, paths(args), readOptions(context)));
44
47
  },
45
48
  };