@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
package/dist/config.js CHANGED
@@ -10,6 +10,8 @@ import { randomUUID } from 'crypto';
10
10
  import { isDeepStrictEqual } from 'util';
11
11
  import { constants as fsConstants } from 'node:fs';
12
12
  import { activeProfile, builtinProfileEmulation, listConfigProfiles, profileConfigDir, validateProfileName } from './config/profiles.js';
13
+ import { osSandboxRequested, profileLimitsAgent } from './config/profile_limits.js';
14
+ import { isSettingsGroup, mergeSettingEntries, mergeSettingValue } from './config/settings_merge.js';
13
15
  import { accountSourceToBackendOptions, canonicalAccountProvider, probeAccountIsolated, resolveActiveAccount, } from './agent/backends/account_pool.js';
14
16
  import { notifyAccountsChanged } from './agent/backends/account_events.js';
15
17
  import { inferDefaultProvider, getDefaultApiKeyForProvider, getDefaultModelForProvider, resolveCodexEffort, unsupportedCodexEffort } from './config/defaults.js';
@@ -23,7 +25,14 @@ import { listAgentProfiles } from './panes/agent_profiles.js';
23
25
  import { loadRouterCredentials, readRouterCredentialsSync, RouterConfigurationError, routerSignInRefusal } from './router_auth.js';
24
26
  import { CODEX_APP_SERVER_SENTINEL, CODEX_LEGACY_PROVIDER, isCodexAppServerProvider, isCodexLegacyProvider, normalizeProviderId } from './agent/backends/provider_ids.js';
25
27
  import { requiredRouterModel } from './config/router_required.js';
28
+ import { holdPinnedRoute, isPinnedRoute, modelPinRequested, pinnedRoute, pinnedRouteMessage, pinnedRouting, pinnedRoutingRefusal, RoutePinnedError, routeChangeError, routeChangeRefusal } from './config/model_pin.js';
29
+ import { hostedSettingsConfigPatch } from './hosted/session_settings.js';
30
+ import { PermissionPinChangedError, permissionPinRequested, permissionPinRestartEnv, PermissionPinUnlimitedError, PermissionsPinnedError, pinnedFactoryResetMessage, pinnedPermissionsMessage, pinnedPermissionsSwitchMessage, PINNED_PERMISSION_SETTINGS, profileRootedAt, takePermissionPinSource } from './config/permission_pin.js';
31
+ import { holdsHostRouterGrant, hostClaimsRouter, hostRouterGrantFor, UNUSABLE_ROUTER_RUNTIME_GRANT_REFUSED } from './config/router_runtime_grant.js';
32
+ import { hostCredential, hostEnvironmentValue } from './config/host_credentials.js';
33
+ import { looksLikeRouterCredential, noPlatformLoginReason, PLATFORM_LOGIN_IS_ROUTER_CREDENTIAL, PLATFORM_LOGIN_NOT_NAMED, PROXY_URL_SOURCE_ENV, SAVED_LOGIN_IS_ROUTER_CREDENTIAL } from './config/platform_login.js';
26
34
  import { DEFAULT_SPINNER_VERBS, resolveSpinnerVerbs } from './utils/spinner_verbs.js';
35
+ import { followProfileProviderKeyEnv } from './utils/subprocess_env.js';
27
36
  import { INLINE_SIZE_THRESHOLD_TOKENS_DEFAULT, INLINE_AGE_TURNS_DEFAULT, } from './agent/tool_response_store.js';
28
37
  import { DEFAULT_MESSAGE_DISPLAY, withMessageDisplayDefaults } from './config/message_display.js';
29
38
  import { DEFAULT_AUTO_COMPACT_THRESHOLD, DEFAULT_COMPACTION_TARGET_PERCENT, parseCompactionTriggerMode, parseContextTokenBudget, resolveAutoCompactThreshold, resolveCompactionTargetPercent, resolveCompactionTriggerMode, resolveCompactionSettings, resolveContextTokenBudget, } from './config/compaction.js';
@@ -211,6 +220,75 @@ export function withBuiltInProfiles(saved) {
211
220
  const own = Object.entries(saved ?? {}).filter(([id, profile]) => !isBuiltInProfileCopy(id, profile));
212
221
  return { ...DEFAULT_PERMISSION_PROFILES, ...Object.fromEntries(own) };
213
222
  }
223
+ /** What a config.json whose `permissionProfiles` are SAVED, as it holds them, defines as ID: its own or a built-in one. */
224
+ function definedPermissionProfile(saved, id) {
225
+ const own = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : undefined;
226
+ const profiles = withBuiltInProfiles(own);
227
+ const profile = Object.prototype.hasOwnProperty.call(profiles, id) ? profiles[id] : undefined;
228
+ return typeof profile === 'object' && profile !== null && !Array.isArray(profile) ? profile : undefined;
229
+ }
230
+ /**
231
+ * How a config.json whose `permissionProfiles` are SAVED holds ID against HELD, the definition this process holds:
232
+ * undefined where it holds ID so, or where it defines ID and that profile doesn't limit the agent (LIMITS false).
233
+ */
234
+ function launchProfileMismatch(saved, id, held, limits) {
235
+ const theirs = definedPermissionProfile(saved, id);
236
+ if (!theirs)
237
+ return { defined: false };
238
+ if (!limits || isDeepStrictEqual(theirs, held))
239
+ return undefined;
240
+ const ours = (held ?? {});
241
+ const other = theirs;
242
+ const fields = [...new Set([...Object.keys(ours), ...Object.keys(other)])]
243
+ .filter(field => !isDeepStrictEqual(ours[field], other[field])).sort();
244
+ return { defined: true, fields, builtIn: isDeepStrictEqual(held, DEFAULT_PERMISSION_PROFILES[id]) };
245
+ }
246
+ /**
247
+ * Why a switch to config profile NAME, whose config.json is at PATH, is refused: it holds ID, the permission profile
248
+ * this process's launch named, as MISMATCH says, and a switch keeps ID as this process holds it. The session stays on
249
+ * CURRENT, whose config.json, at CURRENT_PATH, this process holds ID from.
250
+ */
251
+ function launchProfileSwitchRefusal(id, mismatch, name, path, current, currentPath) {
252
+ const kept = 'A config-profile switch keeps that permission profile as this ZTC holds it and never falls back to '
253
+ + `another, so this session stays on config profile "${current}".`;
254
+ const launched = `the permission profile "${id}" this ZTC was started with (--permission-profile ${id})`;
255
+ if (!mismatch.defined) {
256
+ return `Config profile "${name}" doesn't define ${launched}. ${kept} To switch to "${name}" under it, define "${id}" `
257
+ + `under "permissionProfiles" in ${path} as this ZTC holds it from ${currentPath}.`;
258
+ }
259
+ const differ = mismatch.fields.length > 0 ? `they differ in ${mismatch.fields.join(', ')}` : 'they differ';
260
+ return mismatch.builtIn
261
+ ? `Config profile "${name}" defines ${launched} otherwise than the built-in one this ZTC holds: ${differ}. ${kept} `
262
+ + `To switch to "${name}" under it, remove "${id}" from "permissionProfiles" in ${path}, where it replaces the `
263
+ + 'built-in one.'
264
+ : `Config profile "${name}" defines ${launched} otherwise than this ZTC holds it from ${currentPath}: ${differ}. `
265
+ + `${kept} To switch to "${name}" under it, give "${id}" under "permissionProfiles" in ${path} the definition `
266
+ + `this ZTC holds.`;
267
+ }
268
+ /**
269
+ * Why a factory reset of the config.json at PATH is refused under ID, the permission profile this process's launch named,
270
+ * which a reset keeps: the config.json a reset leaves defines the built-in permission profiles alone, which hold ID as
271
+ * MISMATCH says.
272
+ */
273
+ function launchProfileResetRefusal(id, mismatch, path) {
274
+ const after = mismatch.defined
275
+ ? `which ${path} redefines; a reset would put the built-in one back, and ${mismatch.fields.length > 0
276
+ ? `they differ in ${mismatch.fields.join(', ')}` : 'they differ'}`
277
+ : `which it holds from ${path}; a reset would remove it there`;
278
+ return `This ZTC was started with --permission-profile ${id}, ${after}. A factory reset keeps the permission profile `
279
+ + 'ZTC was started with, as it holds it, and never falls back to another, so nothing was reset. '
280
+ + `To reset ${path}, start ZTC without --permission-profile ${id}.`;
281
+ }
282
+ /**
283
+ * A setting as save() writes it (see persistedSettings): permission profiles without the built-in profiles' copies, and
284
+ * none when that leaves none; any other setting as it is.
285
+ */
286
+ function savedSettingValue(key, value) {
287
+ if (key !== 'permissionProfiles' || !value)
288
+ return value;
289
+ const own = Object.entries(value).filter(([id, profile]) => !isBuiltInProfileCopy(id, profile));
290
+ return own.length > 0 ? Object.fromEntries(own) : undefined;
291
+ }
214
292
  const DEFAULT_INTENTS = {
215
293
  enabled: false,
216
294
  autoWrite: false,
@@ -243,6 +321,15 @@ const PERSONAL_DEFAULT_MODEL = 'deepseek-v4.1-flash';
243
321
  const PERSONAL_DEFAULT_PROXY_URL = 'https://zergrouter.com';
244
322
  /** Environment variables that already name a working provider route. */
245
323
  const ROUTE_CREDENTIAL_ENV = [...Object.values(PROVIDER_API_KEY_ENV).flat(), 'ZTC_AUTH_TOKEN'];
324
+ /** What a run says, once, when ZTC_AUTH_TOKEN holds the host's Router runtime grant. It never repeats the grant. */
325
+ const PLATFORM_TOKEN_IS_HOST_GRANT = '[ztc] ZTC_AUTH_TOKEN holds the host\'s Router runtime grant, so ZTC does not take it as the '
326
+ + 'ZergAI platform login and sends it nowhere but the Router ZERG_ROUTER_BASE_URL names.';
327
+ /** What ZTC says once when it sends a platform login the environment handed over (ZTC_AUTH_TOKEN) to no platform API. */
328
+ const PLATFORM_LOGIN_NOTICES = Object.freeze({
329
+ host_grant: PLATFORM_TOKEN_IS_HOST_GRANT,
330
+ router_credential: PLATFORM_LOGIN_IS_ROUTER_CREDENTIAL,
331
+ not_named: PLATFORM_LOGIN_NOT_NAMED,
332
+ });
246
333
  /**
247
334
  * Modal DeepSeek through Zerg Router is the default for a person starting
248
335
  * fresh. The Modal route needs a Router device login, so a process launched
@@ -252,7 +339,7 @@ const ROUTE_CREDENTIAL_ENV = [...Object.values(PROVIDER_API_KEY_ENV).flat(), 'ZT
252
339
  * the default does not depend on files in the user's home.
253
340
  */
254
341
  function default_provider() {
255
- const hasRouteCredential = ROUTE_CREDENTIAL_ENV.some(name => Boolean(process.env[name]?.trim()));
342
+ const hasRouteCredential = ROUTE_CREDENTIAL_ENV.some(name => Boolean(hostEnvironmentValue(name)?.trim()));
256
343
  return hasRouteCredential ? inferDefaultProvider() : PERSONAL_DEFAULT_PROVIDER;
257
344
  }
258
345
  export const DEFAULT_TERMINAL_INTERACTION = {
@@ -354,6 +441,54 @@ const ROUTING_SETTING_KEYS = [
354
441
  'apiEnvironment',
355
442
  'zrouterRoutePlan',
356
443
  ];
444
+ /**
445
+ * What a running ZTC under a permission profile that limits the agent (config/profile_limits.ts) takes as it was at
446
+ * startup, or as this process itself last set it, whatever config.json says later: its hooks, MCP servers, permission
447
+ * profiles and active profile, tool permissions and sandbox settings, and the skills and workflow settings that name
448
+ * extension roots. Another process that could write config.json (an agent that reached ZTC's config folder) would
449
+ * otherwise have ZTC run its hook or MCP server outside the sandbox, or drop the sandbox, at the next reload. The
450
+ * edit stays in the file for the next start (see frozenFileValues).
451
+ */
452
+ const FROZEN_UNDER_LIMITS = Object.freeze([
453
+ 'hooks', 'mcpServers', 'mcp', 'permissionProfiles', 'permissionProfile', 'toolPermissions', 'sandbox',
454
+ 'skills', 'desktopDelegatedSkillRoots', 'workflows',
455
+ ]);
456
+ /**
457
+ * The permission settings a pin taken from SOURCE holds: its profile's definition (a built-in one where the settings
458
+ * define none), the sandbox settings over their defaults and the tool permissions, each a copy.
459
+ */
460
+ function permissionsHeldFrom(source) {
461
+ const profile = source.defined ?? DEFAULT_PERMISSION_PROFILES[source.profileId];
462
+ return {
463
+ profileId: source.profileId,
464
+ profile: profile === undefined ? undefined : structuredClone(profile),
465
+ sandbox: structuredClone({ ...DEFAULT_SANDBOX, ...(source.sandbox ?? {}) }),
466
+ toolPermissions: structuredClone(source.toolPermissions ?? { ...DEFAULT_TOOL_PERMISSIONS }),
467
+ };
468
+ }
469
+ /** Whether HELD is what PIN holds. */
470
+ function holdsPinnedPermissions(pin, held) {
471
+ return held.profileId === pin.profileId && isDeepStrictEqual(held.profile, pin.profile)
472
+ && isDeepStrictEqual(held.sandbox, pin.sandbox) && isDeepStrictEqual(held.toolPermissions, pin.toolPermissions);
473
+ }
474
+ /**
475
+ * Settings whose fields belong together: a sign-in, a connection's address with its key, a route plan, the account pool
476
+ * with the accounts its choices name. Where this ZTC and another both changed one, a save or reload keeps this ZTC's
477
+ * whole, as it does any setting both changed, rather than mixing one ZTC's fields with the other's (mergeSavedSettings).
478
+ */
479
+ const WHOLE_SETTINGS = new Set([
480
+ 'auth', 'openaiCompatible', 'nativeAnthropicMessagesRouter', 'keptAnthropicKey', 'zrouterRoutePlan', 'accounts',
481
+ ]);
482
+ /**
483
+ * Settings whose entries each belong together: an MCP server's address or command with the credential sent to it. A
484
+ * merge goes into the setting entry by entry, but keeps an entry both ZTCs changed as this ZTC's whole
485
+ * (mergeSettingEntries), so one pane's new server address is never saved with the token another rotated for the old one.
486
+ */
487
+ const WHOLE_ENTRY_SETTINGS = new Set(['mcpServers']);
488
+ /** KEY's three-way merge (mergeSettingValue), with each entry of a setting of WHOLE_ENTRY_SETTINGS kept whole. */
489
+ function mergeSetting(key, base, ours, theirs) {
490
+ return WHOLE_ENTRY_SETTINGS.has(key) ? mergeSettingEntries(base, ours, theirs) : mergeSettingValue(base, ours, theirs);
491
+ }
357
492
  /** Settings an environment variable can set for one process (see applyEnvOverrides); save() never writes what it set. */
358
493
  const ENVIRONMENT_SETTING_KEYS = [
359
494
  'provider',
@@ -584,17 +719,21 @@ function routerAuthFile() {
584
719
  /**
585
720
  * What a save writes when another ZTC saved the profile since this one last read or wrote it: the file as that ZTC
586
721
  * left it, with each setting this ZTC changed since (from `base`, what it last read or wrote, to `ours`) applied over
587
- * it, and a setting this ZTC removed removed. A setting both changed keeps this save's: the last one saved wins.
722
+ * it, and a setting this ZTC removed removed. Within a group of settings (panes, apiKeys, toolPermissions, sandbox, …)
723
+ * the same holds field by field, so a pane's next change to one pane setting no longer writes back, from its old copy,
724
+ * the panes.agentPermissions another pane saved (mergeSettingValue). A value both changed keeps this save's: the last
725
+ * one saved wins; a setting of WHOLE_SETTINGS keeps this save's whole.
588
726
  */
589
727
  function mergeSavedSettings(base, ours, theirs) {
590
728
  const merged = { ...theirs };
591
729
  for (const key of new Set([...Object.keys(base), ...Object.keys(ours)])) {
592
730
  if (isDeepStrictEqual(base[key], ours[key]))
593
731
  continue;
594
- if (ours[key] === undefined)
732
+ const value = WHOLE_SETTINGS.has(key) ? ours[key] : mergeSetting(key, base[key], ours[key], theirs[key]);
733
+ if (value === undefined)
595
734
  delete merged[key];
596
735
  else
597
- merged[key] = ours[key];
736
+ merged[key] = value;
598
737
  }
599
738
  return merged;
600
739
  }
@@ -694,6 +833,8 @@ export class ConfigStore {
694
833
  * compares against to tell this process's own changes from another ZTC's (see mergeSavedSettings).
695
834
  */
696
835
  savedBase;
836
+ /** This process's settings as it held them when savedBase was taken: what a reload merges this process's changes from. */
837
+ savedBaseConfig;
697
838
  configScope = 'global';
698
839
  /** See onChange. */
699
840
  changeListeners = new Set();
@@ -747,6 +888,22 @@ export class ConfigStore {
747
888
  sessionRouteChoice;
748
889
  /** This process's session settings are a hosted thread's, not the person's choice in it (see markHostedSession). */
749
890
  hostedSession = false;
891
+ /**
892
+ * The hosted thread's settings this session took last (applyHostedThreadSettings): the host's, which a clear of the
893
+ * session's own settings leaves in place (clearSessionOverrides).
894
+ */
895
+ hostedThreadSettings = null;
896
+ /**
897
+ * The sandbox settings and tool permissions as config.json saves them, without ZTC's defaults (load). A host's pin of
898
+ * the permission settings is taken from these (pinStartupPermissions), so a ZTC of another version, started again in
899
+ * place, resolves them with its own defaults.
900
+ */
901
+ savedPermissionSettings = {};
902
+ /**
903
+ * The permission settings this session's host pinned (ZTC_PERMISSION_PROFILE_PINNED; config/permission_pin.ts), as the
904
+ * session held them once its startup was done (pinStartupPermissions): taken once, and never changed or ended.
905
+ */
906
+ permissionPin;
750
907
  /**
751
908
  * The move off the retired routes, when it could not be saved with its
752
909
  * backup: it applies to this run only, and save() writes that backup before
@@ -766,6 +923,28 @@ export class ConfigStore {
766
923
  environmentRouteSources = [];
767
924
  /** The model the environment pins this load; a retired one is ignored and pins nothing. */
768
925
  environmentModelPin;
926
+ /**
927
+ * What save() writes for each setting a reload kept as this process had it, under a profile that limits the agent
928
+ * (FROZEN_UNDER_LIMITS), where that is not what this process holds: the value config.json holds, with only what this
929
+ * process changed in the setting itself applied over it (noteFrozenValueToSave), so this process never undoes an edit
930
+ * it did not take, and the edit applies at the next start. A restart in place would take each (see
931
+ * listSettingsARestartWouldTake).
932
+ */
933
+ frozenFileValues = new Map();
934
+ /** The frozen settings whose ignored edit this process has said (see keepFrozenSettings): each is said once. */
935
+ frozenEditsSaid = new Set();
936
+ /** The config.json this process last read, whose later edits a profile that limits the agent does not take. */
937
+ loadedConfigFile;
938
+ /**
939
+ * For each config.json this process left for another config profile's under a permission profile that limits the
940
+ * agent, and for the copy /profile duplicate made of the one it ran on: the settings of FROZEN_UNDER_LIMITS as it held
941
+ * them there. A switch back under such a profile holds them so again (switchProfile), as a reload of that config.json
942
+ * would, so an edit to them that it held back there, or one made there while it was away, waits for a restart, as it
943
+ * would had it stayed.
944
+ */
945
+ heldForConfigFile = new Map();
946
+ /** What the switch under way holds for the config.json it loads (heldForConfigFile), which load() takes. */
947
+ switchHolds;
769
948
  deriveZRouterUrl(apiBaseUrl) {
770
949
  return `${apiBaseUrl.replace(/\/$/, '')}/api/zrouter`;
771
950
  }
@@ -863,7 +1042,7 @@ export class ConfigStore {
863
1042
  ...(standard && !isClaudeCodeToken(standard.value) ? { anthropicKeyInEnvironment: standard.name } : {}),
864
1043
  namedAnthropicKeySet: Boolean(named && !isClaudeCodeToken(named)),
865
1044
  ...(routerCurrent && credentials && (!forcedOrigin || forcedOrigin === credentials.origin) ? { routerOrigin: credentials.origin } : {}),
866
- claudeCodeTokenInEnvironment: Boolean(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim()),
1045
+ claudeCodeTokenInEnvironment: Boolean(hostEnvironmentValue('CLAUDE_CODE_OAUTH_TOKEN')?.trim()),
867
1046
  home: homedir(),
868
1047
  claudeHome: join(homedir(), '.claude'),
869
1048
  takenProfileNames: listAgentProfiles('claude'),
@@ -994,17 +1173,26 @@ export class ConfigStore {
994
1173
  if (providerEnvKey && this.legacyApiKeyFromEnvironment) {
995
1174
  this.config.apiKey = providerEnvKey;
996
1175
  }
997
- if (process.env.ZTC_API_KEY) {
998
- this.config.apiKey = process.env.ZTC_API_KEY;
1176
+ const environmentKey = hostEnvironmentValue('ZTC_API_KEY');
1177
+ if (environmentKey) {
1178
+ this.config.apiKey = environmentKey;
999
1179
  this.legacyApiKeyFromEnvironment = true;
1000
1180
  }
1001
- // Platform auth token (for ZergAPIBackend — routes LLM through platform)
1002
- if (process.env.ZTC_AUTH_TOKEN) {
1181
+ // Platform auth token (for ZergAPIBackend — routes LLM through platform). It is a credential of ZTC's own, which
1182
+ // the host-credential store holds outside process.env. One that holds the host's Router runtime grant (an
1183
+ // entrypoint that sets ZTC_AUTH_TOKEN from ZERG_API_TOKEN, which ZergCloud sets to the grant, hands it over so) is
1184
+ // that grant under another name, which goes only to the Router ZERG_ROUTER_BASE_URL names: it is no platform login,
1185
+ // and the platform API is never sent it.
1186
+ const platformToken = hostCredential('ZTC_AUTH_TOKEN');
1187
+ if (platformToken && holdsHostRouterGrant(platformToken)) {
1188
+ runtimeDiagOnce('warn', PLATFORM_LOGIN_NOTICES.host_grant);
1189
+ }
1190
+ else if (platformToken) {
1003
1191
  if (!this.config.auth) {
1004
- this.config.auth = { token: process.env.ZTC_AUTH_TOKEN, userId: 0, email: '' };
1192
+ this.config.auth = { token: platformToken, userId: 0, email: '' };
1005
1193
  }
1006
1194
  else {
1007
- this.config.auth.token = process.env.ZTC_AUTH_TOKEN;
1195
+ this.config.auth.token = platformToken;
1008
1196
  }
1009
1197
  }
1010
1198
  // API environment (localhost, development, production)
@@ -1055,10 +1243,257 @@ export class ConfigStore {
1055
1243
  this.environmentValues.set(key, { applied: structuredClone(this.config[key]), saved: before });
1056
1244
  }
1057
1245
  }
1246
+ // A platform login the environment handed over that ZTC sends to no platform API: said once, never its value.
1247
+ const refusal = platformToken && this.config.auth?.token === platformToken ? this.platformLoginRefusal(platformToken) : undefined;
1248
+ if (refusal)
1249
+ runtimeDiagOnce('warn', PLATFORM_LOGIN_NOTICES[refusal]);
1250
+ }
1251
+ /**
1252
+ * Whether the permission profile this process runs under now limits the agent (config/profile_limits.ts), decided as a
1253
+ * reload decides whether to keep the settings ZTC started with: startup asks it once the profile is known.
1254
+ */
1255
+ permissionProfileLimitsAgent() {
1256
+ return this.profileLimitsAgentNow();
1257
+ }
1258
+ /** Whether the permission profile this process runs under now limits the agent, as get() resolves it. */
1259
+ profileLimitsAgentNow() {
1260
+ if (this.permissionPin)
1261
+ return profileLimitsAgent(this.permissionPin.profile, this.permissionPin.sandbox);
1262
+ const id = this.cliOverrides.permissionProfile ?? this.sessionOverrides.permissionProfile ?? this.config.permissionProfile ?? 'trusted';
1263
+ const profiles = this.sessionOverrides.permissionProfiles ?? this.config.permissionProfiles;
1264
+ return profileLimitsAgent(profiles?.[id] ?? DEFAULT_PERMISSION_PROFILES[id], this.sessionOverrides.sandbox ?? this.config.sandbox);
1265
+ }
1266
+ /**
1267
+ * Whether this process holds what could widen its permission profile as it started (FROZEN_UNDER_LIMITS), taking no
1268
+ * config.json edit to it on a reload: under a profile that limits the agent, and whenever its host pinned its
1269
+ * permission settings (ZTC_PERMISSION_PROFILE_PINNED), whether or not that profile limits the agent.
1270
+ */
1271
+ holdsWhatCouldWiden() {
1272
+ return this.permissionPin !== undefined || this.profileLimitsAgentNow();
1273
+ }
1274
+ /**
1275
+ * Pin the permission settings this session holds now, its startup done, as its only ones where its host asked for that
1276
+ * (ZTC_PERMISSION_PROFILE_PINNED; config/permission_pin.ts): the permission profile (the launch's --permission-profile,
1277
+ * a hosted thread's, or the one config.json saves) with its definition, the sandbox settings and the tool permissions,
1278
+ * as get() resolves them now. From then on get() holds them whatever another layer says, every change of them is
1279
+ * refused naming the variable, and nothing ends the pin: the variable is read here, once. Without it, nothing changes.
1280
+ * The profile's relative file roots are resolved here against the folder the session started in (process.cwd(), which
1281
+ * --cwd chose), its mounted workspace, and get() holds them so: the agent's file tools and the OS sandbox of its
1282
+ * commands resolve a relative root against the folder the agent works in, which a controller's /cd moves.
1283
+ * A ZTC started again in place in a pinned one's stead is handed what that one's pin was taken from: where its own
1284
+ * differs (another process edited config.json, or the host's thread, after the restart's check, while this ZTC was
1285
+ * still to read them), it throws PermissionPinChangedError, and its caller doesn't start. Where the profile it would
1286
+ * pin limits nothing (trusted, the default), or lets the agent's commands run outside an OS sandbox, it throws
1287
+ * PermissionPinUnlimitedError, and its caller doesn't start either.
1288
+ */
1289
+ pinStartupPermissions() {
1290
+ // Taken out of the environment first, pinned or not, so no program this ZTC starts inherits it.
1291
+ const handedOver = takePermissionPinSource();
1292
+ if (this.permissionPin || !permissionPinRequested())
1293
+ return;
1294
+ const config = this.get();
1295
+ const profileId = config.permissionProfile || 'trusted';
1296
+ const folder = process.cwd();
1297
+ // What the session holds now, as get() resolves it.
1298
+ const held = permissionsHeldFrom({ profileId, defined: config.permissionProfiles?.[profileId], sandbox: config.sandbox,
1299
+ toolPermissions: config.toolPermissions, folder });
1300
+ // What it holds them from, as config.json or the host's thread gives them: no built-in profile they don't redefine,
1301
+ // and the sandbox settings and tool permissions without ZTC's defaults. A ZTC started again in place, perhaps another
1302
+ // version after an update, resolves this and the source it is handed alike, with its own built-ins and defaults.
1303
+ const shown = config.permissionProfiles?.[profileId];
1304
+ const given = (key) => Object.hasOwn(this.sessionOverrides, key) ? this.sessionOverrides[key] : this.savedPermissionSettings[key];
1305
+ const source = JSON.parse(JSON.stringify({ profileId,
1306
+ defined: shown === undefined || isBuiltInProfileCopy(profileId, shown) ? undefined : shown,
1307
+ sandbox: given('sandbox'), toolPermissions: given('toolPermissions'), folder }));
1308
+ if (handedOver !== undefined && (handedOver === null || handedOver.folder !== source.folder
1309
+ || !holdsPinnedPermissions(permissionsHeldFrom(handedOver), permissionsHeldFrom(source)))) {
1310
+ throw new PermissionPinChangedError();
1311
+ }
1312
+ // A host that pins the permission settings means them to limit the agent: a profile that limits nothing (trusted, the
1313
+ // default, whatever gave it) is never pinned, and ZTC doesn't start.
1314
+ if (!profileLimitsAgent(held.profile, held.sandbox))
1315
+ throw new PermissionPinUnlimitedError(profileId);
1316
+ // Nor one that lets the agent's commands run outside an OS sandbox (one that only turns a capability off): they reach
1317
+ // ZTC's own state, the config.json the pin is taken from among it (the reviewer's recheck of round 2, 2026-11-23). One
1318
+ // that runs no command, or keeps its commands in the sandbox, is pinned.
1319
+ const runsCommands = held.profile?.capabilities?.shell_exec !== false && held.toolPermissions?.shell_exec !== false;
1320
+ if (runsCommands && !osSandboxRequested(held.profile, held.sandbox)) {
1321
+ throw new PermissionPinUnlimitedError(profileId, true);
1322
+ }
1323
+ this.permissionPin = {
1324
+ ...held,
1325
+ rooted: held.profile === undefined ? undefined : profileRootedAt(structuredClone(held.profile), source.folder),
1326
+ rootedAt: source.folder,
1327
+ source,
1328
+ hostedProfile: this.hostedThreadSettings ? hostedSettingsConfigPatch(this.hostedThreadSettings).permissionProfile : undefined,
1329
+ };
1330
+ }
1331
+ /** Whether this session's host pinned its permission profile and sandbox (pinStartupPermissions). */
1332
+ permissionsPinned() {
1333
+ return this.permissionPin !== undefined;
1334
+ }
1335
+ /**
1336
+ * The folder the session started in, where its host's pin holds the permission profile's relative roots, or undefined
1337
+ * without the pin: a ZTC started again in place starts there, as it pins those roots at the folder it starts in.
1338
+ */
1339
+ permissionPinFolder() {
1340
+ return this.permissionPin?.rootedAt;
1341
+ }
1342
+ /**
1343
+ * What a ZTC started again in place in this one's stead is handed under the host's pin, so it pins what this one does
1344
+ * or doesn't start (pinStartupPermissions); nothing without the pin.
1345
+ */
1346
+ permissionPinRestartEnv() {
1347
+ return permissionPinRestartEnv(this.permissionPin?.source);
1348
+ }
1349
+ /**
1350
+ * Why a change of this session's permission profile, sandbox or tool permissions is refused, or undefined when it may
1351
+ * go: its host pinned them (ZTC_PERMISSION_PROFILE_PINNED). The message names the variable and nothing of the profile.
1352
+ */
1353
+ permissionPinRefusal() {
1354
+ return this.permissionPin ? pinnedPermissionsMessage() : undefined;
1355
+ }
1356
+ /**
1357
+ * The permission settings the host's pin holds, over every other layer of the settings (composeConfig): copies, so no
1358
+ * caller changes the pin through what get() returns. The pinned profile's definition replaces the one PROFILES holds
1359
+ * under its id: by default as the pin holds it for the agent, its relative roots those of the folder the session started
1360
+ * in; AS_DEFINED, as config.json (or ZTC, for a built-in one) defines it, which a write of the same settings may name.
1361
+ */
1362
+ pinnedPermissionLayer(profiles, asDefined = false) {
1363
+ const pin = this.permissionPin;
1364
+ const { [pin.profileId]: _held, ...others } = profiles ?? {};
1365
+ const profile = asDefined ? pin.profile : pin.rooted;
1366
+ return {
1367
+ permissionProfile: pin.profileId,
1368
+ permissionProfiles: profile === undefined ? others : { ...others, [pin.profileId]: structuredClone(profile) },
1369
+ sandbox: structuredClone(pin.sandbox),
1370
+ toolPermissions: structuredClone(pin.toolPermissions),
1371
+ };
1372
+ }
1373
+ /**
1374
+ * Refuse KEY = VALUE where the host pinned this session's permission settings (permissionPin) and KEY is one of them
1375
+ * (PINNED_PERMISSION_SETTINGS): another value than the pin holds throws PermissionsPinnedError, naming the variable.
1376
+ * True when the pin holds KEY, so the caller writes nothing: what the pin holds is never saved as the person's choice,
1377
+ * nor kept in a layer of the session's own.
1378
+ */
1379
+ refusePinnedPermissionChange(key, value) {
1380
+ if (!this.permissionPin || !PINNED_PERMISSION_SETTINGS.includes(key))
1381
+ return false;
1382
+ const pinned = this.get();
1383
+ // The profiles as the pin holds them (get()'s, the pinned one's relative roots resolved) or as config.json defines
1384
+ // them are the same settings.
1385
+ const sameProfiles = () => {
1386
+ const profiles = withBuiltInProfiles(value);
1387
+ return isDeepStrictEqual(profiles, withBuiltInProfiles(pinned.permissionProfiles))
1388
+ || isDeepStrictEqual(profiles, withBuiltInProfiles(this.pinnedPermissionLayer(pinned.permissionProfiles, true).permissionProfiles));
1389
+ };
1390
+ const same = key === 'permissionProfile' ? (value || 'trusted') === pinned.permissionProfile
1391
+ : key === 'permissionProfiles' ? sameProfiles()
1392
+ : key === 'sandbox' ? isDeepStrictEqual({ ...DEFAULT_SANDBOX, ...(value ?? {}) }, pinned.sandbox)
1393
+ : isDeepStrictEqual(value ?? { ...DEFAULT_TOOL_PERMISSIONS }, pinned.toolPermissions);
1394
+ if (!same)
1395
+ throw new PermissionsPinnedError();
1396
+ return true;
1397
+ }
1398
+ /**
1399
+ * The permission settings this session would hold on SAVED, the config.json a switch to another config profile's
1400
+ * folder loads (or HOLDS, what this process held there), with the launch's permission profile it keeps (KEPT): its
1401
+ * session settings go with the old folder.
1402
+ */
1403
+ permissionsHeldOn(saved, kept) {
1404
+ const profileId = kept ?? (typeof saved?.permissionProfile === 'string' && saved.permissionProfile ? saved.permissionProfile : 'trusted');
1405
+ return {
1406
+ profileId,
1407
+ profile: definedPermissionProfile(saved?.permissionProfiles, profileId),
1408
+ sandbox: { ...DEFAULT_SANDBOX, ...(saved?.sandbox ?? {}) },
1409
+ toolPermissions: saved?.toolPermissions ?? { ...DEFAULT_TOOL_PERMISSIONS },
1410
+ };
1411
+ }
1412
+ /**
1413
+ * After a reload under a profile that limits the agent: put back each setting of FROZEN_UNDER_LIMITS as this process
1414
+ * held it (HELD), keep what the file said for save() (frozenFileValues), and say once which edit was ignored.
1415
+ */
1416
+ keepFrozenSettings(held) {
1417
+ if (!held)
1418
+ return;
1419
+ const ignored = [];
1420
+ const record = this.config;
1421
+ for (const key of FROZEN_UNDER_LIMITS) {
1422
+ const fromFile = record[key];
1423
+ record[key] = structuredClone(held[key]);
1424
+ if (isDeepStrictEqual(fromFile, held[key])) {
1425
+ this.frozenFileValues.delete(key);
1426
+ }
1427
+ else {
1428
+ this.frozenFileValues.set(key, structuredClone(fromFile));
1429
+ if (!this.frozenEditsSaid.has(key))
1430
+ ignored.push(key);
1431
+ this.frozenEditsSaid.add(key);
1432
+ }
1433
+ }
1434
+ if (ignored.length > 0) {
1435
+ runtimeDiag('warn', `[ztc] ${configFile()} changed ${ignored.join(', ')} while this ZTC runs under a permission profile `
1436
+ + 'that limits the agent; it keeps them as they were when it started until it restarts.');
1437
+ }
1438
+ }
1439
+ /**
1440
+ * What save() writes for KEY, a setting of FROZEN_UNDER_LIMITS that this process holds as it started, kept in
1441
+ * frozenFileValues while it is not what this process holds: this process's own change to it since it last read or
1442
+ * wrote config.json (from savedBaseConfig, the setting as it held it then, to the setting as it holds it now) applied
1443
+ * over config.json's value then (savedBase), field by field within a group of settings (mergeSettingValue). So a change
1444
+ * of its own to one field of the tool permissions or the sandbox never writes back, from what it holds, a field another
1445
+ * ZTC changed, and where it changed nothing config.json's value is written back as it is.
1446
+ */
1447
+ noteFrozenValueToSave(key) {
1448
+ const own = savedSettingValue(key, this.config[key]);
1449
+ const toSave = mergeSetting(key, savedSettingValue(key, this.savedBaseConfig?.[key]), own, this.savedBase?.[key]);
1450
+ if (isDeepStrictEqual(toSave, own))
1451
+ this.frozenFileValues.delete(key);
1452
+ else
1453
+ this.frozenFileValues.set(key, structuredClone(toSave));
1454
+ }
1455
+ /**
1456
+ * KEY, set by this process itself: a setting of FROZEN_UNDER_LIMITS is saved as its change over config.json's value
1457
+ * (noteFrozenValueToSave), also once the profile no longer limits the agent, until this process reads the profile
1458
+ * again, since it still holds the setting as it started. Where it read the setting from config.json, as it does under
1459
+ * a profile that limits nothing, that is its own value.
1460
+ */
1461
+ noteOwnSetting(key) {
1462
+ if (FROZEN_UNDER_LIMITS.includes(key))
1463
+ this.noteFrozenValueToSave(key);
1464
+ }
1465
+ /**
1466
+ * Whether the next load takes the settings of FROZEN_UNDER_LIMITS as this process holds them (see keepFrozenSettings):
1467
+ * a reload of the same config.json under a profile that limits the agent, or where the host pinned the permission
1468
+ * settings (holdsWhatCouldWiden).
1469
+ */
1470
+ reloadHoldsFrozenSettings() {
1471
+ return this.loaded && this.loadedConfigFile === configFile() && this.holdsWhatCouldWiden();
1472
+ }
1473
+ /** The settings of FROZEN_UNDER_LIMITS as this process holds them now: a copy of its own. */
1474
+ frozenSettingsAsHeld() {
1475
+ return structuredClone(Object.fromEntries(FROZEN_UNDER_LIMITS.map(key => [key, this.config[key]])));
1476
+ }
1477
+ /**
1478
+ * Take SAVED as the settings this process last read or wrote (savedBase), and HELD, by default its settings as it
1479
+ * holds them now, as what it held then (savedBaseConfig).
1480
+ */
1481
+ noteSavedBase(saved, held = structuredClone(this.config)) {
1482
+ this.savedBase = saved;
1483
+ this.savedBaseConfig = held;
1058
1484
  }
1059
1485
  async load(force = false, options = {}) {
1060
1486
  if (this.loaded && !force && !options.strictConfig)
1061
1487
  return this.config;
1488
+ // A reload of the same config.json under a profile that limits the agent takes nothing from it that could widen
1489
+ // that profile (FROZEN_UNDER_LIMITS), nor does a switch back to one this process ran on under such a profile, or to
1490
+ // the copy it made of one (switchHolds). Any other config profile's folder (a switch the person makes; the agent can
1491
+ // name none) is read as it is.
1492
+ const frozen = this.reloadHoldsFrozenSettings() ? this.frozenSettingsAsHeld()
1493
+ : this.switchHolds ? structuredClone(this.switchHolds) : undefined;
1494
+ if (!frozen)
1495
+ this.frozenFileValues.clear();
1496
+ this.loadedConfigFile = configFile();
1062
1497
  this.profileEmulation = builtinProfileEmulation(activeProfile());
1063
1498
  this.routerCredentialsError = null;
1064
1499
  this.savedAuthStamp = fileStamp(routerAuthFile());
@@ -1091,9 +1526,11 @@ export class ConfigStore {
1091
1526
  throw new Error('Required profile config.json is missing or invalid');
1092
1527
  // File doesn't exist or is invalid, use defaults.
1093
1528
  this.config = build_default_config();
1529
+ this.savedPermissionSettings = {};
1094
1530
  this.legacyApiKeyFromEnvironment = true;
1095
1531
  this.applyEnvOverrides();
1096
- this.savedBase = this.persistedSettings();
1532
+ this.keepFrozenSettings(frozen);
1533
+ this.noteSavedBase(this.persistedSettings());
1097
1534
  this.loaded = true;
1098
1535
  return this.config;
1099
1536
  }
@@ -1111,6 +1548,7 @@ export class ConfigStore {
1111
1548
  saved = await this.moveOffRetiredRoutes(saved, savedText);
1112
1549
  saved = await this.clearMovedClaudeDefault(saved);
1113
1550
  this.config = { ...build_default_config(), ...saved };
1551
+ this.savedPermissionSettings = structuredClone({ sandbox: saved.sandbox, toolPermissions: saved.toolPermissions });
1114
1552
  this.legacyApiKeyFromEnvironment = saved.apiKey === undefined;
1115
1553
  // Defaults were built for the preset provider. A saved provider without
1116
1554
  // a saved key must not inherit that other provider's credential.
@@ -1133,7 +1571,8 @@ export class ConfigStore {
1133
1571
  this.config.terminalInteraction = resolveTerminalInteractionSettings(this.config.terminalInteraction);
1134
1572
  this.config.compaction = resolveCompactionSettings(this.config);
1135
1573
  this.applyEnvOverrides();
1136
- this.savedBase = this.persistedSettings();
1574
+ this.keepFrozenSettings(frozen);
1575
+ this.noteSavedBase(this.persistedSettings());
1137
1576
  this.loaded = true;
1138
1577
  return this.config;
1139
1578
  }
@@ -1144,8 +1583,16 @@ export class ConfigStore {
1144
1583
  * changed while it reads still counts, and a save waits for it (see withSettingsLock). True when it loaded.
1145
1584
  */
1146
1585
  async refreshIfChangedElsewhere() {
1586
+ return this.readSettingsAgain(false);
1587
+ }
1588
+ /**
1589
+ * Load the profile again as refreshIfChangedElsewhere does: where its files' stamps (inode, size, modification time)
1590
+ * changed since this process last read or wrote them, or, WHATEVER_THE_STAMPS, in any case. True when it loaded.
1591
+ */
1592
+ async readSettingsAgain(whateverTheStamps) {
1147
1593
  const loaded = await this.withSettingsLock(async () => {
1148
- if (fileStamp(configFile()) === this.savedFileStamp && fileStamp(routerAuthFile()) === this.savedAuthStamp)
1594
+ if (!whateverTheStamps && fileStamp(configFile()) === this.savedFileStamp
1595
+ && fileStamp(routerAuthFile()) === this.savedAuthStamp)
1149
1596
  return false;
1150
1597
  await this.reloadKeepingRoute();
1151
1598
  return true;
@@ -1154,6 +1601,27 @@ export class ConfigStore {
1154
1601
  this.notifyChange();
1155
1602
  return loaded;
1156
1603
  }
1604
+ /**
1605
+ * What a ZTC started again in place (a hot restart: this ZTC again, resuming its session) would take from config.json
1606
+ * that this one, under a permission profile that limits the agent, does not (FROZEN_UNDER_LIMITS): an edit to its
1607
+ * hooks, MCP servers, profiles, tool permissions, sandbox or extension roots made since it started. config.json is read
1608
+ * now, whatever its stamp says, so an edit made since the last reload counts, and so does one another process made in
1609
+ * place that kept the file's inode, size and modification time, which its stamp doesn't tell apart from no edit (the
1610
+ * reviewer's restart probe, 2026-11-22). Empty under a profile that limits nothing (unless the host pinned the
1611
+ * permission settings, under which a reload holds them all the same), and when config.json holds what this ZTC does. A
1612
+ * config.json that can't be read again counts as such an edit, and says why.
1613
+ */
1614
+ async listSettingsARestartWouldTake() {
1615
+ if (!this.loaded || !this.holdsWhatCouldWiden())
1616
+ return [];
1617
+ try {
1618
+ await this.readSettingsAgain(true);
1619
+ }
1620
+ catch (error) {
1621
+ return [`config.json (${error instanceof Error ? error.message : String(error)})`];
1622
+ }
1623
+ return this.holdsWhatCouldWiden() ? [...this.frozenFileValues.keys()] : [];
1624
+ }
1157
1625
  /**
1158
1626
  * Run `work` (a save, or a read of another ZTC's save) after the one before it ends, so neither writes the profile
1159
1627
  * from settings the other is replacing.
@@ -1187,17 +1655,36 @@ export class ConfigStore {
1187
1655
  const ours = this.persistedSettings();
1188
1656
  const unsaved = base ? Object.keys({ ...base, ...ours }).filter(key => !isDeepStrictEqual(base[key], ours[key])) : [];
1189
1657
  const before = structuredClone({ config: held.config, sessionOverrides: held.sessionOverrides });
1658
+ // The settings as this process held them when it last read or wrote the file, which its changes are made from.
1659
+ const heldBase = this.savedBaseConfig ?? before.config;
1190
1660
  const scope = this.configScope;
1661
+ const holdsFrozen = this.reloadHoldsFrozenSettings();
1191
1662
  await this.load(true);
1192
1663
  this.sessionOverrides = held.sessionOverrides;
1193
1664
  this.configScope = scope;
1194
1665
  // That, and what changed here while the file was read (a picker's choice, a key prompt's), is this process's
1195
- // newest: it applies over what was read, key by key, as a save's merge does, and the save that follows writes it.
1196
- // A route chosen here is this pane's, not a default that moved.
1666
+ // newest: it applies over what was read, as a save's merge does (field by field within a group of settings), and
1667
+ // the save that follows writes it. A route chosen here is this pane's, not a default that moved.
1197
1668
  const changed = [...new Set([...unsaved, ...Object.keys({ ...before.config, ...held.config })
1198
1669
  .filter(key => !isDeepStrictEqual(before.config[key], held.config[key]))])];
1199
- for (const key of changed)
1200
- this.config[key] = held.config[key];
1670
+ const read = this.config;
1671
+ const frozenHere = changed.filter(key => holdsFrozen && FROZEN_UNDER_LIMITS.includes(key));
1672
+ for (const key of changed) {
1673
+ const group = isSettingsGroup(held.config[key]) || isSettingsGroup(read[key]);
1674
+ read[key] = group && !frozenHere.includes(key) && !WHOLE_SETTINGS.has(key)
1675
+ ? mergeSetting(key, heldBase[key], held.config[key], read[key])
1676
+ : held.config[key];
1677
+ }
1678
+ // A setting held as this process started took nothing from the file, so what this process changed in it since it
1679
+ // last read or wrote the file is still its change from the setting as it held it then (heldBase), not from
1680
+ // config.json as it read it now or then, which may hold another ZTC's edit this process never took. The save writes
1681
+ // that change over what config.json says now (see noteFrozenValueToSave), neither dropping it nor undoing the edit.
1682
+ if (holdsFrozen) {
1683
+ for (const key of FROZEN_UNDER_LIMITS) {
1684
+ this.savedBaseConfig[key] = structuredClone(heldBase[key]);
1685
+ this.noteFrozenValueToSave(key);
1686
+ }
1687
+ }
1201
1688
  const sessionBefore = before.sessionOverrides;
1202
1689
  const routeChosenHere = changed.some(key => ROUTE_KEYS.includes(key))
1203
1690
  || ROUTE_KEYS.some(key => !isDeepStrictEqual(sessionBefore[key], held.sessionOverrides[key]));
@@ -1257,15 +1744,37 @@ export class ConfigStore {
1257
1744
  */
1258
1745
  async duplicateProfile(requestedName, source = activeProfile(), activate = () => { }) {
1259
1746
  const name = await copyProfileFiles(source, requestedName);
1747
+ // A copy of the config profile this process runs on is that config profile under another name: under a permission
1748
+ // profile that limits the agent, this process holds the settings that could widen it there as it holds them here,
1749
+ // so an edit to them that it held back here, copied with the rest, is held back there too (heldForConfigFile).
1750
+ const copy = join(profileConfigDir(name), 'config.json');
1751
+ if (profileConfigDir(source) === profileConfigDir() && this.holdsWhatCouldWiden()) {
1752
+ this.heldForConfigFile.set(copy, this.frozenSettingsAsHeld());
1753
+ }
1754
+ else
1755
+ this.heldForConfigFile.delete(copy);
1260
1756
  try {
1261
1757
  await this.switchProfile(name, activate);
1262
1758
  }
1263
1759
  catch (error) {
1760
+ this.heldForConfigFile.delete(copy);
1264
1761
  await rm(profileConfigDir(name), { recursive: true, force: true });
1265
1762
  throw error;
1266
1763
  }
1267
1764
  return name;
1268
1765
  }
1766
+ /**
1767
+ * The launch overrides a switch to another config profile's folder keeps: the permission profile `--permission-profile`
1768
+ * named, which holds the agent to it and to the OS sandbox it requires, so no switch (the person's /profile, a
1769
+ * controller's or a relayed one, /profile create and duplicate, the settings panel's picker) drops them. No other launch
1770
+ * flag sets the sandbox. The launch's route and effort (--provider, --model, --auth-mode, --router-url, --effort) go with
1771
+ * the config profile they were given for, as before: another one keeps its own routes and the keys and sign-ins they
1772
+ * need, and a route limits nothing the agent does.
1773
+ */
1774
+ launchOverridesKeptAcrossProfiles() {
1775
+ const { permissionProfile } = this.cliOverrides;
1776
+ return permissionProfile === undefined ? {} : { permissionProfile };
1777
+ }
1269
1778
  /** Load a profile in this process; restore the old view if runtime activation fails. */
1270
1779
  async switchProfile(name, activate) {
1271
1780
  const next = validateProfileName(name);
@@ -1273,17 +1782,43 @@ export class ConfigStore {
1273
1782
  return;
1274
1783
  const sameConfigDirectory = profileConfigDir(next) === profileConfigDir();
1275
1784
  const target = join(profileConfigDir(next), 'config.json');
1785
+ let saved;
1276
1786
  try {
1277
- const saved = JSON.parse(await readFile(target, 'utf-8'));
1278
- if (!saved || typeof saved !== 'object' || Array.isArray(saved)) {
1787
+ const parsed = JSON.parse(await readFile(target, 'utf-8'));
1788
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1279
1789
  throw new Error('config.json must contain an object');
1280
1790
  }
1791
+ saved = parsed;
1281
1792
  }
1282
1793
  catch (error) {
1283
1794
  if (error.code !== 'ENOENT') {
1284
1795
  throw new Error(`Cannot load config profile ${next}: ${error.message}`);
1285
1796
  }
1286
1797
  }
1798
+ // Under a permission profile that limits the agent, or one the host pinned, a config.json this process ran on and
1799
+ // left, or the copy it made of one, holds the settings that could widen that profile as this process held them there
1800
+ // (heldForConfigFile).
1801
+ const limits = this.holdsWhatCouldWiden();
1802
+ const holds = !sameConfigDirectory && limits ? this.heldForConfigFile.get(target) : undefined;
1803
+ // The launch's permission profile goes with this process into the other folder, as this process holds it. One the
1804
+ // folder's config.json doesn't define, or, where that profile limits the agent, defines otherwise (a built-in one
1805
+ // included), is refused before anything changes: the switch never falls back to another permission profile.
1806
+ const kept = sameConfigDirectory ? {} : this.launchOverridesKeptAcrossProfiles();
1807
+ // Where the host pinned the permission settings (ZTC_PERMISSION_PROFILE_PINNED), the other folder must hold all of
1808
+ // them as the pin does: its config.json's profile (or the launch's kept), its definition, sandbox and tool permissions.
1809
+ // Any other is refused before anything changes, naming the variable; the folder this one already is changes none.
1810
+ if (this.permissionPin && !sameConfigDirectory
1811
+ && !holdsPinnedPermissions(this.permissionPin, this.permissionsHeldOn(holds ?? saved, kept.permissionProfile))) {
1812
+ throw new PermissionsPinnedError(pinnedPermissionsSwitchMessage(next, activeProfile()));
1813
+ }
1814
+ if (kept.permissionProfile !== undefined) {
1815
+ const id = kept.permissionProfile;
1816
+ const mismatch = launchProfileMismatch((holds ?? saved)?.permissionProfiles, id, this.config.permissionProfiles?.[id] ?? DEFAULT_PERMISSION_PROFILES[id], limits);
1817
+ if (mismatch)
1818
+ throw new Error(launchProfileSwitchRefusal(id, mismatch, next, target, activeProfile(), this.getConfigPath()));
1819
+ }
1820
+ // What this process holds here, which a switch back holds again.
1821
+ const left = { path: configFile(), holds: !sameConfigDirectory && limits ? this.frozenSettingsAsHeld() : undefined };
1287
1822
  const previousEnv = process.env.ZTC_PROFILE;
1288
1823
  const previous = {
1289
1824
  config: this.config,
@@ -1300,6 +1835,18 @@ export class ConfigStore {
1300
1835
  configScope: this.configScope,
1301
1836
  launchRoute: this.launchRoute,
1302
1837
  sessionRouteChoice: this.sessionRouteChoice,
1838
+ // What this process last read of its config.json, and what it held back of it: a failed switch that left the other
1839
+ // folder's here would have the next reload read this one's as another profile's, taking an edit it held back.
1840
+ loadedConfigFile: this.loadedConfigFile,
1841
+ savedFileStamp: this.savedFileStamp,
1842
+ savedAuthStamp: this.savedAuthStamp,
1843
+ routerCredentialsStamp: this.routerCredentialsStamp,
1844
+ savedBase: this.savedBase,
1845
+ savedBaseConfig: this.savedBaseConfig,
1846
+ frozenFileValues: new Map(this.frozenFileValues),
1847
+ environmentValues: this.environmentValues,
1848
+ environmentRouteSources: this.environmentRouteSources,
1849
+ environmentModelPin: this.environmentModelPin,
1303
1850
  };
1304
1851
  process.env.ZTC_PROFILE = next;
1305
1852
  // A pane's own route was chosen against the old profile's routes and logins.
@@ -1312,16 +1859,19 @@ export class ConfigStore {
1312
1859
  }
1313
1860
  else {
1314
1861
  this.sessionOverrides = {};
1315
- this.cliOverrides = {};
1862
+ this.cliOverrides = { ...kept };
1316
1863
  this.configScope = 'global';
1317
1864
  this.launchRoute = undefined;
1318
1865
  this.sessionRouteChoice = undefined;
1319
1866
  }
1320
1867
  try {
1868
+ this.switchHolds = holds;
1321
1869
  await this.load(true);
1870
+ this.switchHolds = undefined;
1322
1871
  await activate();
1323
1872
  }
1324
1873
  catch (error) {
1874
+ this.switchHolds = undefined;
1325
1875
  if (previousEnv === undefined)
1326
1876
  delete process.env.ZTC_PROFILE;
1327
1877
  else
@@ -1329,6 +1879,12 @@ export class ConfigStore {
1329
1879
  Object.assign(this, previous);
1330
1880
  throw error;
1331
1881
  }
1882
+ if (!sameConfigDirectory) {
1883
+ if (left.holds)
1884
+ this.heldForConfigFile.set(left.path, left.holds);
1885
+ else
1886
+ this.heldForConfigFile.delete(left.path);
1887
+ }
1332
1888
  this.notifyChange();
1333
1889
  }
1334
1890
  /**
@@ -1351,7 +1907,8 @@ export class ConfigStore {
1351
1907
  if (envKey && envKey === this.config.apiKey) {
1352
1908
  delete toSave.apiKey;
1353
1909
  }
1354
- if (process.env.ZTC_API_KEY && process.env.ZTC_API_KEY === this.config.apiKey) {
1910
+ const environmentKey = hostEnvironmentValue('ZTC_API_KEY');
1911
+ if (environmentKey && environmentKey === this.config.apiKey) {
1355
1912
  delete toSave.apiKey;
1356
1913
  }
1357
1914
  const record = toSave;
@@ -1361,6 +1918,14 @@ export class ConfigStore {
1361
1918
  else
1362
1919
  record[key] = saved;
1363
1920
  }
1921
+ // A setting a reload kept as this process had it is saved as the file says (see frozenFileValues).
1922
+ for (const [key, saved] of this.frozenFileValues) {
1923
+ const own = savedSettingValue(key, saved);
1924
+ if (own === undefined)
1925
+ delete record[key];
1926
+ else
1927
+ record[key] = own;
1928
+ }
1364
1929
  return structuredClone(record);
1365
1930
  }
1366
1931
  async save() {
@@ -1392,6 +1957,7 @@ export class ConfigStore {
1392
1957
  try {
1393
1958
  await mkdir(directory, { recursive: true });
1394
1959
  const ours = this.persistedSettings();
1960
+ const oursHeld = structuredClone(this.config);
1395
1961
  // Another ZTC on this profile saved it since this one last read or wrote it: keep what it saved, and apply only
1396
1962
  // what this one changed since (a pane's new default must survive the main ZTC's next save of anything else).
1397
1963
  const elsewhere = fileStamp(path) !== this.savedFileStamp;
@@ -1412,18 +1978,39 @@ export class ConfigStore {
1412
1978
  // also replaces a 0644 file left by an earlier ZTC.
1413
1979
  await replaceSettingsFile(path, JSON.stringify(toSave, null, 2));
1414
1980
  this.savedFileStamp = fileStamp(path);
1415
- // Read back what the other ZTC saved, keeping this pane on the route it runs on.
1416
- if (theirs)
1981
+ // Read back what the other ZTC saved, keeping this pane on the route it runs on. What this process changed is saved
1982
+ // now, so its next change is made from the settings as it held them for this save.
1983
+ if (theirs) {
1984
+ this.savedBaseConfig = oursHeld;
1417
1985
  await this.reloadKeepingRoute();
1986
+ }
1418
1987
  else
1419
- this.savedBase = structuredClone(ours);
1988
+ this.noteSavedBase(structuredClone(ours), oursHeld);
1420
1989
  }
1421
1990
  catch (err) {
1422
1991
  runtimeDiag('error', `Failed to save config: ${err?.message ?? err}`);
1423
1992
  }
1424
1993
  }
1425
- /** Clear the active profile's saved settings and reset this process's settings view. */
1994
+ /**
1995
+ * Clear the active profile's saved settings and reset this process's settings view. The permission profile this
1996
+ * process's launch named (`--permission-profile`) is kept, as a config-profile switch keeps it: the config.json a reset
1997
+ * leaves defines the built-in permission profiles alone, so a reset that would leave it undefined there (one only
1998
+ * config.json defines), or, where it limits the agent, defined otherwise (a built-in one config.json redefines), is
1999
+ * refused before anything is removed. Its other launch flags go, as before. Under the host's pin of the permission
2000
+ * settings (ZTC_PERMISSION_PROFILE_PINNED), every reset is refused.
2001
+ */
1426
2002
  async factoryReset() {
2003
+ // Where the host pinned the permission settings (ZTC_PERMISSION_PROFILE_PINNED), a reset would remove the config.json
2004
+ // a ZTC started again reads them from: it is refused, naming the variable, before anything is removed.
2005
+ if (this.permissionPin)
2006
+ throw new PermissionsPinnedError(pinnedFactoryResetMessage());
2007
+ const kept = this.launchOverridesKeptAcrossProfiles();
2008
+ if (kept.permissionProfile !== undefined) {
2009
+ const id = kept.permissionProfile;
2010
+ const mismatch = launchProfileMismatch(undefined, id, this.config.permissionProfiles?.[id] ?? DEFAULT_PERMISSION_PROFILES[id], this.profileLimitsAgentNow());
2011
+ if (mismatch)
2012
+ throw new Error(launchProfileResetRefusal(id, mismatch, configFile()));
2013
+ }
1427
2014
  for (const path of [configFile(), join(configDir(), 'router-auth.json')]) {
1428
2015
  try {
1429
2016
  await unlink(path);
@@ -1435,7 +2022,7 @@ export class ConfigStore {
1435
2022
  }
1436
2023
  this.sessionOverrides = {};
1437
2024
  this.paneRoute = undefined;
1438
- this.cliOverrides = {};
2025
+ this.cliOverrides = { ...kept };
1439
2026
  this.configScope = 'global';
1440
2027
  this.launchRoute = undefined;
1441
2028
  this.sessionRouteChoice = undefined;
@@ -1470,7 +2057,9 @@ export class ConfigStore {
1470
2057
  provider: this.getProvider(),
1471
2058
  model: this.getModel(),
1472
2059
  };
1473
- return { ...config, terminalInteraction: resolveTerminalInteractionSettings(config.terminalInteraction) };
2060
+ // What the host's pin holds outranks every layer (ZTC_PERMISSION_PROFILE_PINNED; pinStartupPermissions).
2061
+ const pinned = this.permissionPin ? this.pinnedPermissionLayer(config.permissionProfiles) : {};
2062
+ return { ...config, ...pinned, terminalInteraction: resolveTerminalInteractionSettings(config.terminalInteraction) };
1474
2063
  }
1475
2064
  cliOverridesWithoutEffort() {
1476
2065
  return {
@@ -1492,10 +2081,18 @@ export class ConfigStore {
1492
2081
  setConfigScope(scope) {
1493
2082
  this.configScope = scope;
1494
2083
  }
2084
+ /**
2085
+ * Clear the settings this session chose for itself. A hosted thread's settings (applyHostedThreadSettings) are the
2086
+ * host's, not the session's choice: its permission profile, sandbox, instructions and route are taken again, so a clear
2087
+ * never drops the profile the host runs the thread under. What the host's pin of the permission settings holds
2088
+ * (ZTC_PERMISSION_PROFILE_PINNED) outranks every layer, so it holds after a clear as before.
2089
+ */
1495
2090
  clearSessionOverrides() {
1496
2091
  this.sessionOverrides = {};
1497
2092
  this.paneRoute = undefined;
1498
2093
  this.sessionRouteChoice = undefined;
2094
+ if (this.hostedThreadSettings)
2095
+ this.applyHostedThreadSettings(this.hostedThreadSettings);
1499
2096
  }
1500
2097
  /**
1501
2098
  * This process's session-scoped settings are a hosted thread's own (its
@@ -1506,6 +2103,57 @@ export class ConfigStore {
1506
2103
  markHostedSession() {
1507
2104
  this.hostedSession = true;
1508
2105
  }
2106
+ /**
2107
+ * Take SETTINGS, a hosted thread's (hosted/session_settings.ts), as this session's, as the host's settings rather
2108
+ * than a route the person chose (markHostedSession): its provider and model, output limit, instructions, route plan,
2109
+ * effort, permission profile and sandbox, through Zerg Router. A session its host pinned (ZTC_MODEL_PINNED) to another
2110
+ * route keeps that route, as a resumed session's saved route leaves it (restoreSessionSelection), and so does one whose
2111
+ * routing the environment pins (ZTC_LLM_AUTH_MODE) when the thread's route runs another way: the thread's provider
2112
+ * and model are not taken, the log says where the thread ran, and the rest of its settings are taken. A session whose
2113
+ * host pinned its permission settings (ZTC_PERMISSION_PROFILE_PINNED) refuses a revision that names another permission
2114
+ * profile than it started on, with PermissionsPinnedError and nothing taken; the pin holds the profile and sandbox.
2115
+ */
2116
+ applyHostedThreadSettings(settings) {
2117
+ const patch = hostedSettingsConfigPatch(settings);
2118
+ // Where the host pinned this session's permission settings (ZTC_PERMISSION_PROFILE_PINNED), the pin holds the profile
2119
+ // and sandbox, so the rest of a revision that names the profile it started on is taken without them.
2120
+ const pin = this.permissionPin;
2121
+ const pinned = this.hostedRevisionPinRefusal(settings);
2122
+ if (pinned)
2123
+ throw new PermissionsPinnedError(pinned);
2124
+ this.hostedThreadSettings = settings;
2125
+ this.markHostedSession();
2126
+ this.setConfigScope('session');
2127
+ const refused = this.routeChangeRefusal(settings.provider, settings.model);
2128
+ if (!refused) {
2129
+ this.set('provider', settings.provider);
2130
+ this.set('model', settings.model);
2131
+ }
2132
+ else {
2133
+ runtimeDiagOnce('info', `[ztc] The hosted thread ran on ${settings.model.startsWith(`${settings.provider}/`)
2134
+ ? settings.model : `${settings.provider}/${settings.model}`}; ${refused}`);
2135
+ }
2136
+ this.set('maxTokens', settings.maxOutputTokens);
2137
+ this.set('hostedThreadInstructions', patch.hostedThreadInstructions);
2138
+ this.set('zrouterRoutePlan', patch.zrouterRoutePlan);
2139
+ this.set('codexEffort', patch.codexEffort);
2140
+ if (!pin)
2141
+ this.set('permissionProfile', patch.permissionProfile);
2142
+ this.set('authMode', 'zrouter');
2143
+ if (!pin)
2144
+ this.set('sandbox', patch.sandbox);
2145
+ }
2146
+ /**
2147
+ * Why the host's pin of this session's permission settings (ZTC_PERMISSION_PROFILE_PINNED) refuses SETTINGS, a hosted
2148
+ * thread's later revision, or undefined when it doesn't: a revision names the permission profile the session started on
2149
+ * (the thread's then, else the pinned one) or nothing of it is taken. A caller asks before it changes anything, so a
2150
+ * refused revision leaves nothing to roll back; the message names the variable and nothing of the profile.
2151
+ */
2152
+ hostedRevisionPinRefusal(settings) {
2153
+ const pin = this.permissionPin;
2154
+ return pin && hostedSettingsConfigPatch(settings).permissionProfile !== (pin.hostedProfile ?? pin.profileId)
2155
+ ? pinnedPermissionsMessage() : undefined;
2156
+ }
1509
2157
  async withConfigScope(scope, fn) {
1510
2158
  const previous = this.configScope;
1511
2159
  this.configScope = scope;
@@ -1526,6 +2174,9 @@ export class ConfigStore {
1526
2174
  this.paneRoute = undefined;
1527
2175
  }
1528
2176
  set(key, value) {
2177
+ this.refuseRouteChange(key, value);
2178
+ if (this.refusePinnedPermissionChange(key, value))
2179
+ return;
1529
2180
  this.releasePaneRoute(key);
1530
2181
  if (key === 'terminalInteraction') {
1531
2182
  const normalized = resolveTerminalInteractionSettings(value);
@@ -1544,10 +2195,14 @@ export class ConfigStore {
1544
2195
  this.replaceEnvironmentValue(key, value);
1545
2196
  this.endRetiredRouteWait(key);
1546
2197
  this.config[key] = value;
2198
+ this.noteOwnSetting(key);
1547
2199
  if (key === 'apiKey')
1548
2200
  this.legacyApiKeyFromEnvironment = false;
1549
2201
  }
1550
2202
  setGlobal(key, value) {
2203
+ this.refuseRouteChange(key, value);
2204
+ if (this.refusePinnedPermissionChange(key, value))
2205
+ return;
1551
2206
  this.releasePaneRoute(key);
1552
2207
  if (key === 'terminalInteraction') {
1553
2208
  this.config.terminalInteraction = resolveTerminalInteractionSettings(value);
@@ -1556,6 +2211,7 @@ export class ConfigStore {
1556
2211
  this.replaceEnvironmentValue(key, value);
1557
2212
  this.endRetiredRouteWait(key);
1558
2213
  this.config[key] = value;
2214
+ this.noteOwnSetting(key);
1559
2215
  if (key === 'apiKey')
1560
2216
  this.legacyApiKeyFromEnvironment = false;
1561
2217
  }
@@ -1608,6 +2264,18 @@ export class ConfigStore {
1608
2264
  this.environmentValues.delete(replaced);
1609
2265
  }
1610
2266
  setAll(next) {
2267
+ // Where the host pinned the permission settings, NEXT may hold them only as the pin does, and they stay the pin's:
2268
+ // none of them is taken into the settings save() writes.
2269
+ if (this.permissionPin) {
2270
+ const held = { ...next };
2271
+ for (const key of PINNED_PERMISSION_SETTINGS) {
2272
+ if (!Object.hasOwn(next, key))
2273
+ continue;
2274
+ this.refusePinnedPermissionChange(key, next[key]);
2275
+ delete held[key];
2276
+ }
2277
+ next = held;
2278
+ }
1611
2279
  for (const key of Object.keys(next))
1612
2280
  this.releasePaneRoute(key);
1613
2281
  this.config = { ...build_default_config(), ...this.config, ...next };
@@ -1635,6 +2303,12 @@ export class ConfigStore {
1635
2303
  && this.get().zergProxyUrl?.replace(/\/+$/, '') === this.routerCredentials.origin
1636
2304
  && Date.parse(this.routerCredentials.expiresAt) > Date.now())
1637
2305
  return true;
2306
+ if (this.getAuthMode() !== 'direct' && this.getHostRouterGrant())
2307
+ return true;
2308
+ // A route through the ZergAI platform's own Router proxy, on a login ZTC sends there (getPlatformProxyLogin): a Router
2309
+ // credential there is no platform login (isAuthenticated), and its turns still go.
2310
+ if (this.getAuthMode() !== 'direct' && this.getPlatformProxyLogin(this.get().zergProxyUrl))
2311
+ return true;
1638
2312
  if (this.getProvider() === 'openai_compatible') {
1639
2313
  try {
1640
2314
  return Boolean(this.getOpenAICompatibleBaseUrl());
@@ -1651,8 +2325,14 @@ export class ConfigStore {
1651
2325
  this.followRouterSignIn();
1652
2326
  return this.routerCredentials?.deviceName;
1653
2327
  }
1654
- /** Router login state for the configured Router origin; never contacts Router. */
2328
+ /**
2329
+ * Router login state for the configured Router origin; never contacts Router. Where the host's Router runtime grant
2330
+ * serves that Router, Router is reached as on a current sign-in, whatever the profile holds: 'signed_in', so nothing
2331
+ * asks for a ZergAI login there (getHostRouterGrantOrigin says it is the grant).
2332
+ */
1655
2333
  getRouterSessionStatus() {
2334
+ if (this.getHostRouterGrant())
2335
+ return 'signed_in';
1656
2336
  this.followRouterSignIn();
1657
2337
  const credentials = this.routerCredentials;
1658
2338
  if (!credentials || this.routerCredentialsError
@@ -1778,7 +2458,7 @@ export class ConfigStore {
1778
2458
  usableKey(value, where) {
1779
2459
  if (!isClaudeCodeToken(value))
1780
2460
  return value;
1781
- const variable = Object.values(PROVIDER_API_KEY_ENV).flat().find(name => process.env[name]?.trim() === value.trim());
2461
+ const variable = Object.values(PROVIDER_API_KEY_ENV).flat().find(name => hostEnvironmentValue(name)?.trim() === value.trim());
1782
2462
  runtimeDiagOnce('warn', `[ztc] ${claudeCodeTokenNotSentMessage(where ?? variable ?? 'A key variable in your environment')}`);
1783
2463
  return undefined;
1784
2464
  }
@@ -1816,6 +2496,40 @@ export class ConfigStore {
1816
2496
  }
1817
2497
  return fallback ?? { kind: 'none' };
1818
2498
  }
2499
+ /**
2500
+ * Every credential this profile holds for ZTC to infer or sign in with, by value: what each variable a profile names
2501
+ * as a provider's key holds (apiKeyEnv), each key saved in ZTC (apiKeys, the custom endpoint's, the legacy single
2502
+ * slot), saved or for this session, the hosted native Messages route's bearer (nativeAnthropicMessagesRouter, its only
2503
+ * credential), each header value the custom endpoint is sent with every request (Azure takes its key as api-key), the
2504
+ * ZergAI login's token, and the Router sign-in's key as router-auth.json holds it now, expired or not. What shows ZTC's
2505
+ * output to someone who is not its user (a read-only observer of the mirror) withholds them (a value too short to be
2506
+ * a credential, as an X-Org header's, only where it is long enough: liveObserverSecrets). Reading them sends nothing
2507
+ * and changes nothing a request or a subprocess is given.
2508
+ */
2509
+ listHeldCredentials() {
2510
+ this.followRouterSignIn();
2511
+ const held = new Set();
2512
+ const hold = (value) => {
2513
+ if (typeof value === 'string' && value.trim())
2514
+ held.add(value.trim());
2515
+ };
2516
+ for (const layer of [this.config, this.sessionOverrides]) {
2517
+ for (const [provider, name] of Object.entries(layer.apiKeyEnv ?? {})) {
2518
+ if (typeof name === 'string')
2519
+ hold(readApiKeyEnvReference(name, provider));
2520
+ }
2521
+ for (const key of Object.values(layer.apiKeys ?? {}))
2522
+ hold(key);
2523
+ hold(layer.openaiCompatible?.apiKey);
2524
+ for (const value of Object.values(layer.openaiCompatible?.headers ?? {}))
2525
+ hold(value);
2526
+ hold(layer.nativeAnthropicMessagesRouter?.authToken);
2527
+ hold(layer.apiKey);
2528
+ hold(layer.auth?.token);
2529
+ }
2530
+ hold(this.routerCredentials?.token);
2531
+ return [...held];
2532
+ }
1819
2533
  /** The environment variable named as this provider's key, if any. */
1820
2534
  getApiKeyEnv(provider) {
1821
2535
  return this.get().apiKeyEnv?.[normalizeProviderId(provider)];
@@ -1929,11 +2643,23 @@ export class ConfigStore {
1929
2643
  this.retiredRouteRequests.push({ source: 'flag', settings: [`--model ${value}`], retired: value });
1930
2644
  return;
1931
2645
  }
2646
+ if (key === 'provider' || key === 'model' || key === 'authMode')
2647
+ this.refuseRouteChange(key, value);
2648
+ // Where the host pinned the permission settings, the launch's profile is the pinned one, and it stays.
2649
+ if (key === 'permissionProfile' && this.permissionPin) {
2650
+ if (value !== this.permissionPin.profileId)
2651
+ throw new PermissionsPinnedError();
2652
+ return;
2653
+ }
1932
2654
  if (value === undefined)
1933
2655
  delete this.cliOverrides[key];
1934
2656
  else
1935
2657
  this.cliOverrides[key] = value;
1936
2658
  }
2659
+ /** The permission profile this process's launch named (`--permission-profile`), which a switch and a reset keep. */
2660
+ getLaunchPermissionProfile() {
2661
+ return this.cliOverrides.permissionProfile;
2662
+ }
1937
2663
  /** This process's own launch overrides of the route (`--provider`, `--model`, `--auth-mode`), as they stand. */
1938
2664
  getLaunchOverrides() {
1939
2665
  const { provider, model, authMode } = this.cliOverrides;
@@ -2136,7 +2862,8 @@ export class ConfigStore {
2136
2862
  }
2137
2863
  /** The provider this pane runs on: its own route's, else the configured one (launch flags, session, saved). */
2138
2864
  getProvider() {
2139
- return this.paneRoute?.provider || this.configuredProvider();
2865
+ // A session its host pinned runs on the route it started on, whatever was chosen since (config/model_pin.ts).
2866
+ return pinnedRoute()?.provider ?? (this.paneRoute?.provider || this.configuredProvider());
2140
2867
  }
2141
2868
  /** The provider launch flags, session settings and the saved profile name, without this pane's own route. */
2142
2869
  configuredProvider() {
@@ -2145,6 +2872,7 @@ export class ConfigStore {
2145
2872
  setProvider(provider) {
2146
2873
  if (isRetiredProvider(provider))
2147
2874
  throw new RetiredProviderError(provider, this.describeRoute());
2875
+ this.refuseRouteChange('provider', provider);
2148
2876
  const previousProvider = this.getProvider();
2149
2877
  // The legacy single key belongs to the persisted provider, even when CLI
2150
2878
  // overrides expose a different selection. Migrate it before changing its
@@ -2428,7 +3156,13 @@ export class ConfigStore {
2428
3156
  getAuthMode() {
2429
3157
  return resolveAuthMode(this.get());
2430
3158
  }
3159
+ /**
3160
+ * Set the routing, as /config routing, the settings panel's Routing row and the mirror's routing setting do. One
3161
+ * other than the routing the environment pins (ZTC_LLM_AUTH_MODE) is refused, and nothing is saved.
3162
+ */
2431
3163
  setAuthMode(mode) {
3164
+ if (routeChangeRefusal({ routing: mode }))
3165
+ throw routeChangeError();
2432
3166
  this.set('authMode', mode);
2433
3167
  }
2434
3168
  // --- Resolved config seams (see ztc/docs/arch/01-configstore.md) ---
@@ -2487,6 +3221,13 @@ export class ConfigStore {
2487
3221
  };
2488
3222
  }
2489
3223
  restoreSessionSelection(metadata) {
3224
+ // A session its host pinned resumes on the pinned route, not the one the session ran on before.
3225
+ if (pinnedRoute()) {
3226
+ if (!isPinnedRoute(metadata.provider, metadata.model)) {
3227
+ runtimeDiagOnce('info', `[ztc] The resumed session ran on ${metadata.provider}/${metadata.model}; ${pinnedRouteMessage()}`);
3228
+ }
3229
+ return;
3230
+ }
2490
3231
  // Legacy sessions did not persist routes. Explicit launch overrides retain priority.
2491
3232
  if (!metadata.authMode || this.cliOverrides.provider || this.cliOverrides.model
2492
3233
  || (metadata.configProfile && metadata.configProfile !== activeProfile()))
@@ -2500,6 +3241,13 @@ export class ConfigStore {
2500
3241
  runtimeDiagOnce('warn', `[ztc] ${retiredRouteWarning(request, this.describeRoute())}`);
2501
3242
  return;
2502
3243
  }
3244
+ // One whose saved route runs off the routing the environment pins (ZTC_LLM_AUTH_MODE), a local login under
3245
+ // zrouter, continues on the configured route, and the log says where it ran (config/model_pin.ts).
3246
+ const offRouting = this.routingRefusal(metadata.provider);
3247
+ if (offRouting) {
3248
+ runtimeDiagOnce('info', `[ztc] The resumed session ran on ${metadata.provider}/${metadata.model}; ${offRouting}`);
3249
+ return;
3250
+ }
2503
3251
  // The pane resumes on the route its session ran on; new panes don't see it. It outranks the --auth-mode (and
2504
3252
  // --router-url) another ZTC launched this pane with, which named the route new panes started on then. One the
2505
3253
  // person typed for this run (`ztc --resume <id> --auth-mode direct`) is their choice, and wins.
@@ -2521,6 +3269,8 @@ export class ConfigStore {
2521
3269
  setPaneRoute(route) {
2522
3270
  if (route && (isRetiredProvider(route.provider) || isRetiredModel(route.model)))
2523
3271
  return;
3272
+ if (route && !isPinnedRoute(route.provider, route.model))
3273
+ throw new RoutePinnedError();
2524
3274
  this.paneRoute = route ? { provider: route.provider, model: route.model, authMode: route.authMode,
2525
3275
  ...(route.routerOrigin ? { routerOrigin: route.routerOrigin } : {}) } : undefined;
2526
3276
  this.paneRouteSource = 'pane';
@@ -2562,13 +3312,17 @@ export class ConfigStore {
2562
3312
  }
2563
3313
  /**
2564
3314
  * The person's own Zerg Router credential: this profile's Router sign-in (a CLI device key), while it is valid. The
2565
- * legacy platform login is not one: it is the platform's, scoped to its /api/zrouter proxy.
3315
+ * legacy platform login is not one: it is the platform's, scoped to its /api/zrouter proxy. On the Router the host
3316
+ * claimed for its Router runtime grant, the grant wins, usable or not, and the sign-in is no credential of this
3317
+ * process's there.
2566
3318
  */
2567
3319
  getPersonalRouterCredential() {
2568
3320
  this.followRouterSignIn();
2569
3321
  const credentials = this.routerCredentials;
2570
3322
  if (!credentials || this.routerCredentialsError || !(Date.parse(credentials.expiresAt) > Date.now()))
2571
3323
  return undefined;
3324
+ if (this.hostClaimsRouter(credentials.origin))
3325
+ return undefined;
2572
3326
  return { origin: credentials.origin, token: credentials.token };
2573
3327
  }
2574
3328
  /**
@@ -2612,17 +3366,55 @@ export class ConfigStore {
2612
3366
  * The ZergAI platform login, for `destination` only when that is the platform's own Router proxy
2613
3367
  * (`<API base>/api/zrouter`), the one place the platform issued it for. Any other Router, Zerg Router's own origin
2614
3368
  * or one a profile or ZERG_PROXY_URL names, gets nothing. ZTC's chat route, its Router catalog and simulation memory
2615
- * all take the platform token from here.
3369
+ * all take the platform token from here. A login the environment handed over (ZTC_AUTH_TOKEN) goes there only when
3370
+ * someone named that platform (platformApiNamed); otherwise it goes nowhere.
2616
3371
  */
2617
3372
  getPlatformProxyLogin(destination) {
2618
3373
  const origin = normalizedOrigin(destination);
2619
- const token = this.getAuthToken();
2620
- return origin && token && origin === this.deriveZRouterUrl(this.getApiBaseUrl()) ? { origin, token } : undefined;
3374
+ const token = this.config.auth?.token;
3375
+ if (!origin || !token || origin !== this.deriveZRouterUrl(this.getApiBaseUrl()))
3376
+ return undefined;
3377
+ // A model turn through the proxy of a platform someone named goes on its login, a Router credential included: that is
3378
+ // inference, as it always was (ZergCloud's hand-port routes so), and no platform API call.
3379
+ return this.unnamedEnvironmentLogin(token) ? undefined : { origin, token };
3380
+ }
3381
+ /**
3382
+ * The host's Router runtime grant (config/router_runtime_grant.ts) for a Router request to DESTINATION, the configured
3383
+ * Router by default: when the host named that Router's origin in ZERG_ROUTER_BASE_URL, and DESTINATION is not the
3384
+ * platform's own proxy (`<API base>/api/zrouter`), whose credential is the platform's login. Deployment routing: where
3385
+ * it is given, it wins over this profile's Router sign-in. Never saved; never shown.
3386
+ */
3387
+ getHostRouterGrant(destination = this.get().zergProxyUrl) {
3388
+ const origin = normalizedOrigin(destination);
3389
+ const token = hostRouterGrantFor(origin, process.env, this.deriveZRouterUrl(this.getApiBaseUrl()));
3390
+ return origin && token ? { origin, token } : undefined;
3391
+ }
3392
+ /**
3393
+ * The configured Router's origin when the host claimed it for its Router runtime grant (hostClaimsRouter), for what ZTC
3394
+ * shows: no sign-in of the profile's is used there, and only a usable grant goes. Never the grant.
3395
+ */
3396
+ getHostRouterGrantOrigin() {
3397
+ return this.hostClaimsRouter() ? normalizedOrigin(this.get().zergProxyUrl) : undefined;
3398
+ }
3399
+ /**
3400
+ * Whether the host claimed DESTINATION's Router (the configured one by default) for its Router runtime grant, a usable
3401
+ * bearer or not (config/router_runtime_grant.ts hostClaimsRouter). There only the grant goes: nothing goes with a
3402
+ * grant that is no usable bearer, and nothing in its place.
3403
+ */
3404
+ hostClaimsRouter(destination = this.get().zergProxyUrl) {
3405
+ return hostClaimsRouter(normalizedOrigin(destination), process.env, this.deriveZRouterUrl(this.getApiBaseUrl()));
2621
3406
  }
2622
3407
  getRouterCatalogConnection(destination = this.get().zergProxyUrl) {
2623
3408
  const origin = normalizedOrigin(destination);
2624
3409
  if (!origin)
2625
3410
  return undefined;
3411
+ // On the Router the host named, its Router runtime grant wins, as it does for the chat route (resolveLLMBackendConfig).
3412
+ const grant = this.getHostRouterGrant(origin);
3413
+ if (grant)
3414
+ return { origin, token: grant.token };
3415
+ // A grant that is no usable bearer reads nothing there, and no sign-in reads in its place.
3416
+ if (this.hostClaimsRouter(origin))
3417
+ return undefined;
2626
3418
  this.followRouterSignIn();
2627
3419
  const credentials = this.routerCredentials;
2628
3420
  if (credentials && !this.routerCredentialsError && credentials.origin === origin) {
@@ -2759,6 +3551,10 @@ export class ConfigStore {
2759
3551
  // --provider chose (see routeAwaitingChoice), whatever else could reach a model.
2760
3552
  if (!opts.asChosen)
2761
3553
  this.assertRouteChosen(opts.provider || opts.config?.provider);
3554
+ // A choice of another route, checked before it is saved, is refused in a session its host pinned.
3555
+ if (opts.asChosen && !isPinnedRoute(opts.provider ?? opts.config?.provider, opts.model ?? opts.config?.model)) {
3556
+ throw new RoutePinnedError();
3557
+ }
2762
3558
  // A hosted application's required profile never consults personal logins,
2763
3559
  // saved session origins, direct keys, account pools, or cheap-model defaults.
2764
3560
  if (process.env.ZTC_ROUTER_REQUIRED === '1') {
@@ -2769,7 +3565,7 @@ export class ConfigStore {
2769
3565
  throw new Error(`Required Router profile permits only ${required.provider}/${required.model}`);
2770
3566
  }
2771
3567
  const proxyUrl = normalizedOrigin(process.env.ZERG_PROXY_URL);
2772
- const authToken = process.env.ZERG_AUTH_TOKEN?.trim();
3568
+ const authToken = hostEnvironmentValue('ZERG_AUTH_TOKEN')?.trim();
2773
3569
  if (!proxyUrl || !authToken)
2774
3570
  throw new Error('Required Router origin and service credential are unavailable');
2775
3571
  const origin = new URL(proxyUrl);
@@ -2802,8 +3598,12 @@ export class ConfigStore {
2802
3598
  ?? opts.model
2803
3599
  ?? (configProvider === provider ? cfg.model : undefined)
2804
3600
  ?? getDefaultModelForProvider(provider);
2805
- const authMode = isLocalSubscriptionProvider(provider)
2806
- || (ownKeyGoesDirect(provider) && Boolean(opts.apiKeyOverride || this.resolveApiKey(cfg, provider))) ? 'direct' : resolveAuthMode(cfg);
3601
+ const authMode = this.routingOf(provider, cfg, opts.apiKeyOverride);
3602
+ // A choice of a route that runs off the routing the environment pins (ZTC_LLM_AUTH_MODE), checked before it is
3603
+ // saved, is refused: under zrouter, a local subscription or Morph on this machine's key, which go direct.
3604
+ if (opts.asChosen && (opts.provider ?? opts.config?.provider) !== undefined && pinnedRoutingRefusal(authMode)) {
3605
+ throw routeChangeError();
3606
+ }
2807
3607
  const proxyUrl = normalizedOrigin(cfg.zergProxyUrl);
2808
3608
  // Legacy platform tokens belong only to its /api/zrouter endpoint. A
2809
3609
  // standalone Router requires its own device login, including after logout.
@@ -2812,7 +3612,19 @@ export class ConfigStore {
2812
3612
  // The sign-in as router-auth.json holds it now: another pane's login since may have replaced the key this read.
2813
3613
  this.followRouterSignIn();
2814
3614
  let routerError = this.routerCredentialsError;
2815
- if (authMode !== 'direct' && this.routerCredentials && !routerError) {
3615
+ // The host's Router runtime grant is deployment routing, like an origin the environment names: on the Router the
3616
+ // host named, it wins over this profile's sign-in, whichever Router that is for and whether or not it is current.
3617
+ const hostGrant = authMode !== 'direct' ? this.getHostRouterGrant(proxyUrl) : undefined;
3618
+ if (hostGrant) {
3619
+ authToken = hostGrant.token;
3620
+ routerError = null;
3621
+ }
3622
+ else if (authMode !== 'direct' && this.hostClaimsRouter(proxyUrl)) {
3623
+ // The host claimed this Router for a grant that is no usable bearer: nothing goes, in either routing mode, and
3624
+ // nothing goes in its place (a saved sign-in, a key, an endpoint).
3625
+ throw new RouterConfigurationError(UNUSABLE_ROUTER_RUNTIME_GRANT_REFUSED, 'host_grant');
3626
+ }
3627
+ else if (authMode !== 'direct' && this.routerCredentials && !routerError) {
2816
3628
  if (proxyUrl?.replace(/\/+$/, '') !== this.routerCredentials.origin) {
2817
3629
  routerError = new Error('Router origin does not match this login. Run ztc auth login --url <origin>.');
2818
3630
  }
@@ -2921,6 +3733,19 @@ export class ConfigStore {
2921
3733
  getConfigPath() {
2922
3734
  return configFile();
2923
3735
  }
3736
+ /**
3737
+ * config.json as it is saved now, parsed, whatever JSON it holds: read again rather than as this process last read it,
3738
+ * since another ZTC on the profile may have saved it since (see refreshIfChangedElsewhere). Undefined when it is
3739
+ * missing or can't be read.
3740
+ */
3741
+ async readSavedSettings() {
3742
+ try {
3743
+ return JSON.parse(await readFile(configFile(), 'utf-8'));
3744
+ }
3745
+ catch {
3746
+ return undefined;
3747
+ }
3748
+ }
2924
3749
  get locationLabel() {
2925
3750
  return configFile();
2926
3751
  }
@@ -3043,8 +3868,69 @@ export class ConfigStore {
3043
3868
  }
3044
3869
  /** The model this pane runs on: its own route's, else the configured one (launch flags, session, saved). */
3045
3870
  getModel() {
3871
+ const pinned = pinnedRoute();
3872
+ if (pinned)
3873
+ return pinned.model;
3046
3874
  return this.paneRoute ? this.paneRoute.model : this.configuredModel();
3047
3875
  }
3876
+ /**
3877
+ * The routing PROVIDER runs on once chosen, as the resolver decides it: direct for a local subscription, and for
3878
+ * Morph on a key this machine holds (APIKEY, else CFG's), which go to the provider itself; otherwise CFG's routing,
3879
+ * ZTC_LLM_AUTH_MODE first. ZTC_LLM_AUTH_MODE=zrouter keeps Morph on Zerg Router wherever its key comes from (a saved
3880
+ * key, MORPH_API_KEY, one /config key gives it later): the pin holds every route that can run through Router there
3881
+ * (config/model_pin.ts).
3882
+ */
3883
+ routingOf(provider, cfg, apiKey) {
3884
+ if (isLocalSubscriptionProvider(provider))
3885
+ return 'direct';
3886
+ const ownKey = ownKeyGoesDirect(provider) && pinnedRouting()?.mode !== 'zrouter'
3887
+ && Boolean(apiKey || this.resolveApiKey(cfg, provider));
3888
+ return ownKey ? 'direct' : resolveAuthMode(cfg);
3889
+ }
3890
+ /**
3891
+ * Why moving this session to PROVIDER/MODEL (either may be left out: it stays as it is) is refused, or undefined when
3892
+ * it may move (config/model_pin.ts): another route than the one its host pinned (ZTC_MODEL_PINNED), else a provider
3893
+ * that runs off the routing the environment pins (ZTC_LLM_AUTH_MODE), such as a local login under zrouter.
3894
+ */
3895
+ routeChangeRefusal(provider, model) {
3896
+ return routeChangeRefusal({ provider, model, routing: provider === undefined ? undefined : this.routingOf(normalizeProviderId(provider), this.get()) });
3897
+ }
3898
+ /**
3899
+ * Why a route on PROVIDER is refused by the routing the environment pins (ZTC_LLM_AUTH_MODE), or undefined when that
3900
+ * provider runs on it: for a pane whose own route only its routing binds (config/model_pin.ts).
3901
+ */
3902
+ routingRefusal(provider) {
3903
+ return pinnedRoutingRefusal(this.routingOf(normalizeProviderId(provider), this.get()));
3904
+ }
3905
+ /**
3906
+ * Pin the route this session started on, its launch flags and environment applied, as its only route when its host
3907
+ * asked for that (ZTC_MODEL_PINNED; config/model_pin.ts): from then on the provider, model and routing read as they
3908
+ * are now, and a change to another is refused with the pinned route named. Without the pin, nothing changes.
3909
+ */
3910
+ pinStartupRoute() {
3911
+ if (!modelPinRequested())
3912
+ return;
3913
+ holdPinnedRoute({ provider: normalizeProviderId(this.getProvider()), model: this.getModel() });
3914
+ this.pinnedAuthMode = this.getAuthMode();
3915
+ }
3916
+ /** The routing a pinned session started on (pinStartupRoute), or undefined when no host pinned it. */
3917
+ pinnedAuthMode;
3918
+ /**
3919
+ * Refuses KEY = VALUE in a pinned session when it would move the session off its route: another provider or model,
3920
+ * or routing the environment doesn't already decide that differs from the routing it started on.
3921
+ */
3922
+ refuseRouteChange(key, value) {
3923
+ if (!pinnedRoute() || value === undefined)
3924
+ return;
3925
+ if (key === 'provider' && !isPinnedRoute(String(value), undefined))
3926
+ throw new RoutePinnedError();
3927
+ if (key === 'model' && !isPinnedRoute(undefined, String(value)))
3928
+ throw new RoutePinnedError();
3929
+ if (key === 'authMode' && this.pinnedAuthMode !== undefined
3930
+ && normalizeAuthMode(process.env.ZTC_LLM_AUTH_MODE || process.env.ZERG_LLM_AUTH_MODE || String(value)) !== this.pinnedAuthMode) {
3931
+ throw new RoutePinnedError();
3932
+ }
3933
+ }
3048
3934
  /** The model launch flags, session settings and the saved profile name, without this pane's own route. */
3049
3935
  configuredModel() {
3050
3936
  if (this.cliOverrides.model) {
@@ -3057,11 +3943,105 @@ export class ConfigStore {
3057
3943
  return this.sessionOverrides.model || this.config.model;
3058
3944
  }
3059
3945
  // --- Auth Methods ---
3946
+ /** Whether ZTC holds a ZergAI platform login it may send to the platform API getApiBaseUrl() returns (getAuthToken). */
3060
3947
  isAuthenticated() {
3061
- return !!this.config.auth?.token;
3948
+ return this.getAuthToken() !== undefined;
3062
3949
  }
3950
+ /**
3951
+ * The ZergAI platform login, for the platform API getApiBaseUrl() returns: the account check, /zerg, the zerg tools,
3952
+ * zerg mode and the platform's legacy LLM endpoint send it as `Authorization: Token`. Undefined when there is none, and
3953
+ * when there is one ZTC sends to no platform API (platformLoginRefusal): a Zerg Router credential, or one the
3954
+ * environment handed over in ZTC_AUTH_TOKEN with no platform API named for it. The platform's own Router proxy gets its
3955
+ * login from getPlatformProxyLogin.
3956
+ */
3063
3957
  getAuthToken() {
3064
- return this.config.auth?.token;
3958
+ const token = this.config.auth?.token;
3959
+ return token && this.platformLoginRefusal(token) === undefined ? token : undefined;
3960
+ }
3961
+ /**
3962
+ * Why ZTC sends the platform login TOKEN to no platform API, or undefined when it goes to getApiBaseUrl(): a Zerg Router
3963
+ * credential goes to none, named or not (holdsRouterCredential); a login the environment handed over (ZTC_AUTH_TOKEN)
3964
+ * goes only to a platform API someone named (unnamedEnvironmentLogin). A login config.json holds (an older release's
3965
+ * /auth login) is the person's own, for the API they signed in to.
3966
+ */
3967
+ platformLoginRefusal(token) {
3968
+ if (this.holdsRouterCredential(token))
3969
+ return 'router_credential';
3970
+ if (this.unnamedEnvironmentLogin(token))
3971
+ return 'not_named';
3972
+ return undefined;
3973
+ }
3974
+ /** Whether TOKEN is the login the environment handed over (ZTC_AUTH_TOKEN) and no platform API is named for it. */
3975
+ unnamedEnvironmentLogin(token) {
3976
+ return token === hostCredential('ZTC_AUTH_TOKEN') && !this.platformApiNamed();
3977
+ }
3978
+ /**
3979
+ * Whether TOKEN (blanks around it aside) is a Zerg Router credential: one of Router's own shapes
3980
+ * (looksLikeRouterCredential), or a value ZTC holds as a Router credential too: the host's Router runtime grant, the
3981
+ * required Router's service credential (ZERG_AUTH_TOKEN), the profile's Router sign-in (router-auth.json, as
3982
+ * router-auth.json holds it now).
3983
+ */
3984
+ holdsRouterCredential(token) {
3985
+ const value = token.trim();
3986
+ if (!value)
3987
+ return false;
3988
+ if (looksLikeRouterCredential(value) || holdsHostRouterGrant(value))
3989
+ return true;
3990
+ if (value === hostEnvironmentValue('ZERG_AUTH_TOKEN')?.trim())
3991
+ return true;
3992
+ this.followRouterSignIn();
3993
+ return this.routerCredentials !== null && value === this.routerCredentials.token.trim();
3994
+ }
3995
+ /**
3996
+ * Whether someone named the ZergAI platform API getApiBaseUrl() returns, so that a platform login the environment
3997
+ * handed over may go there:
3998
+ *
3999
+ * - ZTC_API_BASE_URL;
4000
+ * - a colony's COLONY_PORT (its API is on COLONY_PORT + 1);
4001
+ * - an apiEnvironment the person chose: one of API_ENDPOINTS' names, saved in config.json or set in this process (the
4002
+ * settings' API environment), and not one the environment applied over it (a null or empty one leaves ZTC's own
4003
+ * default, which nobody chose);
4004
+ * - that API's own Router proxy (`<API>/api/zrouter`) named in ZERG_PROXY_URL by the launcher, as the ZergAI platform
4005
+ * launches its zergs (ZERG_PROXY_URL=https://api.zergai.com/api/zrouter with the zerg's platform token).
4006
+ *
4007
+ * Nothing else names one: not ZTC's built-in default (https://api.zergai.com); not ZTC_API_ENVIRONMENT or
4008
+ * ZERG_DEPLOY_TIER, which zerg/docker-entrypoint.sh sets for every zerg (ZERG_DEPLOY_TIER=local by default, so
4009
+ * http://localhost:8000), ZergCloud's on a Router credential among them; not a ZERG_PROXY_URL that entrypoint filled in
4010
+ * itself from the tier or a Router address, as it says in PROXY_URL_SOURCE_ENV (a dev or prod tier gets its platform's
4011
+ * proxy whatever token the launcher hands over); not a Router address (ZERG_ROUTER_BASE_URL, --router-url, a saved
4012
+ * Zerg Router URL), which names a Router and no platform API.
4013
+ */
4014
+ platformApiNamed() {
4015
+ if (process.env.ZTC_API_BASE_URL || process.env.COLONY_PORT)
4016
+ return true;
4017
+ const chosen = this.config.apiEnvironment;
4018
+ if (typeof chosen === 'string' && Object.hasOwn(API_ENDPOINTS, chosen) && !this.environmentValues.has('apiEnvironment'))
4019
+ return true;
4020
+ if (process.env[PROXY_URL_SOURCE_ENV]?.trim())
4021
+ return false;
4022
+ const proxy = normalizedOrigin(process.env.ZERG_PROXY_URL);
4023
+ if (proxy === undefined)
4024
+ return false;
4025
+ const api = this.getApiBaseUrl();
4026
+ return Boolean(api) && proxy === this.deriveZRouterUrl(api);
4027
+ }
4028
+ /**
4029
+ * Why there is no platform login to send, for /zerg, the zerg tools and zerg mode to say (never its value), or
4030
+ * undefined when there is one, or none was handed over or saved. It names what holds the login: ZTC_AUTH_TOKEN for
4031
+ * the one the environment handed over, config.json for one saved there (only a Zerg Router credential is refused so).
4032
+ */
4033
+ getPlatformLoginRefusal() {
4034
+ const token = this.config.auth?.token;
4035
+ if (token) {
4036
+ const refusal = this.platformLoginRefusal(token);
4037
+ if (refusal === undefined)
4038
+ return undefined;
4039
+ const saved = token !== hostCredential('ZTC_AUTH_TOKEN');
4040
+ return saved && refusal === 'router_credential' ? SAVED_LOGIN_IS_ROUTER_CREDENTIAL : noPlatformLoginReason(refusal);
4041
+ }
4042
+ // The host's grant in ZTC_AUTH_TOKEN is never taken as a login at all (applyEnvOverrides).
4043
+ const environment = hostCredential('ZTC_AUTH_TOKEN');
4044
+ return environment && holdsHostRouterGrant(environment) ? noPlatformLoginReason('host_grant') : undefined;
3065
4045
  }
3066
4046
  getActiveWorkspace() {
3067
4047
  if (!this.config.auth?.activeWorkspaceId)
@@ -3242,4 +4222,7 @@ export class ConfigStore {
3242
4222
  }
3243
4223
  }
3244
4224
  export const configStore = new ConfigStore();
4225
+ // A native helper ZTC starts (utils/subprocess_env.ts buildNativeHelperEnv) starts without the variables this profile
4226
+ // names as provider keys, as a stdio MCP server does, in every mode: the terminal app keeps none of them from its tools.
4227
+ followProfileProviderKeyEnv(() => configStore.get().apiKeyEnv);
3245
4228
  export default configStore;