@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
@@ -7,7 +7,7 @@ import { spawn } from 'node:child_process';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { activeProfile, validateProfileName } from '../config/profiles.js';
9
9
  import { writeFileAtomic } from '../utils/atomic_write.js';
10
- import { withoutMirrorCredentials } from '../web/pane_credentials.js';
10
+ import { buildUserSubprocessEnv } from '../utils/subprocess_env.js';
11
11
  const root = () => join(process.env.ZTC_CONFIG_DIR || join(homedir(), '.ztc'), 'environments');
12
12
  const namePattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
13
13
  const valid = (name) => {
@@ -302,9 +302,10 @@ export async function startEnvironmentService(name, sessionId, serviceName, comm
302
302
  await save(record);
303
303
  const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
304
304
  const runner = fileURLToPath(new URL(`./service_runner.${extension}`, import.meta.url));
305
- // The runner starts without the mirror's credentials this process holds: any program running as this user can read
306
- // the environment a process starts with.
307
- const child = spawn(process.execPath, [...(extension === 'ts' ? ['--import', import.meta.resolve('tsx')] : []), runner, serviceDir], { cwd: serviceCwd, detached: true, stdio: 'ignore', env: withoutMirrorCredentials(process.env) });
305
+ // The runner starts with a user subprocess's environment, the one its service gets: none of ZTC's credentials (the
306
+ // mirror's, the Router grant), which any program running as this user can read in the environment a process
307
+ // starts with, and no route credential a headless run keeps from its tools.
308
+ const child = spawn(process.execPath, [...(extension === 'ts' ? ['--import', import.meta.resolve('tsx')] : []), runner, serviceDir], { cwd: serviceCwd, detached: true, stdio: 'ignore', env: buildUserSubprocessEnv(process.env) });
308
309
  child.unref();
309
310
  try {
310
311
  await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
@@ -4,10 +4,20 @@ export type ExtensionDiscoveryPolicy = 'default' | 'explicit';
4
4
  * Resolve the process-wide extension discovery policy.
5
5
  *
6
6
  * `explicit` is a hosted-runtime boundary: only roots named by the relevant
7
- * `ZTC_*_PATHS` variable and packaged builtins may participate. Leaving the
8
- * variable unset preserves interactive ZTC's cwd/repository/home discovery.
7
+ * `ZTC_*_PATHS` variable and packaged builtins may participate. A host sets it
8
+ * with ZTC_EXTENSION_DISCOVERY=explicit. With the variable unset (or blank), a
9
+ * ZTC that holds a host Router runtime grant (holdsHostRouterGrant), one that
10
+ * takes effect or not, discovers explicitly too, so a resident on a grant
11
+ * imports no plugin, mode, skill or workflow from its working directory, that
12
+ * directory's repository or HOME, where an agent writes, into the process that
13
+ * holds the grant. A host that sets the variable still decides: `default`
14
+ * keeps interactive ZTC's cwd/repository/home discovery, grant or not. With it
15
+ * unset and no grant (the desktop's and an npm install's ZTC), discovery is
16
+ * `default`.
9
17
  */
10
18
  export declare function extensionDiscoveryPolicy(environment?: NodeJS.ProcessEnv): ExtensionDiscoveryPolicy;
11
19
  export declare function isExplicitExtensionDiscovery(environment?: NodeJS.ProcessEnv): boolean;
20
+ /** ARGS, a ZTC's launch arguments, without the flags before a `--` that add extension roots, nor the value each takes. */
21
+ export declare function withoutExtensionRootFlags(args: readonly string[]): string[];
12
22
  /** Resolve one ordered, platform-delimited extension-root variable. */
13
23
  export declare function extensionPathsFromEnvironment(variable: string, environment?: NodeJS.ProcessEnv, cwd?: string): string[];
@@ -1,23 +1,68 @@
1
1
  import { delimiter, isAbsolute, resolve } from 'node:path';
2
+ import { hostEnvironmentValue, ROUTER_RUNTIME_GRANT_ENV } from './config/host_credentials.js';
2
3
  export const ZTC_EXTENSION_DISCOVERY_ENV = 'ZTC_EXTENSION_DISCOVERY';
4
+ /**
5
+ * Whether ENVIRONMENT holds a host Router runtime grant: ZTC_ROUTER_RUNTIME_GRANT set to anything but blanks, whether or
6
+ * not it takes effect (a usable bearer for a Router ZERG_ROUTER_BASE_URL names over https or loopback http). This
7
+ * process's own environment is read through the host-credential store, which took the grant out of it at startup and
8
+ * holds it either way, where code running in this process can read it (as panes/motsi.ts remoteViewMotsi reads it).
9
+ */
10
+ function holdsHostRouterGrant(environment) {
11
+ return Boolean(hostEnvironmentValue(ROUTER_RUNTIME_GRANT_ENV, environment)?.trim());
12
+ }
3
13
  /**
4
14
  * Resolve the process-wide extension discovery policy.
5
15
  *
6
16
  * `explicit` is a hosted-runtime boundary: only roots named by the relevant
7
- * `ZTC_*_PATHS` variable and packaged builtins may participate. Leaving the
8
- * variable unset preserves interactive ZTC's cwd/repository/home discovery.
17
+ * `ZTC_*_PATHS` variable and packaged builtins may participate. A host sets it
18
+ * with ZTC_EXTENSION_DISCOVERY=explicit. With the variable unset (or blank), a
19
+ * ZTC that holds a host Router runtime grant (holdsHostRouterGrant), one that
20
+ * takes effect or not, discovers explicitly too, so a resident on a grant
21
+ * imports no plugin, mode, skill or workflow from its working directory, that
22
+ * directory's repository or HOME, where an agent writes, into the process that
23
+ * holds the grant. A host that sets the variable still decides: `default`
24
+ * keeps interactive ZTC's cwd/repository/home discovery, grant or not. With it
25
+ * unset and no grant (the desktop's and an npm install's ZTC), discovery is
26
+ * `default`.
9
27
  */
10
28
  export function extensionDiscoveryPolicy(environment = process.env) {
11
29
  const value = environment[ZTC_EXTENSION_DISCOVERY_ENV]?.trim();
12
- if (value === undefined || value === '')
13
- return 'default';
14
- if (value === 'explicit')
15
- return 'explicit';
16
- throw new Error(`${ZTC_EXTENSION_DISCOVERY_ENV} must be "explicit" or unset`);
30
+ if (value === 'explicit' || value === 'default')
31
+ return value;
32
+ if (value !== undefined && value !== '') {
33
+ throw new Error(`${ZTC_EXTENSION_DISCOVERY_ENV} must be "explicit" or unset, or "default" for discovery from the working directory, its repository and HOME with a host's grant`);
34
+ }
35
+ return holdsHostRouterGrant(environment) ? 'explicit' : 'default';
17
36
  }
18
37
  export function isExplicitExtensionDiscovery(environment = process.env) {
19
38
  return extensionDiscoveryPolicy(environment) === 'explicit';
20
39
  }
40
+ /**
41
+ * The launch flags that add an extension root of a ZTC's own: --domain-paths, which src/cli_main.ts turns into
42
+ * ZTC_DOMAIN_PATHS. A ZTC that another ZTC starts with explicit discovery is given none (withoutExtensionRootFlags): its
43
+ * roots are the ZTC_*_PATHS its host set, which it inherits, never a folder an agent or a relay client named.
44
+ */
45
+ const EXTENSION_ROOT_FLAGS = ['--domain-paths'];
46
+ /** ARGS, a ZTC's launch arguments, without the flags before a `--` that add extension roots, nor the value each takes. */
47
+ export function withoutExtensionRootFlags(args) {
48
+ const kept = [];
49
+ for (let i = 0; i < args.length; i++) {
50
+ const arg = args[i];
51
+ if (arg === '--') {
52
+ kept.push(...args.slice(i));
53
+ break;
54
+ }
55
+ if (EXTENSION_ROOT_FLAGS.includes(arg)) {
56
+ if (args[i + 1] !== undefined && !args[i + 1].startsWith('-'))
57
+ i++;
58
+ continue;
59
+ }
60
+ if (EXTENSION_ROOT_FLAGS.some(flag => arg.startsWith(`${flag}=`)))
61
+ continue;
62
+ kept.push(arg);
63
+ }
64
+ return kept;
65
+ }
21
66
  /** Resolve one ordered, platform-delimited extension-root variable. */
22
67
  export function extensionPathsFromEnvironment(variable, environment = process.env, cwd = process.cwd()) {
23
68
  // Validate the generic policy at every loader boundary, including loaders
@@ -305,6 +305,14 @@ export declare class HeadlessApp {
305
305
  private readonly effectivePolicy;
306
306
  private readonly approvalClient;
307
307
  constructor(options: HeadlessOptions, sinks?: HeadlessSinks);
308
+ /** A notice from the agent or a summary's request: its diagnostic already went to stderr; a JSON consumer gets it as a status. */
309
+ private reportNotice;
310
+ /**
311
+ * Zerg Router took a request only without the images the person attached that NOTE stands in for (all but those of a
312
+ * media type in KEEP): the note stands in for them in the conversation this run keeps and saves, so no later turn or
313
+ * resumed session sends them.
314
+ */
315
+ private withholdAttachedImages;
308
316
  private buildHandoffSummarizer;
309
317
  private outputPromptComplete;
310
318
  /**
package/dist/headless.js CHANGED
@@ -1,9 +1,13 @@
1
1
  import { environmentOperationInProgress } from './agent/commands/environment.js';
2
+ import { withheldAttachedImages } from './agent/attached_images.js';
3
+ import { pinnedRouteCommandRefusal } from './config/model_pin.js';
2
4
  import { isAnnouncementOnly } from './agent/loop_policy.js';
3
- import { PermissionProfileUnsupportedError } from './config/permissions.js';
5
+ import { commandPolicyFor, PermissionProfileUnsupportedError } from './config/permissions.js';
6
+ import { hostCredential } from './config/host_credentials.js';
4
7
  import { ASK_USER_SKIP } from './app/ask_user_response.js';
5
8
  import { getEnvironment, openEnvironment, releaseEnvironment, describeEnvironmentForAgent, isEnvironmentWorkspacePath, EnvironmentRecoveryError } from './environment/store.js';
6
9
  import { inferAgentPaneTitle, readPaneLabels } from './panes/labels.js';
10
+ import { remoteViewMotsi } from './panes/motsi.js';
7
11
  import { listCommandJobs, shutdownCommandJobs, subscribeCommandJobs } from './agent/runtime/command_jobs.js';
8
12
  import { TurnTimeLimit } from './agent/runtime/turn_limit.js';
9
13
  import { ToolResponseStore } from './agent/tool_response_store.js';
@@ -39,6 +43,7 @@ import { formatTaskHandoffContext, handoffSubstance, projectTaskHandoff } from '
39
43
  import { describeRun, describeRunCommand, handoffRunRows, listRuns, openFailures } from './agent/runtime/run_log.js';
40
44
  import { RouterConfigurationError } from './router_auth.js';
41
45
  import { currentRouterOnlyModelError, RouterOnlyModelError } from './agent/commands/provider_choices.js';
46
+ import { RemoteResourceConfigurationError } from './agent/runtime/remote_resource_errors.js';
42
47
  import { DiagnosticExportError } from './diagnostics/session_export.js';
43
48
  import { redactErrorText } from './agent/backends/http_error.js';
44
49
  import { routerRefusalOf } from './agent/backends/router_refusal.js';
@@ -78,7 +83,7 @@ import { LocalWorkspaceCoordinator } from './workspace_collision.js';
78
83
  import { HeadlessPaneManager } from './ui/ratatui/headless_pane_manager.js';
79
84
  import { modelHandoffSummarizer } from './utils/compaction.js';
80
85
  import { setPaneToolsTuiProcess, clearPaneToolsTuiProcess, setBusTransport, clearBusTransport, getBackgroundRegistry, clearBackgroundRegistry, resetAskUserTurnFlag, setTodoUpdateCallback } from './agent/tools/index.js';
81
- import { PaneRelayServer, generateRelaySocketPath } from './ui/ratatui/pane_relay.js';
86
+ import { PaneRelayServer, generateRelaySocketPath, startStaleRelaySweep } from './ui/ratatui/pane_relay.js';
82
87
  import { writePaneResponseSync } from './utils/pane_response.js';
83
88
  import { terminateActiveShellChildren } from './utils/shell.js';
84
89
  import { launchedByAnotherZtc, reserveModelRouteCredentials } from './utils/subprocess_env.js';
@@ -235,7 +240,8 @@ function failureReasonOf(error, message) {
235
240
  * the default guidance. Every variant keeps the established prefix.
236
241
  */
237
242
  function missingCredentialsMessage(profile) {
238
- const alternatives = 'set a provider API key for direct mode, or provide ZTC_AUTH_TOKEN for platform routing.';
243
+ // A platform login goes only to a platform API someone named (ConfigStore.platformApiNamed).
244
+ const alternatives = 'set a provider API key for direct mode, or provide ZTC_AUTH_TOKEN with ZTC_API_BASE_URL for platform routing.';
239
245
  if (profileConfigDir(profile) === profileConfigDir('default')) {
240
246
  return `No API credentials configured. Run ztc auth login for Zerg Router, ${alternatives}`;
241
247
  }
@@ -360,7 +366,8 @@ function stableErrorCode(error) {
360
366
  }
361
367
  function initializationFailure(error) {
362
368
  if (error instanceof RouterConfigurationError || error instanceof EnvironmentRecoveryError || error instanceof RouteAwaitingChoiceError
363
- || error instanceof RouterOnlyModelError || error instanceof PermissionProfileUnsupportedError) {
369
+ || error instanceof RouterOnlyModelError || error instanceof PermissionProfileUnsupportedError
370
+ || error instanceof RemoteResourceConfigurationError) {
364
371
  return { message: error.message };
365
372
  }
366
373
  if (error instanceof DiagnosticExportError)
@@ -679,7 +686,7 @@ export class HeadlessApp {
679
686
  constructor(options, sinks = {}) {
680
687
  this.effectivePolicy = sinks.policy ?? null;
681
688
  const approvalUrl = options.approvalUrl ?? process.env.ZTC_APPROVAL_URL;
682
- this.approvalClient = approvalUrl ? new RemoteApprovalClient(approvalUrl, process.env.ZTC_APPROVAL_TOKEN) : null;
689
+ this.approvalClient = approvalUrl ? new RemoteApprovalClient(approvalUrl, hostCredential('ZTC_APPROVAL_TOKEN')) : null;
683
690
  this.outputSchema = sinks.outputSchema ?? null;
684
691
  this.trajectory = sinks.trajectory ?? null;
685
692
  this.options = {
@@ -763,13 +770,32 @@ export class HeadlessApp {
763
770
  model: configStore.getModel(),
764
771
  }),
765
772
  getApprovalRequester: () => (request) => this.requestHookApproval(request),
773
+ // A hook runs under the agent's permission profile: inside the OS sandbox it requires, as run_command does.
774
+ getCommandPolicy: () => commandPolicyFor(configStore.get()),
766
775
  });
767
776
  }
777
+ /** A notice from the agent or a summary's request: its diagnostic already went to stderr; a JSON consumer gets it as a status. */
778
+ reportNotice(message) {
779
+ if (this.options.json)
780
+ this.output({ type: 'status', timestamp: new Date().toISOString(), data: { status: 'notice', message } });
781
+ }
782
+ /**
783
+ * Zerg Router took a request only without the images the person attached that NOTE stands in for (all but those of a
784
+ * media type in KEEP): the note stands in for them in the conversation this run keeps and saves, so no later turn or
785
+ * resumed session sends them.
786
+ */
787
+ withholdAttachedImages(note, keep) {
788
+ this.messages.splice(0, this.messages.length, ...withheldAttachedImages(this.messages, note, keep));
789
+ }
768
790
  buildHandoffSummarizer(signal, messages) {
769
791
  const agent = this.agent;
770
792
  if (!agent)
771
793
  return undefined;
772
- const context = agent.getHandoffContext(messages ?? this.messages);
794
+ // A summary is asked for between turns as much as during one: what its request went without is told here.
795
+ const context = agent.getHandoffContext(messages ?? this.messages, {
796
+ onNotice: message => this.reportNotice(message),
797
+ onAttachedImagesWithheld: (note, keep) => this.withholdAttachedImages(note, keep),
798
+ });
773
799
  return modelHandoffSummarizer(context.backend, context.model, {
774
800
  request: context,
775
801
  signal,
@@ -1104,10 +1130,10 @@ export class HeadlessApp {
1104
1130
  });
1105
1131
  break;
1106
1132
  case 'notice':
1107
- // The notice's diagnostic already went to stderr; a JSON consumer gets it as a status.
1108
- if (this.options.json) {
1109
- this.output({ type: 'status', timestamp: new Date().toISOString(), data: { status: 'notice', message: event.message } });
1110
- }
1133
+ this.reportNotice(event.message);
1134
+ break;
1135
+ case 'attached_images_withheld':
1136
+ this.withholdAttachedImages(event.note, event.keep);
1111
1137
  break;
1112
1138
  case 'history_checkpoint':
1113
1139
  // A compaction replaces what the model sees; an orchestrator should know even under --quiet, since file
@@ -1836,8 +1862,14 @@ export class HeadlessApp {
1836
1862
  // Start pane relay server so child panes (--pane) can connect and use pane tools
1837
1863
  const relayPath = generateRelaySocketPath();
1838
1864
  process.env.ZTC_PANE_RELAY = relayPath;
1839
- this.paneRelay = new PaneRelayServer(this.paneManager, relayPath);
1865
+ // A ZTC pane a child asks for through MotSi runs inside the motsi this ZTC's MotSi remote view names, never the
1866
+ // child's (ztc_launch_trust.ts).
1867
+ this.paneRelay = new PaneRelayServer(this.paneManager, relayPath, {
1868
+ ztcPanesThroughMotsi: () => remoteViewMotsi(configStore.get().panes),
1869
+ });
1840
1870
  await this.paneRelay.start();
1871
+ // A relay with a directory of its own in /tmp clears the ones relays that are gone left there.
1872
+ startStaleRelaySweep(relayPath);
1841
1873
  await runtimePluginRegistry.runMuxStartHooks({
1842
1874
  paneManager: this.paneManager,
1843
1875
  relayPath,
@@ -2245,7 +2277,7 @@ export class HeadlessApp {
2245
2277
  const servers = configStore.get().mcpServers;
2246
2278
  if ((servers && Object.keys(servers).length > 0) || colonyOptIn()) {
2247
2279
  const { initMcpServers } = await import('./mcp/client.js');
2248
- await initMcpServers(servers);
2280
+ await initMcpServers(servers, { providerKeyEnv: configStore.get().apiKeyEnv });
2249
2281
  }
2250
2282
  };
2251
2283
  const reloadSkills = async () => {
@@ -2605,6 +2637,10 @@ export class HeadlessApp {
2605
2637
  if (denial) {
2606
2638
  return denial;
2607
2639
  }
2640
+ // A session its host pinned keeps its route, whoever asks to move it (config/model_pin.ts).
2641
+ const pinned = pinnedRouteCommandRefusal(cmd, cmdArgs);
2642
+ if (pinned)
2643
+ return pinned;
2608
2644
  // Global command lookup first — global commands may have richer behavior than mode handlers
2609
2645
  if (cmd.toLowerCase() === 'model' && (this.turnAdmissionCount > 0 || this.activeRunController || this.runtimeMutationDone))
2610
2646
  return 'Cannot switch model while an active agent turn or account change is running.';
@@ -3737,7 +3773,10 @@ export class HeadlessApp {
3737
3773
  if (!agent)
3738
3774
  return null;
3739
3775
  process.stderr.write('[ztc] Asking the model for a short handoff after the time limit (up to 30s).\n');
3740
- const context = agent.getHandoffContext(this.messages);
3776
+ const context = agent.getHandoffContext(this.messages, {
3777
+ onNotice: message => this.reportNotice(message),
3778
+ onAttachedImagesWithheld: (note, keep) => this.withholdAttachedImages(note, keep),
3779
+ });
3741
3780
  // One try within 30 s: the run is already past its time. No output limit: a reasoning model spends one thinking.
3742
3781
  const summarize = modelHandoffSummarizer(context.backend, context.model, { request: context, system: context.system,
3743
3782
  tools: context.tools, timeoutMs: 30_000, apiRetry: { ...context.apiRetry, maxAttempts: 1 }, prompt: TIMEOUT_HANDOFF_PROMPT });
@@ -2,6 +2,7 @@
2
2
  import { resolve } from 'node:path';
3
3
  import { refuseRetiredRoute, retiredRouteRefusalFor, sayRetiredRouteNotices } from './app/retired_route_gate.js';
4
4
  import { getDefaultModelForProvider } from './config/defaults.js';
5
+ import { PermissionPinChangedError, PermissionPinUnlimitedError, pinnedUnlimitedMessage } from './config/permission_pin.js';
5
6
  import { CODEX_REASONING_EFFORTS } from './config/types.js';
6
7
  import { parseHeadlessCliArgs } from './headless_cli_args.js';
7
8
  import { unsupportedEffortMessage } from './utils/models.js';
@@ -114,7 +115,7 @@ async function main() {
114
115
  const servers = configStore.get().mcpServers;
115
116
  if (servers && Object.keys(servers).length > 0) {
116
117
  const { initMcpServers } = await import('./mcp/client.js');
117
- await initMcpServers(servers);
118
+ await initMcpServers(servers, { providerKeyEnv: configStore.get().apiKeyEnv });
118
119
  }
119
120
  try {
120
121
  const { preloadSkillsManifest } = await import('./skills/registry.js');
@@ -143,6 +144,20 @@ async function main() {
143
144
  throw new Error(`Agent domain "${options.agentDomain}" is incomplete: no executable handler for ${missingTools.join(', ')}`);
144
145
  }
145
146
  }
147
+ // Startup is done: a host that pins the permission settings (ZTC_PERMISSION_PROFILE_PINNED) pins them now, as `ztc`
148
+ // does, so no command in the run changes them; a profile that limits nothing it pins none, and the run doesn't start.
149
+ try {
150
+ configStore.pinStartupPermissions();
151
+ }
152
+ catch (error) {
153
+ if (!(error instanceof PermissionPinChangedError) && !(error instanceof PermissionPinUnlimitedError))
154
+ throw error;
155
+ // This package takes no --permission-profile: the profile it runs under is the one config.json saves.
156
+ const message = error instanceof PermissionPinUnlimitedError ? pinnedUnlimitedMessage(error.profileId, false, error.unsandboxed) : error.message;
157
+ process.stderr.write(`[ztc-headless] ${message}\n`);
158
+ process.exitCode = 2;
159
+ return;
160
+ }
146
161
  const { runHeadless } = await import('./headless.js');
147
162
  const headlessOptions = {
148
163
  approvalUrl: options.approvalUrl,
@@ -19,7 +19,7 @@ export async function runTriggeredWorkflowTool(input) {
19
19
  },
20
20
  hooks: input.hooks,
21
21
  approvalRequester: input.approvalRequester,
22
- policy: new CapabilityPolicy(input.toolPermissions ?? config.toolPermissions, input.permissionProfile ?? resolveActivePermissionProfile(config), input.cwd),
22
+ policy: new CapabilityPolicy(input.toolPermissions ?? config.toolPermissions, input.permissionProfile ?? resolveActivePermissionProfile(config), input.cwd, { sandbox: config.sandbox }),
23
23
  });
24
24
  }
25
25
  function resolveActivePermissionProfile(config) {
@@ -1,15 +1,23 @@
1
+ import type { SandboxCommandOptions } from '../utils/sandbox.js';
1
2
  import type { HookApprovalRequester, HookBaseContext, HookCommandConfig, HookDispatchResult, HookEventName, ZTCHooksConfig } from './types.js';
2
3
  export interface HookEntryFingerprint {
3
4
  event: HookEventName;
4
5
  command: string;
5
6
  tools?: string[];
6
7
  paths?: string[];
8
+ /** The variables the hook is given beyond its defaults (HookCommandConfig.passEnv). */
9
+ passEnv?: string[];
7
10
  }
8
11
  export declare function hashHookEntry(fp: HookEntryFingerprint): string;
9
12
  export interface HookDispatcherDeps {
10
13
  approvedHashes: Set<string>;
11
14
  persistApprovedHash?: (hash: string) => void;
12
15
  approvalRequester?: HookApprovalRequester;
16
+ /**
17
+ * The agent's command policy as it stands when a hook runs: under one that requires an OS sandbox, hooks run inside
18
+ * it, as run_command does, or not at all (runner.ts).
19
+ */
20
+ commandPolicy?: () => SandboxCommandOptions | undefined;
13
21
  }
14
22
  export declare class HookDispatcher {
15
23
  private hooks;
@@ -9,6 +9,10 @@ export function hashHookEntry(fp) {
9
9
  tools: fp.tools && fp.tools.length > 0 ? [...fp.tools].sort() : [],
10
10
  paths: fp.paths && fp.paths.length > 0 ? [...fp.paths].sort() : [],
11
11
  };
12
+ // What a hook is given is part of what was approved, so a hook whose passEnv is widened is asked about again. A hook
13
+ // that names none keeps the hash it always had, and with it the approval stored for it.
14
+ if (fp.passEnv && fp.passEnv.length > 0)
15
+ canonical.passEnv = [...new Set(fp.passEnv)].sort();
12
16
  return createHash('sha256').update(JSON.stringify(canonical)).digest('hex');
13
17
  }
14
18
  // Supports only `*` wildcards (zero or more of anything, including `/`).
@@ -65,6 +69,7 @@ export class HookDispatcher {
65
69
  approvedHashes: deps?.approvedHashes ?? new Set(),
66
70
  persistApprovedHash: deps?.persistApprovedHash,
67
71
  approvalRequester: deps?.approvalRequester,
72
+ commandPolicy: deps?.commandPolicy,
68
73
  };
69
74
  }
70
75
  setHooks(hooks) {
@@ -80,6 +85,8 @@ export class HookDispatcher {
80
85
  this.deps.persistApprovedHash = deps.persistApprovedHash;
81
86
  if (deps.approvalRequester !== undefined)
82
87
  this.deps.approvalRequester = deps.approvalRequester;
88
+ if (deps.commandPolicy !== undefined)
89
+ this.deps.commandPolicy = deps.commandPolicy;
83
90
  }
84
91
  getHooks(event) {
85
92
  return this.hooks[event] || [];
@@ -99,6 +106,7 @@ export class HookDispatcher {
99
106
  command: entry.command,
100
107
  tools: entry.tools,
101
108
  paths: entry.paths,
109
+ passEnv: entry.passEnv,
102
110
  });
103
111
  if (this.deps.approvedHashes.has(hash))
104
112
  return true;
@@ -120,12 +128,14 @@ export class HookDispatcher {
120
128
  toolName: entry.command,
121
129
  args: {},
122
130
  capabilities: [],
123
- reason: `First run of ${event} hook this session`,
131
+ reason: `First run of ${event} hook this session${entry.passEnv?.length
132
+ ? `; its passEnv asks for ${[...new Set(entry.passEnv)].join(', ')} from ZTC's environment` : ''}`,
124
133
  firstRun: {
125
134
  event,
126
135
  command: entry.command,
127
136
  ...(entry.tools ? { tools: entry.tools } : {}),
128
137
  ...(entry.paths ? { paths: entry.paths } : {}),
138
+ ...(entry.passEnv?.length ? { passEnv: [...new Set(entry.passEnv)] } : {}),
129
139
  hash,
130
140
  },
131
141
  });
@@ -179,7 +189,17 @@ export class HookDispatcher {
179
189
  isSubagent: this.context.isSubagent,
180
190
  payload,
181
191
  };
182
- const result = await runHookEntries(event, gatedEntries, envelope);
192
+ let commandPolicy;
193
+ try {
194
+ commandPolicy = this.deps.commandPolicy?.();
195
+ }
196
+ catch (error) {
197
+ // A policy that cannot be read is never read as no policy: no hook runs on it.
198
+ const reason = error instanceof Error ? error.message : String(error);
199
+ return { matched: matchedEntries.length, executed: 0, failed: true, failureReason: `${event} hook refused: no command policy`,
200
+ messages: [...skipMessages, { level: 'error', text: `${event} hooks were not run: ZTC could not read the permission profile they run under (${reason}).` }] };
201
+ }
202
+ const result = await runHookEntries(event, gatedEntries, envelope, { commandPolicy });
183
203
  if (skipMessages.length > 0) {
184
204
  result.messages.unshift(...skipMessages);
185
205
  }
@@ -1,5 +1,6 @@
1
1
  import { HookDispatcher } from './dispatcher.js';
2
2
  import { type HookApprovalRequester, type ZTCHooksConfig } from './types.js';
3
+ import type { SandboxCommandOptions } from '../utils/sandbox.js';
3
4
  export interface HookLifecycleOptions {
4
5
  sessionId: string;
5
6
  getCwd: () => string;
@@ -9,6 +10,11 @@ export interface HookLifecycleOptions {
9
10
  getSessionStartPayload?: () => Record<string, unknown>;
10
11
  isSubagent?: boolean;
11
12
  getApprovalRequester?: () => HookApprovalRequester | undefined;
13
+ /**
14
+ * The agent's command policy (its permission profile and sandbox settings), read when a hook runs: under one that
15
+ * requires an OS sandbox, hooks run inside it or not at all (runner.ts).
16
+ */
17
+ getCommandPolicy?: () => SandboxCommandOptions | undefined;
12
18
  approvedStorePath?: string;
13
19
  }
14
20
  export declare class HookLifecycle {
@@ -67,6 +67,7 @@ export class HookLifecycle {
67
67
  approvedHashes: this.approvedHashes,
68
68
  persistApprovedHash: this.persistApprovedHash,
69
69
  approvalRequester,
70
+ ...(this.options.getCommandPolicy ? { commandPolicy: this.options.getCommandPolicy } : {}),
70
71
  });
71
72
  }
72
73
  else {
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The files a hook's COMMAND starts, run from CWD with ENV (its PATH and HOME): the program of each of its commands,
3
+ * found as its shell would find it; the interpreter a script's #! names, /usr/bin/env's program found on PATH; and the
4
+ * script an interpreter (INTERPRETERS) is given, its first argument that is a file. Each is given with the file its
5
+ * links lead to. Under a profile that limits the agent and lets it write, a hook's OS sandbox reads these beside the
6
+ * system and the project (hooks/runner.ts): the hook's own code, which its command line names. That command line is
7
+ * the person's, held as it was at startup under such a profile; no path the agent chooses is among them, and nothing
8
+ * else a hook reads or writes is.
9
+ */
10
+ export declare function hookProgramFiles(command: string, cwd: string, env: NodeJS.ProcessEnv): string[];