@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
@@ -13,7 +13,7 @@ import { recallToolResponseTool } from '../tools/recall_tool_response.js';
13
13
  import { sessionEvidenceTool } from '../tools/session_evidence.js';
14
14
  import { parseVerificationRequest } from './source_verification_contract.js';
15
15
  import { readCommandTool, runCommandTool, stopCommandTool } from '../tools/shell.js';
16
- import { ztcCommandCapabilities, ztcCommandTool } from '../tools/ztc_command.js';
16
+ import { ztcCommandCapabilities, ztcCommandConfined, ztcCommandTool } from '../tools/ztc_command.js';
17
17
  import { verifyArtifactTool } from '../tools/verify_artifact.js';
18
18
  import { benchmarkCPUTool } from '../tools/benchmark_cpu.js';
19
19
  import { compareBenchmarksTool } from '../tools/compare_benchmarks.js';
@@ -97,6 +97,19 @@ function prependMessages(base, messages) {
97
97
  // An image result keeps its image: the words go before its description.
98
98
  return base ? withToolResultNote(base, '', `${prefix}\n`) : prefix;
99
99
  }
100
+ /**
101
+ * What leads a hook's note: a paragraph of its own after a tool's result, failed or not, so the result stays as the tool
102
+ * gave it (a JSON one still parses from its start), or after the refusal of a call a PreToolUse hook's failure kept from
103
+ * running.
104
+ */
105
+ const HOOK_NOTE = '\n\n[hook] ';
106
+ /** CONTENT with MESSAGES after it as a hook's note (HOOK_NOTE). An image result keeps its image: the note goes with its text. */
107
+ function appendHookNote(content, messages) {
108
+ if (messages.length === 0)
109
+ return content;
110
+ const note = `${HOOK_NOTE}${buildHookText(messages)}`;
111
+ return content ? withToolResultNote(content, note) : note.trimStart();
112
+ }
100
113
  // Global output cap: prevent any single tool result from dominating the context window. Claude Code caps at ~100K
101
114
  // chars; we use 80K (~20K tokens). The model gets the head + tail of large outputs to preserve both the beginning
102
115
  // (headers, structure) and end (final status, errors).
@@ -192,6 +205,9 @@ export async function executeToolWithRuntime(name, args, options) {
192
205
  const requiredCapabilities = (input) => (sourceTool === runCommandTool && Object.hasOwn(input, 'verification')
193
206
  ? [...new Set([...ordinaryCapabilities, ToolCapability.FILE_READ])]
194
207
  : callCapabilities(input));
208
+ // Whether the call starts nothing of the agent's outside run_command's OS sandbox (Tool.confinedCommands). ztc_command
209
+ // runs no program itself: a command that does declares it (ztcCommandConfined), and that call is judged by it.
210
+ const confinedCall = (input) => (sourceTool === ztcCommandTool ? ztcCommandConfined(input) : tool?.confinedCommands === true);
195
211
  let capabilities = requiredCapabilities(args);
196
212
  let effectiveArgs = args;
197
213
  let approvalGranted = false;
@@ -251,8 +267,11 @@ export async function executeToolWithRuntime(name, args, options) {
251
267
  capabilities = requiredCapabilities(effectiveArgs);
252
268
  }
253
269
  if (preHook.failed || preHook.decision === 'deny') {
270
+ const refusal = preHook.decisionReason || preHook.failureReason || `Tool denied by PreToolUse hook: ${name}`;
254
271
  return {
255
- content: prependMessages(preHook.decisionReason || preHook.failureReason || `Tool denied by PreToolUse hook: ${name}`, preMessages),
272
+ // A hook that denies the call blocks it, with its refusal as the result. One that failed without denying it keeps
273
+ // the tool from running too, and the hook's failure follows the refusal as its note.
274
+ content: preHook.decision === 'deny' ? prependMessages(refusal, preMessages) : appendHookNote(refusal, preMessages),
256
275
  isError: true,
257
276
  effectiveArgs,
258
277
  };
@@ -296,10 +315,128 @@ export async function executeToolWithRuntime(name, args, options) {
296
315
  const mutatesHostState = capabilities.includes(ToolCapability.FILE_WRITE)
297
316
  || capabilities.includes(ToolCapability.SHELL_EXEC)
298
317
  || capabilities.includes(ToolCapability.COMPUTER_CONTROL);
318
+ const policy = options.policy;
319
+ // Where the call runs and the shell text it runs, as its tool maps them (resolveExecutionCwd, resolveExecutionCommand),
320
+ // which the policy judges.
321
+ let policyExecutionCommand;
322
+ if (policy && tool && !hostControlPlaneWrite) {
323
+ try {
324
+ policyExecutionCwd = tool.resolveExecutionCwd?.(effectiveArgs, options.context);
325
+ policyExecutionCommand = tool.resolveExecutionCommand?.(effectiveArgs);
326
+ }
327
+ catch (error) {
328
+ return handleToolFailure(error);
329
+ }
330
+ }
331
+ /**
332
+ * Why the policy refuses TARGETS, files the call writes (writePaths), each with the check write_file's `path` gets plus
333
+ * its rules for written files, or none; and whether one of them asks the host first.
334
+ */
335
+ const refuseWrites = (targets) => {
336
+ let approvalRequired = false;
337
+ if (!policy)
338
+ return { approvalRequired };
339
+ // Every path this call writes, so the policy can refuse a set that completes a git directory across them as one.
340
+ const writeSet = targets.map(target => target.path);
341
+ for (const target of targets) {
342
+ let decision;
343
+ try {
344
+ decision = policy.evaluateTool({
345
+ name, args: { path: target.path }, capabilities: [ToolCapability.FILE_WRITE], writeTargets: true, writeSet,
346
+ });
347
+ }
348
+ catch (error) {
349
+ decision = {
350
+ allowed: false,
351
+ reason: `Permission denied: path cannot be resolved for write admission (${error instanceof Error ? error.message : String(error)})`,
352
+ };
353
+ }
354
+ if (!decision.allowed) {
355
+ return {
356
+ refusal: `${decision.reason || `Permission denied: ${name}`}. ${name} wrote nothing: ${target.label} is refused, `
357
+ + 'and every path a call writes must be allowed.',
358
+ approvalRequired,
359
+ };
360
+ }
361
+ approvalRequired ||= decision.approvalRequired === true;
362
+ }
363
+ return { approvalRequired };
364
+ };
365
+ /** Why the policy refuses PATHS (absolute), files the call reads, each with the check read_file's `path` gets, or none. */
366
+ const refuseReads = (paths) => {
367
+ if (!policy)
368
+ return undefined;
369
+ for (const path of paths) {
370
+ let decision;
371
+ try {
372
+ decision = policy.evaluateTool({ name, args: { path }, capabilities: [ToolCapability.FILE_READ] });
373
+ }
374
+ catch (error) {
375
+ decision = { allowed: false,
376
+ reason: `Permission denied: path cannot be resolved for read admission (${error instanceof Error ? error.message : String(error)})` };
377
+ }
378
+ if (!decision.allowed)
379
+ return `${decision.reason || `Permission denied: ${name}`}. ${name} read nothing.`;
380
+ }
381
+ return undefined;
382
+ };
383
+ /**
384
+ * The refusal of the files the call reads that its tool names (readPaths), checked before anyone is asked about the
385
+ * call, or none: under ask_before_mutation and tests_allowed an LSP tool's file outside the profile's roots was put to
386
+ * the person and refused once they approved it (the reviewer's recheck, 2026-11-23).
387
+ */
388
+ const readPathsRefusal = async () => {
389
+ if (!tool?.readPaths)
390
+ return undefined;
391
+ let paths;
392
+ try {
393
+ paths = tool.readPaths(effectiveArgs, options.context);
394
+ }
395
+ catch (error) {
396
+ return handleToolFailure(error);
397
+ }
398
+ const refusal = refuseReads(paths);
399
+ return refusal === undefined ? undefined : { content: refusal, isError: true, effectiveArgs };
400
+ };
401
+ /** The policy's decision on this call, APPROVED where the person approved it first. */
402
+ const judged = (activePolicy, approved) => activePolicy.evaluateTool({
403
+ name,
404
+ args: effectiveArgs,
405
+ capabilities: callCapabilities(effectiveArgs),
406
+ ...(tool?.sandboxedCommands ? { sandboxedCommands: true } : {}),
407
+ ...(confinedCall(effectiveArgs) ? { confinedCommands: true } : {}),
408
+ // ask_before_mutation's prompt and a PreToolUse hook's ask come before this: the person decided the call.
409
+ ...(approved ? { approved: true } : {}),
410
+ ...(policyExecutionCwd === undefined ? {} : { executionCwd: policyExecutionCwd }),
411
+ ...(policyExecutionCommand === undefined ? {} : { executionCommand: policyExecutionCommand }),
412
+ });
299
413
  if (asksBeforeMutation
300
414
  && mutatesHostState
301
415
  && !hostControlPlaneWrite
302
416
  && !approvalGranted) {
417
+ // A call the profile refuses whatever the person answers (a working directory or a path outside its roots, a file a
418
+ // patch writes there) is refused before they are asked: judged as it is once they approve it, below. Asked first,
419
+ // they approved such a call and it was refused all the same (the reviewer's ask_before_mutation probe, 2026-11-22).
420
+ if (policy && tool) {
421
+ const decision = judged(policy, true);
422
+ if (!decision.allowed)
423
+ return { content: decision.reason || `Permission denied: ${name}`, isError: true, effectiveArgs };
424
+ if (tool.writePaths) {
425
+ let targets;
426
+ try {
427
+ targets = await tool.writePaths(effectiveArgs, options.context);
428
+ }
429
+ catch (error) {
430
+ return handleToolFailure(error);
431
+ }
432
+ const { refusal } = refuseWrites(targets);
433
+ if (refusal !== undefined)
434
+ return { content: refusal, isError: true, effectiveArgs };
435
+ }
436
+ const unreadable = await readPathsRefusal();
437
+ if (unreadable)
438
+ return unreadable;
439
+ }
303
440
  const reason = `The ${name} tool can mutate hosted workspace state.`;
304
441
  if (options.hooks) {
305
442
  await options.hooks.dispatch('PermissionRequest', {
@@ -344,37 +481,6 @@ export async function executeToolWithRuntime(name, args, options) {
344
481
  // write_file's `path` gets plus the policy's rules for written files, and
345
482
  // one refusal refuses the whole call before anything is written.
346
483
  let writeTargets = [];
347
- const policy = options.policy;
348
- const refuseWrites = (targets) => {
349
- let approvalRequired = false;
350
- if (!policy)
351
- return { approvalRequired };
352
- // Every path this call writes, so the policy can refuse a set that completes a git directory across them as one.
353
- const writeSet = targets.map(target => target.path);
354
- for (const target of targets) {
355
- let decision;
356
- try {
357
- decision = policy.evaluateTool({
358
- name, args: { path: target.path }, capabilities: [ToolCapability.FILE_WRITE], writeTargets: true, writeSet,
359
- });
360
- }
361
- catch (error) {
362
- decision = {
363
- allowed: false,
364
- reason: `Permission denied: path cannot be resolved for write admission (${error instanceof Error ? error.message : String(error)})`,
365
- };
366
- }
367
- if (!decision.allowed) {
368
- return {
369
- refusal: `${decision.reason || `Permission denied: ${name}`}. ${name} wrote nothing: ${target.label} is refused, `
370
- + 'and every path a call writes must be allowed.',
371
- approvalRequired,
372
- };
373
- }
374
- approvalRequired ||= decision.approvalRequired === true;
375
- }
376
- return { approvalRequired };
377
- };
378
484
  const admitWriteTargets = () => {
379
485
  const { refusal, approvalRequired } = refuseWrites(writeTargets);
380
486
  if (refusal !== undefined)
@@ -382,25 +488,10 @@ export async function executeToolWithRuntime(name, args, options) {
382
488
  profileApprovalRequired ||= approvalRequired;
383
489
  return undefined;
384
490
  };
385
- let policyExecutionCommand;
386
491
  if (policy
387
492
  && tool
388
493
  && !hostControlPlaneWrite) {
389
- try {
390
- policyExecutionCwd = tool.resolveExecutionCwd?.(effectiveArgs, options.context);
391
- policyExecutionCommand = tool.resolveExecutionCommand?.(effectiveArgs);
392
- }
393
- catch (error) {
394
- return handleToolFailure(error);
395
- }
396
- const decision = policy.evaluateTool({
397
- name,
398
- args: effectiveArgs,
399
- capabilities: callCapabilities(effectiveArgs),
400
- ...(tool.sandboxedCommands ? { sandboxedCommands: true } : {}),
401
- ...(policyExecutionCwd === undefined ? {} : { executionCwd: policyExecutionCwd }),
402
- ...(policyExecutionCommand === undefined ? {} : { executionCommand: policyExecutionCommand }),
403
- });
494
+ const decision = judged(policy, approvalGranted);
404
495
  profileApprovalRequired = decision.approvalRequired === true;
405
496
  if (!decision.allowed) {
406
497
  return {
@@ -425,6 +516,10 @@ export async function executeToolWithRuntime(name, args, options) {
425
516
  capabilities = [...capabilities, ToolCapability.FILE_WRITE];
426
517
  }
427
518
  }
519
+ // Before the host's approval below (tests_allowed asks before each shell command).
520
+ const unreadable = await readPathsRefusal();
521
+ if (unreadable)
522
+ return unreadable;
428
523
  }
429
524
  const verificationAdmission = () => {
430
525
  const adapter = sourceTool === verifyArtifactTool || sourceTool === benchmarkCPUTool;
@@ -556,8 +651,17 @@ export async function executeToolWithRuntime(name, args, options) {
556
651
  throw new Error(refusal);
557
652
  }
558
653
  : undefined;
654
+ // And the real path a file tool is about to read, which a link may have moved since admission.
655
+ const admitReads = policy && tool && !hostControlPlaneWrite
656
+ ? (paths) => {
657
+ const refusal = refuseReads(paths);
658
+ if (refusal !== undefined)
659
+ throw new Error(refusal);
660
+ }
661
+ : undefined;
559
662
  const toolContext = options.context ? { ...options.context,
560
663
  admitWrites,
664
+ admitReads,
561
665
  onOutput: sourceTool === runCommandTool || tool?.outputSource === runCommandTool
562
666
  ? options.context.onOutput : undefined,
563
667
  canInspectVerificationSource: sourceTool === runCommandTool || sourceTool === readCommandTool || sourceTool === stopCommandTool || sourceTool === verifyArtifactTool || sourceTool === benchmarkCPUTool
@@ -653,12 +757,11 @@ export async function executeToolWithRuntime(name, args, options) {
653
757
  capabilities,
654
758
  result: output,
655
759
  });
656
- // On success, don't prepend hook messages — many tool results are JSON
657
- // and a plain-text prefix breaks consumer parsing. Hook stdout already
658
- // flows to SSE/trace via HookMessage. Prepend only on deny/failure,
659
- // where the feedback is the actionable signal.
760
+ // The result stays as the tool gave it: many are JSON, which a line before them broke. Hook stdout flows to
761
+ // SSE/trace via HookMessage; only a failure (or a deny) is the model's to know, as a note after the result. Under a
762
+ // profile that limits the agent a hook runs in the OS sandbox, where one that logs to HOME or uses the network fails.
660
763
  if (postHook.failed || postHook.decision === 'deny') {
661
- resultContent = prependMessages(resultContent, [postHook.decisionReason || postHook.failureReason || `PostToolUse hook failed for ${name}`]);
764
+ resultContent = appendHookNote(resultContent, [`${postHook.decisionReason || postHook.failureReason || 'PostToolUse hook failed'} (after ${name} ran; not part of its result)`]);
662
765
  }
663
766
  }
664
767
  await recordToolTrace({ tool: name, args_keys: Object.keys(effectiveArgs), isError: false, durationMs: Date.now() - traceStartedAt });
@@ -689,10 +792,14 @@ export async function executeToolWithRuntime(name, args, options) {
689
792
  capabilities,
690
793
  error: message,
691
794
  });
692
- message = prependMessages(message, failureHook.messages.map(item => item.text));
693
- if (failureHook.failed || failureHook.decision === 'deny') {
694
- message = prependMessages(message, [failureHook.decisionReason || failureHook.failureReason || `PostToolUseFailure hook failed for ${name}`]);
695
- }
795
+ // The failed result stays as the tool gave it (read_command's receipt is JSON): what the hook says, and its own
796
+ // failure, follow it as a note, as a PostToolUse hook's failure follows a result.
797
+ const failed = failureHook.failed || failureHook.decision === 'deny';
798
+ message = appendHookNote(message, [
799
+ ...(failed ? [`${failureHook.decisionReason || failureHook.failureReason || 'PostToolUseFailure hook failed'} `
800
+ + `(after ${name} failed; not part of its result)`] : []),
801
+ ...failureHook.messages.map(item => item.text),
802
+ ]);
696
803
  }
697
804
  await recordToolTrace({ tool: name, args_keys: Object.keys(effectiveArgs), isError: true, durationMs: Date.now() - traceStartedAt });
698
805
  return {
@@ -3,7 +3,7 @@ import type { ToolContext } from '../tools/types.js';
3
3
  export declare const VERIFIER_INPUT_MAX_BYTES = 65536;
4
4
  /** The recipe consumes these detached strings, not paths it could reopen.
5
5
  * File reads are sequential observations; no atomic filesystem snapshot is claimed. */
6
- export declare function captureVerifierInputs(context: Pick<ToolContext, 'cwd' | 'signal' | 'canInspectVerificationSource'>, paths: readonly string[]): Promise<{
6
+ export declare function captureVerifierInputs(context: Pick<ToolContext, 'cwd' | 'signal' | 'canInspectVerificationSource' | 'commandPolicy'>, paths: readonly string[]): Promise<{
7
7
  source: SourceSnapshot;
8
8
  documents: ReadonlyMap<string, string>;
9
9
  }>;
@@ -3,6 +3,7 @@ import { constants } from 'node:fs';
3
3
  import { lstat, open, realpath } from 'node:fs/promises';
4
4
  import { dirname, resolve } from 'node:path';
5
5
  import { canonicalSourceContent, canonicalSourceIdentity, parseSourceSnapshot, parseVerificationRequest } from './source_verification_contract.js';
6
+ import { ownStateLinkGuard } from '../../utils/ztc_own_state.js';
6
7
  export const VERIFIER_INPUT_MAX_BYTES = 65536;
7
8
  const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
8
9
  function seal(source) {
@@ -31,6 +32,9 @@ export async function captureVerifierInputs(context, paths) {
31
32
  cwd, origin: 'local', captured_at: new Date().toISOString(), git: { commit: null, dirty: null }, coverage: 'incomplete',
32
33
  files: [...paths].sort().map(path => ({ path, kind: 'unavailable', sha256: null, bytes: 0, mode: 0 })) };
33
34
  const documents = new Map();
35
+ // Under a profile that limits the agent, an input that is one of ZTC's own files under another name (a hard link into
36
+ // its config, approvals or sessions) is denied, as the file tools deny it: a check against it would tell its contents.
37
+ const ownStateLink = ownStateLinkGuard(context.commandPolicy);
34
38
  for (const row of source.files) {
35
39
  const absolute = resolve(cwd, row.path);
36
40
  try {
@@ -50,6 +54,8 @@ export async function captureVerifierInputs(context, paths) {
50
54
  const before = await handle.stat();
51
55
  if (!before.isFile() || before.size > VERIFIER_INPUT_MAX_BYTES || before.dev !== location.dev || before.ino !== location.ino)
52
56
  continue;
57
+ if (ownStateLink && await ownStateLink(before) !== null)
58
+ continue;
53
59
  // One extra byte detects growth without exceeding the capture budget.
54
60
  const bytes = Buffer.alloc(before.size + 1);
55
61
  let used = 0;
@@ -3,26 +3,58 @@ import { execFileSync } from 'node:child_process';
3
3
  import { existsSync, readFileSync, statSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import { writeFileAtomicSync } from '../../utils/atomic_write.js';
6
- const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8', timeout: 10_000, maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
6
+ import { GIT_PROBE_OPTIONS } from '../../utils/git_probe_options.js';
7
+ import { GIT_NO_REPOSITORY_PROGRAM_OPTIONS, gitProbesStartNoRepositoryProgram } from '../../utils/git_repository_programs.js';
8
+ import { buildGitSubprocessEnvFor } from '../../utils/subprocess_env.js';
9
+ /**
10
+ * git in CWD's repository, with ENV: buildGitSubprocessEnvFor(CWD), so a CWD with a repository of its own is read as
11
+ * that one whatever GIT_DIR or another repository variable of this process's environment says, and a vcsh or yadm work
12
+ * tree, which has none, as the repository its GIT_DIR names. git runs the programs its config names and writes the
13
+ * variables trace2.envVars names, so ENV is a user subprocess's: none of ZTC's credentials. Under every profile it takes
14
+ * GIT_PROBE_OPTIONS (utils/git_probe_options.ts): a status read never runs the fsmonitor a repository's config names,
15
+ * and the subject's log never the signature program.
16
+ */
17
+ const git = (cwd, env, args, options = GIT_PROBE_OPTIONS) => execFileSync('git', [...options, ...args], { cwd, encoding: 'utf8', timeout: 10_000, maxBuffer: 32 * 1024 * 1024,
18
+ stdio: ['ignore', 'pipe', 'ignore'], env });
19
+ /** The most paths a work state reads one by one where it reads every file's (see readWorkState); more is unknown. */
20
+ const LISTED_PATHS_LIMIT = 200_000;
7
21
  /** Null outside a git repository, before its first commit, or when git cannot answer in time. */
8
22
  export function readWorkState(cwd) {
9
23
  try {
10
- const head = git(cwd, ['rev-parse', 'HEAD']).trim();
11
- const subject = git(cwd, ['log', '-1', '--format=%s']).trim();
12
- const top = git(cwd, ['rev-parse', '--show-toplevel']).trim();
24
+ const env = buildGitSubprocessEnvFor(cwd);
25
+ // Where the agent may have written the repository's config, its programs never run here
26
+ // (utils/git_repository_programs.ts): no status, whose clean filter and index write a changed file starts.
27
+ const barred = gitProbesStartNoRepositoryProgram();
28
+ const options = barred ? GIT_NO_REPOSITORY_PROGRAM_OPTIONS : undefined;
29
+ const head = git(cwd, env, ['rev-parse', 'HEAD'], options).trim();
30
+ const subject = git(cwd, env, ['log', '-1', '--format=%s'], options).trim();
31
+ const top = git(cwd, env, ['rev-parse', '--show-toplevel'], options).trim();
13
32
  const digest = createHash('sha256');
14
- // Content edits to a file already listed leave its status line alone; its size or time changes.
15
- for (const entry of git(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=all']).split('\0').filter(Boolean).slice(0, 20_000)) {
16
- digest.update(entry).update('\0');
17
- try {
18
- const info = statSync(join(top, entry.slice(3)));
19
- digest.update(`${info.size}:${info.mtimeMs}\0`);
20
- }
21
- catch {
22
- digest.update('gone\0');
33
+ const changes = (entries) => {
34
+ for (const { line, path } of entries) {
35
+ digest.update(line).update('\0');
36
+ try {
37
+ const info = statSync(join(top, path));
38
+ digest.update(`${info.size}:${info.mtimeMs}\0`);
39
+ }
40
+ catch {
41
+ digest.update('gone\0');
42
+ }
23
43
  }
44
+ return digest.digest('hex');
45
+ };
46
+ if (barred) {
47
+ // Every tracked and untracked path with its size and time, which change when its content does, read from the index
48
+ // and the folders alone.
49
+ const listed = [...git(top, env, ['ls-files', '-z'], options).split('\0'),
50
+ ...git(top, env, ['ls-files', '-z', '--others', '--exclude-standard'], options).split('\0')].filter(Boolean);
51
+ if (listed.length > LISTED_PATHS_LIMIT)
52
+ return null;
53
+ return { head, subject, changes: changes(listed.map(path => ({ line: path, path }))) };
24
54
  }
25
- return { head, subject, changes: digest.digest('hex') };
55
+ // Content edits to a file already listed leave its status line alone; its size or time changes.
56
+ const entries = git(cwd, env, ['status', '--porcelain=v1', '-z', '--untracked-files=all']).split('\0').filter(Boolean).slice(0, 20_000);
57
+ return { head, subject, changes: changes(entries.map(entry => ({ line: entry, path: entry.slice(3) }))) };
26
58
  }
27
59
  catch {
28
60
  return null;
@@ -5,6 +5,7 @@ import { resolve, dirname } from 'path';
5
5
  import { existsSync, createWriteStream, mkdirSync } from 'fs';
6
6
  import { configStore } from '../../config.js';
7
7
  import { PROVIDER_API_KEY_ENV } from '../../config/provider_api_key_env.js';
8
+ import { buildUserSubprocessEnv, modelRouteCredentialsReserved } from '../../utils/subprocess_env.js';
8
9
  // --- Module-level subprocess state (following delegate.ts pattern) ---
9
10
  let activeProcess = null;
10
11
  let progressEvents = [];
@@ -35,7 +36,12 @@ export function truncateDetails(d) {
35
36
  }
36
37
  return out;
37
38
  }
38
- function resolveRunnerPath() {
39
+ /**
40
+ * The connector generation CLI to run. BESIDE_WORKING_DIRECTORY allows the monorepo checkout beside the working
41
+ * directory (3), the only runner an npm or desktop install finds by itself; a run that keeps its route credentials
42
+ * from its tools leaves it out, since there a model drives the agent that writes beside the working directory.
43
+ */
44
+ function resolveRunnerPath(options) {
39
45
  const cliRelative = ['zaai', 'domains', 'connector_generation', 'cli.py'];
40
46
  // 1. Explicit override (highest priority)
41
47
  if (process.env.ZERG_ADAPTATION_RUNNER) {
@@ -54,10 +60,13 @@ function resolveRunnerPath() {
54
60
  return candidate;
55
61
  }
56
62
  }
57
- // 3. Fallback: sibling directory to ZTC in the monorepo (ztc/../zerg/zaai/domains/connector_generation/cli.py)
58
- const siblingCandidate = resolve(process.cwd(), '..', 'zerg', ...cliRelative);
59
- if (existsSync(siblingCandidate))
60
- return siblingCandidate;
63
+ // 3. Fallback: sibling directory to ZTC in the monorepo (ztc/../zerg/zaai/domains/connector_generation/cli.py), when
64
+ // the run allows it (see above)
65
+ if (options.besideWorkingDirectory) {
66
+ const siblingCandidate = resolve(process.cwd(), '..', 'zerg', ...cliRelative);
67
+ if (existsSync(siblingCandidate))
68
+ return siblingCandidate;
69
+ }
61
70
  // 4. Fallback: __dirname-based — source vs compiled layouts
62
71
  // Source: ztc/src/agent/tools/ — 4 levels up to checkout root, then descend into zerg/
63
72
  // Compiled: ztc/dist/src/agent/tools/ — 5 levels up to checkout root, then descend into zerg/
@@ -149,9 +158,12 @@ export const adaptationRunTool = {
149
158
  message: `Missing required parameters: ${missing.join(', ')}. Pass all connector configuration from the wizard answers.`,
150
159
  });
151
160
  }
161
+ // A run that keeps its route credentials from its tools (a --headless run, a headless mirror) is driven by a model:
162
+ // its runner comes only from where the host put it, and gets only the key injected below.
163
+ const keepsRouteCredentials = modelRouteCredentialsReserved();
152
164
  let runnerPath;
153
165
  try {
154
- runnerPath = resolveRunnerPath();
166
+ runnerPath = resolveRunnerPath({ besideWorkingDirectory: !keepsRouteCredentials });
155
167
  }
156
168
  catch (err) {
157
169
  return JSON.stringify({ status: 'error', message: err.message });
@@ -203,7 +215,10 @@ export const adaptationRunTool = {
203
215
  stderrBuffer = '';
204
216
  // Inject API key from ZTC config into subprocess env so the Python runner can find it.
205
217
  // The runner checks ANTHROPIC_API_KEY / OPENAI_API_KEY env vars to auto-detect the backend.
206
- const spawnEnv = { ...process.env };
218
+ // It starts from a user subprocess's environment: none of ZTC's own credentials, the person's provider keys in the
219
+ // interactive app, and none of the route credentials a run that keeps them from its tools reserved, so there it
220
+ // has only the key injected here.
221
+ const spawnEnv = buildUserSubprocessEnv(process.env);
207
222
  const provider = configStore.getProvider();
208
223
  const apiKey = configStore.getRequestApiKey();
209
224
  // A profile waiting for a route choice sends only the key its route sends
@@ -228,6 +243,13 @@ export const adaptationRunTool = {
228
243
  env: spawnEnv,
229
244
  });
230
245
  activeProcess = proc;
246
+ // Node reports a Python it cannot start (ENOENT, EACCES) as an 'error' event once spawn has returned, never as a
247
+ // throw, and an 'error' event that nothing listens for ends ZTC: listen before the failed start below returns.
248
+ proc.on('error', (err) => {
249
+ logStream?.end();
250
+ activeProcess = null;
251
+ finalResult = { runner: 'adaptation', event: 'complete', status: 'error', message: err.message };
252
+ });
231
253
  // Detect synchronous spawn failure (e.g., ENOENT for missing Python binary).
232
254
  // Node.js sets pid=undefined when the OS can't create the process.
233
255
  if (!proc.pid) {
@@ -273,11 +295,6 @@ export const adaptationRunTool = {
273
295
  };
274
296
  }
275
297
  });
276
- proc.on('error', (err) => {
277
- logStream?.end();
278
- activeProcess = null;
279
- finalResult = { runner: 'adaptation', event: 'complete', status: 'error', message: err.message };
280
- });
281
298
  // Return immediately — caller polls with action="status"
282
299
  return JSON.stringify({ status: 'started', pid: proc.pid, connector: args.connector_name });
283
300
  },
@@ -1,12 +1,14 @@
1
1
  import { constants } from 'fs';
2
2
  import { chmod, lstat, mkdir, mkdtemp, open, readlink, realpath, rm, stat, unlink, writeFile } from 'fs/promises';
3
3
  import { devNull, tmpdir } from 'os';
4
- import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'path';
4
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'path';
5
5
  import { execFile } from 'child_process';
6
6
  import { promisify } from 'util';
7
7
  import { ToolCapability } from '../runtime/capabilities.js';
8
8
  import { writeFileAtomic } from '../../utils/atomic_write.js';
9
- import { isWellFormedText } from '../../utils/canonical_path.js';
9
+ import { canonicalPath, isWellFormedText } from '../../utils/canonical_path.js';
10
+ import { readAdmittedFile, writeAdmittedFileAtomic } from '../../utils/admitted_open.js';
11
+ import { openAdmission } from './file.js';
10
12
  import { withPathLocks } from '../../utils/path_lock.js';
11
13
  import { buildUserSubprocessEnv } from '../../utils/subprocess_env.js';
12
14
  import { assertTemporaryWritePathAllowed } from '../../utils/temporary_write_root.js';
@@ -197,7 +199,7 @@ async function admitTemporaryWrite(target, root, cwd, writeSet) {
197
199
  }
198
200
  }
199
201
  function patchHost(docker, context) {
200
- return docker ? containerPatchHost(docker) : hostPatchHost(context?.cwd || process.cwd(), context?.subprocessEnv);
202
+ return docker ? containerPatchHost(docker) : hostPatchHost(context?.cwd || process.cwd(), context?.subprocessEnv, openAdmission(context));
201
203
  }
202
204
  /** Variables that point git at another repository, work tree or index. */
203
205
  const GIT_REPOSITORY_ENV = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
@@ -242,7 +244,7 @@ async function withScratchRepository(diff, use) {
242
244
  await rm(scratch, { recursive: true, force: true });
243
245
  }
244
246
  }
245
- function hostPatchHost(cwd, subprocessEnv) {
247
+ function hostPatchHost(cwd, subprocessEnv, admission) {
246
248
  const env = buildUserSubprocessEnv(subprocessEnv);
247
249
  const run = async (args, runEnv) => {
248
250
  try {
@@ -266,7 +268,7 @@ function hostPatchHost(cwd, subprocessEnv) {
266
268
  return { root, cwd: physical, spelled: resolve(cwd) };
267
269
  })();
268
270
  return {
269
- files: hostFiles(cwd),
271
+ files: admission ? admittedHostFiles(cwd, admission) : hostFiles(cwd),
270
272
  resolveFrom: (base, path) => resolve(base, path),
271
273
  workTree,
272
274
  spell: (at, path) => {
@@ -1026,6 +1028,61 @@ function hostFiles(cwd) {
1026
1028
  setMode: (path, mode) => chmod(path, mode),
1027
1029
  };
1028
1030
  }
1031
+ /**
1032
+ * The host's files under a profile that limits the agent: what a structured patch reads, inspects and writes is the file
1033
+ * the policy admitted, in the folder its parent really is, checked after each open (utils/admitted_open.ts). A link
1034
+ * flipped between the patch's admission and its write leads nowhere outside.
1035
+ */
1036
+ function admittedHostFiles(cwd, admission) {
1037
+ const host = hostFiles(cwd);
1038
+ const inFolder = async (path) => {
1039
+ try {
1040
+ return join(await realpath(dirname(path)), basename(path));
1041
+ }
1042
+ catch (error) {
1043
+ const code = error.code;
1044
+ if (code === 'ENOENT' || code === 'ENOTDIR')
1045
+ return null;
1046
+ throw error;
1047
+ }
1048
+ };
1049
+ return {
1050
+ ...host,
1051
+ inspect: async (path) => {
1052
+ const target = await inFolder(path);
1053
+ if (target === null)
1054
+ return null;
1055
+ const info = await lstat(target).catch((error) => {
1056
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
1057
+ return null;
1058
+ throw error;
1059
+ });
1060
+ if (info === null)
1061
+ return null;
1062
+ if (info.isSymbolicLink())
1063
+ return { kind: 'link', target: await readlink(target) };
1064
+ if (!info.isFile())
1065
+ return { kind: 'other' };
1066
+ return { kind: 'file', text: (await readAdmittedFile(target, admission, { admit: 'write' })).data.toString('utf8') };
1067
+ },
1068
+ read: async (path) => (await readAdmittedFile(path, admission, { admit: 'write' })).data.toString('utf-8'),
1069
+ write: async (path, content) => {
1070
+ await mkdir(canonicalPath(dirname(path)), { recursive: true });
1071
+ await writeAdmittedFileAtomic(path, content, admission);
1072
+ },
1073
+ // A delete or a mode change lands in the folder the path's parent really is, admitted there just before.
1074
+ remove: async (path) => {
1075
+ const target = await inFolder(path) ?? path;
1076
+ admission.write(target);
1077
+ await unlink(target);
1078
+ },
1079
+ setMode: async (path, mode) => {
1080
+ const target = await realpath(path);
1081
+ admission.write(target);
1082
+ await chmod(target, mode);
1083
+ },
1084
+ };
1085
+ }
1029
1086
  function containerFiles(docker) {
1030
1087
  return {
1031
1088
  resolve: path => containerPath(docker, path),
@@ -18,6 +18,8 @@ export function getBackgroundRegistry() {
18
18
  return registry;
19
19
  }
20
20
  export const spawnBackgroundAgentTool = {
21
+ // Its agent runs its commands through run_command, under this agent's policy (see Tool.confinedCommands).
22
+ confinedCommands: true,
21
23
  capabilities: [ToolCapability.FILE_READ, ToolCapability.SHELL_EXEC],
22
24
  definition: {
23
25
  name: 'spawn_background_agent',
@@ -7,6 +7,8 @@ import { ToolCapability } from '../runtime/capabilities.js';
7
7
  import { captureVerifierInputs } from '../runtime/verifier_capture.js';
8
8
  import { parseCommandVerificationReceipt, parseVerificationRequest } from '../runtime/source_verification_contract.js';
9
9
  export const benchmarkCPUTool = Object.freeze({
10
+ // It runs only the registered recipe, on integers it read (see Tool.confinedCommands).
11
+ confinedCommands: true,
10
12
  capabilities: Object.freeze([ToolCapability.FILE_READ, ToolCapability.SHELL_EXEC]), effect: 'write',
11
13
  definition: { name: 'benchmark_cpu',
12
14
  description: 'Execute the registered bounded CPU integer-sum benchmark using immutable captured JSON data and config, actual monotonic measurements and an independent exact oracle. Input is1–1024 integers with absolute value≤1000000. Config: {schema_version:1,variant:"for_loop"|"array_reduce",iterations:1–2048,warmup:0–4,samples:3|5|7|9}. Admits only this fixture; never project code, reported scores, generic command results, production/GPU performance or a plateau. Local execution and exact source-read permissions required; guarded remote sessions cannot use this adapter. Each file≤65536B.',