@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
@@ -3,13 +3,24 @@
3
3
  * provider's default. It lives in `<profile dir>/provider-models.json` (mode 0600), not config.json:
4
4
  * ConfigStore.save() rewrites config.json from memory without reading it again, so another pane's save would erase
5
5
  * what this one wrote. Each write reads the file and merges into it instead, so panes sharing a profile keep each
6
- * other's entries.
6
+ * other's entries: one write at a time in a process (withPathLock, as ConfigStore's withSettingsLock queues its saves),
7
+ * and across processes under the file's lock, each reading the file as it is once it holds the lock.
7
8
  */
8
9
  import { randomUUID } from 'node:crypto';
9
10
  import { readFileSync } from 'node:fs';
10
11
  import { mkdir, rename, unlink, writeFile } from 'node:fs/promises';
11
12
  import { join } from 'node:path';
12
13
  import { profileConfigDir } from './profiles.js';
14
+ import { withPathLock } from '../utils/path_lock.js';
15
+ let fileLock;
16
+ /**
17
+ * proper-lockfile, loaded with the first write, as the Codex token refresh loads it: a package that ships without it
18
+ * still takes this process's writes one at a time.
19
+ */
20
+ function loadFileLock() {
21
+ fileLock ??= import('proper-lockfile').then(module => (module.default ?? module), () => null);
22
+ return fileLock;
23
+ }
13
24
  /** At most this many providers are remembered; the one used longest ago goes first. */
14
25
  export const MAX_REMEMBERED_PROVIDERS = 64;
15
26
  const FILE = 'provider-models.json';
@@ -61,21 +72,37 @@ export function rememberedModel(choiceId, directory) {
61
72
  const models = readProviderModels(directory);
62
73
  return Object.hasOwn(models, choiceId) ? models[choiceId].model : undefined;
63
74
  }
64
- /** Merge `updates` into the profile's file: read it, keep each provider's newest entry, and replace it atomically. */
75
+ /**
76
+ * Merge `updates` into the profile's file: read it, keep each provider's newest entry, and replace it atomically. Two
77
+ * writes at once, in this process or another, each read the file before the other replaced it, and the second dropped
78
+ * the first's entry (PR #902 UPG-4): a write waits for any other in this process, then holds the file's lock against
79
+ * other processes while it reads, merges and replaces it.
80
+ */
65
81
  export async function recordProviderModels(updates, directory = profileConfigDir()) {
66
82
  if (entries(updates).length === 0)
67
83
  return;
68
84
  await mkdir(directory, { recursive: true });
69
85
  const file = join(directory, FILE);
70
- const merged = mergeProviderModels(readProviderModels(directory), updates);
71
- const temporary = `${file}.${randomUUID()}.tmp`;
72
- try {
73
- await writeFile(temporary, `${JSON.stringify(merged, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
74
- await rename(temporary, file);
75
- }
76
- finally {
77
- await unlink(temporary).catch(() => { });
78
- }
86
+ await withPathLock(file, async () => {
87
+ const lockfile = await loadFileLock();
88
+ // The lock is a directory beside the file (provider-models.json.lock), which needs no file to exist yet.
89
+ const release = lockfile ? await lockfile.lock(file, { realpath: false, stale: 10_000,
90
+ retries: { retries: 100, factor: 1.2, minTimeout: 5, maxTimeout: 100, randomize: true } }) : async () => { };
91
+ try {
92
+ const merged = mergeProviderModels(readProviderModels(directory), updates);
93
+ const temporary = `${file}.${randomUUID()}.tmp`;
94
+ try {
95
+ await writeFile(temporary, `${JSON.stringify(merged, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
96
+ await rename(temporary, file);
97
+ }
98
+ finally {
99
+ await unlink(temporary).catch(() => { });
100
+ }
101
+ }
102
+ finally {
103
+ await release();
104
+ }
105
+ });
79
106
  }
80
107
  /** Remember that `choiceId` was last used with `model`, now unless `usedAt` says when. */
81
108
  export async function rememberProviderModel(choiceId, model, options = {}) {
@@ -18,8 +18,30 @@ export interface RepoConfig {
18
18
  workflowAllowlist?: string[];
19
19
  }
20
20
  export declare function repoConfigPath(cwd: string): string;
21
+ /** The repository config at CWD (repoConfigOf), or null when there is none or explicit discovery reads none. */
21
22
  export declare function readRepoConfig(cwd: string): RepoConfig | null;
22
23
  export declare function writeRepoConfig(cwd: string, config: RepoConfig): void;
24
+ /**
25
+ * Whether CWD's `.ztc` directory is ZTC's own: ~/.ztc, the config root of every ZTC not given another, this process's
26
+ * root (ZTC_CONFIG_DIR) or the active profile's directory. In the home directory `.ztc/config.json` is ZTC's saved
27
+ * config, its keys and sign-ins: a home directory is no repository, and nothing writes a repository's config there.
28
+ */
29
+ export declare function isZtcConfigDirectory(cwd: string): boolean;
30
+ /**
31
+ * Change CWD's repository config by PATCH: a model override set (or cleared with null) and a workflow allowlist set,
32
+ * each only when PATCH names it. Every other key the file holds is kept as it was (permissionProfiles, which /permissions
33
+ * imports, among them): the file is read whole for this write only, and nothing it holds beyond RepoConfig is published.
34
+ * A file that is no JSON object is replaced. A link there (git checks links out, so a clone's can point at
35
+ * ../../.ztc/config.json) is not the repository's own file: it is read as readRepoConfig reads it, only the repository
36
+ * settings it holds, and replaced by the repository's own file, so nothing else of what it points at (ZTC's saved
37
+ * config, its keys and sign-ins, or another program's) is written into the repository, and that file is left as it was.
38
+ * Refused (an Error saying why, nothing written) where the file is ZTC's own saved config (isZtcConfigDirectory).
39
+ * Returns the repository config as written (readRepoConfig).
40
+ */
41
+ export declare function updateRepoConfig(cwd: string, patch: {
42
+ model?: RepoConfig['model'] | null;
43
+ workflowAllowlist?: string[];
44
+ }): RepoConfig;
23
45
  /**
24
46
  * The repo's model override, or null. Only well-formed overrides (both
25
47
  * provider and model strings) resolve — a partial edit must not half-apply.
@@ -10,16 +10,39 @@
10
10
  * use it when no CLI/session/renderer override exists) and a workflow
11
11
  * allowlist (workflow ids permitted to run on this repo).
12
12
  */
13
- import { existsSync, mkdirSync, readFileSync } from 'fs';
14
- import { dirname, join } from 'path';
13
+ import { existsSync, lstatSync, mkdirSync, readFileSync } from 'fs';
14
+ import { homedir } from 'os';
15
+ import { dirname, join, resolve } from 'path';
15
16
  import { isExplicitExtensionDiscovery } from '../extension_discovery.js';
16
17
  import { writeFileAtomicSync } from '../utils/atomic_write.js';
18
+ import { canonicalPath, sameFileKey } from '../utils/canonical_path.js';
17
19
  import { runtimeDiagOnce } from '../utils/debug_log.js';
20
+ import { profileConfigDir } from './profiles.js';
18
21
  import { isRetiredProvider, retiredProviderMessage } from './retired_routes.js';
19
22
  const REPO_CONFIG_RELATIVE_PATH = join('.ztc', 'config.json');
20
23
  export function repoConfigPath(cwd) {
21
24
  return join(cwd, REPO_CONFIG_RELATIVE_PATH);
22
25
  }
26
+ /**
27
+ * VALUE, a parsed `.ztc/config.json`, as a repository's config: only what RepoConfig holds, each part well formed (a
28
+ * model override names a provider and a model, an allowlist holds workflow ids). Nothing else the file holds is read:
29
+ * in the home directory this file is ZTC's own saved config, whose keys and tokens are no repository's settings, and
30
+ * what reads a repository's config (the browser mirror's settings page among them) is given none of them.
31
+ */
32
+ function repoConfigOf(value) {
33
+ const config = {};
34
+ const { model, workflowAllowlist } = value;
35
+ if (model && typeof model === 'object' && !Array.isArray(model)) {
36
+ const { provider, model: id } = model;
37
+ if (typeof provider === 'string' && provider && typeof id === 'string' && id)
38
+ config.model = { provider, model: id };
39
+ }
40
+ if (Array.isArray(workflowAllowlist)) {
41
+ config.workflowAllowlist = workflowAllowlist.filter((id) => typeof id === 'string');
42
+ }
43
+ return config;
44
+ }
45
+ /** The repository config at CWD (repoConfigOf), or null when there is none or explicit discovery reads none. */
23
46
  export function readRepoConfig(cwd) {
24
47
  if (isExplicitExtensionDiscovery())
25
48
  return null;
@@ -28,7 +51,7 @@ export function readRepoConfig(cwd) {
28
51
  return null;
29
52
  try {
30
53
  const parsed = JSON.parse(readFileSync(path, 'utf8'));
31
- return parsed && typeof parsed === 'object' ? parsed : null;
54
+ return parsed && typeof parsed === 'object' ? repoConfigOf(parsed) : null;
32
55
  }
33
56
  catch {
34
57
  // A hand-edited corrupt file must not break agent creation — treat as absent.
@@ -40,6 +63,57 @@ export function writeRepoConfig(cwd, config) {
40
63
  mkdirSync(dirname(path), { recursive: true });
41
64
  writeFileAtomicSync(path, JSON.stringify(config, null, 2) + '\n');
42
65
  }
66
+ /**
67
+ * Whether CWD's `.ztc` directory is ZTC's own: ~/.ztc, the config root of every ZTC not given another, this process's
68
+ * root (ZTC_CONFIG_DIR) or the active profile's directory. In the home directory `.ztc/config.json` is ZTC's saved
69
+ * config, its keys and sign-ins: a home directory is no repository, and nothing writes a repository's config there.
70
+ */
71
+ export function isZtcConfigDirectory(cwd) {
72
+ const key = (path) => sameFileKey(canonicalPath(resolve(path)));
73
+ const repo = key(join(cwd, '.ztc'));
74
+ const own = [join(homedir(), '.ztc'), profileConfigDir(), ...(process.env.ZTC_CONFIG_DIR ? [process.env.ZTC_CONFIG_DIR] : [])];
75
+ return own.some(dir => key(dir) === repo);
76
+ }
77
+ /**
78
+ * Change CWD's repository config by PATCH: a model override set (or cleared with null) and a workflow allowlist set,
79
+ * each only when PATCH names it. Every other key the file holds is kept as it was (permissionProfiles, which /permissions
80
+ * imports, among them): the file is read whole for this write only, and nothing it holds beyond RepoConfig is published.
81
+ * A file that is no JSON object is replaced. A link there (git checks links out, so a clone's can point at
82
+ * ../../.ztc/config.json) is not the repository's own file: it is read as readRepoConfig reads it, only the repository
83
+ * settings it holds, and replaced by the repository's own file, so nothing else of what it points at (ZTC's saved
84
+ * config, its keys and sign-ins, or another program's) is written into the repository, and that file is left as it was.
85
+ * Refused (an Error saying why, nothing written) where the file is ZTC's own saved config (isZtcConfigDirectory).
86
+ * Returns the repository config as written (readRepoConfig).
87
+ */
88
+ export function updateRepoConfig(cwd, patch) {
89
+ const path = repoConfigPath(cwd);
90
+ if (isZtcConfigDirectory(cwd)) {
91
+ throw new Error(`${path} is ZTC's own saved config, not a repository's: open the repository to change its settings.`);
92
+ }
93
+ let file = {};
94
+ if (existsSync(path)) {
95
+ try {
96
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
97
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
98
+ file = lstatSync(path).isSymbolicLink() ? { ...repoConfigOf(parsed) } : parsed;
99
+ }
100
+ }
101
+ catch {
102
+ // A hand-edited corrupt file holds nothing to keep: it is replaced, as readRepoConfig treats it as absent.
103
+ }
104
+ }
105
+ if ('model' in patch) {
106
+ if (patch.model)
107
+ file.model = patch.model;
108
+ else
109
+ delete file.model;
110
+ }
111
+ if (patch.workflowAllowlist !== undefined)
112
+ file.workflowAllowlist = patch.workflowAllowlist;
113
+ mkdirSync(dirname(path), { recursive: true });
114
+ writeFileAtomicSync(path, JSON.stringify(file, null, 2) + '\n');
115
+ return repoConfigOf(file);
116
+ }
43
117
  /**
44
118
  * The repo's model override, or null. Only well-formed overrides (both
45
119
  * provider and model strings) resolve — a partial edit must not half-apply.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The host's Router runtime grant.
3
+ *
4
+ * A host that runs a resident ZTC (ZergCloud runs one in each service zerg) routes its model traffic through Zerg Router
5
+ * on a Router runtime grant it mints and revokes for that resident. It hands ZTC the grant in ZTC_ROUTER_RUNTIME_GRANT and
6
+ * names the Router it is for in ZERG_ROUTER_BASE_URL; one without the other is no grant. The grant lives in this
7
+ * process's memory only, in the host-credential store (config/host_credentials.ts), which takes it out of process.env
8
+ * as ZTC starts: ZTC never saves it, and no child process inherits it (utils/subprocess_env.ts) but the ZTC panes and
9
+ * colony cells it is given to (hostRouterGrantForZtcChild), which route on it too.
10
+ *
11
+ * Stripping keeps the grant out of a child's own environment, not out of its reach: a process this ZTC's user runs can
12
+ * read the environment this process was started with (`ps -E` on macOS, /proc/<pid>/environ on Linux), as it can for
13
+ * every credential handed over in an environment variable, ZTC_AUTH_TOKEN among them. A host keeps the grant out of
14
+ * that environment by handing it over in a file instead (ZTC_ROUTER_RUNTIME_GRANT_FILE), which ZTC reads once as it
15
+ * starts and removes (config/host_credentials.ts). What remains is this process's memory, which a program running as
16
+ * the same user or as root can read, and the environment of each ZTC pane the grant is given to.
17
+ */
18
+ import { ROUTER_RUNTIME_GRANT_ENV } from './host_credentials.js';
19
+ /** The host-only variable that holds the grant. */
20
+ export { ROUTER_RUNTIME_GRANT_ENV };
21
+ /** What a run says, once, about a grant it can't send for not being a usable bearer. It never repeats the grant. */
22
+ export declare const UNUSABLE_ROUTER_RUNTIME_GRANT: string;
23
+ /**
24
+ * What a request to the Router the host claimed for its grant says when the grant is no usable bearer: nothing was sent,
25
+ * and nothing goes in the grant's place (a saved sign-in, a key, another route). It never repeats the grant.
26
+ */
27
+ export declare const UNUSABLE_ROUTER_RUNTIME_GRANT_REFUSED: string;
28
+ /**
29
+ * The grant a Router request to DESTINATION goes with: the host's, when the host named its Router with
30
+ * ZERG_ROUTER_BASE_URL (https, or http on loopback) and DESTINATION is on that URL's origin, compared as URL origins and
31
+ * never as strings (a path, a trailing slash or the case of a scheme or host is no other Router; a host or port that
32
+ * only begins the same is). The ZergAI platform's own Router proxy (PLATFORM_PROXY, `<API base>/api/zrouter`) never
33
+ * gets it, wherever it is: the platform's login is the credential there. Undefined otherwise.
34
+ */
35
+ export declare function hostRouterGrantFor(destination: string | undefined, env?: NodeJS.ProcessEnv, platformProxy?: string): string | undefined;
36
+ /**
37
+ * Whether the host claimed DESTINATION's Router for its grant: it set ZTC_ROUTER_RUNTIME_GRANT, a usable bearer or not,
38
+ * and DESTINATION is where hostRouterGrantFor would send one. There only the grant goes: a usable one, else nothing, and
39
+ * never a saved sign-in, a key or another route in its place.
40
+ */
41
+ export declare function hostClaimsRouter(destination: string | undefined, env?: NodeJS.ProcessEnv, platformProxy?: string): boolean;
42
+ /** Whether TOKEN, a Router bearer a request goes with, is the host's grant. */
43
+ export declare function isHostRouterGrant(token: string | undefined, env?: NodeJS.ProcessEnv): boolean;
44
+ /**
45
+ * Whether VALUE, another variable's, holds what the host set ZTC_ROUTER_RUNTIME_GRANT to (blanks around either aside),
46
+ * usable as a bearer or not: the grant under another name, which goes nowhere the grant itself doesn't.
47
+ */
48
+ export declare function holdsHostRouterGrant(value: string | undefined, env?: NodeJS.ProcessEnv): boolean;
49
+ /**
50
+ * What a turn says when Zerg Router refused the host's grant (its own 401 or 403, before any provider was called): the
51
+ * grant expired or the host revoked it. Nothing else is tried: no saved sign-in, no key, no other route.
52
+ */
53
+ export declare const ROUTER_RUNTIME_GRANT_REFUSED: string;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The host's Router runtime grant.
3
+ *
4
+ * A host that runs a resident ZTC (ZergCloud runs one in each service zerg) routes its model traffic through Zerg Router
5
+ * on a Router runtime grant it mints and revokes for that resident. It hands ZTC the grant in ZTC_ROUTER_RUNTIME_GRANT and
6
+ * names the Router it is for in ZERG_ROUTER_BASE_URL; one without the other is no grant. The grant lives in this
7
+ * process's memory only, in the host-credential store (config/host_credentials.ts), which takes it out of process.env
8
+ * as ZTC starts: ZTC never saves it, and no child process inherits it (utils/subprocess_env.ts) but the ZTC panes and
9
+ * colony cells it is given to (hostRouterGrantForZtcChild), which route on it too.
10
+ *
11
+ * Stripping keeps the grant out of a child's own environment, not out of its reach: a process this ZTC's user runs can
12
+ * read the environment this process was started with (`ps -E` on macOS, /proc/<pid>/environ on Linux), as it can for
13
+ * every credential handed over in an environment variable, ZTC_AUTH_TOKEN among them. A host keeps the grant out of
14
+ * that environment by handing it over in a file instead (ZTC_ROUTER_RUNTIME_GRANT_FILE), which ZTC reads once as it
15
+ * starts and removes (config/host_credentials.ts). What remains is this process's memory, which a program running as
16
+ * the same user or as root can read, and the environment of each ZTC pane the grant is given to.
17
+ */
18
+ import { hostEnvironmentValue, ROUTER_RUNTIME_GRANT_ENV } from './host_credentials.js';
19
+ import { runtimeDiagOnce } from '../utils/debug_log.js';
20
+ /** The host-only variable that holds the grant. */
21
+ export { ROUTER_RUNTIME_GRANT_ENV };
22
+ /**
23
+ * A grant as it can go in an Authorization header: visible ASCII, no spaces or line breaks, at most 16 KiB. Anything
24
+ * else would be refused as a header, and a refused header's error repeats it.
25
+ */
26
+ const USABLE_BEARER = /^[\x21-\x7e]{1,16384}$/;
27
+ /** What a run says, once, about a grant it can't send for not being a usable bearer. It never repeats the grant. */
28
+ export const UNUSABLE_ROUTER_RUNTIME_GRANT = '[ztc] ZTC_ROUTER_RUNTIME_GRANT is set but is not a usable Router bearer (only visible '
29
+ + 'ASCII characters, with no spaces or line breaks), so ZTC sends nothing with it, and nothing in its place.';
30
+ /**
31
+ * What a request to the Router the host claimed for its grant says when the grant is no usable bearer: nothing was sent,
32
+ * and nothing goes in the grant's place (a saved sign-in, a key, another route). It never repeats the grant.
33
+ */
34
+ export const UNUSABLE_ROUTER_RUNTIME_GRANT_REFUSED = 'ZTC_ROUTER_RUNTIME_GRANT is set for this Router but is not a usable Router '
35
+ + 'bearer (only visible ASCII characters, with no spaces or line breaks), so nothing was sent. The host must set a valid '
36
+ + 'grant; ZTC does not fall back to a saved sign-in or another route.';
37
+ /** The host's grant, when it is set to a usable bearer; undefined when unset, empty, or set to something else. */
38
+ function grantValue(env) {
39
+ const grant = hostEnvironmentValue(ROUTER_RUNTIME_GRANT_ENV, env)?.trim();
40
+ return grant && USABLE_BEARER.test(grant) ? grant : undefined;
41
+ }
42
+ /**
43
+ * The URL origin (scheme, host and port) of a Router address, or undefined for one that is not an absolute URL or that
44
+ * carries credentials of its own: a request there would go with those, or to a host other than the one it reads as.
45
+ */
46
+ function urlOrigin(value) {
47
+ if (!value?.trim())
48
+ return undefined;
49
+ let url;
50
+ try {
51
+ url = new URL(value.trim());
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ return url.username || url.password ? undefined : url.origin;
57
+ }
58
+ /** The hosts a Router may be reached on over plain http: this machine's loopback, as a Router login allows (router_auth.ts). */
59
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
60
+ /**
61
+ * The origin the host's grant is for: ZERG_ROUTER_BASE_URL's, when it is https, or http on loopback. A grant sent in the
62
+ * clear to any other host could be read on the way.
63
+ */
64
+ function grantOrigin(env) {
65
+ const origin = urlOrigin(env.ZERG_ROUTER_BASE_URL);
66
+ if (!origin)
67
+ return undefined;
68
+ const { protocol, hostname } = new URL(origin);
69
+ return protocol === 'https:' || (protocol === 'http:' && LOOPBACK_HOSTS.has(hostname)) ? origin : undefined;
70
+ }
71
+ /** Whether DESTINATION is PLATFORM_PROXY (the ZergAI platform's Router proxy, `<API base>/api/zrouter`) or under it. */
72
+ function underPlatformProxy(destination, platformProxy) {
73
+ if (!platformProxy)
74
+ return false;
75
+ let target;
76
+ let proxy;
77
+ try {
78
+ target = new URL(destination.trim());
79
+ proxy = new URL(platformProxy.trim());
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ const path = (url) => url.pathname.replace(/\/+$/, '');
85
+ return target.origin === proxy.origin && (path(target) === path(proxy) || path(target).startsWith(`${path(proxy)}/`));
86
+ }
87
+ /**
88
+ * The grant a Router request to DESTINATION goes with: the host's, when the host named its Router with
89
+ * ZERG_ROUTER_BASE_URL (https, or http on loopback) and DESTINATION is on that URL's origin, compared as URL origins and
90
+ * never as strings (a path, a trailing slash or the case of a scheme or host is no other Router; a host or port that
91
+ * only begins the same is). The ZergAI platform's own Router proxy (PLATFORM_PROXY, `<API base>/api/zrouter`) never
92
+ * gets it, wherever it is: the platform's login is the credential there. Undefined otherwise.
93
+ */
94
+ export function hostRouterGrantFor(destination, env = process.env, platformProxy) {
95
+ if (!hostClaimsRouter(destination, env, platformProxy))
96
+ return undefined;
97
+ const grant = grantValue(env);
98
+ if (!grant)
99
+ runtimeDiagOnce('warn', UNUSABLE_ROUTER_RUNTIME_GRANT);
100
+ return grant;
101
+ }
102
+ /**
103
+ * Whether the host claimed DESTINATION's Router for its grant: it set ZTC_ROUTER_RUNTIME_GRANT, a usable bearer or not,
104
+ * and DESTINATION is where hostRouterGrantFor would send one. There only the grant goes: a usable one, else nothing, and
105
+ * never a saved sign-in, a key or another route in its place.
106
+ */
107
+ export function hostClaimsRouter(destination, env = process.env, platformProxy) {
108
+ const origin = grantOrigin(env);
109
+ if (!hostEnvironmentValue(ROUTER_RUNTIME_GRANT_ENV, env)?.trim() || !origin || !destination || urlOrigin(destination) !== origin)
110
+ return false;
111
+ return !underPlatformProxy(destination, platformProxy);
112
+ }
113
+ /** Whether TOKEN, a Router bearer a request goes with, is the host's grant. */
114
+ export function isHostRouterGrant(token, env = process.env) {
115
+ const grant = grantValue(env);
116
+ return grant !== undefined && token === grant;
117
+ }
118
+ /**
119
+ * Whether VALUE, another variable's, holds what the host set ZTC_ROUTER_RUNTIME_GRANT to (blanks around either aside),
120
+ * usable as a bearer or not: the grant under another name, which goes nowhere the grant itself doesn't.
121
+ */
122
+ export function holdsHostRouterGrant(value, env = process.env) {
123
+ const grant = hostEnvironmentValue(ROUTER_RUNTIME_GRANT_ENV, env)?.trim();
124
+ return Boolean(grant) && value?.trim() === grant;
125
+ }
126
+ /**
127
+ * What a turn says when Zerg Router refused the host's grant (its own 401 or 403, before any provider was called): the
128
+ * grant expired or the host revoked it. Nothing else is tried: no saved sign-in, no key, no other route.
129
+ */
130
+ export const ROUTER_RUNTIME_GRANT_REFUSED = 'The host\'s Router runtime grant was refused by Zerg Router (expired or revoked), so '
131
+ + 'nothing was sent to a provider. The host must issue a new grant; ZTC does not fall back to another route or sign-in.';
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The three-way merge of one saved setting that ZTC runs when another ZTC on the same profile saved it since this one
3
+ * last read or wrote it (ConfigStore's save, and its reload of that save): BASE is the setting as this ZTC last read or
4
+ * wrote it, OURS as it holds it now, THEIRS as the other ZTC saved it.
5
+ */
6
+ /** Whether VALUE is a group of settings a merge goes into field by field: a plain object (prototype Object or null). */
7
+ export declare function isSettingsGroup(value: unknown): value is Record<string, unknown>;
8
+ /**
9
+ * One setting merged. What only one side changed takes that side's value: a setting this ZTC left as it was is the
10
+ * other's (removed, if the other removed it), and one the other left as it was is this ZTC's (removed, if this ZTC
11
+ * removed it). Where both changed a group of settings, the merge goes into it field by field; where both changed the
12
+ * same value, or one made a group a value of another kind (a list, a word, a number), this ZTC's wins: the last one
13
+ * saved wins. A list, a value of a class and every other value is replaced whole. Undefined is a setting not there.
14
+ */
15
+ export declare function mergeSettingValue(base: unknown, ours: unknown, theirs: unknown): unknown;
16
+ /**
17
+ * One setting whose entries each belong together (an MCP server's address or command with the credential sent to it),
18
+ * merged as mergeSettingValue merges a group, entry by entry, but with an entry both sides changed kept as this ZTC's
19
+ * whole: never one side's address with the other side's credential. An entry only one side changed, added or removed
20
+ * takes that side's.
21
+ */
22
+ export declare function mergeSettingEntries(base: unknown, ours: unknown, theirs: unknown): unknown;
@@ -0,0 +1,75 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ /**
3
+ * The three-way merge of one saved setting that ZTC runs when another ZTC on the same profile saved it since this one
4
+ * last read or wrote it (ConfigStore's save, and its reload of that save): BASE is the setting as this ZTC last read or
5
+ * wrote it, OURS as it holds it now, THEIRS as the other ZTC saved it.
6
+ */
7
+ /** Whether VALUE is a group of settings a merge goes into field by field: a plain object (prototype Object or null). */
8
+ export function isSettingsGroup(value) {
9
+ if (typeof value !== 'object' || value === null)
10
+ return false;
11
+ const prototype = Object.getPrototypeOf(value);
12
+ return prototype === Object.prototype || prototype === null;
13
+ }
14
+ /** A group of settings, or none: a group that isn't there merges as an empty one. */
15
+ function groupOrNone(value) {
16
+ return value === undefined || isSettingsGroup(value);
17
+ }
18
+ /** GROUP's own field KEY, or undefined; a saved "__proto__" is a field like any other, never the group's prototype. */
19
+ function field(group, key) {
20
+ return group !== undefined && Object.hasOwn(group, key) ? group[key] : undefined;
21
+ }
22
+ /** Set KEY on GROUP as its own field, whatever the key is called. */
23
+ function setField(group, key, value) {
24
+ Object.defineProperty(group, key, { value, enumerable: true, writable: true, configurable: true });
25
+ }
26
+ /**
27
+ * One setting merged. What only one side changed takes that side's value: a setting this ZTC left as it was is the
28
+ * other's (removed, if the other removed it), and one the other left as it was is this ZTC's (removed, if this ZTC
29
+ * removed it). Where both changed a group of settings, the merge goes into it field by field; where both changed the
30
+ * same value, or one made a group a value of another kind (a list, a word, a number), this ZTC's wins: the last one
31
+ * saved wins. A list, a value of a class and every other value is replaced whole. Undefined is a setting not there.
32
+ */
33
+ export function mergeSettingValue(base, ours, theirs) {
34
+ if (isDeepStrictEqual(base, ours))
35
+ return theirs;
36
+ if (isDeepStrictEqual(base, theirs))
37
+ return ours;
38
+ if (!groupOrNone(base) || !groupOrNone(ours) || !groupOrNone(theirs))
39
+ return ours;
40
+ const merged = { ...theirs };
41
+ for (const key of new Set([...Object.keys(base ?? {}), ...Object.keys(ours ?? {})])) {
42
+ const value = mergeSettingValue(field(base, key), field(ours, key), field(theirs, key));
43
+ if (value === undefined)
44
+ delete merged[key];
45
+ else
46
+ setField(merged, key, value);
47
+ }
48
+ // A group one side removed keeps only what the other added to it, and is gone when that is nothing.
49
+ return Object.keys(merged).length === 0 && (ours === undefined || theirs === undefined) ? undefined : merged;
50
+ }
51
+ /**
52
+ * One setting whose entries each belong together (an MCP server's address or command with the credential sent to it),
53
+ * merged as mergeSettingValue merges a group, entry by entry, but with an entry both sides changed kept as this ZTC's
54
+ * whole: never one side's address with the other side's credential. An entry only one side changed, added or removed
55
+ * takes that side's.
56
+ */
57
+ export function mergeSettingEntries(base, ours, theirs) {
58
+ if (isDeepStrictEqual(base, ours))
59
+ return theirs;
60
+ if (isDeepStrictEqual(base, theirs))
61
+ return ours;
62
+ if (!groupOrNone(base) || !groupOrNone(ours) || !groupOrNone(theirs))
63
+ return ours;
64
+ const merged = { ...theirs };
65
+ for (const key of new Set([...Object.keys(base ?? {}), ...Object.keys(ours ?? {})])) {
66
+ const own = field(ours, key);
67
+ if (isDeepStrictEqual(field(base, key), own))
68
+ continue;
69
+ if (own === undefined)
70
+ delete merged[key];
71
+ else
72
+ setField(merged, key, own);
73
+ }
74
+ return Object.keys(merged).length === 0 && (ours === undefined || theirs === undefined) ? undefined : merged;
75
+ }
@@ -774,6 +774,14 @@ export interface MCPServerConfig {
774
774
  command?: string;
775
775
  args?: string[];
776
776
  env?: Record<string, string>;
777
+ /**
778
+ * Variables of ZTC's environment the server is started with beyond what a tool child gets
779
+ * (utils/subprocess_env.ts buildMcpServerEnv), as a hook's passEnv: a provider key, ZERG_AUTH_TOKEN or ZTC_API_KEY,
780
+ * say, which a server is otherwise started without. ZTC's own credentials and variables, and a variable holding a
781
+ * copy of one of its credentials, are never given; the server's startup diagnostics say so. A list of variable
782
+ * names; anything else keeps the server from starting.
783
+ */
784
+ passEnv?: string[];
777
785
  url?: string;
778
786
  headers?: Record<string, string>;
779
787
  }