@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
@@ -83,12 +83,14 @@ export function createAgentWithConfig(overrides = {}) {
83
83
  });
84
84
  }
85
85
  catch (error) {
86
- // A Router sign-in still to come, a model Zerg Router serves while the
87
- // route isn't Router, or a profile still waiting for a route choice, leaves
88
- // startup without an agent until there is a route. A provider nothing says
89
- // Router serves is a configuration error, as an unknown provider was: a
90
- // profile switch onto it fails and keeps the profile in use.
91
- const unavailable = (error instanceof RouterConfigurationError && error.needsSignIn) || error instanceof RouteAwaitingChoiceError
86
+ // A Router sign-in still to come, a host's Router runtime grant that is no
87
+ // usable bearer, a model Zerg Router serves while the route isn't Router, or
88
+ // a profile still waiting for a route choice, leaves startup without an
89
+ // agent until there is a route. A provider nothing says Router serves is a
90
+ // configuration error, as an unknown provider was: a profile switch onto it
91
+ // fails and keeps the profile in use.
92
+ const unavailable = (error instanceof RouterConfigurationError && (error.needsSignIn || error.kind === 'host_grant'))
93
+ || error instanceof RouteAwaitingChoiceError
92
94
  || (error instanceof RouterOnlyModelError && error.served);
93
95
  if (!allowUnavailableRouterAuth || !unavailable)
94
96
  throw error;
@@ -3,7 +3,7 @@
3
3
  * the Ink interface, which has no session manager. One owner, because Ink's own copy drifted: it did not mark the
4
4
  * model-written handoff, so its compactions dropped the person's request and cut the handoff (forge3d, 2026-11-16).
5
5
  */
6
- import type { Agent } from '../agent/agent.js';
6
+ import type { Agent, HandoffReport } from '../agent/agent.js';
7
7
  import type { Message, ModelUsageObserver } from '../types.js';
8
8
  import { type CompactionResult, type CompactionSummarizer } from '../utils/compaction.js';
9
9
  import { type AutoCompactDecision } from '../utils/context.js';
@@ -18,8 +18,11 @@ export declare function compactionSummarizer(handoff: CompactionSummarizer | und
18
18
  signal?: AbortSignal;
19
19
  onHandoffError?: (error: Error) => void;
20
20
  }): CompactionSummarizer;
21
- /** The handoff the agent's own model writes, with the agent's own request context. */
22
- export declare function agentHandoffSummarizer(agent: Agent, messages: Message[], signal?: AbortSignal, onFallback?: () => void): CompactionSummarizer;
21
+ /**
22
+ * The handoff the agent's own model writes, with the agent's own request context; REPORT is how the host's transcript
23
+ * hears what its request went without (Agent.getHandoffContext).
24
+ */
25
+ export declare function agentHandoffSummarizer(agent: Agent, messages: Message[], signal?: AbortSignal, onFallback?: () => void, report?: HandoffReport): CompactionSummarizer;
23
26
  /**
24
27
  * Compaction that has to shrink the history: mid-turn, or after a provider rejected the request. Lands at about
25
28
  * `percent`% of the window and at most half of the history now, since a provider can reject a request's structure
@@ -34,9 +34,12 @@ export function compactionSummarizer(handoff, options = {}) {
34
34
  };
35
35
  return summarize;
36
36
  }
37
- /** The handoff the agent's own model writes, with the agent's own request context. */
38
- export function agentHandoffSummarizer(agent, messages, signal, onFallback) {
39
- const context = agent.getHandoffContext(messages);
37
+ /**
38
+ * The handoff the agent's own model writes, with the agent's own request context; REPORT is how the host's transcript
39
+ * hears what its request went without (Agent.getHandoffContext).
40
+ */
41
+ export function agentHandoffSummarizer(agent, messages, signal, onFallback, report) {
42
+ const context = agent.getHandoffContext(messages, report);
40
43
  return modelHandoffSummarizer(context.backend, context.model, {
41
44
  request: context, signal, apiRetry: context.apiRetry, onFallback, system: context.system, tools: context.tools,
42
45
  });
@@ -24,6 +24,7 @@ function buildCommandCatalogEntries() {
24
24
  scope: 'global',
25
25
  agentRunnable: c.agentRunnable === true,
26
26
  ...(c.agentCapabilities ? { capabilities: c.agentCapabilities } : {}),
27
+ ...(c.agentConfined ? { confined: true } : {}),
27
28
  }));
28
29
  const registry = getModeRegistry();
29
30
  for (const mode of registry.listModes()) {
package/dist/audio/sfx.js CHANGED
@@ -11,6 +11,7 @@
11
11
  * 2. <bundled>/audio/packs/<name>/ (shipped with ZTC)
12
12
  */
13
13
  import { spawn } from 'child_process';
14
+ import { buildUserSubprocessEnv } from '../utils/subprocess_env.js';
14
15
  import { readFileSync, existsSync } from 'fs';
15
16
  import { join, dirname } from 'path';
16
17
  import { fileURLToPath } from 'url';
@@ -130,11 +131,16 @@ function playFile(filePath, volume) {
130
131
  else {
131
132
  return;
132
133
  }
134
+ // A player that cannot start (none installed, as on a Linux host without paplay) is reported as an 'error' event
135
+ // once spawn has returned, which the catch below never sees and which ends ZTC when nothing listens for it. The
136
+ // listener before unref() hears it, so it costs only the sound.
133
137
  try {
134
138
  const child = spawn(command, args, {
135
139
  detached: true,
136
140
  stdio: 'ignore',
141
+ env: buildUserSubprocessEnv(),
137
142
  });
143
+ child.on('error', () => { });
138
144
  child.unref();
139
145
  }
140
146
  catch {
@@ -10,9 +10,11 @@
10
10
  * No auto-merge — each branch is independently mergeable.
11
11
  */
12
12
  import { execFile } from 'child_process';
13
- import { join } from 'path';
13
+ import { join, resolve } from 'path';
14
14
  import { rm, rmdir } from 'fs/promises';
15
15
  import { promisify } from 'util';
16
+ import { GIT_DIFF_OPTIONS, GIT_PROBE_OPTIONS } from '../utils/git_probe_options.js';
17
+ import { buildGitSubprocessEnvFor } from '../utils/subprocess_env.js';
16
18
  const execFileAsync = promisify(execFile);
17
19
  /** Sanitize a string for use in git branch names and filesystem paths. */
18
20
  export function slugify(input) {
@@ -24,16 +26,26 @@ export function slugify(input) {
24
26
  || 'task';
25
27
  }
26
28
  /**
27
- * Options every git run here takes first, as runtime_info's probes do. /batch runs git in the work tree and in the
28
- * worktrees its workers write to, in ZTC's own process and outside any sandbox they run under: core.fsmonitor=false
29
- * keeps a core.fsmonitor command in the repository's config from running on an add, a diff or a commit, and
30
- * safe.bareRepository=explicit keeps git from taking a bare repository planted there for the repository and running
31
- * its config. Both leave normal work trees and linked worktrees working.
29
+ * Options every git run here takes first, as runtime_info's probes do, and each diff GIT_DIFF_OPTIONS
30
+ * (utils/git_probe_options.ts). /batch runs git in the work tree and in the worktrees its workers write to, in ZTC's own
31
+ * process and outside any sandbox they run under: no core.fsmonitor command in the repository's config runs on an add, a
32
+ * diff or a commit, no external diff, textconv or signature program on a diff or a log, and no bare repository planted
33
+ * there is taken for the repository. Each leaves normal work trees and linked worktrees working.
34
+ */
35
+ const GIT_OPTIONS = GIT_PROBE_OPTIONS;
36
+ /**
37
+ * Run a git command in a given directory, with a user subprocess's environment: git runs the repository's hooks
38
+ * (post-checkout on a worktree add, pre-commit on a commit) and the programs its config names with it, so they get
39
+ * the person's environment and none of ZTC's credentials. The directory is named in git's arguments too (-C), and a
40
+ * directory with a repository of its own (a project, a worker's worktree) takes no GIT_DIR or other repository
41
+ * variable from ZTC's environment (buildGitSubprocessEnvFor), so the repository git acts on is CWD's whatever else
42
+ * holds: on Nov 20 a mutant that dropped these options made a test's worktree add register itself, and its branch, in
43
+ * the repository the test ran from. A vcsh or yadm work tree, which has none, keeps them: they name its repository.
32
44
  */
33
- const GIT_OPTIONS = ['-c', 'core.fsmonitor=false', '-c', 'safe.bareRepository=explicit'];
34
- /** Run a git command in a given directory. */
35
45
  async function git(args, cwd) {
36
- const { stdout } = await execFileAsync('git', [...GIT_OPTIONS, ...args], { cwd, maxBuffer: 10 * 1024 * 1024 });
46
+ const directory = resolve(cwd);
47
+ const { stdout } = await execFileAsync('git', ['-C', directory, ...GIT_OPTIONS, ...args], { cwd: directory,
48
+ maxBuffer: 10 * 1024 * 1024, env: buildGitSubprocessEnvFor(directory) });
37
49
  return stdout.trim();
38
50
  }
39
51
  /** Get the repository root from any directory inside it. */
@@ -72,7 +84,7 @@ export async function commitWorktreeChanges(worktreePath, message) {
72
84
  // Stage everything
73
85
  await git(['add', '-A'], worktreePath);
74
86
  // Check for staged changes
75
- const diff = await git(['diff', '--cached', '--name-only'], worktreePath);
87
+ const diff = await git(['diff', ...GIT_DIFF_OPTIONS, '--cached', '--name-only'], worktreePath);
76
88
  if (!diff) {
77
89
  return { sha: null, filesChanged: [] };
78
90
  }
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { admitBoardOrigin } from './binding.js';
3
+ import { hostEnvironmentValue } from '../config/host_credentials.js';
3
4
  export class BoardApiError extends Error {
4
5
  status;
5
6
  constructor(status) {
@@ -17,7 +18,7 @@ export function configuredBoardOrigin() {
17
18
  export async function boardRequest(origin, sessionId, path, schema, options = {}) {
18
19
  if (admitBoardOrigin(origin) !== configuredBoardOrigin())
19
20
  throw new Error('Configured Zergboard origin changed; restore the attached destination before syncing');
20
- const token = process.env.ZTC_ZERGBOARD_TOKEN;
21
+ const token = hostEnvironmentValue('ZTC_ZERGBOARD_TOKEN');
21
22
  if (!token)
22
23
  throw new Error('Set ZTC_ZERGBOARD_TOKEN to a token with access to this board');
23
24
  const response = await fetch(new URL(path, origin), { method: options.method ?? 'GET', redirect: 'manual',
@@ -8,4 +8,5 @@
8
8
  *
9
9
  * The actual TUI application lives in cli_ratatui.ts (RatatuiApp class).
10
10
  */
11
+ import './host_credentials_startup.js';
11
12
  import './utils/compile_cache.js';
package/dist/cli_main.js CHANGED
@@ -13,11 +13,16 @@
13
13
  // (config store, session store, headless runner, modes framework, the TUI in
14
14
  // cli_ratatui.ts, audio, MCP commands) are dynamically imported at the point
15
15
  // where the selected code path actually needs them.
16
+ // First of all: ZTC's credentials leave process.env for the host-credential store before any other module body runs,
17
+ // so no program ZTC starts without an environment of its own inherits them (config/host_credentials.ts).
18
+ import './host_credentials_startup.js';
16
19
  import './utils/compile_cache.js';
17
20
  import { dirname, resolve } from 'path';
18
21
  import { statSync, existsSync, mkdirSync, accessSync, constants } from 'fs';
19
22
  import { homedir } from 'os';
20
23
  import { execSync, spawnSync, spawn as spawnChild } from 'child_process';
24
+ import { buildUserSubprocessEnv, ztcRelaunchWithheldEnv } from './utils/subprocess_env.js';
25
+ import { HOST_HANDOFF_FLAG, removeHostHandoff, writeHostHandoff } from './config/host_credentials.js';
21
26
  import { installColonyParentWatchdog } from './colony_parent_watchdog.js';
22
27
  import { DEFAULT_ANTHROPIC_MODEL, DEFAULT_OPENAI_MODEL, getDefaultModelForProvider } from './config/defaults.js';
23
28
  import { getVersion } from './utils/version.js';
@@ -33,10 +38,27 @@ import { parseHeadlessInteractionMode } from './app/headless_interaction.js';
33
38
  import { installEmergencyHandlers } from './app/emergency_exit.js';
34
39
  import { buildCliCommonStarts } from './onboarding/first_run.js';
35
40
  import { validateProfileName } from './config/profiles.js';
41
+ import { PermissionPinChangedError, PermissionPinUnlimitedError } from './config/permission_pin.js';
36
42
  import { loadDesktopRuntime } from './desktop/runtime.js';
37
43
  import { resolveOwnedCliLaunch } from './desktop/cli_launch.js';
38
44
  import { consumePaneCredentialHandoff } from './web/pane_credentials.js';
39
45
  import { consumeDesktopCredentialHandoff } from './desktop/daily/control_credentials.js';
46
+ /**
47
+ * Pin the permission settings where the host asked (ZTC_PERMISSION_PROFILE_PINNED; ConfigStore.pinStartupPermissions). A
48
+ * ZTC started again in place whose permission settings changed after the ZTC it replaces checked them pins nothing of
49
+ * them, and a ZTC whose permission profile limits nothing pins none: either says why and exits 2.
50
+ */
51
+ function pinStartupPermissionsOrExit(store) {
52
+ try {
53
+ store.pinStartupPermissions();
54
+ }
55
+ catch (error) {
56
+ if (!(error instanceof PermissionPinChangedError) && !(error instanceof PermissionPinUnlimitedError))
57
+ throw error;
58
+ console.error(`[ztc] ${error.message}`);
59
+ process.exit(2);
60
+ }
61
+ }
40
62
  // A ZTC pane is handed its mirror credential in a one-time file its command line names: take it, and the flag, before
41
63
  // anything reads the arguments, and keep it out of the environment every program this ZTC starts inherits (see
42
64
  // pane_credentials.ts).
@@ -1027,6 +1049,11 @@ if (connectZergIndex >= 0) {
1027
1049
  function shellEscape(s) {
1028
1050
  return `'${s.replace(/'/g, "'\\''")}'`;
1029
1051
  }
1052
+ /** ARGS with OPTION among the program's own options: before an end of options ('--') and what follows it, else last. */
1053
+ function withProgramOption(args, option) {
1054
+ const end = args.indexOf('--');
1055
+ return end < 0 ? [...args, ...option] : [...args.slice(0, end), ...option, ...args.slice(end)];
1056
+ }
1030
1057
  function openWithTerminalApp(command, cols, rows, maximize) {
1031
1058
  const sizeScript = maximize
1032
1059
  ? `\n tell application "System Events" to tell process "Terminal"\n set frontmost to true\n click menu item "Zoom" of menu "Window" of menu bar 1\n end tell`
@@ -1036,8 +1063,15 @@ tell application "Terminal"
1036
1063
  do script "${command.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"${sizeScript}
1037
1064
  activate
1038
1065
  end tell`;
1039
- execSync(`osascript -e ${shellEscape(script)}`, { stdio: 'ignore' });
1066
+ execSync(`osascript -e ${shellEscape(script)}`, { stdio: 'ignore', env: buildUserSubprocessEnv() });
1040
1067
  }
1068
+ /**
1069
+ * The variables an owned relaunch's command line sets (the admitted bundle's renderer in its CLI mode): the bundle's
1070
+ * state routing. The renderer's CLI bridge then gives the ZTC it starts a runtime lease of its own.
1071
+ */
1072
+ const OWNED_RELAUNCH_ENV = [
1073
+ 'ZTC_DESKTOP_RUNTIME_MANIFEST', 'ZTC_PROFILE', 'ZTC_CONFIG_DIR', 'ZTC_SESSIONS_DIR',
1074
+ ];
1041
1075
  /**
1042
1076
  * Opens a new terminal window and re-launches the current command (minus --new-window).
1043
1077
  * Detects the terminal emulator from TERM_PROGRAM and uses the appropriate mechanism.
@@ -1058,13 +1092,15 @@ function openInNewWindow(maximize) {
1058
1092
  ? 'npx tsx'
1059
1093
  : shellEscape(process.execPath);
1060
1094
  // Terminal/iTerm start a fresh shell; carry only the admitted bundle's state routing.
1061
- const ownerEnvironment = ownedLaunch
1062
- ? ['ZTC_DESKTOP_RUNTIME_MANIFEST', 'ZTC_PROFILE', 'ZTC_CONFIG_DIR', 'ZTC_SESSIONS_DIR'].flatMap(key => {
1063
- const value = process.env[key];
1064
- return value === undefined ? [] : [`${key}=${shellEscape(value)}`];
1065
- })
1066
- : [];
1067
- const relaunchCmd = `cd ${shellEscape(process.cwd())} && ${[...ownerEnvironment, runner, ...(ownedLaunch?.args ?? filteredArgs).map(shellEscape)].join(' ')}`;
1095
+ const ownerVariables = ownedLaunch ? OWNED_RELAUNCH_ENV : [];
1096
+ const ownerEnvironment = ownerVariables.flatMap(key => {
1097
+ const value = process.env[key];
1098
+ return value === undefined ? [] : [`${key}=${shellEscape(value)}`];
1099
+ });
1100
+ const programArgs = ownedLaunch?.args ?? filteredArgs;
1101
+ const relaunchCommand = (option = []) => `cd ${shellEscape(process.cwd())} && ${[...ownerEnvironment,
1102
+ runner, ...withProgramOption(programArgs, option).map(shellEscape)].join(' ')}`;
1103
+ const relaunchCmd = relaunchCommand();
1068
1104
  const COLS = 220;
1069
1105
  const ROWS = 55;
1070
1106
  const termProgram = process.env.TERM_PROGRAM || '';
@@ -1080,20 +1116,36 @@ tell application "iTerm2"
1080
1116
  write text "${relaunchCmd.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"${maximize ? '' : `\n set columns to ${COLS}\n set rows to ${ROWS}`}
1081
1117
  end tell${maximizeScript}
1082
1118
  end tell`;
1083
- execSync(`osascript -e ${shellEscape(script)}`, { stdio: 'ignore' });
1119
+ execSync(`osascript -e ${shellEscape(script)}`, { stdio: 'ignore', env: buildUserSubprocessEnv() });
1084
1120
  }
1085
1121
  else if (termProgram === 'ghostty') {
1086
1122
  // Ghostty supports -e flag for running a command
1123
+ let handoff = null;
1087
1124
  try {
1088
- const result = spawnSync('which', ['ghostty'], { encoding: 'utf8' });
1125
+ const result = spawnSync('which', ['ghostty'], { encoding: 'utf8', env: buildUserSubprocessEnv() });
1089
1126
  if (result.status === 0) {
1090
- const ghosttyArgs = ['-e', `/bin/bash -c ${shellEscape(relaunchCmd)}`];
1127
+ // Ghostty runs the new window's ZTC with ghostty's own environment, which is a user subprocess's: someone else's
1128
+ // program never holds ZTC's credentials. That ZTC is this one again, so what that environment leaves out of the
1129
+ // one this ZTC was started with (its own settings, the mirror's sign-in among them, and its credentials) goes
1130
+ // over in a one-time handoff its command line names (HOST_HANDOFF_FLAG), never in an environment or on a
1131
+ // command line. Without it the new window's mirror would start open: no window, then. What the relaunch sets
1132
+ // afresh stays out of it: the bundle state routing on an owned relaunch's command line, and the runtime lease
1133
+ // ZTerm's CLI bridge gives the new window's ZTC. This process's lease marker, taken from a handoff, would
1134
+ // replace that one, and the new window's ZTC would fail desktop admission.
1135
+ const withheld = ztcRelaunchWithheldEnv(process.env, ownerVariables);
1136
+ handoff = writeHostHandoff(withheld);
1137
+ if (!handoff && Object.keys(withheld).length > 0) {
1138
+ console.error('[ztc] --new-window could not hand this ZTC\'s settings and credentials over to the new window (the temporary folder could not be written), so it opened none.');
1139
+ process.exit(1);
1140
+ }
1141
+ const ghosttyArgs = ['-e', `/bin/bash -c ${shellEscape(relaunchCommand(handoff ? [HOST_HANDOFF_FLAG, handoff] : []))}`];
1091
1142
  if (maximize) {
1092
1143
  ghosttyArgs.unshift('--window-decoration=true', '--maximize=true');
1093
1144
  }
1094
1145
  spawnChild('ghostty', ghosttyArgs, {
1095
1146
  detached: true,
1096
1147
  stdio: 'ignore',
1148
+ env: buildUserSubprocessEnv(),
1097
1149
  }).unref();
1098
1150
  }
1099
1151
  else {
@@ -1101,6 +1153,8 @@ end tell`;
1101
1153
  }
1102
1154
  }
1103
1155
  catch {
1156
+ if (handoff)
1157
+ removeHostHandoff(handoff);
1104
1158
  openWithTerminalApp(relaunchCmd, COLS, ROWS, maximize);
1105
1159
  }
1106
1160
  }
@@ -1146,6 +1200,10 @@ async function main() {
1146
1200
  // Raw (pre-load) config read, same as the historical module-scope read; the
1147
1201
  // --max-iterations flag parsed at module scope wins over the config value.
1148
1202
  const headlessMaxIterations = headlessMaxIterationsFlag !== undefined ? headlessMaxIterationsFlag : configStore.get().maxIterations;
1203
+ // ZTC's own files as they are before its settings are read, which may rewrite config.json (a settings migration
1204
+ // replaces it, ending a hard link it had): the check below, once the permission profile is known, sees them as read.
1205
+ const { inspectOwnStateFiles, ownStateFileRefusals } = await import('./config/own_state_files.js');
1206
+ const ownStateFilesAtStart = inspectOwnStateFiles();
1149
1207
  await configStore.load(true, { strictConfig: headlessPolicyHash !== undefined });
1150
1208
  debugLog('[main] Config loaded');
1151
1209
  // A retired Claude Code route in the launch flags (scripts, launchers and
@@ -1177,6 +1235,60 @@ async function main() {
1177
1235
  }
1178
1236
  // Session store (light module, but only needed once a real session path runs).
1179
1237
  const { deleteSession, generateSessionId, loadMostRecentSession, loadSessionFromFile, loadSessionByIdOrName, setSessionName, } = await import('./session.js');
1238
+ const ttyAvailable = isTTY();
1239
+ const headlessMirror = computeHeadlessMirror({
1240
+ headlessMode,
1241
+ mirrorEnabled,
1242
+ paneMode,
1243
+ ttyAvailable,
1244
+ headlessMux: !!process.env.ZTC_HEADLESS_MUX,
1245
+ });
1246
+ // This process's tool permissions, never saved: the tools the profile forbids are not offered (see the agent factory).
1247
+ const permissionProfileIndex = args.indexOf('--permission-profile');
1248
+ if (permissionProfileIndex >= 0) {
1249
+ const name = args[permissionProfileIndex + 1];
1250
+ const known = Object.keys(configStore.get().permissionProfiles ?? {});
1251
+ if (!known.includes(name)) {
1252
+ console.error(`[ztc] Unknown permission profile "${name}". Profiles: ${known.join(', ')}.`);
1253
+ process.exit(2);
1254
+ }
1255
+ configStore.setCliOverride('permissionProfile', name);
1256
+ }
1257
+ // Under a permission profile that limits the agent, ZTC does not start while one of its own files has another name or
1258
+ // is not a regular file of its own: a name in the agent's workspace that no check of a path sees
1259
+ // (config/own_state_files.ts). Asked before anything config.json names starts (its MCP servers, plugins), under the
1260
+ // profile this process runs on and, for a resident on a host's thread, the one the thread's settings will give it; and
1261
+ // asked again once those settings are taken. UNDER is a profile this process is about to take.
1262
+ const refuseLinkedOwnState = (under) => {
1263
+ const refusals = ownStateFileRefusals(under?.limits ?? configStore.permissionProfileLimitsAgent(), under?.profile ?? configStore.getActivePermissionProfileId(), ownStateFilesAtStart, configStore.get().accounts);
1264
+ if (refusals.length === 0)
1265
+ return;
1266
+ for (const refusal of refusals)
1267
+ console.error(`[ztc] ${refusal}`);
1268
+ process.exit(2);
1269
+ };
1270
+ refuseLinkedOwnState();
1271
+ // A resident on a host's thread (--session-file) takes the thread's settings further on (applyHostedThreadSettings),
1272
+ // which keep the agent's commands in an OS sandbox: ZTC's own files are held to that profile before anything starts
1273
+ // too. The thread is read again there, where a file that can't be read is said.
1274
+ if (headlessMirror && explicitSessionFile) {
1275
+ const thread = await loadSessionFromFile(explicitSessionFile, false).catch(() => null);
1276
+ const { hostedSettingsConfigPatch, hostedSettingsFromSession } = await import('./hosted/session_settings.js');
1277
+ let hosted;
1278
+ try {
1279
+ hosted = thread ? hostedSettingsConfigPatch(hostedSettingsFromSession(thread)) : undefined;
1280
+ }
1281
+ catch { /* said where the thread is read again */ }
1282
+ if (hosted?.permissionProfile) {
1283
+ const { profileLimitsAgent } = await import('./config/profile_limits.js');
1284
+ refuseLinkedOwnState({ profile: hosted.permissionProfile,
1285
+ limits: profileLimitsAgent(configStore.getEffectivePermissionProfile(hosted.permissionProfile), hosted.sandbox) });
1286
+ }
1287
+ }
1288
+ // The repositories earlier ZTCs' plans found, which every plan of a command under a profile whose commands write inside
1289
+ // an OS sandbox protects from its first command on (utils/git_program_files.ts); what it says of a record it cannot
1290
+ // take, the first such command's result says.
1291
+ (await import('./utils/git_program_files.js')).loadKnownRepositoryRecord();
1180
1292
  // Preload skills so the cached manifest is ready for the (sync) agent
1181
1293
  // factory. Failures are non-fatal — an empty manifest just means no skills
1182
1294
  // are advertised to the LLM. Colony children skip this — they're agent
@@ -1229,7 +1341,7 @@ async function main() {
1229
1341
  const { colonyOptIn } = await import('./mcp/registry.js');
1230
1342
  if ((mcpServers && Object.keys(mcpServers).length > 0) || colonyOptIn()) {
1231
1343
  const { initMcpServers } = await import('./mcp/client.js');
1232
- await initMcpServers(mcpServers);
1344
+ await initMcpServers(mcpServers, { providerKeyEnv: configStore.get().apiKeyEnv });
1233
1345
  }
1234
1346
  const routerUrlIndex = args.indexOf('--router-url');
1235
1347
  if (cliAuthMode !== null || routerUrlIndex >= 0) {
@@ -1279,6 +1391,9 @@ async function main() {
1279
1391
  }
1280
1392
  if (effectiveCliModel)
1281
1393
  configStore.setCliOverride('model', effectiveCliModel);
1394
+ // A host that pins the session's route (ZTC_MODEL_PINNED) pins the one it starts on now: ZTC_PROVIDER and ZTC_MODEL, or
1395
+ // --provider and --model, applied (config/model_pin.ts).
1396
+ configStore.pinStartupRoute();
1282
1397
  const effortIndex = args.indexOf('--effort');
1283
1398
  const thinkingIndex = args.indexOf('--thinking');
1284
1399
  if (effortIndex >= 0 || thinkingIndex >= 0) {
@@ -1295,17 +1410,6 @@ async function main() {
1295
1410
  process.exit(2);
1296
1411
  }
1297
1412
  }
1298
- // This process's tool permissions, never saved: the tools the profile forbids are not offered (see the agent factory).
1299
- const permissionProfileIndex = args.indexOf('--permission-profile');
1300
- if (permissionProfileIndex >= 0) {
1301
- const name = args[permissionProfileIndex + 1];
1302
- const known = Object.keys(configStore.get().permissionProfiles ?? {});
1303
- if (!known.includes(name)) {
1304
- console.error(`[ztc] Unknown permission profile "${name}". Profiles: ${known.join(', ')}.`);
1305
- process.exit(2);
1306
- }
1307
- configStore.setCliOverride('permissionProfile', name);
1308
- }
1309
1413
  // A run nobody watches doesn't start on a profile the move off the retired
1310
1414
  // routes left without a route, unless its own --provider just chose one (a
1311
1415
  // route only the environment reaches was never chosen); one that starts
@@ -1449,6 +1553,8 @@ async function main() {
1449
1553
  // overlap; HeadlessApp.init joins this scan instead of starting another.
1450
1554
  const { prefetchStartupGitSnapshot } = await import('./runtime_info.js');
1451
1555
  prefetchStartupGitSnapshot(process.cwd());
1556
+ // Startup is done: a host that pins the permission settings (ZTC_PERMISSION_PROFILE_PINNED) pins them now.
1557
+ pinStartupPermissionsOrExit(configStore);
1452
1558
  const { runHeadless } = await import('./headless.js');
1453
1559
  await runHeadless({
1454
1560
  approvalUrl: headlessApprovalUrl,
@@ -1489,6 +1595,8 @@ async function main() {
1489
1595
  // child responds via ~/.ztc/pane_responses/{ZTC_PANE_ID}.json after each turn.
1490
1596
  if (headlessFromParent) {
1491
1597
  debugLog(`[main] Running as headless child pane (ZTC_PANE_ID=${process.env.ZTC_PANE_ID})`);
1598
+ // The pane's startup is done: it pins its permission settings where its host (or the ZTC that opened it) asks.
1599
+ pinStartupPermissionsOrExit(configStore);
1492
1600
  const { runHeadless } = await import('./headless.js');
1493
1601
  await runHeadless({
1494
1602
  approvalUrl: headlessApprovalUrl,
@@ -1571,14 +1679,6 @@ async function main() {
1571
1679
  registerBuiltinHandlers((name, handler) => registry.registerCommandHandler(name, handler));
1572
1680
  debugLog(`[main] Modes loaded: ${registry.listModes().map(m => m.name).join(', ')}`);
1573
1681
  }
1574
- const ttyAvailable = isTTY();
1575
- const headlessMirror = computeHeadlessMirror({
1576
- headlessMode,
1577
- mirrorEnabled,
1578
- paneMode,
1579
- ttyAvailable,
1580
- headlessMux: !!process.env.ZTC_HEADLESS_MUX,
1581
- });
1582
1682
  // Check if we have a TTY first (skip for headless mirror — no terminal needed)
1583
1683
  if (!headlessMirror && !desktopMode && !ttyAvailable) {
1584
1684
  console.error('Error: ztc requires a terminal (TTY) for interactive use.');
@@ -1621,22 +1721,14 @@ async function main() {
1621
1721
  return;
1622
1722
  }
1623
1723
  if (resumedSession) {
1624
- const { hostedSettingsConfigPatch, hostedSettingsFromSession, } = await import('./hosted/session_settings.js');
1724
+ const { hostedSettingsFromSession } = await import('./hosted/session_settings.js');
1625
1725
  const settings = hostedSettingsFromSession(resumedSession);
1626
1726
  resumedSession.hosted_settings = settings;
1627
- const patch = hostedSettingsConfigPatch(settings);
1628
- // The thread's settings are the host's, not a route the person chose in this session.
1629
- configStore.markHostedSession();
1630
- configStore.setConfigScope('session');
1631
- configStore.set('provider', settings.provider);
1632
- configStore.set('model', settings.model);
1633
- configStore.set('maxTokens', settings.maxOutputTokens);
1634
- configStore.set('hostedThreadInstructions', patch.hostedThreadInstructions);
1635
- configStore.set('zrouterRoutePlan', patch.zrouterRoutePlan);
1636
- configStore.set('codexEffort', patch.codexEffort);
1637
- configStore.set('permissionProfile', patch.permissionProfile);
1638
- configStore.set('authMode', 'zrouter');
1639
- configStore.set('sandbox', patch.sandbox);
1727
+ // The thread's settings are the host's, not a route the person chose in this session; a session its host pinned to
1728
+ // another route keeps that one.
1729
+ configStore.applyHostedThreadSettings(settings);
1730
+ // Its permission profile and sandbox are now this process's: ZTC's own files are checked again under them.
1731
+ refuseLinkedOwnState();
1640
1732
  }
1641
1733
  }
1642
1734
  else if (resumeSessionId) {
@@ -1677,6 +1769,10 @@ async function main() {
1677
1769
  }
1678
1770
  }
1679
1771
  }
1772
+ // Startup is done for the permission settings: the launch's --permission-profile and the hosted thread's profile and
1773
+ // sandbox are taken. A host that pins them (ZTC_PERMISSION_PROFILE_PINNED, config/permission_pin.ts) pins them now,
1774
+ // once; from here on every change of them is refused, naming the variable.
1775
+ pinStartupPermissionsOrExit(configStore);
1680
1776
  // --name <name>: resume by name if it exists, otherwise create-and-name a
1681
1777
  // fresh session right now so /sessions list and `ztc resume <name>` work
1682
1778
  // without a prior turn. Also reached via the --resume / --session-id
@@ -792,6 +792,11 @@ export declare class RatatuiApp {
792
792
  */
793
793
  private refusesMirrorClose;
794
794
  private clearLegacyCommandPrompt;
795
+ /**
796
+ * `atTerminal`: the command is the person's own, typed at this ZTC's terminal (see runCommand). Only then does an answer
797
+ * it gives the attention queue keep their own paths; any other command's answer is mirror text
798
+ * (MirrorStreamServer.respondAttention).
799
+ */
795
800
  private buildCommandContext;
796
801
  /**
797
802
  * Panels that replace the transcript while open.
@@ -832,8 +837,12 @@ export declare class RatatuiApp {
832
837
  * Main's MESSAGE while this ZTC runs no mirror (it started without one, or /mirror stop stopped it): there is no bus,
833
838
  * so it is typed into the panes it is for. One for this ZTC itself reaches its own agent, as a mirror's member 0
834
839
  * hands it over. A Claude Code or Codex pane gets it as a mirror types it in (registerMirrorPaneFallbacks); any other
835
- * pane, as the prompt "[Message from Main]: …", Main named as its pane is. A broadcast reaches the ZTC panes, the
836
- * members a bus would have, and no shell, which would run it as a command.
840
+ * pane that runs a ZTC agent (runsZtcAgent), as the prompt "[Message from Main]: …", Main named as its pane is, in one
841
+ * inert line (formatTypedPaneMessage), since the pane submits it as its own typing. Any other pane (a shell, a command,
842
+ * another program) gets nothing, as a bus would deliver it nothing: the message is refused in the bus's words
843
+ * (notAnAgentResult), since a shell would run it as a command; for one of the desktop app's native Claude Code, Codex,
844
+ * shell or delegated panes (nativeNonAgentPane), in the words that say what that pane takes. A broadcast reaches the
845
+ * ZTC panes, the members a bus would have, and no shell.
837
846
  */
838
847
  private typeOverseerMessage;
839
848
  /**
@@ -1050,6 +1059,15 @@ export declare class RatatuiApp {
1050
1059
  /** Retire awaited startup continuations without reporting user exit as failure. */
1051
1060
  private assertStartupActive;
1052
1061
  start(): Promise<void>;
1062
+ /**
1063
+ * A headless mirror (a resident `--headless --mirror`, a headless ZTC pane, a colony cell with no terminal) runs
1064
+ * whatever its model and the holders of its mirror ask, with no one at a terminal watching each command. So, as a
1065
+ * `--headless` run does, it keeps the run's inference credentials from its tool children (run_command shells, panes,
1066
+ * language servers, search and git helpers): reserveModelRouteCredentials. This process keeps them. The interactive
1067
+ * app is the person's own session: their commands keep their environment, provider keys included. Reservation is
1068
+ * additive and idempotent, so the agent's every construction repeats it for a profile that names a new apiKeyEnv.
1069
+ */
1070
+ private reserveHeadlessRouteCredentials;
1053
1071
  private startRuntime;
1054
1072
  private checkForUpdates;
1055
1073
  /**
@@ -1730,7 +1748,8 @@ export declare class RatatuiApp {
1730
1748
  private currentQueueEditIndex;
1731
1749
  /**
1732
1750
  * `origin`: 'relayed' for a command the person didn't enter themselves, or one a ZTC another ZTC launched into one of
1733
- * its panes reads from its terminal (see handleSubmit).
1751
+ * its panes reads from its terminal (see handleSubmit). `atTerminal`: the person entered it at this ZTC's own terminal,
1752
+ * not in the browser mirror (see buildCommandContext).
1734
1753
  */
1735
1754
  private handleCommand;
1736
1755
  private runCommand;
@@ -1912,7 +1931,12 @@ export declare class RatatuiApp {
1912
1931
  private displayWorkflowEvent;
1913
1932
  /** Render a batch event as a system message or trigger the approval widget. */
1914
1933
  private displayBatchEvent;
1915
- /** What a ZTC pane needs to join this workspace; its mirror credential is its own (see pane.ts childZtcPaneEnv). */
1934
+ /**
1935
+ * What a ZTC pane needs to join this workspace; its mirror credential is its own (see pane.ts childZtcPaneEnv). The
1936
+ * renderer that starts it holds this process's environment: the pane keeps a host's grant that takes effect, and gets
1937
+ * a blank for one that doesn't, and with the grant it imports no plugin from where an agent writes, as the panes an
1938
+ * agent opens do (hostRouterGrantBlank, hostRouterGrantDiscovery).
1939
+ */
1916
1940
  private childZtcPaneEnv;
1917
1941
  /**
1918
1942
  * ZTerm (or the palette) asked for a ZTC pane. The request may carry the
@@ -1986,6 +2010,14 @@ export declare class RatatuiApp {
1986
2010
  * zmux accepted the pane.
1987
2011
  */
1988
2012
  private spawnShellPane;
2013
+ /**
2014
+ * Ctrl+G: open the plan in $EDITOR (vim when it is unset) in a pane of its own, where ZTC has panes (zmux, the
2015
+ * desktop app, or a pane of either through its relay), as open_editor_pane opens a file. The renderer starts the
2016
+ * editor on the pane's own terminal, so the keys typed in it are the editor's. The single-pane renderer reads ZTC's
2017
+ * terminal the whole time ZTC runs: an editor ZTC started on that terminal would get only some of the keys typed for
2018
+ * it and ZTC the rest, so there ZTC starts none and says where the plan is.
2019
+ */
2020
+ private openPlanInEditor;
1989
2021
  /**
1990
2022
  * Run a command in a shell pane — how a custom option becomes a pane. Returns
1991
2023
  * an error to report, or null when zmux accepted the pane.
@@ -2052,6 +2084,19 @@ export declare class RatatuiApp {
2052
2084
  * Both hot restart (same session, new code) and resume-from-panel (another
2053
2085
  * session, possibly another workspace) run through this one path so the
2054
2086
  * relaunch semantics can never drift apart.
2087
+ *
2088
+ * Under a permission profile that limits the agent, ZTC takes no config.json edit to its hooks, MCP servers,
2089
+ * profiles, sandbox or extension roots while it runs, and the ZTC it would exec reads config.json afresh: while
2090
+ * config.json holds such an edit it starts none, says why, and returns false (it never returns otherwise). The
2091
+ * agent's own command can ask for a hot restart (SIGUSR1, as a mux pane's /restart does), so the edit another process
2092
+ * made would otherwise reach the agent's next command. `takesEdits`: the person asked for this restart (their /restart,
2093
+ * their pick in the resume panel), so it takes config.json as it is, as starting ZTC again would (the reviewer's owner
2094
+ * run: an owner's /restart after their own edit was refused). The restart after an update keeps the check. Where the
2095
+ * host pinned the permission settings (ZTC_PERMISSION_PROFILE_PINNED), an edit to them refuses every restart in place,
2096
+ * the person's included: the ZTC started again would pin what config.json says (config/permission_pin.ts). Under that
2097
+ * pin it also starts only in the folder the session started in, whose relative roots the pin holds, as the ZTC started
2098
+ * again pins them at the folder it starts in: an environment left elsewhere moved this process's folder to the one a
2099
+ * /cd named (the reviewer's resident probe, 2026-11-22), and the resume panel may pick a session that works elsewhere.
2055
2100
  */
2056
2101
  private relaunchTui;
2057
2102
  /**