@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
@@ -1,13 +1,18 @@
1
1
  import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs';
2
2
  import { randomUUID } from 'crypto';
3
3
  import { homedir, tmpdir } from 'os';
4
- import { basename, dirname, join, resolve, sep } from 'path';
4
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'path';
5
5
  import { execFileSync, spawnSync } from 'child_process';
6
- import { buildCredentialSafeSubprocessEnv } from './subprocess_env.js';
6
+ import { buildCredentialSafeSubprocessEnv, buildUserSubprocessEnv } from './subprocess_env.js';
7
+ import { bubblewrapGitProgramBinds, gitProgramFiles, putBackBrokenRepositories, seatbeltGitProgramRules, undoGitProgramWrites } from './git_program_files.js';
7
8
  import { hostShell } from './host_shell.js';
9
+ import { canonicalPath } from './canonical_path.js';
10
+ import { osSandboxRequested, osSandboxRequired, profileLimitsAgent } from '../config/profile_limits.js';
11
+ import { ztcOwnSkillRoots, ztcOwnStateRoots, ztcRuntimeEntries, ztcRuntimeSeatbeltPatterns } from './ztc_own_state.js';
8
12
  function commandExists(command) {
9
13
  const result = spawnSync('/usr/bin/env', ['sh', '-c', `command -v ${shellEscape(command)} >/dev/null 2>&1`], {
10
14
  stdio: 'ignore',
15
+ env: buildUserSubprocessEnv(),
11
16
  });
12
17
  return result.status === 0;
13
18
  }
@@ -17,8 +22,12 @@ function shellEscape(value) {
17
22
  function schemeString(value) {
18
23
  return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
19
24
  }
25
+ /** ROOT as a profile names it, with `~` for the home folder spelled out: relative where it doesn't start at /. */
26
+ function expandedRoot(root) {
27
+ return root === '~' ? homedir() : root.replace(/^~(?=\/|$)/, homedir());
28
+ }
20
29
  function normalizeRoot(root, cwd) {
21
- const expanded = root === '~' ? homedir() : root.replace(/^~(?=\/|$)/, homedir());
30
+ const expanded = expandedRoot(root);
22
31
  return resolve(expanded.startsWith(sep) ? expanded : resolve(cwd, expanded));
23
32
  }
24
33
  /** Whether sandboxed commands may use the network: the profile's sandbox says, else its network capability does. */
@@ -28,12 +37,36 @@ function profileAllowsNetwork(profile) {
28
37
  function profileAllowsFileWrite(profile) {
29
38
  return profile?.capabilities?.file_write !== false;
30
39
  }
31
- function allowedRoots(profile, cwd) {
32
- const roots = profile?.allowedPaths?.length ? profile.allowedPaths : [cwd];
33
- return Array.from(new Set(roots.map(root => normalizeRoot(root, cwd))));
40
+ /**
41
+ * Where a command in CWD may write: the profile's allowedPaths, a relative one resolved against ROOTS_CWD, the session's
42
+ * folder (SandboxCommandOptions.sessionCwd), as the agent's file tools resolve it; or CWD itself for a profile that names
43
+ * none. A command the agent runs in another folder (run_command's `cwd`) had that folder as the root `.` names, outside
44
+ * the mounted workspace (the reviewer's pinned-resident probe, 2026-11-22).
45
+ */
46
+ function allowedRoots(profile, cwd, rootsCwd = cwd) {
47
+ const roots = profile?.allowedPaths?.length ? profile.allowedPaths.map(root => normalizeRoot(root, rootsCwd)) : [normalizeRoot(cwd, cwd)];
48
+ return Array.from(new Set(roots));
49
+ }
50
+ /**
51
+ * ROOTS as Seatbelt's rules must name them, each as named and by its real path (canonicalPath: the part that exists
52
+ * resolved, the rest as named). Seatbelt matches a rule against the real path of what a command opens, so a root spelled
53
+ * through a link matched nothing: with the session's folder named through one (a /cd to it by another name, the agent
54
+ * built again there), a command could write nowhere in its workspace, and could make a denied folder that didn't exist
55
+ * yet (the reviewer's resident probe, 2026-11-22).
56
+ */
57
+ function seatbeltRoots(roots) {
58
+ return Array.from(new Set(roots.flatMap(root => {
59
+ try {
60
+ return [root, canonicalPath(root)];
61
+ }
62
+ catch {
63
+ return [root];
64
+ }
65
+ })));
34
66
  }
35
- function deniedRoots(profile, cwd) {
36
- const roots = (profile?.deniedPaths || []).map(root => normalizeRoot(root, cwd));
67
+ /** What the profile's deniedPaths deny, a relative one resolved against ROOTS_CWD, the session's folder (allowedRoots). */
68
+ function deniedRoots(profile, rootsCwd) {
69
+ const roots = (profile?.deniedPaths || []).map(root => normalizeRoot(root, rootsCwd));
37
70
  for (const root of [...roots]) {
38
71
  try {
39
72
  roots.push(realpathSync(root));
@@ -44,6 +77,24 @@ function deniedRoots(profile, cwd) {
44
77
  }
45
78
  return Array.from(new Set(roots));
46
79
  }
80
+ /**
81
+ * The folders of ZTC's own state (utils/ztc_own_state.ts), which a command under a profile that limits the agent never
82
+ * sees: its config folder and ~/.ztc. The entries of its runtime in a temp folder are denied by name on Seatbelt
83
+ * (ztcRuntimeSeatbeltPatterns) and hidden one by one on bwrap (ztcRuntimeEntries).
84
+ */
85
+ function ownStateRoots(hidden) {
86
+ return hidden ? ztcOwnStateRoots() : [];
87
+ }
88
+ /**
89
+ * The person's skills folders inside ZTC's own state (ztcOwnSkillRoots) that a command whose reads reach READ_ROOTS
90
+ * would have read but for that state's denial: read again, never written, as the file tools read them.
91
+ */
92
+ function ownSkillReadRoots(hidden, readRoots) {
93
+ if (!hidden)
94
+ return [];
95
+ const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
96
+ return ztcOwnSkillRoots().filter(root => existsSync(root) && readRoots.some(read => inside(root, read)));
97
+ }
47
98
  /**
48
99
  * Whether a profile's commands read the whole filesystem: one that writes nothing and names no `allowedPaths`, as the
49
100
  * built-in read_only does, so git reads ~/.gitconfig and a worktree's repository outside the project (a read_only
@@ -206,15 +257,19 @@ function gitReadRoots(cwd, home = homedir()) {
206
257
  }
207
258
  return Array.from(new Set(roots)).filter(root => existsSync(root));
208
259
  }
209
- /** Where a sandboxed command may read, as the audit records it. */
210
- function commandReadRoots(profile, cwd, systemRoots) {
260
+ /**
261
+ * Where a sandboxed command may read, as the audit records it: its roots (relative ones the session's folder's, ROOTS_CWD),
262
+ * and the files READ_PATHS names beside them.
263
+ */
264
+ function commandReadRoots(profile, cwd, systemRoots, readPaths = [], rootsCwd = cwd) {
211
265
  if (readsEverywhere(profile))
212
266
  return ['/'];
213
267
  return Array.from(new Set([
214
268
  ...systemRoots.filter(root => existsSync(root)),
215
269
  cwd,
216
- ...allowedRoots(profile, cwd),
270
+ ...allowedRoots(profile, cwd, rootsCwd),
217
271
  ...(profileAllowsFileWrite(profile) ? [] : gitReadRoots(cwd)),
272
+ ...readPaths.filter(path => isAbsolute(path) && existsSync(path)),
218
273
  ]));
219
274
  }
220
275
  function selectedDeveloperReadRoots(cwd, env = process.env) {
@@ -272,31 +327,20 @@ function selectedDeveloperReadRoots(cwd, env = process.env) {
272
327
  return [];
273
328
  }
274
329
  }
330
+ /** Whether commands under OPTIONS run only inside an OS sandbox, or not at all (osSandboxRequired). */
331
+ function requiresOsSandbox(options) {
332
+ return osSandboxRequired(options.profile, options.sandbox);
333
+ }
275
334
  /**
276
- * Whether a profile's commands need the OS sandbox whatever the settings say: one that writes nothing has no other
277
- * way to keep a command from writing. A custom no-write profile with no sandbox block ran run_command without one
278
- * (Idan's review of #884, round 2).
335
+ * Whether a command under OPTIONS runs only inside an OS sandbox, or not at all: what buildSandboxCommandPlan refuses
336
+ * to plan without one. A hook's command follows the same rule as run_command's (hooks/runner.ts).
279
337
  */
280
- function requiresOsSandbox(options) {
281
- return Boolean(options.sandbox?.requireOsEnforcement || options.profile?.sandbox?.requireOsEnforcement)
282
- || !profileAllowsFileWrite(options.profile) && options.profile !== undefined;
338
+ export function commandsRequireOsSandbox(options) {
339
+ return requiresOsSandbox(options);
283
340
  }
341
+ /** Whether commands under OPTIONS are planned in an OS sandbox at all (osSandboxRequested). */
284
342
  function needsSandbox(options) {
285
- const profile = options.profile;
286
- if (requiresOsSandbox(options))
287
- return true;
288
- if (options.sandbox?.enabled === false)
289
- return false;
290
- if (profile?.sandbox?.backend && profile.sandbox.backend !== 'auto' && profile.sandbox.backend !== 'none') {
291
- return true;
292
- }
293
- if (profile?.allowedPaths?.length || profile?.deniedPaths?.length) {
294
- return true;
295
- }
296
- if (profile?.capabilities?.network === false) {
297
- return true;
298
- }
299
- return false;
343
+ return osSandboxRequested(options.profile, options.sandbox);
300
344
  }
301
345
  function preferredBackend(options) {
302
346
  return options.profile?.sandbox?.backend || options.sandbox?.backend || 'auto';
@@ -372,7 +416,7 @@ function appleToolLinkDir() {
372
416
  return appleToolLinks;
373
417
  appleToolLinks = null;
374
418
  try {
375
- const developer = execFileSync('/usr/bin/xcode-select', ['-p'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
419
+ const developer = execFileSync('/usr/bin/xcode-select', ['-p'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], env: buildUserSubprocessEnv() }).trim();
376
420
  const tools = join(developer, 'usr', 'bin');
377
421
  const links = mkdtempSync(join(tmpdir(), 'ztc-apple-tools-'));
378
422
  for (const name of readdirSync(tools))
@@ -392,13 +436,39 @@ function withoutAppleToolShims(env) {
392
436
  }
393
437
  /** What every Seatbelt command reads besides its project: the system and its tools. */
394
438
  const SEATBELT_SYSTEM_READ_ROOTS = ['/bin', '/sbin', '/usr', '/System', '/Library', '/opt'];
395
- function writeSeatbeltProfile(profile, cwd, env) {
439
+ /**
440
+ * What a command in CWD under PROFILE may not change of the repositories it can write (utils/git_program_files.ts): the
441
+ * one it runs in, the session's (SESSION_CWD), each its writable roots hold, and each an earlier plan of this process
442
+ * found there. Null for a profile that writes nothing.
443
+ */
444
+ function commandGitProgramFiles(profile, cwd, sessionCwd) {
445
+ if (!profileAllowsFileWrite(profile))
446
+ return null;
447
+ const roots = allowedRoots(profile, cwd, sessionCwd ?? cwd);
448
+ return gitProgramFiles([cwd, ...(sessionCwd ? [sessionCwd] : []), ...roots], roots);
449
+ }
450
+ /** The notices each ZTC process has said already (sandboxNoticesToTell). */
451
+ const toldNotices = new Set();
452
+ /** PLAN's notices that this ZTC process has not said yet, each now counted as said: a result that shows them says them. */
453
+ export function sandboxNoticesToTell(plan) {
454
+ const fresh = (plan.notices ?? []).filter(notice => !toldNotices.has(notice));
455
+ for (const notice of fresh)
456
+ toldNotices.add(notice);
457
+ return fresh;
458
+ }
459
+ function writeSeatbeltProfile(profile, cwd, env, hideOwnState = false, sessionCwd, readPaths = []) {
396
460
  // A profile that writes nothing and names no allowedPaths reads everywhere (see readsEverywhere). Denied roots still
397
- // apply below.
398
- const readRoots = commandReadRoots(profile, cwd, [...SEATBELT_SYSTEM_READ_ROOTS, ...selectedDeveloperReadRoots(cwd, env)]);
399
- const writeRoots = profileAllowsFileWrite(profile) ? allowedRoots(profile, cwd) : [];
400
- const denyRoots = deniedRoots(profile, cwd);
461
+ // apply below, and so does the denial of ZTC's own state, over the files READ_PATHS names too. The profile's relative
462
+ // roots are the session's folder's, wherever in it or outside it the command runs (allowedRoots).
463
+ const rootsCwd = sessionCwd ?? cwd;
464
+ const readRoots = seatbeltRoots(commandReadRoots(profile, cwd, [...SEATBELT_SYSTEM_READ_ROOTS, ...selectedDeveloperReadRoots(cwd, env)], readPaths, rootsCwd));
465
+ const writeRoots = profileAllowsFileWrite(profile) ? seatbeltRoots(allowedRoots(profile, cwd, rootsCwd)) : [];
466
+ const denyRoots = seatbeltRoots(deniedRoots(profile, rootsCwd));
401
467
  const writes = profileAllowsFileWrite(profile);
468
+ // Where the repositories the command may write name the programs git starts: read-only to it, though it may commit,
469
+ // stage, branch and fetch (utils/git_program_files.ts).
470
+ const programs = commandGitProgramFiles(profile, cwd, sessionCwd);
471
+ const gitPrograms = programs ? seatbeltGitProgramRules(programs, schemeString) : [];
402
472
  const lines = [
403
473
  '(version 1)',
404
474
  '(deny default)',
@@ -424,10 +494,31 @@ function writeSeatbeltProfile(profile, cwd, env) {
424
494
  '(allow file-read-data file-write-data (literal "/dev/null"))',
425
495
  ...readRoots.map(root => `(allow file-read* (subpath ${schemeString(root)}))`),
426
496
  ...writeRoots.map(root => `(allow file-write* (subpath ${schemeString(root)}))`),
427
- ...(profileAllowsNetwork(profile) ? ['(allow network*)'] : []),
497
+ // After the writable roots, so these denials win over them.
498
+ ...gitPrograms,
499
+ // The network as IP: out to any address, in and bind on local ones, and the system's name resolver, whose Unix socket
500
+ // getaddrinfo uses. No other Unix socket: `(allow network*)` let a command connect to any of the host's (tmux's,
501
+ // Docker Desktop's docker.sock, an ssh-agent's), whose programs run commands outside the sandbox, as bubblewrap
502
+ // binds none of the folders that hold them (the reviewer's recheck of round 2, 2026-11-23).
503
+ ...(profileAllowsNetwork(profile) ? [
504
+ '(allow network-outbound (remote ip))',
505
+ '(allow network-inbound (local ip))',
506
+ '(allow network-bind (local ip))',
507
+ '(allow network-outbound (literal "/private/var/run/mDNSResponder"))',
508
+ ] : []),
428
509
  // Match the allowed operations: generic denies lose to more-specific
429
510
  // grants, including the exact read/write-data bootstrap permissions above.
430
511
  ...denyRoots.map(root => `(deny file* file-read* file-read-data file-write* file-write-data (subpath ${schemeString(root)}))`),
512
+ // ZTC's own state, under a profile that limits the agent: its folders, and every entry of its runtime in a temp
513
+ // folder, now or later, which a command may neither open nor, for the relay's endpoint, connect to.
514
+ ...ownStateRoots(hideOwnState).map(root => `(deny file* file-read* file-read-data file-write* file-write-data (subpath ${schemeString(root)}))`),
515
+ ...(hideOwnState ? ztcRuntimeSeatbeltPatterns().flatMap(pattern => [
516
+ `(deny file* file-read* file-read-data file-write* file-write-data (regex #"${pattern}"))`,
517
+ `(deny network-outbound (regex #"${pattern}"))`,
518
+ ]) : []),
519
+ // The person's skills folder in it, which the agent reads as the file tools do: reads alone, after the denial, so they
520
+ // win as equally specific rules that come later do; a link there into the rest of ZTC's state stays denied.
521
+ ...ownSkillReadRoots(hideOwnState, readRoots).map(root => `(allow file-read* file-read-data (subpath ${schemeString(root)}))`),
431
522
  ];
432
523
  // Every plan owns its policy. Timestamp names let simultaneous plans replace
433
524
  // each other's permissions before sandbox-exec has read the file.
@@ -441,10 +532,23 @@ function writeSeatbeltProfile(profile, cwd, env) {
441
532
  cleanup();
442
533
  throw error;
443
534
  }
444
- return { path, cleanup };
535
+ return { path, cleanup, programs };
445
536
  }
446
537
  /** What every bubblewrap command reads besides its project: the system and its tools. */
447
538
  const BUBBLEWRAP_SYSTEM_READ_ROOTS = ['/bin', '/usr', '/lib', '/lib64', '/etc'];
539
+ /**
540
+ * The folders every command the OS sandbox runs under OPTIONS here reads, whatever its profile's roots: the system and
541
+ * its tools, and on macOS the selected Xcode's developer folders (as CWD's xcode-select names them). A command whose
542
+ * working directory is one of them reads nothing there its roots don't already give it.
543
+ */
544
+ export function sandboxSystemReadRoots(options, cwd) {
545
+ const backend = platformBackend({ ...options, sandbox: options.sandbox || { enabled: true, backend: 'auto' } });
546
+ if (backend === 'seatbelt')
547
+ return [...SEATBELT_SYSTEM_READ_ROOTS, ...selectedDeveloperReadRoots(cwd, options.env)];
548
+ return backend === 'bubblewrap' ? [...BUBBLEWRAP_SYSTEM_READ_ROOTS] : [];
549
+ }
550
+ /** Where host services keep their sockets and scratch, besides the session's XDG_RUNTIME_DIR (hostSocketDirs). */
551
+ const HOST_SOCKET_DIRS = ['/run', '/var/run', '/tmp', '/var/tmp'];
448
552
  /**
449
553
  * The folders where host services keep their sockets and scratch, each made private and empty for a command that reads
450
554
  * everywhere: /run (and /var/run where it is a folder of its own) holds the session bus and docker.sock, /tmp tmux's
@@ -452,7 +556,7 @@ const BUBBLEWRAP_SYSTEM_READ_ROOTS = ['/bin', '/usr', '/lib', '/lib64', '/etc'];
452
556
  */
453
557
  function hostSocketDirs(env) {
454
558
  const dirs = [];
455
- for (const candidate of ['/run', '/var/run', '/tmp', '/var/tmp', env.XDG_RUNTIME_DIR]) {
559
+ for (const candidate of [...HOST_SOCKET_DIRS, env.XDG_RUNTIME_DIR]) {
456
560
  if (!candidate || !candidate.startsWith('/'))
457
561
  continue;
458
562
  const directory = resolve(candidate);
@@ -466,6 +570,102 @@ function hostSocketDirs(env) {
466
570
  }
467
571
  return dirs;
468
572
  }
573
+ /**
574
+ * How PATH (REAL, its real path, where it has one) stands to the folders where the host's services keep their sockets
575
+ * (/tmp's tmux, /run's session bus and docker.sock, the session's XDG_RUNTIME_DIR, as named or by their real paths, on this
576
+ * host or not), as a refusal says it: it is one, holds one (or is /, which holds them all), or, where LIES_IN counts, lies
577
+ * in one; undefined where none of these holds.
578
+ */
579
+ function hostSocketRelation(path, real, env, liesIn) {
580
+ const folders = Array.from(new Set([...HOST_SOCKET_DIRS, env.XDG_RUNTIME_DIR, process.env.XDG_RUNTIME_DIR]
581
+ .filter((folder) => typeof folder === 'string' && folder.startsWith(sep))
582
+ .flatMap(folder => { try {
583
+ return [resolve(folder), realpathSync(folder)];
584
+ }
585
+ catch {
586
+ return [resolve(folder)];
587
+ } })));
588
+ const inside = (candidate, root) => candidate === root || candidate.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
589
+ const relation = (candidate) => {
590
+ if (candidate === sep)
591
+ return 'holds the folders where the host\'s services keep their sockets';
592
+ if (folders.includes(candidate))
593
+ return 'is a folder where the host\'s services keep their sockets';
594
+ const holder = liesIn ? folders.find(folder => inside(candidate, folder)) : undefined;
595
+ if (holder !== undefined)
596
+ return `lies in ${holder}, where the host's services keep their sockets`;
597
+ const held = folders.find(folder => inside(folder, candidate));
598
+ return held === undefined ? undefined : `holds ${held}, where the host's services keep their sockets`;
599
+ };
600
+ return relation(path) ?? (real === undefined ? undefined : relation(real));
601
+ }
602
+ /**
603
+ * Why bubblewrap won't start a command in CWD (REAL, its real path, where it has one), a folder no bind of its plan holds,
604
+ * or undefined. The plan binds such a folder read-only for the command to start there, and a read-only bind does not stop
605
+ * connect(): a working directory that is, lies in or holds a folder where the host's services keep their sockets
606
+ * (hostSocketRelation), or that is / which holds them all, put them in reach of a command whose profile keeps the network
607
+ * (the reviewer's recheck of the bwrap plan, 2026-11-23). ROOTS, and the session's folder SESSION where a bind holds it,
608
+ * are where to run the command instead.
609
+ */
610
+ function hostSocketFolderRefusal(cwd, real, env, roots, session) {
611
+ const what = hostSocketRelation(cwd, real, env, true);
612
+ if (what === undefined)
613
+ return undefined;
614
+ return `Permission denied: working directory ${what} (${cwd}), which bubblewrap keeps out of a command's reach. `
615
+ + `Run the command in a folder inside this profile's roots (${roots.join(', ')}): give it one there as its working directory`
616
+ + `${session !== undefined && session !== cwd ? ', or none to run it in the session\'s folder' : ''}.`;
617
+ }
618
+ /**
619
+ * Why bubblewrap won't plan a command in CWD under PROFILE whose roots (allowedRoots, a relative one ROOTS_CWD's) would put
620
+ * the host's services' sockets in its reach, or undefined; its caller asks only where no filter refuses the command Unix
621
+ * sockets (a profile that keeps the network). The plan binds each root as it is, read-write for a profile that writes,
622
+ * over the private /tmp, and a bind of a folder that is or holds a folder where those services keep their sockets, or of
623
+ * / that holds them all, put tmux's socket, the session bus and docker.sock in reach: a session started in /tmp or / gave
624
+ * workspace_autonomous's `.` that folder, and a profile that names no allowedPaths, whose only root is the folder its
625
+ * command runs in, bound any folder the agent named (the reviewer's recheck of round 2, 2026-11-23). There, as for a
626
+ * folder no bind holds (hostSocketFolderRefusal), one that lies in such a folder is refused too, unless it is the
627
+ * session's folder (SESSION_CWD) or lies in it: the folder the person started ZTC in is theirs to work in.
628
+ */
629
+ function hostSocketRootRefusal(profile, cwd, rootsCwd, env, sessionCwd) {
630
+ const real = (path) => { try {
631
+ return realpathSync(path);
632
+ }
633
+ catch {
634
+ return undefined;
635
+ } };
636
+ const reach = 'which bubblewrap keeps out of a command\'s reach.';
637
+ if (profile?.allowedPaths?.length) {
638
+ for (const entry of profile.allowedPaths) {
639
+ const root = normalizeRoot(entry, rootsCwd);
640
+ const what = hostSocketRelation(root, real(root), env, false);
641
+ if (what === undefined)
642
+ continue;
643
+ const instead = expandedRoot(entry).startsWith(sep)
644
+ ? 'Name a project\'s folder in its allowedPaths instead, to run commands under it.'
645
+ : `Start ZTC in a project's folder, which its relative root (${entry}) then names, to run commands under it.`;
646
+ return `Permission denied: this profile's root ${what} (${root}), ${reach} ${instead}`;
647
+ }
648
+ return undefined;
649
+ }
650
+ const folder = resolve(cwd);
651
+ const session = sessionCwd === undefined ? undefined : resolve(sessionCwd);
652
+ const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
653
+ const realFolder = real(folder);
654
+ // The session's own by where it leads, which bwrap binds: a link in the session's folder to tmux's folder is not its own.
655
+ const canonical = (path) => { try {
656
+ return canonicalPath(path);
657
+ }
658
+ catch {
659
+ return path;
660
+ } };
661
+ const inSession = session === undefined || inside(canonical(folder), canonical(session));
662
+ const what = hostSocketRelation(folder, realFolder, env, !inSession);
663
+ if (what === undefined)
664
+ return undefined;
665
+ const sessionUsable = session !== undefined && session !== folder && hostSocketRelation(session, real(session), env, false) === undefined;
666
+ return `Permission denied: working directory ${what} (${cwd}), ${reach} Run the command in another folder, such as a project's: `
667
+ + `give it one as its working directory${sessionUsable ? ', or none to run it in the session\'s folder' : ''}.`;
668
+ }
469
669
  /**
470
670
  * A seccomp filter, as bwrap --seccomp reads it, that refuses socket(AF_UNIX, …) with EACCES, and io_uring, whose
471
671
  * socket requests seccomp does not see. Pathname sockets are files, so no mount hides every one: this keeps a command
@@ -514,17 +714,22 @@ export function unixSocketFilter(arch = process.arch) {
514
714
  */
515
715
  export function buildBubblewrapArgs(command, cwd, profile, env = process.env,
516
716
  /** The descriptor bwrap reads a seccomp filter from (see unixSocketFilter), for a profile without network. */
517
- seccompFd) {
717
+ seccompFd, plan = {}) {
718
+ const hideOwnState = plan.hideOwnState ?? profileLimitsAgent(profile);
518
719
  const args = [
519
720
  '--die-with-parent',
520
721
  '--new-session',
521
722
  '--unshare-pid',
522
723
  '--unshare-ipc',
523
724
  '--unshare-uts',
524
- '--clearenv',
525
725
  ];
526
- for (const [name, value] of Object.entries(buildCredentialSafeSubprocessEnv(env))) {
527
- args.push('--setenv', name, value);
726
+ // A command that keeps the environment its caller built and started bwrap with (a hook's) is given it as it is,
727
+ // with none of its values in argv.
728
+ if (!plan.keepEnvironment) {
729
+ args.push('--clearenv');
730
+ for (const [name, value] of Object.entries(buildCredentialSafeSubprocessEnv(env))) {
731
+ args.push('--setenv', name, value);
732
+ }
528
733
  }
529
734
  // A profile that reads everywhere (see readsEverywhere) sees the whole filesystem read-only, as Seatbelt reads it on
530
735
  // macOS, except the folders where host services keep their sockets: a read-only bind does not stop connect(), and
@@ -542,33 +747,99 @@ seccompFd) {
542
747
  args.push('--ro-bind', root, root);
543
748
  }
544
749
  }
545
- // The project and what git reads, bound again over the private folders above where they lie under one.
546
- for (const root of allowedRoots(profile, cwd)) {
750
+ // The project and what git reads, bound again over the private folders above where they lie under one. The profile's
751
+ // relative roots are the session's folder's, wherever the command runs (allowedRoots).
752
+ const rootsCwd = plan.sessionCwd ?? cwd;
753
+ // Where no filter refuses the command Unix sockets, no root is bound that would put the host's services' sockets in
754
+ // its reach (hostSocketRootRefusal): the command doesn't start, and says why.
755
+ if (seccompFd === undefined) {
756
+ const refusal = hostSocketRootRefusal(profile, cwd, rootsCwd, env, plan.sessionCwd);
757
+ if (refusal !== undefined)
758
+ throw new Error(refusal);
759
+ }
760
+ // The files the command may also read (a hook's own program and script), bound read-only below.
761
+ const readPaths = everywhere ? [] : (plan.readPaths ?? []).filter(path => isAbsolute(path) && existsSync(path));
762
+ const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
763
+ const bound = [...(everywhere ? [] : BUBBLEWRAP_SYSTEM_READ_ROOTS.filter(root => existsSync(root))), ...allowedRoots(profile, cwd, rootsCwd),
764
+ ...(profileAllowsFileWrite(profile) ? [] : gitReadRoots(cwd)), ...readPaths];
765
+ // bwrap starts the command only in a folder its new root holds. A folder named through a link into a bound root (the
766
+ // workspace by another name) is entered by its real path. One no bind holds, which a profile that doesn't require the
767
+ // sandbox lets a command run in (the policy refuses it otherwise), is bound read-only, as Seatbelt lets a command read
768
+ // the folder it runs in, before the roots, so one it holds stays writable: since a profile's relative roots are the
769
+ // session's folder's, nothing bound it, and the command didn't start (the reviewer's bwrap argv probe, 2026-11-22). A
770
+ // profile that reads everywhere binds its folder as its root (allowedRoots). A folder where the host's services keep
771
+ // their sockets, or / that holds them, is never bound so: the command doesn't start, and says why
772
+ // (hostSocketFolderRefusal).
773
+ let chdir = cwd;
774
+ if (!bound.some(root => inside(cwd, root))) {
775
+ let real;
776
+ try {
777
+ real = realpathSync(cwd);
778
+ }
779
+ catch { /* bwrap says it can't enter it */ }
780
+ if (real !== undefined && bound.some(root => inside(real, root)))
781
+ chdir = real;
782
+ else {
783
+ const sessionHeld = bound.some(root => inside(rootsCwd, root)) ? rootsCwd : undefined;
784
+ const refusal = hostSocketFolderRefusal(cwd, real, env, allowedRoots(profile, cwd, rootsCwd), sessionHeld);
785
+ if (refusal !== undefined)
786
+ throw new Error(refusal);
787
+ if (real !== undefined) {
788
+ args.push('--ro-bind', cwd, cwd);
789
+ bound.push(cwd);
790
+ }
791
+ }
792
+ }
793
+ for (const root of allowedRoots(profile, cwd, rootsCwd)) {
547
794
  args.push(profileAllowsFileWrite(profile) ? '--bind' : '--ro-bind', root, root);
548
795
  }
796
+ // Where the repositories the command may work in name the programs git starts, read-only inside the writable roots
797
+ // though the command may commit (utils/git_program_files.ts): after the roots are bound, before anything is hidden.
798
+ const programs = plan.gitPrograms !== undefined ? plan.gitPrograms : commandGitProgramFiles(profile, cwd, plan.sessionCwd);
799
+ if (programs)
800
+ args.push(...bubblewrapGitProgramBinds(programs));
549
801
  if (!profileAllowsFileWrite(profile)) {
550
802
  for (const root of gitReadRoots(cwd))
551
803
  args.push('--ro-bind', root, root);
552
804
  }
805
+ // The files the command may also read (a hook's own program and script), read-only, after its roots and before
806
+ // anything is hidden, so ZTC's own state stays hidden under them too.
807
+ for (const path of readPaths)
808
+ args.push('--ro-bind', path, path);
553
809
  // Denied paths go last, so they win as Seatbelt's denies do: an empty folder over a denied folder, /dev/null over a
554
- // denied file. bwrap dropped them, so read_only with deniedPaths ['~/.ssh'] read the keys on Linux.
555
- for (const root of deniedRoots(profile, cwd)) {
810
+ // denied file. bwrap dropped them, so read_only with deniedPaths ['~/.ssh'] read the keys on Linux. ZTC's own state
811
+ // under a profile that limits the agent is hidden the same way where the command would see it; where nothing binds
812
+ // it, it is not there at all.
813
+ const emptied = everywhere ? hostSocketDirs(env) : ['/tmp'];
814
+ const seen = (path) => bound.some(root => inside(path, root)) || (everywhere && !emptied.some(root => inside(path, root)));
815
+ const hidden = [...deniedRoots(profile, rootsCwd), ...[...ownStateRoots(hideOwnState), ...(hideOwnState ? ztcRuntimeEntries() : [])].filter(seen)];
816
+ const emptiedOwnState = [];
817
+ for (const root of Array.from(new Set(hidden))) {
556
818
  try {
557
819
  const info = statSync(root);
558
- if (info.isDirectory())
820
+ if (info.isDirectory()) {
559
821
  args.push('--tmpfs', root);
822
+ emptiedOwnState.push(root);
823
+ }
560
824
  else
561
825
  args.push('--ro-bind', '/dev/null', root);
562
826
  }
563
827
  catch { /* nothing there to hide */ }
564
828
  }
829
+ // The person's skills folder in ZTC's own state, where hiding that state emptied it: bound back read-only, as the file
830
+ // tools read it, after every hide; a link in it into the rest of that state leads into the empty folder.
831
+ for (const root of ztcOwnSkillRoots()) {
832
+ if (hideOwnState && existsSync(root) && emptiedOwnState.some(folder => inside(root, folder) && root !== folder)) {
833
+ args.push('--ro-bind', root, root);
834
+ }
835
+ }
565
836
  if (!profileAllowsNetwork(profile)) {
566
837
  args.push('--unshare-net');
567
838
  // A socket file outside the folders above is still in reach: a profile without network may not open one.
568
839
  if (seccompFd !== undefined)
569
840
  args.push('--seccomp', String(seccompFd));
570
841
  }
571
- args.push('--chdir', cwd, '--', '/bin/sh', '-c', command);
842
+ args.push('--chdir', chdir, '--', '/bin/sh', '-c', command);
572
843
  return args;
573
844
  }
574
845
  function writeAudit(command, plan, options) {
@@ -579,6 +850,8 @@ function writeAudit(command, plan, options) {
579
850
  // A busy session can emit many per-command audit files; cap by age, count, or total size.
580
851
  const createdAt = new Date().toISOString();
581
852
  const auditPath = join(auditDir, `${createdAt.replace(/[:.]/g, '-')}-${process.pid}-${randomUUID()}.json`);
853
+ // The profile's relative roots are the session's folder's (allowedRoots), as the plan bound them.
854
+ const rootsCwd = options.sessionCwd ?? plan.cwd;
582
855
  writeFileSync(auditPath, JSON.stringify({
583
856
  schema_version: 1,
584
857
  created_at: createdAt,
@@ -587,16 +860,78 @@ function writeAudit(command, plan, options) {
587
860
  backend: plan.backend,
588
861
  enforcement: plan.enforcement,
589
862
  profile_id: options.profileId || null,
590
- allowed_paths: allowedRoots(options.profile, plan.cwd),
863
+ allowed_paths: allowedRoots(options.profile, plan.cwd, rootsCwd),
591
864
  // Where the command may read: the whole filesystem for a profile that reads everywhere (see readsEverywhere).
592
865
  read_paths: plan.enforcement !== 'os' ? null
593
- : commandReadRoots(options.profile, plan.cwd, plan.backend === 'seatbelt' ? SEATBELT_SYSTEM_READ_ROOTS : BUBBLEWRAP_SYSTEM_READ_ROOTS),
594
- denied_paths: deniedRoots(options.profile, plan.cwd),
866
+ : commandReadRoots(options.profile, plan.cwd, plan.backend === 'seatbelt' ? SEATBELT_SYSTEM_READ_ROOTS : BUBBLEWRAP_SYSTEM_READ_ROOTS, options.readPaths, rootsCwd),
867
+ denied_paths: deniedRoots(options.profile, rootsCwd),
868
+ // ZTC's own state, which a command under a profile that limits the agent never sees (utils/ztc_own_state.ts).
869
+ ztc_state_denied: ownStateRoots(plan.enforcement === 'os' && profileLimitsAgent(options.profile, options.sandbox)),
595
870
  network_hosts: options.profile?.networkHosts || null,
596
871
  notes: plan.notes,
597
872
  }, null, 2), { encoding: 'utf-8', mode: 0o600, flag: 'wx' });
598
873
  return auditPath;
599
874
  }
875
+ /**
876
+ * The bwrap plan for COMMAND in CWD under OPTIONS, which buildSandboxCommandPlan makes once it has found bwrap on this
877
+ * host: its argv (buildBubblewrapArgs), and the step after the command (afterCommand) that undoes what bwrap could not
878
+ * refuse it where a repository names the programs git starts, then puts back what it broke of a repository the plan
879
+ * knew, both from what the plan found before it ran.
880
+ */
881
+ export function buildBubblewrapCommandPlan(command, cwd, options = {}) {
882
+ const hideOwnState = profileLimitsAgent(options.profile, options.sandbox || { enabled: true, backend: 'auto' });
883
+ // Without network, bwrap reads a filter refusing Unix sockets from descriptor 3, which a shell opens for it.
884
+ const filter = profileAllowsNetwork(options.profile) ? null : unixSocketFilter();
885
+ // A plan whose roots would put the host's services' sockets in the command's reach is refused before anything looks
886
+ // for repositories in them (hostSocketRootRefusal), so it walks and records none.
887
+ if (!filter) {
888
+ const refusal = hostSocketRootRefusal(options.profile, cwd, options.sessionCwd ?? cwd, options.env ?? process.env, options.sessionCwd);
889
+ if (refusal !== undefined)
890
+ throw new Error(refusal);
891
+ }
892
+ const gitPrograms = commandGitProgramFiles(options.profile, cwd, options.sessionCwd);
893
+ const planOptions = { hideOwnState, keepEnvironment: options.keepEnvironment, sessionCwd: options.sessionCwd,
894
+ gitPrograms, readPaths: options.readPaths };
895
+ const afterCommand = gitPrograms
896
+ ? { afterCommand: () => [...undoGitProgramWrites(gitPrograms), ...putBackBrokenRepositories(gitPrograms)] }
897
+ : {};
898
+ const said = gitPrograms?.notes.length ? { notices: gitPrograms.notes } : {};
899
+ if (filter) {
900
+ // The argv first: a command it refuses to start leaves no filter behind (hostSocketFolderRefusal).
901
+ const bwrapArgs = buildBubblewrapArgs(command, cwd, options.profile, options.env, 3, planOptions);
902
+ const directory = mkdtempSync(join(tmpdir(), 'ztc-seccomp-'));
903
+ const cleanup = () => rmSync(directory, { recursive: true, force: true });
904
+ const filterPath = join(directory, 'unix-sockets.bpf');
905
+ try {
906
+ writeFileSync(filterPath, filter, { mode: 0o600, flag: 'wx' });
907
+ }
908
+ catch (error) {
909
+ cleanup();
910
+ throw error;
911
+ }
912
+ return {
913
+ executable: '/bin/sh',
914
+ args: ['-c', 'exec bwrap "$@" 3<"$0"', filterPath, ...bwrapArgs],
915
+ cwd,
916
+ backend: 'bubblewrap',
917
+ enforcement: 'os',
918
+ notes: ['bubblewrap namespace sandbox active; Unix sockets refused.', ...(gitPrograms?.notes ?? [])],
919
+ cleanup,
920
+ ...said,
921
+ ...afterCommand,
922
+ };
923
+ }
924
+ return {
925
+ executable: 'bwrap',
926
+ args: buildBubblewrapArgs(command, cwd, options.profile, options.env, undefined, planOptions),
927
+ cwd,
928
+ backend: 'bubblewrap',
929
+ enforcement: 'os',
930
+ notes: ['bubblewrap namespace sandbox active.', ...(gitPrograms?.notes ?? [])],
931
+ ...said,
932
+ ...afterCommand,
933
+ };
934
+ }
600
935
  export function buildSandboxCommandPlan(command, cwd, options = {}) {
601
936
  const sandbox = options.sandbox || { enabled: true, backend: 'auto' };
602
937
  if (!needsSandbox({ ...options, sandbox })) {
@@ -613,6 +948,8 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
613
948
  }
614
949
  const backend = platformBackend({ ...options, sandbox });
615
950
  const requireOs = requiresOsSandbox({ ...options, sandbox });
951
+ // Under a profile that limits the agent, its commands never see ZTC's own state (utils/ztc_own_state.ts).
952
+ const hideOwnState = profileLimitsAgent(options.profile, sandbox);
616
953
  let plan;
617
954
  if (backend === 'seatbelt') {
618
955
  if (process.platform !== 'darwin' || !commandExists('sandbox-exec')) {
@@ -626,7 +963,7 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
626
963
  };
627
964
  }
628
965
  else {
629
- const { path: profilePath, cleanup } = writeSeatbeltProfile(options.profile, cwd, options.env);
966
+ const { path: profilePath, cleanup, programs } = writeSeatbeltProfile(options.profile, cwd, options.env, hideOwnState, options.sessionCwd, options.readPaths);
630
967
  plan = {
631
968
  executable: '/usr/bin/sandbox-exec',
632
969
  args: ['-f', profilePath, '/bin/sh', '-c', command],
@@ -634,7 +971,10 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
634
971
  cwd,
635
972
  backend: 'seatbelt',
636
973
  enforcement: 'os',
637
- notes: [`Seatbelt profile: ${profilePath}`],
974
+ notes: [`Seatbelt profile: ${profilePath}`, ...(programs?.notes ?? [])],
975
+ ...(programs?.notes.length ? { notices: programs.notes } : {}),
976
+ // Seatbelt refuses what bwrap's step undoes, but not a write to HEAD, refs or objects, which a checkout needs.
977
+ ...(programs ? { afterCommand: () => putBackBrokenRepositories(programs) } : {}),
638
978
  cleanup,
639
979
  };
640
980
  }
@@ -651,39 +991,7 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
651
991
  };
652
992
  }
653
993
  else {
654
- // Without network, bwrap reads a filter refusing Unix sockets from descriptor 3, which a shell opens for it.
655
- const filter = profileAllowsNetwork(options.profile) ? null : unixSocketFilter();
656
- if (filter) {
657
- const directory = mkdtempSync(join(tmpdir(), 'ztc-seccomp-'));
658
- const cleanup = () => rmSync(directory, { recursive: true, force: true });
659
- const filterPath = join(directory, 'unix-sockets.bpf');
660
- try {
661
- writeFileSync(filterPath, filter, { mode: 0o600, flag: 'wx' });
662
- }
663
- catch (error) {
664
- cleanup();
665
- throw error;
666
- }
667
- plan = {
668
- executable: '/bin/sh',
669
- args: ['-c', 'exec bwrap "$@" 3<"$0"', filterPath, ...buildBubblewrapArgs(command, cwd, options.profile, options.env, 3)],
670
- cwd,
671
- backend: 'bubblewrap',
672
- enforcement: 'os',
673
- notes: ['bubblewrap namespace sandbox active; Unix sockets refused.'],
674
- cleanup,
675
- };
676
- }
677
- else {
678
- plan = {
679
- executable: 'bwrap',
680
- args: buildBubblewrapArgs(command, cwd, options.profile, options.env),
681
- cwd,
682
- backend: 'bubblewrap',
683
- enforcement: 'os',
684
- notes: ['bubblewrap namespace sandbox active.'],
685
- };
686
- }
994
+ plan = buildBubblewrapCommandPlan(command, cwd, { ...options, sandbox });
687
995
  }
688
996
  }
689
997
  else if (backend === 'windows-job') {