@zergai/ztc 0.19.0-beta.1 → 0.20.0-beta.1

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 (196) hide show
  1. package/README.md +222 -6
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/agent/agent.d.ts +17 -0
  8. package/dist/agent/agent.js +77 -4
  9. package/dist/agent/backends/index.js +5 -3
  10. package/dist/agent/backends/zrouter_stream.js +8 -4
  11. package/dist/agent/commands/goal.d.ts +2 -0
  12. package/dist/agent/commands/goal.js +7 -2
  13. package/dist/agent/factory.d.ts +2 -0
  14. package/dist/agent/factory.js +1 -0
  15. package/dist/agent/request_encoder.d.ts +2 -1
  16. package/dist/agent/request_encoder.js +4 -3
  17. package/dist/agent/runtime/policy.d.ts +1 -0
  18. package/dist/agent/runtime/policy.js +23 -3
  19. package/dist/agent/runtime/tool_runtime.js +13 -12
  20. package/dist/agent/subagent.js +2 -1
  21. package/dist/agent/tools/ask_user.d.ts +1 -1
  22. package/dist/agent/tools/ask_user.js +15 -8
  23. package/dist/agent/tools/pane.d.ts +6 -0
  24. package/dist/agent/tools/pane.js +18 -4
  25. package/dist/agent/tools/search.js +1 -1
  26. package/dist/agent/tools/sim_domain_tools.d.ts +4 -0
  27. package/dist/agent/tools/sim_domain_tools.js +28 -2
  28. package/dist/agent/tools/types.d.ts +3 -0
  29. package/dist/app/correlated_turn.d.ts +14 -0
  30. package/dist/app/correlated_turn.js +78 -0
  31. package/dist/app/prompt_turn.d.ts +2 -1
  32. package/dist/app/prompt_turn.js +15 -2
  33. package/dist/app/session_manager.d.ts +17 -11
  34. package/dist/app/session_manager.js +74 -30
  35. package/dist/app/tool_callbacks.d.ts +1 -1
  36. package/dist/app/workspace_layout_controller.d.ts +21 -2
  37. package/dist/app/workspace_layout_controller.js +61 -10
  38. package/dist/app/workspace_monitor.js +67 -7
  39. package/dist/app/workspace_presets.d.ts +1 -0
  40. package/dist/app/workspace_presets.js +2 -2
  41. package/dist/cli.js +6 -2
  42. package/dist/cli_args.js +1 -0
  43. package/dist/cli_main.js +48 -2
  44. package/dist/cli_ratatui.d.ts +56 -8
  45. package/dist/cli_ratatui.js +689 -109
  46. package/dist/config/permissions.js +1 -1
  47. package/dist/config/router_required.d.ts +11 -0
  48. package/dist/config/router_required.js +23 -0
  49. package/dist/config/types.d.ts +5 -0
  50. package/dist/config.d.ts +3 -1
  51. package/dist/config.js +66 -49
  52. package/dist/desktop/daily/broker.d.ts +26 -0
  53. package/dist/desktop/daily/broker.js +140 -0
  54. package/dist/desktop/daily/codex_config.d.ts +2 -0
  55. package/dist/desktop/daily/codex_config.js +119 -0
  56. package/dist/desktop/daily/codex_exec_adapter.d.ts +42 -0
  57. package/dist/desktop/daily/codex_exec_adapter.js +251 -0
  58. package/dist/desktop/daily/control_client.d.ts +4 -0
  59. package/dist/desktop/daily/control_client.js +214 -0
  60. package/dist/desktop/daily/control_credentials.d.ts +15 -0
  61. package/dist/desktop/daily/control_credentials.js +85 -0
  62. package/dist/desktop/daily/control_hello.d.ts +10 -0
  63. package/dist/desktop/daily/control_hello.js +6 -0
  64. package/dist/desktop/daily/control_protocol.d.ts +39 -0
  65. package/dist/desktop/daily/control_protocol.js +4 -0
  66. package/dist/desktop/daily/control_schema.d.ts +9 -0
  67. package/dist/desktop/daily/control_schema.js +25 -0
  68. package/dist/desktop/daily/control_server.d.ts +44 -0
  69. package/dist/desktop/daily/control_server.js +286 -0
  70. package/dist/desktop/daily/daily_store.d.ts +71 -0
  71. package/dist/desktop/daily/daily_store.js +290 -0
  72. package/dist/desktop/daily/delegated_ztc_contract.d.ts +37 -0
  73. package/dist/desktop/daily/delegated_ztc_contract.js +90 -0
  74. package/dist/desktop/daily/desktop_wiring.d.ts +112 -0
  75. package/dist/desktop/daily/desktop_wiring.js +1048 -0
  76. package/dist/desktop/daily/enrollment.d.ts +74 -0
  77. package/dist/desktop/daily/enrollment.js +77 -0
  78. package/dist/desktop/daily/file_facts.d.ts +2 -0
  79. package/dist/desktop/daily/file_facts.js +41 -0
  80. package/dist/desktop/daily/lease.d.ts +57 -0
  81. package/dist/desktop/daily/lease.js +332 -0
  82. package/dist/desktop/daily/legacy_codex_homes.d.ts +1 -0
  83. package/dist/desktop/daily/legacy_codex_homes.js +26 -0
  84. package/dist/desktop/daily/native_pane_launcher.d.ts +31 -0
  85. package/dist/desktop/daily/native_pane_launcher.js +226 -0
  86. package/dist/desktop/daily/native_records.d.ts +13 -0
  87. package/dist/desktop/daily/native_records.js +81 -0
  88. package/dist/desktop/daily/native_status.d.ts +4 -0
  89. package/dist/desktop/daily/native_status.js +28 -0
  90. package/dist/desktop/daily/native_tool.d.ts +134 -0
  91. package/dist/desktop/daily/native_tool.js +91 -0
  92. package/dist/desktop/daily/owner_files.d.ts +3 -0
  93. package/dist/desktop/daily/owner_files.js +88 -0
  94. package/dist/desktop/daily/owner_seals.d.ts +9 -0
  95. package/dist/desktop/daily/owner_seals.js +56 -0
  96. package/dist/desktop/daily/process_identity.d.ts +13 -0
  97. package/dist/desktop/daily/process_identity.js +137 -0
  98. package/dist/desktop/daily/profile_bootstrap.d.ts +60 -0
  99. package/dist/desktop/daily/profile_bootstrap.js +194 -0
  100. package/dist/desktop/daily/raw_receipts.d.ts +1 -0
  101. package/dist/desktop/daily/raw_receipts.js +18 -0
  102. package/dist/desktop/daily/recipes.d.ts +36 -0
  103. package/dist/desktop/daily/recipes.js +177 -0
  104. package/dist/desktop/daily/router_state.d.ts +33 -0
  105. package/dist/desktop/daily/router_state.js +39 -0
  106. package/dist/desktop/daily/schema_registry.d.ts +19 -0
  107. package/dist/desktop/daily/schema_registry.js +71 -0
  108. package/dist/desktop/daily/source_baseline.d.ts +13 -0
  109. package/dist/desktop/daily/source_baseline.js +44 -0
  110. package/dist/desktop/daily/status_restore.d.ts +9 -0
  111. package/dist/desktop/daily/status_restore.js +114 -0
  112. package/dist/desktop/daily/summary.d.ts +59 -0
  113. package/dist/desktop/daily/summary.js +75 -0
  114. package/dist/desktop/daily/worker_provenance.d.ts +2 -0
  115. package/dist/desktop/daily/worker_provenance.js +18 -0
  116. package/dist/desktop/daily/worker_stop.d.ts +2 -0
  117. package/dist/desktop/daily/worker_stop.js +26 -0
  118. package/dist/desktop/daily/ztc_headless_adapter.d.ts +40 -0
  119. package/dist/desktop/daily/ztc_headless_adapter.js +194 -0
  120. package/dist/domain.d.ts +1 -1
  121. package/dist/domain.js +1 -1
  122. package/dist/events.d.ts +23 -1
  123. package/dist/headless.d.ts +9 -0
  124. package/dist/headless.js +161 -26
  125. package/dist/headless_approval.d.ts +29 -0
  126. package/dist/headless_approval.js +69 -0
  127. package/dist/headless_cli.js +2 -0
  128. package/dist/headless_cli_args.d.ts +4 -0
  129. package/dist/headless_cli_args.js +5 -0
  130. package/dist/library.d.ts +20 -0
  131. package/dist/library.js +66 -12
  132. package/dist/mcp/client.d.ts +16 -1
  133. package/dist/mcp/client.js +11 -5
  134. package/dist/mcp/registry.d.ts +3 -1
  135. package/dist/mcp/registry.js +10 -1
  136. package/dist/panes/pane_registry.js +14 -3
  137. package/dist/panes/types.d.ts +7 -1
  138. package/dist/panes/ztc_launch.d.ts +5 -0
  139. package/dist/panes/ztc_launch.js +30 -14
  140. package/dist/session.d.ts +6 -3
  141. package/dist/session.js +21 -2
  142. package/dist/simulation/domain_types.d.ts +2 -0
  143. package/dist/simulation/domains/loader.d.ts +7 -1
  144. package/dist/simulation/domains/loader.js +33 -1
  145. package/dist/simulation/living/context.d.ts +19 -19
  146. package/dist/simulation/living/definition.d.ts +2 -2
  147. package/dist/simulation/living/frame.d.ts +1 -1
  148. package/dist/simulation/living/open-world.d.ts +3 -3
  149. package/dist/simulation/living/types.d.ts +24 -24
  150. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  151. package/dist/skills/bundled/init-context/SKILL.md +16 -0
  152. package/dist/skills/registry.js +7 -3
  153. package/dist/tools.d.ts +6 -0
  154. package/dist/tools.js +14 -0
  155. package/dist/types.d.ts +30 -0
  156. package/dist/ui/ratatui/mux_persistence.d.ts +3 -1
  157. package/dist/ui/ratatui/mux_persistence.js +9 -2
  158. package/dist/ui/ratatui/pane_credential_broker.d.ts +8 -4
  159. package/dist/ui/ratatui/pane_credential_broker.js +26 -11
  160. package/dist/ui/ratatui/pane_relay.d.ts +2 -0
  161. package/dist/ui/ratatui/process.d.ts +6 -0
  162. package/dist/ui/ratatui/process.js +104 -6
  163. package/dist/ui/ratatui/protocol.d.ts +13 -0
  164. package/dist/ui/ratatui/protocol.js +1 -0
  165. package/dist/utils/compaction.js +6 -4
  166. package/dist/utils/subprocess_env.js +2 -0
  167. package/dist/web/browser_events.d.ts +10 -0
  168. package/dist/web/browser_events.js +9 -0
  169. package/dist/web/mirror_stream.d.ts +17 -5
  170. package/dist/web/mirror_stream.js +105 -13
  171. package/dist/web/pane_credentials.d.ts +6 -3
  172. package/dist/web/pane_credentials.js +20 -12
  173. package/dist/web/pane_registry.js +1 -0
  174. package/dist/workspace_agent.d.ts +2 -1
  175. package/dist/workspace_agent.js +7 -1
  176. package/dist/workspace_collision.d.ts +3 -0
  177. package/dist/workspace_collision.js +1 -1
  178. package/dist/workspace_layout.d.ts +3 -2
  179. package/dist/workspace_layout.js +8 -2
  180. package/dist/workspace_runtime.d.ts +7 -1
  181. package/dist/workspace_runtime.js +3 -3
  182. package/dist/zerg/manifest_builder_tools.js +35 -4
  183. package/dist/zerg/manifest_validator.js +55 -0
  184. package/dist/zlm-embed.mjs +261 -116
  185. package/node_modules/@zerg/model-contracts/README.md +19 -0
  186. package/node_modules/@zerg/model-contracts/index.js +19 -1
  187. package/node_modules/@ztc/sim-graph/dist/index.d.ts +1 -0
  188. package/node_modules/@ztc/sim-graph/dist/index.js +1 -0
  189. package/node_modules/@ztc/sim-graph/dist/sim_graph.d.ts +351 -0
  190. package/node_modules/@ztc/sim-graph/dist/sim_graph.js +795 -0
  191. package/node_modules/@ztc/sim-graph/package.json +37 -0
  192. package/node_modules/@ztc/sim-graph/src/index.ts +1 -0
  193. package/node_modules/@ztc/sim-graph/src/sim_graph.ts +1305 -0
  194. package/package.json +25 -24
  195. package/packages/model-contracts/README.md +19 -0
  196. package/packages/model-contracts/index.js +19 -1
@@ -12,7 +12,7 @@ const profileSchema = z.object({
12
12
  description: z.string().max(2000).optional(),
13
13
  capabilities: z.object(Object.fromEntries(PERMISSION_CAPABILITIES.map(cap => [cap, z.boolean().optional()]))).strict().optional(),
14
14
  approvalRequiredCapabilities: z.array(z.enum(PERMISSION_CAPABILITIES)).max(7).optional(),
15
- allowedPaths: strings.optional(), deniedPaths: strings.optional(),
15
+ allowedPaths: strings.optional(), deniedPaths: strings.optional(), pathPrecedence: z.enum(['deny_first', 'specific']).optional(),
16
16
  allowedShellCommands: strings.optional(), deniedShellCommands: strings.optional(),
17
17
  networkHosts: z.object({ allow: strings.optional(), deny: strings.optional() }).strict().optional(),
18
18
  sandbox: z.object({ backend: z.enum(['auto', 'none', 'seatbelt', 'bubblewrap', 'windows-job']).optional(), requireOsEnforcement: z.boolean().optional() }).strict().optional(),
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The one model a required Router host may use. Atlas workers run exactly
3
+ * openai/gpt-6.1-sol; another host may pin a different single model with
4
+ * ZTC_ROUTER_REQUIRED_MODEL=provider/model. Callers and ZTC_MODEL cannot move it.
5
+ * Claude Code is no longer a ZTC model provider, so a pin can't name a retired
6
+ * provider or a model alias only those routes understood (retired_routes.ts).
7
+ */
8
+ export declare function requiredRouterModel(): {
9
+ provider: string;
10
+ model: string;
11
+ };
@@ -0,0 +1,23 @@
1
+ import { isRetiredModel, isRetiredProvider, RetiredProviderError, retiredModelMessage } from './retired_routes.js';
2
+ /**
3
+ * The one model a required Router host may use. Atlas workers run exactly
4
+ * openai/gpt-6.1-sol; another host may pin a different single model with
5
+ * ZTC_ROUTER_REQUIRED_MODEL=provider/model. Callers and ZTC_MODEL cannot move it.
6
+ * Claude Code is no longer a ZTC model provider, so a pin can't name a retired
7
+ * provider or a model alias only those routes understood (retired_routes.ts).
8
+ */
9
+ export function requiredRouterModel() {
10
+ const pinned = process.env.ZTC_ROUTER_REQUIRED_MODEL?.trim();
11
+ if (!pinned)
12
+ return { provider: 'openai', model: 'gpt-6.1-sol' };
13
+ const slash = pinned.indexOf('/');
14
+ if (slash <= 0 || slash === pinned.length - 1)
15
+ throw new Error('ZTC_ROUTER_REQUIRED_MODEL must be provider/model');
16
+ const provider = pinned.slice(0, slash);
17
+ const model = pinned.slice(slash + 1);
18
+ if (isRetiredProvider(provider))
19
+ throw new RetiredProviderError(provider);
20
+ if (isRetiredModel(model))
21
+ throw new Error(retiredModelMessage(model));
22
+ return { provider, model };
23
+ }
@@ -193,6 +193,7 @@ export interface ZTCPermissionProfile {
193
193
  approvalRequiredCapabilities?: ZTCToolCapability[];
194
194
  /** File roots that read/write tools may access. Relative entries resolve from the current cwd. */
195
195
  allowedPaths?: string[];
196
+ pathPrecedence?: 'deny_first' | 'specific';
196
197
  /** File roots that read/write tools may never access. Relative entries resolve from the current cwd. */
197
198
  deniedPaths?: string[];
198
199
  /** Shell command prefixes that are permitted when present. Empty/undefined means no prefix restriction. */
@@ -477,6 +478,7 @@ export interface ZTCConfig {
477
478
  emulationId?: string;
478
479
  spinnerVerbs?: string[];
479
480
  toolPermissions?: Partial<Record<ZTCToolCapability, boolean>>;
481
+ desktopDelegatedSkillRoots?: string[];
480
482
  permissionProfile?: string;
481
483
  permissionProfiles?: Record<string, ZTCPermissionProfile>;
482
484
  sandbox?: ZTCSandboxSettings;
@@ -684,3 +686,6 @@ export interface MCPServerConfig {
684
686
  url?: string;
685
687
  headers?: Record<string, string>;
686
688
  }
689
+ export interface ConfigLoadOptions {
690
+ strictConfig?: boolean;
691
+ }
package/dist/config.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type ReasoningWireSurface } from '@zerg/model-contracts';
2
2
  import { type RouterCatalog, type RouterCatalogConnection } from './utils/router_catalog.js';
3
3
  import { type ReasoningContract } from './utils/reasoning.js';
4
+ import type { ConfigLoadOptions } from './config/types.js';
4
5
  import { ZTCConfig, ZTCAuthCredentials, ApiEnvironment, ZTCAuthMode, ZTCConfigScope, CompactionTriggerMode, OpenAICompatibleSettings, ZTCPermissionProfile, IntentLayerSettings, ContextProgressBarSettings, CodexReasoningEffort, WorkflowSettings, Account, type NoticeLaunchStep, type TerminalInteractionSettings } from './config/types.js';
5
6
  import type { AuthContext, ResolvedLLMConfig } from './config/resolved.js';
6
7
  import { type RetiredRouteRequest } from './config/retired_routes.js';
@@ -24,6 +25,7 @@ export declare function shouldRefreshSuperuserStatus(env?: NodeJS.ProcessEnv): b
24
25
  * The one masking style for /config, /status and their confirmations.
25
26
  */
26
27
  export declare function maskApiKey(key: string): string;
28
+ export declare function copyProfileFiles(source: string, requestedName: string): Promise<string>;
27
29
  export declare class ConfigStore {
28
30
  private config;
29
31
  private profileEmulation;
@@ -132,7 +134,7 @@ export declare class ConfigStore {
132
134
  */
133
135
  private moveOffRetiredRoutes;
134
136
  private applyEnvOverrides;
135
- load(force?: boolean): Promise<ZTCConfig>;
137
+ load(force?: boolean, options?: ConfigLoadOptions): Promise<ZTCConfig>;
136
138
  refresh(): Promise<void>;
137
139
  /**
138
140
  * Run `listener` after this store saves its settings (in any scope) or
package/dist/config.js CHANGED
@@ -3,11 +3,12 @@ import { isLocalSubscriptionProvider } from './agent/backends/provider_ids.js';
3
3
  import { resolveRouterModel, readRouterCatalog } from './utils/router_catalog.js';
4
4
  import { reasoningContractChoices } from './utils/reasoning.js';
5
5
  import { dirname, join, resolve } from 'path';
6
- import { stat, readFile, readlink, writeFile, mkdir, rm, unlink, rename, realpath } from 'fs/promises';
6
+ import { stat, readFile, readlink, writeFile, mkdir, chmod, rm, unlink, rename, realpath, copyFile } from 'fs/promises';
7
7
  import { readFileSync, statSync } from 'fs';
8
8
  import { homedir } from 'os';
9
9
  import { randomUUID } from 'crypto';
10
10
  import { isDeepStrictEqual } from 'util';
11
+ import { constants as fsConstants } from 'node:fs';
11
12
  import { activeProfile, builtinProfileEmulation, listConfigProfiles, profileConfigDir, validateProfileName } from './config/profiles.js';
12
13
  import { accountSourceToBackendOptions, canonicalAccountProvider, probeAccountIsolated, resolveActiveAccount, } from './agent/backends/account_pool.js';
13
14
  import { notifyAccountsChanged } from './agent/backends/account_events.js';
@@ -21,6 +22,7 @@ import { withoutRetiredLaunchFlags } from './config/retired_ids.js';
21
22
  import { listAgentProfiles } from './panes/agent_profiles.js';
22
23
  import { loadRouterCredentials, RouterConfigurationError } from './router_auth.js';
23
24
  import { CODEX_APP_SERVER_SENTINEL, CODEX_LEGACY_PROVIDER, isCodexAppServerProvider, isCodexLegacyProvider, normalizeProviderId } from './agent/backends/provider_ids.js';
25
+ import { requiredRouterModel } from './config/router_required.js';
24
26
  import { DEFAULT_SPINNER_VERBS } from './utils/spinner_verbs.js';
25
27
  import { INLINE_SIZE_THRESHOLD_TOKENS_DEFAULT, INLINE_AGE_TURNS_DEFAULT, } from './agent/tool_response_store.js';
26
28
  import { DEFAULT_MESSAGE_DISPLAY } from './config/message_display.js';
@@ -264,6 +266,7 @@ export function build_default_config() {
264
266
  emulationId: undefined,
265
267
  spinnerVerbs: DEFAULT_SPINNER_VERBS,
266
268
  toolPermissions: { ...DEFAULT_TOOL_PERMISSIONS },
269
+ desktopDelegatedSkillRoots: [],
267
270
  permissionProfile: 'trusted',
268
271
  permissionProfiles: { ...DEFAULT_PERMISSION_PROFILES },
269
272
  sandbox: { ...DEFAULT_SANDBOX },
@@ -545,6 +548,55 @@ export function shouldRefreshSuperuserStatus(env = process.env) {
545
548
  export function maskApiKey(key) {
546
549
  return key.length >= 12 ? `••••${key.slice(-4)}` : '••••';
547
550
  }
551
+ export async function copyProfileFiles(source, requestedName) {
552
+ const name = validateProfileName(requestedName.trim());
553
+ const from = validateProfileName(source);
554
+ if (name === 'default' || builtinProfileEmulation(name)) {
555
+ throw new Error(`Cannot duplicate onto "${name}": it is a built-in profile sharing the default settings. Pick another name.`);
556
+ }
557
+ if (name === from || (await listConfigProfiles()).includes(name)) {
558
+ throw new Error(`Config profile "${name}" already exists. Pick another name.`);
559
+ }
560
+ const sourceDir = profileConfigDir(from);
561
+ const emulation = builtinProfileEmulation(from);
562
+ if (from !== 'default' && !emulation && !(await stat(sourceDir)).isDirectory()) {
563
+ throw new Error(`Config profile "${from}" does not exist.`);
564
+ }
565
+ let saved = {};
566
+ try {
567
+ const parsed = JSON.parse(await readFile(join(sourceDir, 'config.json'), 'utf8'));
568
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
569
+ throw new Error(`Invalid config profile "${from}": expected an object.`);
570
+ }
571
+ saved = parsed;
572
+ }
573
+ catch (error) {
574
+ if (error.code !== 'ENOENT')
575
+ throw error;
576
+ }
577
+ if (emulation)
578
+ saved.emulationId = emulation;
579
+ const destination = profileConfigDir(name);
580
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
581
+ // An existing destination, including one created concurrently, is never ours to modify.
582
+ await mkdir(destination, { mode: 0o700 });
583
+ try {
584
+ await writeFile(join(destination, 'config.json'), JSON.stringify(saved, null, 2), { flag: 'wx', mode: 0o600 });
585
+ try {
586
+ await copyFile(join(sourceDir, 'router-auth.json'), join(destination, 'router-auth.json'), fsConstants.COPYFILE_EXCL);
587
+ await chmod(join(destination, 'router-auth.json'), 0o600);
588
+ }
589
+ catch (error) {
590
+ if (error.code !== 'ENOENT')
591
+ throw error;
592
+ }
593
+ }
594
+ catch (error) {
595
+ await rm(destination, { recursive: true, force: true });
596
+ throw error;
597
+ }
598
+ return name;
599
+ }
548
600
  export class ConfigStore {
549
601
  config = build_default_config();
550
602
  profileEmulation = builtinProfileEmulation(activeProfile());
@@ -882,8 +934,8 @@ export class ConfigStore {
882
934
  }
883
935
  }
884
936
  }
885
- async load(force = false) {
886
- if (this.loaded && !force)
937
+ async load(force = false, options = {}) {
938
+ if (this.loaded && !force && !options.strictConfig)
887
939
  return this.config;
888
940
  this.profileEmulation = builtinProfileEmulation(activeProfile());
889
941
  this.routerCredentialsError = null;
@@ -911,6 +963,8 @@ export class ConfigStore {
911
963
  saved = parsed;
912
964
  }
913
965
  catch {
966
+ if (options.strictConfig)
967
+ throw new Error('Required profile config.json is missing or invalid');
914
968
  // File doesn't exist or is invalid, use defaults.
915
969
  this.config = build_default_config();
916
970
  this.legacyApiKeyFromEnvironment = true;
@@ -992,51 +1046,12 @@ export class ConfigStore {
992
1046
  * Account registrations retain their credential paths; account homes are not cloned.
993
1047
  */
994
1048
  async duplicateProfile(requestedName, source = activeProfile(), activate = () => { }) {
995
- const name = validateProfileName(requestedName.trim());
996
- const from = validateProfileName(source);
997
- if (name === 'default' || builtinProfileEmulation(name)) {
998
- throw new Error(`Cannot duplicate onto "${name}": it is a built-in profile sharing the default settings. Pick another name.`);
999
- }
1000
- if (name === from || (await listConfigProfiles()).includes(name)) {
1001
- throw new Error(`Config profile "${name}" already exists. Pick another name.`);
1002
- }
1003
- const sourceDir = profileConfigDir(from);
1004
- const emulation = builtinProfileEmulation(from);
1005
- if (from !== 'default' && !emulation && !(await stat(sourceDir)).isDirectory()) {
1006
- throw new Error(`Config profile "${from}" does not exist.`);
1007
- }
1008
- let saved = {};
1009
- try {
1010
- const parsed = JSON.parse(await readFile(join(sourceDir, 'config.json'), 'utf8'));
1011
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1012
- throw new Error(`Invalid config profile "${from}": expected an object.`);
1013
- }
1014
- saved = parsed;
1015
- }
1016
- catch (error) {
1017
- if (error.code !== 'ENOENT')
1018
- throw error;
1019
- }
1020
- if (emulation)
1021
- saved.emulationId = emulation;
1022
- const destination = profileConfigDir(name);
1023
- await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
1024
- // An existing destination, including one created concurrently, is never ours to modify.
1025
- await mkdir(destination, { mode: 0o700 });
1049
+ const name = await copyProfileFiles(source, requestedName);
1026
1050
  try {
1027
- await writeFile(join(destination, 'config.json'), JSON.stringify(saved, null, 2), { flag: 'wx', mode: 0o600 });
1028
- try {
1029
- const auth = await readFile(join(sourceDir, 'router-auth.json'));
1030
- await writeFile(join(destination, 'router-auth.json'), auth, { flag: 'wx', mode: 0o600 });
1031
- }
1032
- catch (error) {
1033
- if (error.code !== 'ENOENT')
1034
- throw error;
1035
- }
1036
1051
  await this.switchProfile(name, activate);
1037
1052
  }
1038
1053
  catch (error) {
1039
- await rm(destination, { recursive: true, force: true });
1054
+ await rm(profileConfigDir(name), { recursive: true, force: true });
1040
1055
  throw error;
1041
1056
  }
1042
1057
  return name;
@@ -2080,7 +2095,7 @@ export class ConfigStore {
2080
2095
  || process.env.OPENAI_COMPATIBLE_BASE_URL
2081
2096
  || (process.env.OLLAMA_HOST ? `${process.env.OLLAMA_HOST.replace(/\/+$/, '')}/v1` : undefined);
2082
2097
  return {
2083
- baseUrl: structured.baseUrl || cfg.openaiCompatibleBaseUrl || envBaseUrl,
2098
+ baseUrl: process.env.ZTC_OPENAI_COMPATIBLE_BASE_URL || structured.baseUrl || cfg.openaiCompatibleBaseUrl || envBaseUrl,
2084
2099
  apiPath: structured.apiPath,
2085
2100
  defaultModel: structured.defaultModel || process.env.OPENAI_COMPAT_MODEL,
2086
2101
  apiKey: structured.apiKey,
@@ -2373,10 +2388,12 @@ export class ConfigStore {
2373
2388
  // A hosted application's required profile never consults personal logins,
2374
2389
  // saved session origins, direct keys, account pools, or cheap-model defaults.
2375
2390
  if (process.env.ZTC_ROUTER_REQUIRED === '1') {
2376
- const provider = normalizeProviderId(opts.provider ?? opts.config?.provider ?? 'openai');
2377
- const model = opts.model ?? opts.config?.model ?? 'gpt-6.1-sol';
2378
- if (provider !== 'openai' || model !== 'gpt-6.1-sol')
2379
- throw new Error('Required Router profile permits only openai/gpt-6.1-sol');
2391
+ const required = requiredRouterModel();
2392
+ const provider = normalizeProviderId(opts.provider ?? opts.config?.provider ?? required.provider);
2393
+ const model = opts.model ?? opts.config?.model ?? required.model;
2394
+ if (provider !== normalizeProviderId(required.provider) || model !== required.model) {
2395
+ throw new Error(`Required Router profile permits only ${required.provider}/${required.model}`);
2396
+ }
2380
2397
  const proxyUrl = normalizedOrigin(process.env.ZERG_PROXY_URL);
2381
2398
  const authToken = process.env.ZERG_AUTH_TOKEN?.trim();
2382
2399
  if (!proxyUrl || !authToken)
@@ -0,0 +1,26 @@
1
+ export interface ApprovalLog {
2
+ requestId: string;
3
+ childPaneId: number;
4
+ receivedAt: number;
5
+ decidedAt: number | null;
6
+ decision: 'approved' | 'denied' | null;
7
+ }
8
+ export interface PendingApproval {
9
+ requestId: string;
10
+ childPaneId: number;
11
+ capabilities: string[];
12
+ approvable: boolean;
13
+ }
14
+ export interface ApprovalBroker {
15
+ readonly url: string;
16
+ readonly pending: readonly PendingApproval[];
17
+ readonly log: readonly Readonly<ApprovalLog>[];
18
+ issueChild(childPaneId: number): string;
19
+ revokeChild(childPaneId: number): void;
20
+ decide(requestId: string, decision: 'approved' | 'denied', by: 'desktop_human'): void;
21
+ close(): Promise<void>;
22
+ }
23
+ export declare function createApprovalBroker(options?: {
24
+ now?: () => number;
25
+ port?: number;
26
+ }): Promise<ApprovalBroker>;
@@ -0,0 +1,140 @@
1
+ import { createServer } from 'node:http';
2
+ import { z } from 'zod';
3
+ import { generateToken, tokensEqual } from './enrollment.js';
4
+ const requestSchema = z.object({ requestId: z.uuid(), kind: z.enum(['approval', 'question']),
5
+ capabilities: z.array(z.string().max(64)).max(16).optional(),
6
+ sessionId: z.string().min(1).max(256), cwd: z.string().min(1).max(4096) });
7
+ export async function createApprovalBroker(options = {}) {
8
+ const now = options.now ?? Date.now;
9
+ const children = new Map();
10
+ const pending = new Map();
11
+ const log = [];
12
+ const reply = (res, status, value = {}) => {
13
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
14
+ res.end(JSON.stringify(value));
15
+ };
16
+ const authenticate = (req) => {
17
+ const header = req.headers.authorization;
18
+ if (!header?.startsWith('Bearer '))
19
+ return null;
20
+ const token = header.slice(7);
21
+ for (const [childPaneId, expected] of children)
22
+ if (tokensEqual(token, expected))
23
+ return { childPaneId, token };
24
+ return null;
25
+ };
26
+ const server = createServer((req, res) => {
27
+ void (async () => {
28
+ const auth = authenticate(req);
29
+ if (!auth) {
30
+ reply(res, 401);
31
+ return;
32
+ }
33
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
34
+ if (url.search || url.hash) {
35
+ reply(res, 404);
36
+ return;
37
+ }
38
+ if (req.method === 'POST' && url.pathname === '/approvals') {
39
+ let bytes = 0;
40
+ const parts = [];
41
+ for await (const part of req) {
42
+ bytes += part.length;
43
+ if (bytes > 65536) {
44
+ reply(res, 413);
45
+ return;
46
+ }
47
+ parts.push(Buffer.from(part));
48
+ }
49
+ let value;
50
+ try {
51
+ value = JSON.parse(Buffer.concat(parts).toString('utf8'));
52
+ }
53
+ catch {
54
+ reply(res, 400);
55
+ return;
56
+ }
57
+ const parsed = requestSchema.safeParse(value);
58
+ if (!parsed.success) {
59
+ reply(res, 400);
60
+ return;
61
+ }
62
+ if (children.get(auth.childPaneId) !== auth.token) {
63
+ reply(res, 401);
64
+ return;
65
+ }
66
+ const requestId = parsed.data.requestId;
67
+ if (pending.has(requestId)) {
68
+ reply(res, 409);
69
+ return;
70
+ }
71
+ const entry = { requestId, childPaneId: auth.childPaneId, receivedAt: now(), decidedAt: null, decision: null };
72
+ const allowed = ['file_read', 'file_write', 'shell_exec', 'network', 'screen_capture', 'computer_control', 'ml_inference'];
73
+ const capabilities = (parsed.data.capabilities ?? []).map(value => allowed.includes(value) ? value : 'unknown');
74
+ log.push(entry);
75
+ pending.set(requestId, { entry, token: auth.token, capabilities, approvable: parsed.data.kind === 'approval' && capabilities.length > 0 && !capabilities.includes('unknown') });
76
+ reply(res, 202);
77
+ return;
78
+ }
79
+ if (req.method === 'GET' && /^\/approvals\/[^/]+$/.test(url.pathname)) {
80
+ const requestId = decodeURIComponent(url.pathname.slice('/approvals/'.length));
81
+ const item = pending.get(requestId);
82
+ if (!item) {
83
+ reply(res, 404);
84
+ return;
85
+ }
86
+ if (item.entry.childPaneId !== auth.childPaneId || !tokensEqual(auth.token, item.token)) {
87
+ reply(res, 401);
88
+ return;
89
+ }
90
+ reply(res, item.entry.decision === null ? 202 : 200, item.entry.decision === null ? {} : { decision: item.entry.decision });
91
+ return;
92
+ }
93
+ reply(res, 404);
94
+ })().catch(() => { if (!res.headersSent)
95
+ reply(res, 400);
96
+ else
97
+ res.end(); });
98
+ });
99
+ server.requestTimeout = 5000;
100
+ server.headersTimeout = 5000;
101
+ await new Promise((resolve, reject) => {
102
+ server.once('error', reject);
103
+ server.listen(options.port ?? 0, '127.0.0.1', () => { server.off('error', reject); resolve(); });
104
+ });
105
+ const address = server.address();
106
+ if (address === null || typeof address === 'string')
107
+ throw new Error('Loopback broker unavailable');
108
+ return {
109
+ url: `http://127.0.0.1:${address.port}/approvals`,
110
+ get log() { return log.map(entry => Object.freeze({ ...entry })); },
111
+ get pending() { return [...pending.values()].filter(item => item.entry.decision === null && children.get(item.entry.childPaneId) === item.token).map(item => ({ requestId: item.entry.requestId, childPaneId: item.entry.childPaneId, capabilities: [...item.capabilities], approvable: item.approvable })); },
112
+ issueChild(childPaneId) {
113
+ if (!Number.isSafeInteger(childPaneId) || childPaneId < 0)
114
+ throw new Error('Invalid child pane');
115
+ const token = generateToken();
116
+ children.set(childPaneId, token);
117
+ return token;
118
+ },
119
+ revokeChild(childPaneId) { children.delete(childPaneId); },
120
+ decide(requestId, decision, by) {
121
+ if (by !== 'desktop_human')
122
+ throw new Error('Human decision required');
123
+ if (decision !== 'approved' && decision !== 'denied')
124
+ throw new Error('Invalid decision');
125
+ const item = pending.get(requestId);
126
+ if (!item)
127
+ throw new Error('Unknown approval request');
128
+ if (children.get(item.entry.childPaneId) !== item.token)
129
+ throw new Error('Child revoked');
130
+ if (item.entry.decision !== null)
131
+ throw new Error('Approval already decided');
132
+ item.entry.decidedAt = now();
133
+ item.entry.decision = decision;
134
+ },
135
+ close: async () => {
136
+ children.clear();
137
+ await new Promise((resolve, reject) => { server.close(error => error ? reject(error) : resolve()); server.closeAllConnections(); });
138
+ },
139
+ };
140
+ }
@@ -0,0 +1,2 @@
1
+ export type CodexCredentialStore = 'file' | 'keyring' | 'auto' | 'ephemeral';
2
+ export declare function readCodexCredentialStore(env: NodeJS.ProcessEnv): Promise<CodexCredentialStore | undefined>;
@@ -0,0 +1,119 @@
1
+ import { constants } from 'node:fs';
2
+ import { open, realpath } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ function credentialStore(text) {
6
+ let result;
7
+ let statement = '';
8
+ let quote = '';
9
+ let triple = false;
10
+ let depth = 0;
11
+ const accept = () => {
12
+ const equal = statement.indexOf('=');
13
+ let key = statement.slice(0, equal).trim();
14
+ if (key.startsWith('"')) {
15
+ try {
16
+ key = JSON.parse(key);
17
+ }
18
+ catch {
19
+ key = '';
20
+ }
21
+ }
22
+ else if (key.startsWith("'"))
23
+ key = key.slice(1, -1);
24
+ if (equal >= 0 && key === 'cli_auth_credentials_store') {
25
+ const value = statement.slice(equal + 1).trim();
26
+ const match = /^(?:"(file|keyring|auto|ephemeral)"|'(file|keyring|auto|ephemeral)')$/.exec(value);
27
+ if (!match || result !== undefined)
28
+ throw new Error('Codex credential store configuration is unsupported');
29
+ result = (match[1] ?? match[2]);
30
+ }
31
+ statement = '';
32
+ };
33
+ for (let index = 0; index < text.length; index++) {
34
+ const char = text[index];
35
+ if (quote) {
36
+ if (quote === '"' && char === '\\') {
37
+ statement += char + (text[++index] ?? '');
38
+ continue;
39
+ }
40
+ if (triple && text.slice(index, index + 3) === quote.repeat(3)) {
41
+ statement += quote.repeat(3);
42
+ index += 2;
43
+ quote = '';
44
+ triple = false;
45
+ continue;
46
+ }
47
+ if (!triple && char === quote)
48
+ quote = '';
49
+ else if (!triple && char === '\n')
50
+ throw new Error('Codex credential store configuration is unsupported');
51
+ statement += char;
52
+ continue;
53
+ }
54
+ if (char === '#') {
55
+ while (index < text.length && text[index] !== '\n')
56
+ index++;
57
+ index--;
58
+ continue;
59
+ }
60
+ if (char === '"' || char === "'") {
61
+ quote = char;
62
+ triple = text.slice(index, index + 3) === char.repeat(3);
63
+ statement += triple ? char.repeat(3) : char;
64
+ if (triple)
65
+ index += 2;
66
+ continue;
67
+ }
68
+ if (char === '[' && depth === 0 && !statement.trim())
69
+ return result;
70
+ if (char === '[' || char === '{')
71
+ depth++;
72
+ if (char === ']' || char === '}') {
73
+ depth--;
74
+ if (depth < 0)
75
+ throw new Error('Codex credential store configuration is unsupported');
76
+ }
77
+ if (char === '\n' && depth === 0)
78
+ accept();
79
+ else
80
+ statement += char;
81
+ }
82
+ if (quote || depth !== 0)
83
+ throw new Error('Codex credential store configuration is unsupported');
84
+ accept();
85
+ return result;
86
+ }
87
+ export async function readCodexCredentialStore(env) {
88
+ let file;
89
+ try {
90
+ const path = await realpath(join(env.CODEX_HOME ?? join(env.HOME ?? homedir(), '.codex'), 'config.toml'));
91
+ file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
92
+ }
93
+ catch (error) {
94
+ if (error.code === 'ENOENT')
95
+ return undefined;
96
+ throw error;
97
+ }
98
+ try {
99
+ const info = await file.stat();
100
+ // home-manager and nix-darwin link this file into a root-owned, read-only /nix/store.
101
+ const trusted = info.uid === process.getuid?.() || (info.uid === 0 && (info.mode & 0o022) === 0);
102
+ if (!info.isFile() || !trusted || info.size > 1048576)
103
+ throw new Error('Codex user configuration is unsafe');
104
+ const buffer = Buffer.alloc(1048577);
105
+ let size = 0;
106
+ while (size < buffer.length) {
107
+ const { bytesRead } = await file.read(buffer, size, buffer.length - size, size);
108
+ if (bytesRead === 0)
109
+ break;
110
+ size += bytesRead;
111
+ }
112
+ if (size > 1048576)
113
+ throw new Error('Codex user configuration is unsafe');
114
+ return credentialStore(buffer.subarray(0, size).toString('utf8'));
115
+ }
116
+ finally {
117
+ await file.close();
118
+ }
119
+ }
@@ -0,0 +1,42 @@
1
+ import { type NativeToolPaneRecord } from './native_tool.js';
2
+ import { type ChildSummary } from './summary.js';
3
+ import { type Projection } from './schema_registry.js';
4
+ declare const itemTypes: readonly ["command_execution", "agent_message", "reasoning", "file_change", "mcp_tool_call", "web_search", "todo_list", "collab_tool_call"];
5
+ export type CodexTaskState = ChildSummary['taskState'] | 'approval_denied';
6
+ export interface CodexObservation {
7
+ baselineDirty: boolean;
8
+ state: CodexTaskState;
9
+ approvalState: ChildSummary['approvalState'];
10
+ errorClass: ChildSummary['errorClass'];
11
+ eventCount: number;
12
+ unclassified: number;
13
+ tokens: {
14
+ input: number;
15
+ output: number;
16
+ };
17
+ cachedInput: number;
18
+ reasoningOutput: number;
19
+ items: Record<typeof itemTypes[number], number>;
20
+ projection: Projection;
21
+ effectObserved: boolean;
22
+ }
23
+ export interface CodexOptions {
24
+ owner: {
25
+ desktopOwnerId: string;
26
+ revision: number;
27
+ };
28
+ command?: string;
29
+ env?: NodeJS.ProcessEnv;
30
+ resume?: boolean;
31
+ prompt?: string;
32
+ writeIntent?: boolean;
33
+ effectPaths?: string[];
34
+ rawEventPath?: string;
35
+ beforeSpawn?: () => boolean;
36
+ onRawLines?: (lines: string[]) => void;
37
+ timeoutMs?: number;
38
+ sourceTreeChanged?: () => Promise<boolean>;
39
+ onUpdate?: (record: NativeToolPaneRecord, observation: CodexObservation) => void;
40
+ }
41
+ export declare function runCodexExec(record: NativeToolPaneRecord, options: CodexOptions): Promise<CodexObservation>;
42
+ export {};