@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
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Where the agent may have written the repository's config: no hook runs (core.hooksPath=/dev/null) and nothing writes
3
+ * the index (--no-optional-locks), beside what every probe takes under every profile (utils/git_probe_options.ts: no
4
+ * fsmonitor, no signature verified by a log, no implicit bare repository). None of rev-parse, branch, symbolic-ref and
5
+ * log then starts a program the repository names.
6
+ */
7
+ export declare const GIT_NO_REPOSITORY_PROGRAM_OPTIONS: readonly string[];
8
+ /**
9
+ * Whether ZTC's own git in the agent's work tree must start no program the repository's config names, under the
10
+ * permission settings this process runs with now: a profile that limits the agent and lets its commands write. One
11
+ * that can't be read counts as one.
12
+ */
13
+ export declare function gitProbesStartNoRepositoryProgram(): boolean;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The git ZTC itself runs in the agent's work tree: the startup snapshot of every start (runtime_info.ts), /status and
3
+ * /runtime, the session's work check (agent/runtime/work_base.ts) and a verified command's source receipt
4
+ * (agent/runtime/source_verification.ts). It runs outside any sandbox the agent works under, as ZTC, and git starts the
5
+ * programs the repository's config names: an external diff and a textconv driver for a diff, a clean filter for a
6
+ * status or a diff of a changed file, a hook when it writes the index, a signature program for a log. Under every
7
+ * profile its diffs and logs start none of the external diff, textconv and signature programs (utils/git_probe_options.ts).
8
+ * Under a profile where the agent writes that config (agentWritesGitConfig), the rest would be the agent's programs run
9
+ * past its sandbox (the reviewer's resident probe, 2026-11-21): there these probes run only commands that start none of
10
+ * them, with the options below, and do not read the work tree's status or diff.
11
+ */
12
+ import { configStore } from '../config.js';
13
+ import { commandPolicyFor } from '../config/permissions.js';
14
+ import { agentWritesGitConfig } from '../config/profile_limits.js';
15
+ import { GIT_PROBE_OPTIONS } from './git_probe_options.js';
16
+ /**
17
+ * Where the agent may have written the repository's config: no hook runs (core.hooksPath=/dev/null) and nothing writes
18
+ * the index (--no-optional-locks), beside what every probe takes under every profile (utils/git_probe_options.ts: no
19
+ * fsmonitor, no signature verified by a log, no implicit bare repository). None of rev-parse, branch, symbolic-ref and
20
+ * log then starts a program the repository names.
21
+ */
22
+ export const GIT_NO_REPOSITORY_PROGRAM_OPTIONS = Object.freeze([
23
+ ...GIT_PROBE_OPTIONS, '-c', 'core.hooksPath=/dev/null', '--no-optional-locks',
24
+ ]);
25
+ /**
26
+ * Whether ZTC's own git in the agent's work tree must start no program the repository's config names, under the
27
+ * permission settings this process runs with now: a profile that limits the agent and lets its commands write. One
28
+ * that can't be read counts as one.
29
+ */
30
+ export function gitProbesStartNoRepositoryProgram() {
31
+ try {
32
+ const policy = commandPolicyFor(configStore.get());
33
+ return agentWritesGitConfig(policy.profile, policy.sandbox);
34
+ }
35
+ catch {
36
+ return true;
37
+ }
38
+ }
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process';
2
+ import { buildUserSubprocessEnv } from './subprocess_env.js';
2
3
  import { existsSync } from 'node:fs';
3
4
  import { delimiter, dirname, join } from 'node:path';
4
5
  /**
@@ -38,5 +39,5 @@ export function hostShell(command) {
38
39
  * taskkill /T walks the tree from `pid`, and /F ends each process, since a console program cannot be asked to close.
39
40
  */
40
41
  export function killWindowsProcessTree(pid) {
41
- spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10_000 });
42
+ spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10_000, env: buildUserSubprocessEnv() });
42
43
  }
@@ -1,3 +1,4 @@
1
+ import { promptCacheTtl } from '../agent/backends/prompt_cache.js';
1
2
  export const IDLE_COMPACT_DEFAULT_LEAD_MS = 60_000;
2
3
  export const IDLE_COMPACT_MIN_CONTEXT_TOKENS = 100_000;
3
4
  const ANTHROPIC_DEFAULT_CACHE_TTL_MS = 60 * 60_000;
@@ -31,8 +32,14 @@ export function parseCacheTtl(value) {
31
32
  default: return Math.round(amount * 1000);
32
33
  }
33
34
  }
35
+ /**
36
+ * How long the prompt cache ZTC asks Anthropic for lives (ZTC_PROMPT_CACHE_TTL, read as the model backends read it,
37
+ * promptCacheTtl): none when it is off, since ZTC's requests then ask Anthropic and Zerg Router for no cache; else the
38
+ * duration it names, or the 1h default.
39
+ */
34
40
  function anthropicCacheTtlMs() {
35
- return parseCacheTtl(process.env.ZTC_PROMPT_CACHE_TTL) ?? ANTHROPIC_DEFAULT_CACHE_TTL_MS;
41
+ const ttl = promptCacheTtl();
42
+ return ttl === 'off' ? undefined : parseCacheTtl(ttl) ?? ANTHROPIC_DEFAULT_CACHE_TTL_MS;
36
43
  }
37
44
  export function shouldCompactBeforeCacheExpiry(input) {
38
45
  if (!input.enabled)
@@ -4,7 +4,10 @@ export declare const IMAGE_MAX_PX = 1568;
4
4
  export declare function imageDimensions(raw: Buffer, mediaType: string): [number, number] | null;
5
5
  /**
6
6
  * The image scaled down so its longest side is at most maxPx, with sips (macOS) or ImageMagick. Null when it already
7
- * fits, its size cannot be read, or no tool here can scale it; the caller then sends it as it is.
7
+ * fits, its size cannot be read, or no tool here can scale it; the caller then sends it as it is. Each scaler is found
8
+ * on PATH, where anything that can write a folder on PATH can put a program of its own under its name, so it gets what
9
+ * any user subprocess gets (buildUserSubprocessEnv): the person's own environment, and none of ZTC's credentials or a
10
+ * copy of one.
8
11
  */
9
12
  export declare function fitImage(raw: Buffer, mediaType: string, maxPx: number): Promise<{
10
13
  data: Buffer;
@@ -3,6 +3,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { promisify } from 'node:util';
6
+ import { buildUserSubprocessEnv } from './subprocess_env.js';
6
7
  const execFileAsync = promisify(execFile);
7
8
  /** The longest side an image is sent at unless the caller asks otherwise; vision models scale past about this anyway. */
8
9
  export const IMAGE_MAX_PX = 1568;
@@ -25,7 +26,10 @@ export function imageDimensions(raw, mediaType) {
25
26
  }
26
27
  /**
27
28
  * The image scaled down so its longest side is at most maxPx, with sips (macOS) or ImageMagick. Null when it already
28
- * fits, its size cannot be read, or no tool here can scale it; the caller then sends it as it is.
29
+ * fits, its size cannot be read, or no tool here can scale it; the caller then sends it as it is. Each scaler is found
30
+ * on PATH, where anything that can write a folder on PATH can put a program of its own under its name, so it gets what
31
+ * any user subprocess gets (buildUserSubprocessEnv): the person's own environment, and none of ZTC's credentials or a
32
+ * copy of one.
29
33
  */
30
34
  export async function fitImage(raw, mediaType, maxPx) {
31
35
  const from = imageDimensions(raw, mediaType);
@@ -41,7 +45,7 @@ export async function fitImage(raw, mediaType, maxPx) {
41
45
  ...(process.platform === 'win32' ? [] : [['convert', [input, '-resize', box, output]]])];
42
46
  for (const [command, args] of scalers) {
43
47
  try {
44
- await execFileAsync(command, args, { timeout: 30_000 });
48
+ await execFileAsync(command, args, { timeout: 30_000, env: buildUserSubprocessEnv() });
45
49
  const data = await readFile(output);
46
50
  const to = imageDimensions(data, mediaType);
47
51
  if (to && Math.max(...to) <= maxPx)
@@ -1,10 +1,11 @@
1
1
  import { execFile } from 'child_process';
2
2
  import { promisify } from 'util';
3
+ import { buildUserSubprocessEnv } from './subprocess_env.js';
3
4
  const execFileAsync = promisify(execFile);
4
5
  const cache = new Map();
5
6
  async function hasCommand(command) {
6
7
  try {
7
- await execFileAsync('which', [command]);
8
+ await execFileAsync('which', [command], { env: buildUserSubprocessEnv() });
8
9
  return true;
9
10
  }
10
11
  catch {
@@ -25,7 +26,7 @@ export async function renderImagePreview(path, width = 40, height = 20) {
25
26
  '--symbols=block',
26
27
  `--size=${width}x${height}`,
27
28
  path
28
- ]);
29
+ ], { env: buildUserSubprocessEnv() });
29
30
  const lines = stdout.split('\n').filter(line => line.length > 0);
30
31
  cache.set(key, lines);
31
32
  return lines;
@@ -18,10 +18,28 @@ export declare function isMirrorMediaPath(localPath: string | undefined | null):
18
18
  * genuine mirror upload under MIRROR_MEDIA_ROOT. The agent's buildContentBlocks turns such a
19
19
  * token into a disk read (loadImageBlock/loadVideoBlock -> readFileSync -> base64 -> LLM), so a
20
20
  * mirror client that controls message text could otherwise exfiltrate any server-readable file
21
- * via a forged token. Degrading the token to its inert path text (dropping the brackets) stops
22
- * it being a read directive while preserving the user's words.
21
+ * via a forged token.
23
22
  *
24
- * Apply ONLY at the mirror ingress — local TTY input (operator clipboard paste under
25
- * ~/.ztc/clipboard, an out-of-root but trusted path) never crosses it, so paste keeps working.
23
+ * A token opens with `[image` or `[video` and any whitespace, control or format character (see
24
+ * MEDIA_SEPARATOR), since a command that rejoins its words, or a display, can make that one space.
25
+ * It closes at its `]`, an inner token's `]` closing that one first. A closed token that holds no
26
+ * other and names a mirror upload stays as it is. Every other opener, unclosed and enclosing ones
27
+ * included, has its `[` turned into `(`: it reads as the words it was, and no later step can make
28
+ * it a token again, as the encoder then finds only the tokens kept. Nothing is removed, so no
29
+ * pieces are spliced into a new token, and one pass over the text does it, whatever the nesting.
30
+ *
31
+ * Apply ONLY to mirror text: at the mirror ingress, to an answer the mirror is sent
32
+ * (stripForeignMediaTokensIn), and to a decoded submit_input envelope, which only a parent's
33
+ * mirror relay sends (cli_ratatui.ts parseStructuredSubmitInput). Local TTY input (operator
34
+ * clipboard paste under ~/.ztc/clipboard, an out-of-root but trusted path) never crosses it, so
35
+ * paste keeps working.
26
36
  */
27
37
  export declare function stripForeignMediaTokens(text: string): string;
38
+ /**
39
+ * VALUE with every string in it neutralized as mirror text (stripForeignMediaTokens): a string itself, and each string an
40
+ * array or an object holds, its keys too, at any depth; every other value as it is. For what the browser mirror sends
41
+ * that isn't a message: an answer to the agent's question, an approval's reason, a prompt widget's fields. A later step
42
+ * makes such a string a message (the answer, a plan's feedback) or a pane's prompt, after decoding it from the JSON it
43
+ * came in, whose escapes can spell a token no sanitizer saw in the text.
44
+ */
45
+ export declare function stripForeignMediaTokensIn(value: unknown): unknown;
@@ -1,5 +1,5 @@
1
1
  import { tmpdir } from 'os';
2
- import { join, resolve, sep } from 'path';
2
+ import { isAbsolute, join, resolve, sep } from 'path';
3
3
  /**
4
4
  * Root directory under which the mirror stores uploaded images
5
5
  * (storeMirrorImage writes to MIRROR_MEDIA_ROOT/<uuid>/<id>.<ext>).
@@ -21,112 +21,113 @@ export function isMirrorMediaPath(localPath) {
21
21
  const target = resolve(localPath);
22
22
  return target === root || target.startsWith(root + sep);
23
23
  }
24
- const IMAGE_TOKEN_PREFIX = '[image ';
25
- const VIDEO_TOKEN_PREFIX = '[video ';
26
- function mediaTokenPrefixAt(text, index) {
27
- if (text.startsWith(IMAGE_TOKEN_PREFIX, index))
28
- return IMAGE_TOKEN_PREFIX;
29
- if (text.startsWith(VIDEO_TOKEN_PREFIX, index))
30
- return VIDEO_TOKEN_PREFIX;
31
- return null;
24
+ const MEDIA_KEYWORDS = ['[image', '[video'];
25
+ /**
26
+ * What can follow a keyword and open a token once later steps have had the text: any whitespace, which a command that
27
+ * splits its words on whitespace rejoins as one space (/loop, /goal), and any control or format character, which a
28
+ * display of the text shows as a space. The agent's request encoder takes only `[image ` and `[video ` with a space.
29
+ */
30
+ const MEDIA_SEPARATOR = /^[\s\p{Cc}\p{Cf}]$/u;
31
+ function isMediaSeparator(character) {
32
+ return character !== undefined && MEDIA_SEPARATOR.test(character);
32
33
  }
33
- function readMediaToken(text, start, prefix) {
34
- const rawPathStart = start + prefix.length;
35
- let nestedTokenDepth = 0;
36
- let index = rawPathStart;
37
- while (index < text.length) {
38
- const nestedPrefix = mediaTokenPrefixAt(text, index);
39
- if (nestedPrefix) {
40
- nestedTokenDepth += 1;
41
- index += nestedPrefix.length;
42
- continue;
43
- }
44
- if (text[index] === ']') {
45
- if (nestedTokenDepth > 0) {
46
- nestedTokenDepth -= 1;
47
- index += 1;
48
- continue;
49
- }
50
- const end = index + 1;
51
- return {
52
- end,
53
- rawPath: text.slice(rawPathStart, index),
54
- };
55
- }
56
- index += 1;
57
- }
58
- return null;
34
+ /** The character (whole code point) of TEXT that starts at INDEX; undefined past the end. */
35
+ function characterAt(text, index) {
36
+ const codePoint = text.codePointAt(index);
37
+ return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
59
38
  }
60
- function neutralizeMediaPath(rawPath) {
61
- const chunks = [];
62
- let cursor = 0;
63
- let index = 0;
64
- while (index < rawPath.length) {
65
- const prefix = mediaTokenPrefixAt(rawPath, index);
66
- if (prefix) {
67
- if (cursor < index)
68
- chunks.push(rawPath.slice(cursor, index));
69
- index += prefix.length;
70
- cursor = index;
71
- continue;
72
- }
73
- if (rawPath[index] === ']') {
74
- if (cursor < index)
75
- chunks.push(rawPath.slice(cursor, index));
76
- index += 1;
77
- cursor = index;
39
+ /** The length of the token opener at INDEX (a keyword and one separator), or 0 when none starts there. */
40
+ function mediaOpenerLength(text, index) {
41
+ if (text.charCodeAt(index) !== 0x5b)
42
+ return 0;
43
+ for (const keyword of MEDIA_KEYWORDS) {
44
+ if (!text.startsWith(keyword, index))
78
45
  continue;
79
- }
80
- index += 1;
46
+ const separator = characterAt(text, index + keyword.length);
47
+ if (separator === undefined || !isMediaSeparator(separator))
48
+ return 0;
49
+ return keyword.length + separator.length;
81
50
  }
82
- if (cursor < rawPath.length)
83
- chunks.push(rawPath.slice(cursor));
84
- return chunks.join('').trim();
51
+ return 0;
52
+ }
53
+ /**
54
+ * Whether a token's PATH names a mirror upload however a later step reads it: an absolute path under MIRROR_MEDIA_ROOT
55
+ * once the encoder trims its whitespace. Absolute, so a relative path never counts by where this process runs, and so
56
+ * one that starts with a control or format character doesn't either: a display could make that character a space,
57
+ * which the encoder would trim, leaving another path.
58
+ */
59
+ function namesMirrorUpload(rawPath) {
60
+ const path = rawPath.trim();
61
+ return isAbsolute(path) && isMirrorMediaPath(path);
85
62
  }
86
63
  /**
87
64
  * Neutralize `[image PATH]` / `[video PATH]` tokens in MIRROR-supplied text whose PATH is not a
88
65
  * genuine mirror upload under MIRROR_MEDIA_ROOT. The agent's buildContentBlocks turns such a
89
66
  * token into a disk read (loadImageBlock/loadVideoBlock -> readFileSync -> base64 -> LLM), so a
90
67
  * mirror client that controls message text could otherwise exfiltrate any server-readable file
91
- * via a forged token. Degrading the token to its inert path text (dropping the brackets) stops
92
- * it being a read directive while preserving the user's words.
68
+ * via a forged token.
93
69
  *
94
- * Apply ONLY at the mirror ingress — local TTY input (operator clipboard paste under
95
- * ~/.ztc/clipboard, an out-of-root but trusted path) never crosses it, so paste keeps working.
70
+ * A token opens with `[image` or `[video` and any whitespace, control or format character (see
71
+ * MEDIA_SEPARATOR), since a command that rejoins its words, or a display, can make that one space.
72
+ * It closes at its `]`, an inner token's `]` closing that one first. A closed token that holds no
73
+ * other and names a mirror upload stays as it is. Every other opener, unclosed and enclosing ones
74
+ * included, has its `[` turned into `(`: it reads as the words it was, and no later step can make
75
+ * it a token again, as the encoder then finds only the tokens kept. Nothing is removed, so no
76
+ * pieces are spliced into a new token, and one pass over the text does it, whatever the nesting.
77
+ *
78
+ * Apply ONLY to mirror text: at the mirror ingress, to an answer the mirror is sent
79
+ * (stripForeignMediaTokensIn), and to a decoded submit_input envelope, which only a parent's
80
+ * mirror relay sends (cli_ratatui.ts parseStructuredSubmitInput). Local TTY input (operator
81
+ * clipboard paste under ~/.ztc/clipboard, an out-of-root but trusted path) never crosses it, so
82
+ * paste keeps working.
96
83
  */
97
84
  export function stripForeignMediaTokens(text) {
98
85
  if (!text.includes('['))
99
86
  return text;
100
- const chunks = [];
101
- let cursor = 0;
87
+ const openers = [];
88
+ const open = [];
102
89
  let index = 0;
103
- let changed = false;
104
90
  while (index < text.length) {
105
- const prefix = mediaTokenPrefixAt(text, index);
106
- if (!prefix) {
107
- index += 1;
108
- continue;
109
- }
110
- const token = readMediaToken(text, index, prefix);
111
- if (!token) {
112
- index += prefix.length;
91
+ const length = mediaOpenerLength(text, index);
92
+ if (length > 0) {
93
+ if (open.length > 0)
94
+ openers[open[open.length - 1]].holdsOpener = true;
95
+ open.push(openers.length);
96
+ openers.push({ start: index, end: index + length, close: -1, holdsOpener: false });
97
+ index += length;
113
98
  continue;
114
99
  }
115
- const path = token.rawPath.trim();
116
- if (isMirrorMediaPath(path)) {
117
- index = token.end;
100
+ if (text.charCodeAt(index) === 0x5d && open.length > 0)
101
+ openers[open.pop()].close = index;
102
+ index += 1;
103
+ }
104
+ const chunks = [];
105
+ let cursor = 0;
106
+ for (const opener of openers) {
107
+ if (opener.close >= 0 && !opener.holdsOpener && namesMirrorUpload(text.slice(opener.end, opener.close)))
118
108
  continue;
119
- }
120
- changed = true;
121
- if (cursor < index)
122
- chunks.push(text.slice(cursor, index));
123
- chunks.push(neutralizeMediaPath(token.rawPath));
124
- index = token.end;
125
- cursor = index;
109
+ chunks.push(text.slice(cursor, opener.start), '(');
110
+ cursor = opener.start + 1;
126
111
  }
127
- if (!changed)
112
+ if (chunks.length === 0)
128
113
  return text;
129
- if (cursor < text.length)
130
- chunks.push(text.slice(cursor));
114
+ chunks.push(text.slice(cursor));
131
115
  return chunks.join('');
132
116
  }
117
+ /**
118
+ * VALUE with every string in it neutralized as mirror text (stripForeignMediaTokens): a string itself, and each string an
119
+ * array or an object holds, its keys too, at any depth; every other value as it is. For what the browser mirror sends
120
+ * that isn't a message: an answer to the agent's question, an approval's reason, a prompt widget's fields. A later step
121
+ * makes such a string a message (the answer, a plan's feedback) or a pane's prompt, after decoding it from the JSON it
122
+ * came in, whose escapes can spell a token no sanitizer saw in the text.
123
+ */
124
+ export function stripForeignMediaTokensIn(value) {
125
+ if (typeof value === 'string')
126
+ return stripForeignMediaTokens(value);
127
+ if (Array.isArray(value))
128
+ return value.map(stripForeignMediaTokensIn);
129
+ if (value === null || typeof value !== 'object')
130
+ return value;
131
+ return Object.fromEntries(Object.entries(value)
132
+ .map(([key, entry]) => [stripForeignMediaTokens(key), stripForeignMediaTokensIn(entry)]));
133
+ }
@@ -9,63 +9,16 @@
9
9
  * Follows the same pattern as dictation_native.ts / computer_native.ts.
10
10
  */
11
11
  import { spawn } from 'child_process';
12
- import { existsSync } from 'fs';
13
12
  import { createInterface } from 'readline';
14
- import { join, dirname } from 'path';
15
- import { homedir, platform, arch } from 'os';
16
- import { fileURLToPath } from 'url';
17
- const __filename = fileURLToPath(import.meta.url);
18
- const __dirname = dirname(__filename);
13
+ import { findNativeProgram, nativeProgramBuildCommand } from './native_install.js';
14
+ import { buildNativeHelperEnv } from './subprocess_env.js';
19
15
  // --- Binary discovery ---
20
- function getBinaryName() {
21
- const p = platform();
22
- const a = arch();
23
- let os;
24
- switch (p) {
25
- case 'darwin':
26
- os = 'darwin';
27
- break;
28
- case 'linux':
29
- os = 'linux';
30
- break;
31
- case 'win32':
32
- os = 'win';
33
- break;
34
- default:
35
- os = p;
36
- }
37
- let cpu;
38
- switch (a) {
39
- case 'x64':
40
- cpu = 'x64';
41
- break;
42
- case 'arm64':
43
- cpu = 'arm64';
44
- break;
45
- default:
46
- cpu = a;
47
- }
48
- const ext = p === 'win32' ? '.exe' : '';
49
- return `ztc-ml-${os}-${cpu}${ext}`;
50
- }
16
+ /**
17
+ * The ztc-ml binary, from ZTC's own install only (native_install.ts findNativeProgram): the package's bin/, then a
18
+ * source checkout's cargo build under the package. Never the working directory or ~/.ztc/bin.
19
+ */
51
20
  function getBinaryPath() {
52
- const binaryName = getBinaryName();
53
- const possiblePaths = [
54
- // Installed via npm (relative to this file in dist/utils/)
55
- join(__dirname, '..', '..', 'bin', binaryName),
56
- // Development: Rust build output
57
- join(process.cwd(), 'packages', 'ztc-ml', 'target', 'release', 'ztc-ml'),
58
- // Development: bin directory
59
- join(process.cwd(), 'bin', binaryName),
60
- // Global install location
61
- join(homedir(), '.ztc', 'bin', binaryName),
62
- ];
63
- for (const p of possiblePaths) {
64
- if (existsSync(p)) {
65
- return p;
66
- }
67
- }
68
- return null;
21
+ return findNativeProgram('ztc-ml');
69
22
  }
70
23
  /**
71
24
  * Check if the native ML binary is available.
@@ -115,7 +68,7 @@ export class MlNative {
115
68
  if (!binaryPath) {
116
69
  this.emit({
117
70
  type: 'error',
118
- message: 'ztc-ml binary not found. Run: cargo build --release in packages/ztc-ml',
71
+ message: `ztc-ml binary not found. Build with: ${nativeProgramBuildCommand('ztc-ml')}`,
119
72
  });
120
73
  return false;
121
74
  }
@@ -126,6 +79,8 @@ export class MlNative {
126
79
  try {
127
80
  this.process = spawn(binaryPath, args, {
128
81
  stdio: ['pipe', 'pipe', 'pipe'],
82
+ // The person's environment, none of ZTC's or its route's credentials.
83
+ env: buildNativeHelperEnv(),
129
84
  });
130
85
  // Parse JSON lines from stdout
131
86
  this.readline = createInterface({
@@ -331,7 +286,7 @@ export function getMlNativeStatus() {
331
286
  }
332
287
  else {
333
288
  parts.push('Native ML: not available');
334
- parts.push('Build with: cd packages/ztc-ml && cargo build --release');
289
+ parts.push(`Build with: ${nativeProgramBuildCommand('ztc-ml')}`);
335
290
  }
336
291
  return parts.join('\n');
337
292
  }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Where ZTC's own native programs are: in ZTC's install only, never where a resident's agent can write. This is the one
3
+ * place that says so (tests/unit/native_helper_resolution_lint.test.ts keeps it the only one).
4
+ *
5
+ * The native helpers (ztc-audio for dictation, ztc-computer, ztc-ml, ztc-tts, the zlicky overlay) and the renderers
6
+ * (ztc-tui, zmux, zterm) are looked for (findNativeProgram) only in:
7
+ * - the package's bin/ beside dist (an npm install, the npm launcher's copy of one, and the desktop app's bundle, which
8
+ * holds the package at <app>.app/Contents/Resources/runtime/ztc), under their packaged names (bin/<name>-<os>-<cpu>,
9
+ * packagedName);
10
+ * - in a source checkout, the package's own build of them: packages/<crate>/target/release for a cargo crate, and its
11
+ * target/debug where the install has no other copy (a debug build is what `cargo build` and `cargo test` leave, and
12
+ * one left stale must not run ahead of the release copy in bin/), and native/zlicky-overlay for the overlay (with its
13
+ * main.swift, which /usr/bin/swift runs where no build is: zlickyOverlaySource).
14
+ * The package is the one this module is in, found from import.meta.url (ZTC_PACKAGE_ROOT), never from the working
15
+ * directory, HOME or the agent's work tree. Never the working directory, ~/.ztc/bin or a folder above the install: an
16
+ * agent writes those, and a binary planted there ran as ZTC's own (a ztc-tui file planted in ~/.ztc/bin let
17
+ * create_ztc_pane open panes where the image ships no renderer). No installer, launcher or the desktop app puts a binary
18
+ * in ~/.ztc/bin (scripts/build-rust.sh writes bin/, the desktop's /desktop install-cli its shim to ~/.local/bin). A
19
+ * packed install ships no build, so none is looked for there: a build put into one was put there afterwards.
20
+ *
21
+ * What a host chooses instead comes from ZTC's launch, which the agent can't change: the desktop app's bundle names its
22
+ * ZTerm in the runtime manifest ZTC_DESKTOP_RUNTIME_MANIFEST names (desktop/runtime.ts, which checks the app's lease), a
23
+ * host that embeds ZTC can hand TuiProcess a renderer of its own (desktopBinaryPath), an installed ZTerm.app in
24
+ * /Applications or ~/Applications comes ahead of the package's zterm, and ZTC_ZLICKY_DISABLE_NATIVE_OVERLAY=1 starts no
25
+ * overlay. No variable names another helper's path.
26
+ */
27
+ /** ZTC's package root: two levels above this module, which is in src/utils or dist/utils. */
28
+ export declare const ZTC_PACKAGE_ROOT: string;
29
+ /**
30
+ * Whether ZTC's install is a packed one, which ships no build: an npm install, and the npm launcher's copy of one that
31
+ * every npm launch runs ZTC from (each carries the launcher, npm-cli/run.cjs, which packing makes, and none of the
32
+ * package's sources), or the desktop app's bundle, which holds the package at <app>.app/Contents/Resources/runtime/ztc.
33
+ * Packing writes the launcher into the package root and nothing removes it, so a source checkout packing ran in has
34
+ * one too: its sources (src/cli_main.ts), which packing never ships (package.json "files"), keep it a checkout.
35
+ */
36
+ export declare function isPackedZtcInstall(root?: string): boolean;
37
+ /** A native program ZTC starts, by the name cargo gives its executable. */
38
+ export type NativeProgram = 'ztc-audio' | 'ztc-computer' | 'ztc-ml' | 'ztc-tts' | 'ztc-zlicky-overlay' | 'ztc-tui' | 'zmux' | 'zterm';
39
+ /** PROGRAM's name in the package's bin/: <name>-<os>-<cpu>, with .exe on Windows (zmux-darwin-arm64, ztc-tui-linux-x64). */
40
+ export declare function packagedName(program: NativeProgram, platform?: string, arch?: string): string;
41
+ /**
42
+ * Every place ZTC looks for PROGRAM, in order: its copy in the package's bin/ and a source checkout's build of it (the
43
+ * release build ahead of bin/ for a buildFirst program), then that checkout's debug build, which runs only where the
44
+ * install has no other copy.
45
+ */
46
+ export declare function nativeProgramCandidates(program: NativeProgram): string[];
47
+ /** PROGRAM's executable in ZTC's own install (nativeProgramCandidates), or null when the install has none. */
48
+ export declare function findNativeProgram(program: NativeProgram): string | null;
49
+ /**
50
+ * The command that builds PROGRAM in a source checkout, for a message that says how to get one: a packed install ships
51
+ * its copy and runs no build.
52
+ */
53
+ export declare function nativeProgramBuildCommand(program: NativeProgram): string;
54
+ /** A source checkout's zlicky overlay source, which /usr/bin/swift can run where no build is; a packed install ships none. */
55
+ export declare function zlickyOverlaySource(): string | null;