@zergai/ztc 0.14.0-beta.1 → 0.15.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 (134) hide show
  1. package/README.md +175 -39
  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 +0 -0
  7. package/dist/App.js +17 -0
  8. package/dist/agent/agent.js +1 -5
  9. package/dist/agent/backends/account_events.d.ts +4 -4
  10. package/dist/agent/backends/account_events.js +4 -4
  11. package/dist/agent/backends/account_login.d.ts +1 -1
  12. package/dist/agent/backends/account_login.js +1 -1
  13. package/dist/agent/backends/account_pool.d.ts +11 -54
  14. package/dist/agent/backends/account_pool.js +12 -134
  15. package/dist/agent/backends/anthropic.js +18 -4
  16. package/dist/agent/backends/codex_app_server.d.ts +3 -4
  17. package/dist/agent/backends/codex_app_server.js +4 -5
  18. package/dist/agent/backends/codex_auth.d.ts +1 -0
  19. package/dist/agent/backends/codex_auth.js +6 -4
  20. package/dist/agent/backends/failover.d.ts +1 -1
  21. package/dist/agent/backends/failover.js +9 -9
  22. package/dist/agent/backends/index.d.ts +3 -24
  23. package/dist/agent/backends/index.js +8 -56
  24. package/dist/agent/backends/kimi_code_auth.d.ts +1 -1
  25. package/dist/agent/backends/kimi_code_auth.js +2 -2
  26. package/dist/agent/backends/provider_ids.d.ts +5 -0
  27. package/dist/agent/backends/provider_ids.js +6 -1
  28. package/dist/agent/backends/rate_limit.d.ts +7 -16
  29. package/dist/agent/backends/rate_limit.js +7 -29
  30. package/dist/agent/backends/types.d.ts +0 -5
  31. package/dist/agent/commands/accounts.d.ts +6 -2
  32. package/dist/agent/commands/accounts.js +97 -70
  33. package/dist/agent/commands/compact.js +4 -2
  34. package/dist/agent/commands/config.js +27 -13
  35. package/dist/agent/commands/connect.js +79 -3
  36. package/dist/agent/commands/credential_status.d.ts +2 -0
  37. package/dist/agent/commands/credential_status.js +5 -1
  38. package/dist/agent/commands/dictation.js +34 -14
  39. package/dist/agent/commands/direct_credential_prompt.js +7 -1
  40. package/dist/agent/commands/model.js +8 -0
  41. package/dist/agent/commands/models.js +5 -6
  42. package/dist/agent/commands/provider_choices.js +5 -5
  43. package/dist/agent/commands/provider_model_defaults.d.ts +3 -4
  44. package/dist/agent/commands/provider_model_defaults.js +4 -16
  45. package/dist/agent/commands/provider_selection.d.ts +4 -3
  46. package/dist/agent/commands/provider_selection.js +15 -7
  47. package/dist/agent/commands/settings.js +36 -50
  48. package/dist/agent/commands/sim.js +9 -0
  49. package/dist/agent/commands/subs.js +3 -2
  50. package/dist/agent/commands/types.d.ts +26 -6
  51. package/dist/agent/factory.js +17 -52
  52. package/dist/agent/subagent.js +4 -11
  53. package/dist/agent/tools/adaptation.js +10 -1
  54. package/dist/agent/tools/pane.js +25 -2
  55. package/dist/agent/tools/sim.js +12 -3
  56. package/dist/agent/tools/supervision.js +4 -0
  57. package/dist/app/agent_runner.js +9 -2
  58. package/dist/app/launch_notices.d.ts +44 -0
  59. package/dist/app/launch_notices.js +41 -0
  60. package/dist/app/retired_route_gate.d.ts +44 -0
  61. package/dist/app/retired_route_gate.js +73 -0
  62. package/dist/app/session_manager.js +2 -1
  63. package/dist/app/task_scope_router.js +1 -13
  64. package/dist/cli_main.js +39 -6
  65. package/dist/cli_ratatui.d.ts +28 -2
  66. package/dist/cli_ratatui.js +178 -40
  67. package/dist/components/InputArea.js +27 -10
  68. package/dist/config/anthropic_models.d.ts +18 -0
  69. package/dist/config/anthropic_models.js +22 -0
  70. package/dist/config/defaults.d.ts +0 -1
  71. package/dist/config/defaults.js +9 -10
  72. package/dist/config/permissions.js +4 -2
  73. package/dist/config/repo_config.js +8 -0
  74. package/dist/config/resolved.d.ts +1 -1
  75. package/dist/config/retired_ids.d.ts +33 -0
  76. package/dist/config/retired_ids.js +39 -0
  77. package/dist/config/retired_routes.d.ts +192 -0
  78. package/dist/config/retired_routes.js +609 -0
  79. package/dist/config/types.d.ts +61 -31
  80. package/dist/config.d.ts +269 -23
  81. package/dist/config.js +727 -106
  82. package/dist/evolution/mutation.js +4 -1
  83. package/dist/headless.js +46 -4
  84. package/dist/headless_cli.js +23 -6
  85. package/dist/headless_cli_args.d.ts +3 -1
  86. package/dist/headless_cli_args.js +7 -0
  87. package/dist/hosted/session_settings.js +11 -2
  88. package/dist/library.js +4 -0
  89. package/dist/onboarding/first_run.js +5 -2
  90. package/dist/onboarding/setup.js +2 -1
  91. package/dist/onboarding/setup_agent_health.js +5 -5
  92. package/dist/optimize/llm.js +4 -1
  93. package/dist/panes/agent_cli.d.ts +1 -1
  94. package/dist/panes/agent_cli.js +5 -2
  95. package/dist/panes/agent_panes.js +12 -4
  96. package/dist/panes/agent_profiles.d.ts +25 -5
  97. package/dist/panes/agent_profiles.js +35 -10
  98. package/dist/panes/model_catalog.d.ts +1 -1
  99. package/dist/panes/model_catalog.js +3 -24
  100. package/dist/panes/pane_registry.js +9 -3
  101. package/dist/panes/ztc_launch.js +28 -6
  102. package/dist/simulation/inference.d.ts +38 -4
  103. package/dist/simulation/inference.js +264 -24
  104. package/dist/simulation/living/context.d.ts +1 -1
  105. package/dist/simulation/living/open-world.d.ts +1 -1
  106. package/dist/simulation/living/types.d.ts +4 -4
  107. package/dist/simulation/llm.js +14 -4
  108. package/dist/simulation/memory/embedding.d.ts +6 -0
  109. package/dist/simulation/memory/embedding.js +35 -8
  110. package/dist/utils/compaction.js +0 -1
  111. package/dist/utils/context.js +2 -7
  112. package/dist/utils/dictation.d.ts +43 -8
  113. package/dist/utils/dictation.js +333 -138
  114. package/dist/utils/idle_compaction.js +1 -1
  115. package/dist/utils/models.js +0 -24
  116. package/dist/utils/subprocess_env.d.ts +14 -3
  117. package/dist/utils/subprocess_env.js +16 -3
  118. package/dist/web/accounts_mirror.d.ts +23 -57
  119. package/dist/web/accounts_mirror.js +52 -171
  120. package/dist/web/mirror_stream.d.ts +14 -3
  121. package/dist/web/mirror_stream.js +16 -12
  122. package/dist/zlicky/vision_locator.js +7 -2
  123. package/dist/zlm-embed.mjs +1398 -1488
  124. package/package.json +12 -10
  125. package/dist/agent/backends/account_rotation.d.ts +0 -138
  126. package/dist/agent/backends/account_rotation.js +0 -323
  127. package/dist/agent/backends/account_state.d.ts +0 -59
  128. package/dist/agent/backends/account_state.js +0 -139
  129. package/dist/agent/backends/claude_cli.d.ts +0 -85
  130. package/dist/agent/backends/claude_cli.js +0 -658
  131. package/dist/agent/backends/claude_code_auth.d.ts +0 -48
  132. package/dist/agent/backends/claude_code_auth.js +0 -171
  133. package/dist/agent/backends/rotation_factory.d.ts +0 -26
  134. package/dist/agent/backends/rotation_factory.js +0 -55
@@ -1,57 +1,39 @@
1
1
  /**
2
- * Account pool — model + resolution for switchable Claude Code + Codex
3
- * subscription accounts.
2
+ * Account pool — model + resolution for switchable Codex and Kimi Code
3
+ * subscription accounts. Accounts switch only when the user chooses one.
4
4
  *
5
5
  * Resolve each active account to an isolated credential path for the backend.
6
6
  * Official CLI logins write each profile's credentials; this module probes
7
7
  * their files and builds the corresponding process environment.
8
+ *
9
+ * Claude accounts are not part of the pool: a Claude subscription runs in a
10
+ * Claude Code pane on a sign-in profile (panes/agent_profiles.ts), and ZTC
11
+ * never reads what Claude Code stores.
8
12
  */
9
- import { spawnSync } from 'node:child_process';
10
13
  import { mkdirSync, realpathSync } from 'node:fs';
11
- import { homedir } from 'node:os';
12
14
  import { basename, dirname, join, resolve } from 'node:path';
13
15
  import { normalizeProviderId } from './provider_ids.js';
14
- import { hasUsableClaudeCodeAuth } from './claude_code_auth.js';
15
16
  import { hasUsableCodexAuth } from './codex_auth.js';
16
17
  import { CODEX_SUBSCRIPTION_CONFIG_ARGS, buildCodexAppServerEnv } from './codex_app_server.js';
17
18
  import { hasUsableKimiCodeAuth } from './kimi_code_auth.js';
18
- import { runtimeDiagOnce } from '../../utils/debug_log.js';
19
19
  import { profileConfigDir } from '../../config/profiles.js';
20
- /** Root dir for ztc-owned per-account credential dirs. */
21
- export const ACCOUNTS_ROOT = join(homedir(), '.ztc', 'accounts');
22
20
  const ACCOUNT_PROVIDERS = [
23
- 'claude_code',
24
21
  'codex_app_server',
25
22
  'codex_legacy',
26
- 'claude_code_direct',
27
23
  'kimi_code',
28
24
  ];
29
25
  /** Type guard for the registerable account providers. */
30
26
  export function isAccountProvider(value) {
31
27
  return ACCOUNT_PROVIDERS.includes(value);
32
28
  }
33
- /** Default auto-rotate policy (applied at read time when `rotation` is unset). */
34
- export const DEFAULT_ACCOUNT_ROTATION = {
35
- enabled: false,
36
- mode: 'failover',
37
- defaultCooldownMs: 5 * 60 * 60 * 1000, // 5h per-window cap
38
- weeklyCooldownMs: 24 * 60 * 60 * 1000, // 24h weekly cap
39
- subagentInheritance: 'inherit',
40
- };
41
29
  /**
42
30
  * Canonical pool key for a provider id. {@link normalizeProviderId} only unifies
43
- * the codex aliases, so fold the `claude-code` hyphen variants into the
31
+ * the codex aliases, so fold the `kimi-code` hyphen variant into the
44
32
  * underscore {@link AccountProvider} form used by {@link Account.provider}.
45
33
  */
46
34
  export function canonicalAccountProvider(provider) {
47
35
  const norm = normalizeProviderId(provider);
48
36
  switch (norm) {
49
- case 'claude-code':
50
- case 'claude_code':
51
- return 'claude_code';
52
- case 'claude-code-direct':
53
- case 'claude_code_direct':
54
- return 'claude_code_direct';
55
37
  case 'kimi-code':
56
38
  case 'kimi_code':
57
39
  return 'kimi_code';
@@ -62,7 +44,7 @@ export function canonicalAccountProvider(provider) {
62
44
  /** The active {@link Account} for a provider, or undefined when no pool/active. */
63
45
  export function resolveActiveAccount(config, provider) {
64
46
  const pool = config.accounts;
65
- if (!pool) {
47
+ if (!pool || !Array.isArray(pool.accounts) || !pool.activePerProvider) {
66
48
  return undefined;
67
49
  }
68
50
  const key = canonicalAccountProvider(provider);
@@ -75,14 +57,10 @@ export function resolveActiveAccount(config, provider) {
75
57
  /** Translate an account's credential source into backend-construction options. */
76
58
  export function accountSourceToBackendOptions(source) {
77
59
  switch (source.kind) {
78
- case 'claude_config_dir':
79
- return { claudeConfigDir: source.path };
80
60
  case 'codex_home':
81
61
  return { codexHome: source.path };
82
62
  case 'codex_auth_file':
83
63
  return { codexAuthFilePath: source.path };
84
- case 'claude_creds_file':
85
- return { claudeCredsFilePath: source.path };
86
64
  case 'kimi_creds_file':
87
65
  return { kimiCredsFilePath: source.path };
88
66
  }
@@ -96,10 +74,6 @@ export function accountBackendOptions(config, provider) {
96
74
  const account = resolveActiveAccount(config, provider);
97
75
  return account ? accountSourceToBackendOptions(account.source) : {};
98
76
  }
99
- /** Effective rotation policy (config override merged over defaults). */
100
- export function resolveRotation(config) {
101
- return { ...DEFAULT_ACCOUNT_ROTATION, ...(config.accounts?.rotation ?? {}) };
102
- }
103
77
  // ---------------------------------------------------------------------------
104
78
  // S1: account ops support (default dirs, usability probe, login invocation).
105
79
  // Still token-free — ztc only ever touches paths/env, never the creds inside.
@@ -125,17 +99,10 @@ export function defaultAccountDir(provider, id) {
125
99
  */
126
100
  export function defaultSourceFor(provider, dir) {
127
101
  switch (provider) {
128
- case 'claude_code':
129
- return { kind: 'claude_config_dir', path: dir };
130
102
  case 'codex_app_server':
131
103
  return { kind: 'codex_home', path: resolve(dir) };
132
104
  case 'codex_legacy':
133
105
  return { kind: 'codex_auth_file', path: basename(dir) === 'auth.json' ? resolve(dir) : join(resolve(dir), 'auth.json') };
134
- case 'claude_code_direct':
135
- return {
136
- kind: 'claude_creds_file',
137
- path: basename(dir) === '.credentials.json' ? dir : join(dir, '.credentials.json'),
138
- };
139
106
  case 'kimi_code':
140
107
  // Nested under credentials/ so the official CLI's KIMI_CODE_HOME=<dir>
141
108
  // layout (which writes <dir>/credentials/kimi-code.json on /login) lands
@@ -149,11 +116,9 @@ export function defaultSourceFor(provider, dir) {
149
116
  /** The credential *dir* backing a source (the dir itself, or a file's parent). */
150
117
  export function sourceDir(source) {
151
118
  switch (source.kind) {
152
- case 'claude_config_dir':
153
119
  case 'codex_home':
154
120
  return source.path;
155
121
  case 'codex_auth_file':
156
- case 'claude_creds_file':
157
122
  case 'kimi_creds_file':
158
123
  return dirname(source.path);
159
124
  }
@@ -184,25 +149,11 @@ export function findCodexHomeCollision(accounts, source) {
184
149
  }
185
150
  /**
186
151
  * Whether an account holds ISOLATED (per-account) credentials. Always probes
187
- * the account's EXPLICIT path — never the cached default — and for the Claude
188
- * kinds suppresses the global env token and shared macOS keychain so one
189
- * account's login never reads as another's.
152
+ * the account's EXPLICIT path — never the cached default.
190
153
  */
191
154
  export function probeAccountIsolated(account) {
192
155
  const source = account.source;
193
156
  switch (source.kind) {
194
- case 'claude_config_dir':
195
- return hasUsableClaudeCodeAuth({
196
- credentialsFilePath: join(source.path, '.credentials.json'),
197
- envToken: null,
198
- keychainReader: () => undefined,
199
- });
200
- case 'claude_creds_file':
201
- return hasUsableClaudeCodeAuth({
202
- credentialsFilePath: source.path,
203
- envToken: null,
204
- keychainReader: () => undefined,
205
- });
206
157
  case 'codex_home':
207
158
  return hasUsableCodexAuth(join(source.path, 'auth.json'));
208
159
  case 'codex_auth_file':
@@ -211,72 +162,9 @@ export function probeAccountIsolated(account) {
211
162
  return hasUsableKimiCodeAuth(source.path);
212
163
  }
213
164
  }
214
- let keychainMemo = null;
215
- /**
216
- * True when the shared macOS keychain item written by the official claude CLI
217
- * exists. Existence check ONLY (`security find-generic-password` without `-w`)
218
- * — ztc never reads credential material. Memoized for 5s on the default runner
219
- * so payload builds don't spawn `security` per account.
220
- */
221
- export function sharedClaudeKeychainPresent(runner) {
222
- if (process.platform !== 'darwin')
223
- return false;
224
- if (runner) {
225
- try {
226
- return runner('security', ['find-generic-password', '-s', 'Claude Code-credentials']).status === 0;
227
- }
228
- catch {
229
- return false;
230
- }
231
- }
232
- const now = Date.now();
233
- if (keychainMemo && now - keychainMemo.at < 5000)
234
- return keychainMemo.present;
235
- let present = false;
236
- try {
237
- present = spawnSync('security', ['find-generic-password', '-s', 'Claude Code-credentials'], {
238
- stdio: 'ignore',
239
- timeout: 2000,
240
- }).status === 0;
241
- }
242
- catch {
243
- present = false;
244
- }
245
- keychainMemo = { at: now, present };
246
- return present;
247
- }
248
- /** Resolve the credential backing for an account (see AccountCredentialSource). */
249
- export function accountCredentialSource(account, keychainPresent = sharedClaudeKeychainPresent) {
250
- if (probeAccountIsolated(account))
251
- return 'isolated';
252
- const kind = account.source.kind;
253
- if ((kind === 'claude_config_dir' || kind === 'claude_creds_file') && keychainPresent()) {
254
- return 'shared_keychain';
255
- }
256
- return 'none';
257
- }
258
- /**
259
- * Whether an account can currently serve requests. Shared-keychain-backed
260
- * claude accounts count as usable (the CLI will run) — they just aren't
261
- * isolated; surface that via {@link accountCredentialSource}, don't hide it by
262
- * reporting a logged-in account as "needs login".
263
- */
264
- export function probeAccountUsable(account, keychainPresent = sharedClaudeKeychainPresent) {
265
- return accountCredentialSource(account, keychainPresent) !== 'none';
266
- }
267
- /**
268
- * Warn when an account is served by the SHARED macOS keychain identity rather
269
- * than isolated per-account credentials. Every claude account on such a machine
270
- * shares that one login, so switching or rotating between them is a silent
271
- * no-op until each logs in per-account. Emits nothing for isolated/none sources.
272
- */
273
- export function warnSharedKeychainAccount(account, keychainPresent = sharedClaudeKeychainPresent, warn = (message) => runtimeDiagOnce('warn', message)) {
274
- if (accountCredentialSource(account, keychainPresent) !== 'shared_keychain')
275
- return;
276
- warn(`[ztc] account: "${account.id}" (${account.label}) is served by the shared macOS `
277
- + `keychain identity, not per-account credentials. All claude accounts on this machine `
278
- + `share that one login — switching or rotating between them has no effect until each `
279
- + `logs in per-account (/accounts).`);
165
+ /** Whether an account can currently serve requests: its own credentials exist. */
166
+ export function probeAccountUsable(account) {
167
+ return probeAccountIsolated(account);
280
168
  }
281
169
  /** Quote a path for the displayed POSIX shell command. */
282
170
  function shellQuote(value) {
@@ -285,16 +173,6 @@ function shellQuote(value) {
285
173
  export function buildLoginCommand(account) {
286
174
  const source = account.source;
287
175
  switch (source.kind) {
288
- case 'claude_config_dir':
289
- case 'claude_creds_file': {
290
- const dir = sourceDir(source);
291
- return {
292
- command: 'claude',
293
- args: ['/login'],
294
- env: { ...process.env, CLAUDE_CONFIG_DIR: dir },
295
- display: `CLAUDE_CONFIG_DIR=${dir} claude /login`,
296
- };
297
- }
298
176
  case 'codex_home':
299
177
  case 'codex_auth_file': {
300
178
  const dir = sourceDir(source);
@@ -2,6 +2,15 @@ import { IncompleteStreamError } from './transport_errors.js';
2
2
  import { modelContract } from '@zerg/model-contracts';
3
3
  import { parseSSEStream } from './sse.js';
4
4
  import { readBoundedProviderError } from './openai_responses.js';
5
+ import { CLAUDE_CODE_TOKEN_NOT_SENT, isClaudeCodeToken } from '../../config/retired_routes.js';
6
+ /**
7
+ * A credential this backend may send, or undefined for a Claude Code sign-in
8
+ * token: Anthropic reserves subscription sign-in for Claude Code itself, so
9
+ * ZTC never sends one, as a key or a bearer, whoever passed it in.
10
+ */
11
+ function sendable(credential) {
12
+ return isClaudeCodeToken(credential) ? undefined : credential;
13
+ }
5
14
  /** Hosted transport with no provider-key or ambient-credential path. */
6
15
  export function createNativeAnthropicMessagesRouterBackend(config) {
7
16
  const url = new URL(config.baseUrl);
@@ -81,7 +90,7 @@ export class AnthropicBackend {
81
90
  this.cacheControl = ttl === 'off' ? null : ttl === '5m' ? { type: 'ephemeral' } : { type: 'ephemeral', ttl: '1h' };
82
91
  }
83
92
  isAuthenticationConfigured() {
84
- return Boolean(this.apiKey || this.authToken || this.authTokenProvider);
93
+ return Boolean(sendable(this.apiKey) || sendable(this.authToken) || this.authTokenProvider);
85
94
  }
86
95
  allowsBufferedFallbackAfterStreamFailure() { return false; }
87
96
  async buildHeaders() {
@@ -89,12 +98,17 @@ export class AnthropicBackend {
89
98
  'Content-Type': 'application/json',
90
99
  'anthropic-version': '2023-06-01'
91
100
  };
92
- const authToken = this.authTokenProvider ? await this.authTokenProvider() : this.authToken;
101
+ const given = this.authTokenProvider ? await this.authTokenProvider() : this.authToken;
102
+ const authToken = sendable(given);
103
+ const apiKey = this.authTokenProvider ? undefined : sendable(this.apiKey);
93
104
  if (authToken?.trim()) {
94
105
  headers.Authorization = `Bearer ${authToken}`;
95
106
  }
96
- else if (this.apiKey && !this.authTokenProvider) {
97
- headers['x-api-key'] = this.apiKey;
107
+ else if (apiKey) {
108
+ headers['x-api-key'] = apiKey;
109
+ }
110
+ else if (isClaudeCodeToken(given) || (!this.authTokenProvider && isClaudeCodeToken(this.apiKey))) {
111
+ throw new Error(CLAUDE_CODE_TOKEN_NOT_SENT);
98
112
  }
99
113
  else {
100
114
  throw new Error('Anthropic auth is not configured');
@@ -50,9 +50,8 @@ export interface CodexAppServerClientOptions {
50
50
  * credentials. Injects the per-account CODEX_HOME (when given) and SCRUBS a
51
51
  * stray auth overrides from the parent env — otherwise the
52
52
  * codex CLI would bill that API key instead of the account's ChatGPT
53
- * subscription (auth.json under CODEX_HOME). This is the codex counterpart to
54
- * {@link buildClaudeCliEnv}'s ANTHROPIC_API_KEY scrub, and it applies even with
55
- * no per-account home so an ambient key never hijacks the default ChatGPT login.
53
+ * subscription (auth.json under CODEX_HOME). It applies even with no
54
+ * per-account home so an ambient key never hijacks the default ChatGPT login.
56
55
  */
57
56
  export declare function buildCodexAppServerEnv(codexHome?: string, base?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
58
57
  export interface CodexTurnOptions {
@@ -98,7 +97,7 @@ export declare function codexItemToObservation(rawItem: unknown): BackendObserva
98
97
  /**
99
98
  * Detect a 429 inside a TurnError whose JSON-encoded message carries the upstream
100
99
  * HTTP status (e.g. {"error":{...},"status":429}), and convert it to the typed
101
- * RateLimitError the rotation engine acts on. Returns null for any other failure.
100
+ * RateLimitError, which says when the limit resets. Returns null for any other failure.
102
101
  */
103
102
  export declare function turnRateLimitError(error: {
104
103
  message?: string;
@@ -23,9 +23,8 @@ const MAX_CODEX_APP_SERVER_MODELS = 2_000;
23
23
  * credentials. Injects the per-account CODEX_HOME (when given) and SCRUBS a
24
24
  * stray auth overrides from the parent env — otherwise the
25
25
  * codex CLI would bill that API key instead of the account's ChatGPT
26
- * subscription (auth.json under CODEX_HOME). This is the codex counterpart to
27
- * {@link buildClaudeCliEnv}'s ANTHROPIC_API_KEY scrub, and it applies even with
28
- * no per-account home so an ambient key never hijacks the default ChatGPT login.
26
+ * subscription (auth.json under CODEX_HOME). It applies even with no
27
+ * per-account home so an ambient key never hijacks the default ChatGPT login.
29
28
  */
30
29
  export function buildCodexAppServerEnv(codexHome, base = process.env) {
31
30
  const env = { ...base };
@@ -173,7 +172,7 @@ function formatTurnError(error) {
173
172
  /**
174
173
  * Detect a 429 inside a TurnError whose JSON-encoded message carries the upstream
175
174
  * HTTP status (e.g. {"error":{...},"status":429}), and convert it to the typed
176
- * RateLimitError the rotation engine acts on. Returns null for any other failure.
175
+ * RateLimitError, which says when the limit resets. Returns null for any other failure.
177
176
  */
178
177
  export function turnRateLimitError(error, now) {
179
178
  const raw = error?.message;
@@ -1065,7 +1064,7 @@ export class CodexAppServerClient {
1065
1064
  // The App Server only populates turn.error when the turn failed.
1066
1065
  // Surface it instead of closing with empty output, so callers see
1067
1066
  // why (e.g. an effort/model/tool incompatibility or a 4xx). A 429 is
1068
- // raised typed so the rotation engine can cool + fail over.
1067
+ // raised typed so the turn can say when the limit resets.
1069
1068
  const rateLimit = turnRateLimitError(turn.error, Date.now());
1070
1069
  waiter.queue.fail(rateLimit ?? new Error(`codex_app_server turn failed: ${formatTurnError(turn.error)}`));
1071
1070
  }
@@ -26,6 +26,7 @@ interface CodexAuthFile {
26
26
  * read and write this file. ZTC replaces it atomically, so concurrent readers
27
27
  * see the old or new credentials and never a truncated JSON document.
28
28
  */
29
+ export declare function codexAuthFilePath(env?: NodeJS.ProcessEnv): string;
29
30
  export declare const CODEX_AUTH_FILE_PATH: string;
30
31
  export declare const CODEX_AUTH_SENTINEL = "codex-subscription-auth";
31
32
  interface ParsedCodexAuthFile {
@@ -29,9 +29,11 @@ function loadFileLock() {
29
29
  * read and write this file. ZTC replaces it atomically, so concurrent readers
30
30
  * see the old or new credentials and never a truncated JSON document.
31
31
  */
32
- export const CODEX_AUTH_FILE_PATH = process.env.CODEX_AUTH_FILE_PATH
33
- || process.env.ZTC_CODEX_AUTH_FILE || process.env.CODEX_AUTH_FILE
34
- || join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'auth.json');
32
+ export function codexAuthFilePath(env = process.env) {
33
+ return env.CODEX_AUTH_FILE_PATH || env.ZTC_CODEX_AUTH_FILE || env.CODEX_AUTH_FILE
34
+ || join(env.CODEX_HOME || join(homedir(), '.codex'), 'auth.json');
35
+ }
36
+ export const CODEX_AUTH_FILE_PATH = codexAuthFilePath();
35
37
  export const CODEX_AUTH_SENTINEL = 'codex-subscription-auth';
36
38
  const OAUTH_TOKEN_URL = 'https://auth.openai.com/oauth/token';
37
39
  const DEFAULT_CODEX_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
@@ -505,7 +507,7 @@ export class CodexAuthBackend {
505
507
  const requestId = /^[A-Za-z0-9._:-]{1,128}$/.test(rawRequestId) ? rawRequestId : '';
506
508
  const errorText = `Codex API error (${response.status})${requestId ? ` request_id=${requestId}` : ''}`;
507
509
  if (response.status === 429) {
508
- // Typed so the rotation engine can cool this account and fail over.
510
+ // Typed so the turn can say when the limit resets; accounts never switch on their own.
509
511
  const now = Date.now();
510
512
  const retryAfter = Number(response.headers.get('retry-after'));
511
513
  const resetSeconds = Number(response.headers.get('x-ratelimit-reset') ?? response.headers.get('x-ratelimit-reset-requests'));
@@ -1,7 +1,7 @@
1
1
  export type FailoverKind = 'rate_limit' | 'transient' | 'auth';
2
2
  export interface FailoverSignal {
3
3
  kind: FailoverKind;
4
- /** The provider's message, surfaced on the cooled account for diagnostics. */
4
+ /** The provider's message, kept with the cooled model for diagnostics. */
5
5
  reason: string;
6
6
  /** rate_limit only: exact epoch-ms reset, when the provider supplied one. */
7
7
  resetAt?: number;
@@ -1,20 +1,20 @@
1
1
  /**
2
- * Failover classification for the account-rotation engine.
2
+ * Failover classification for worker model pools (model_pool.ts).
3
3
  *
4
- * The {@link RotatingBackend} only moves off an account for errors it can place.
5
- * A rate limit is the obvious one, but a provider timeout, an overload (5xx /
6
- * Anthropic 529), a dropped connection, or a revoked token are just as much a
7
- * reason to try another account instead of failing the turn. This maps a raw
8
- * error into one of three failover kinds — or null, meaning "not our problem,
9
- * rethrow" (a real 4xx client bug must surface, not be masked by rotating).
4
+ * A pool only moves off a model for errors it can place. A rate limit is the
5
+ * obvious one, but a provider timeout, an overload (5xx / Anthropic 529), a
6
+ * dropped connection, or a revoked token are just as much a reason to try the
7
+ * next model instead of failing the turn. This maps a raw error into one of
8
+ * three failover kinds — or null, meaning "not our problem, rethrow" (a real
9
+ * 4xx client bug must surface, not be masked by failing over).
10
10
  *
11
11
  * Dependency-free apart from {@link RateLimitError} so every backend + the pool
12
12
  * can import it without a cycle. Cooldown *durations* are the pool's policy, not
13
13
  * this module's — it only says which kind of failover applies.
14
14
  */
15
15
  import { RateLimitError } from './rate_limit.js';
16
- // Timeouts (Node, fetch/AbortSignal, undici) and dropped connections — a healthy
17
- // account can serve the next turn, so a short backoff + rotate beats failing.
16
+ // Timeouts (Node, fetch/AbortSignal, undici) and dropped connections — the next
17
+ // model in the pool can serve the turn, so a short cooldown beats failing it.
18
18
  const TIMEOUT_NAMES = new Set(['TimeoutError', 'AbortError', 'ConnectTimeoutError', 'HeadersTimeoutError', 'BodyTimeoutError']);
19
19
  const TRANSIENT_CODES = new Set([
20
20
  'ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED', 'ECONNABORTED', 'EPIPE', 'ENOTFOUND', 'EAI_AGAIN',
@@ -14,12 +14,10 @@ export { CodexAppServerBackend, CodexAppServerClient } from './codex_app_server.
14
14
  export { CodexAuthBackend, CodexAuthManager, CODEX_AUTH_FILE_PATH, CODEX_AUTH_SENTINEL } from './codex_auth.js';
15
15
  export { CODEX_APP_SERVER_PROVIDER, CODEX_APP_SERVER_SENTINEL, CODEX_LEGACY_PROVIDER, normalizeProviderId } from './provider_ids.js';
16
16
  export { ClarifaiBackend, normalizeClarifaiModel, CLARIFAI_BASE_URL } from './clarifai.js';
17
- export { ClaudeCodeAuthBackend, ClaudeCodeAuthManager } from './claude_code_auth.js';
18
17
  export { KimiCodeAuthBackend, KimiCodeAuthManager, KIMI_CODE_AUTH_SENTINEL, KIMI_CODE_PROVIDER, hasUsableKimiCodeAuth } from './kimi_code_auth.js';
19
- export { ClaudeCliBackend, ClaudeCliError, CLAUDE_CODE_AUTH_SENTINEL, hasUsableClaudeCodeCliAuth as hasUsableClaudeCodeAuth } from './claude_cli.js';
18
+ export { RetiredProviderError } from '../../config/retired_routes.js';
20
19
  export type { AgentBackend, BackendObservation, BackendRequest, BackendResponse, ContentBlock, TextBlock, ToolUseBlock, ThinkingBlock, RedactedThinkingBlock, LlmMessage, RequestContentBlock, RequestVideoBlock, ToolResultBlock, TokenUsage, StreamEvent } from './types.js';
21
20
  import type { AgentBackend, BackendRequest, BackendResponse, StreamEvent } from './types.js';
22
- import { AccountPool, type RotationMode } from './account_rotation.js';
23
21
  import type { Message } from '../../types.js';
24
22
  export interface CreateBackendOptions {
25
23
  bedrock?: BedrockBackendConfig;
@@ -33,31 +31,12 @@ export interface CreateBackendOptions {
33
31
  extraHeaders?: Record<string, string>;
34
32
  /** Path appended to baseUrl for chat completions (default `/chat/completions`). */
35
33
  apiPath?: string;
36
- /** Account pool: env CLAUDE_CONFIG_DIR for the spawned `claude` (claude_code). */
37
- claudeConfigDir?: string;
38
34
  /** Account pool: env CODEX_HOME for the spawned `codex app-server` (codex_app_server). */
39
35
  codexHome?: string;
40
36
  /** Account pool: auth.json path for CodexAuthManager (codex_legacy). */
41
37
  codexAuthFilePath?: string;
42
- /** Account pool: .credentials.json path for ClaudeCodeAuthManager (claude_code_direct). */
43
- claudeCredsFilePath?: string;
44
38
  /** Account pool: kimi-code.json path for KimiCodeAuthManager (kimi_code). */
45
39
  kimiCredsFilePath?: string;
46
- /**
47
- * Shared-keychain reader for the AMBIENT claude_code_direct path (injectable for
48
- * tests; undefined in prod = the default macOS keychain lookup). A POOLED build
49
- * (claudeCredsFilePath set) always suppresses the keychain and never consults
50
- * this, so a pooled account with no isolated creds fails closed.
51
- */
52
- keychainReader?: () => string | undefined;
53
- /** Auto-rotate: the live pool. When set with `rotation`, wraps in a RotatingBackend. */
54
- rotationPool?: AccountPool;
55
- /** Auto-rotate policy. Present only when the caller opted this build into rotation. */
56
- rotation?: {
57
- mode: RotationMode;
58
- defaultCooldownMs: number;
59
- weeklyCooldownMs: number;
60
- };
61
40
  }
62
41
  export declare class TracedBackend implements AgentBackend {
63
42
  private readonly provider;
@@ -67,8 +46,8 @@ export declare class TracedBackend implements AgentBackend {
67
46
  constructor(provider: string, backend: AgentBackend);
68
47
  getModelCapabilities(model: string): import("../../utils/router_catalog.js").RouterModelCapabilities | undefined;
69
48
  steerUserMessage(message: Message): Promise<boolean>;
70
- /** Forward disposal so a process-backed inner (RotatingBackend, codex child)
71
- * is closed when the agent is. Without this, tracing (ZTC_BACKEND_TRACE=1)
49
+ /** Forward disposal so a process-backed inner (a codex child) is closed when
50
+ * the agent is. Without this, tracing (ZTC_BACKEND_TRACE=1)
72
51
  * leaks the child on every agent swap/dispose. */
73
52
  close(): void;
74
53
  /** Forward the wrapped backend's per-request streaming nature so the agent's path choice is unchanged by tracing. */
@@ -13,9 +13,8 @@ export { CodexAppServerBackend, CodexAppServerClient } from './codex_app_server.
13
13
  export { CodexAuthBackend, CodexAuthManager, CODEX_AUTH_FILE_PATH, CODEX_AUTH_SENTINEL } from './codex_auth.js';
14
14
  export { CODEX_APP_SERVER_PROVIDER, CODEX_APP_SERVER_SENTINEL, CODEX_LEGACY_PROVIDER, normalizeProviderId } from './provider_ids.js';
15
15
  export { ClarifaiBackend, normalizeClarifaiModel, CLARIFAI_BASE_URL } from './clarifai.js';
16
- export { ClaudeCodeAuthBackend, ClaudeCodeAuthManager } from './claude_code_auth.js';
17
16
  export { KimiCodeAuthBackend, KimiCodeAuthManager, KIMI_CODE_AUTH_SENTINEL, KIMI_CODE_PROVIDER, hasUsableKimiCodeAuth } from './kimi_code_auth.js';
18
- export { ClaudeCliBackend, ClaudeCliError, CLAUDE_CODE_AUTH_SENTINEL, hasUsableClaudeCodeCliAuth as hasUsableClaudeCodeAuth } from './claude_cli.js';
17
+ export { RetiredProviderError } from '../../config/retired_routes.js';
19
18
  import { AnthropicBackend } from './anthropic.js';
20
19
  import { deepseekRequestParams } from '../../utils/deepseek.js';
21
20
  import { OpenAIBackend } from './openai.js';
@@ -26,14 +25,11 @@ import { KimiBackend } from './kimi.js';
26
25
  import { CodexAppServerBackend, CODEX_SUBSCRIPTION_CONFIG_ARGS, buildCodexAppServerEnv } from './codex_app_server.js';
27
26
  import { CodexAuthManager, CodexAuthBackend } from './codex_auth.js';
28
27
  import { ClarifaiBackend } from './clarifai.js';
29
- import { ClaudeCodeAuthBackend, ClaudeCodeAuthManager } from './claude_code_auth.js';
30
28
  import { KimiCodeAuthBackend, KimiCodeAuthManager } from './kimi_code_auth.js';
31
- import { ClaudeCliBackend } from './claude_cli.js';
32
29
  import { ZRouterStreamBackend } from './zrouter_stream.js';
33
30
  import { CODEX_APP_SERVER_PROVIDER, CODEX_LEGACY_PROVIDER, normalizeProviderId } from './provider_ids.js';
34
31
  import { writeBackendTrace } from './trace.js';
35
- import { accountSourceToBackendOptions } from './account_pool.js';
36
- import { RotatingBackend } from './account_rotation.js';
32
+ import { assertProviderNotRetired } from '../../config/retired_routes.js';
37
33
  export class TracedBackend {
38
34
  provider;
39
35
  backend;
@@ -47,8 +43,8 @@ export class TracedBackend {
47
43
  async steerUserMessage(message) {
48
44
  return this.backend.steerUserMessage?.(message) ?? false;
49
45
  }
50
- /** Forward disposal so a process-backed inner (RotatingBackend, codex child)
51
- * is closed when the agent is. Without this, tracing (ZTC_BACKEND_TRACE=1)
46
+ /** Forward disposal so a process-backed inner (a codex child) is closed when
47
+ * the agent is. Without this, tracing (ZTC_BACKEND_TRACE=1)
52
48
  * leaks the child on every agent swap/dispose. */
53
49
  close() {
54
50
  this.backend.close?.();
@@ -128,31 +124,9 @@ export function createBackendForProvider(provider, opts) {
128
124
  throw new Error('Required Router origin must be a credential-free HTTPS origin');
129
125
  return traced(provider, new ZRouterStreamBackend({ provider, model: 'gpt-6.1-sol', apiKey, proxyUrl: origin.origin }));
130
126
  }
131
- // Auto-rotate non-Codex providers only: when the caller opted in and >1
132
- // account is REGISTERED, wrap the concrete backend so a 429 cools the active account and
133
- // fails over. Gate on registered (not ready) count: with one ready account and
134
- // the config-active pointer on a different cooling/logged-out one, a ready-only
135
- // gate would build directly on the stale active and hard-fail the first turn —
136
- // the wrapper's selectActive is what moves off it. The inner build recurses
137
- // with rotation cleared + the chosen account's source.
138
- if (normalizeProviderId(provider) !== CODEX_APP_SERVER_PROVIDER
139
- && normalizeProviderId(provider) !== CODEX_LEGACY_PROVIDER
140
- && opts.rotation && opts.rotationPool && opts.rotationPool.accountsFor(provider).length > 1) {
141
- const pool = opts.rotationPool;
142
- return traced(provider, new RotatingBackend({
143
- provider,
144
- pool,
145
- mode: opts.rotation.mode,
146
- defaultCooldownMs: opts.rotation.defaultCooldownMs,
147
- weeklyCooldownMs: opts.rotation.weeklyCooldownMs,
148
- buildInner: (account) => createBackendForProvider(provider, {
149
- ...opts,
150
- rotation: undefined,
151
- rotationPool: undefined,
152
- ...accountSourceToBackendOptions(account.source),
153
- }),
154
- }));
155
- }
127
+ // Claude Code is no longer a model backend: Anthropic reserves subscription
128
+ // sign-in for Claude Code itself. Say where to go instead of "unknown provider".
129
+ assertProviderNotRetired(provider);
156
130
  const resolvedProvider = normalizeProviderId(provider);
157
131
  switch (resolvedProvider) {
158
132
  case 'bedrock': return traced(provider, new BedrockBackend(opts.bedrock));
@@ -198,7 +172,7 @@ export function createBackendForProvider(provider, opts) {
198
172
  sandbox: opts.codexAppServerSandbox,
199
173
  // Point the spawned app-server at this account's codex home AND scrub a
200
174
  // stray OPENAI_API_KEY so it uses the account's ChatGPT subscription, not
201
- // an API key (mirrors the claude_code ANTHROPIC_API_KEY scrub).
175
+ // an API key.
202
176
  env: buildCodexAppServerEnv(opts.codexHome),
203
177
  requireChatGptSubscription: opts.codexHome !== undefined,
204
178
  }));
@@ -208,28 +182,6 @@ export function createBackendForProvider(provider, opts) {
208
182
  authManager.loadCredentialsSync();
209
183
  return traced(provider, new CodexAuthBackend(authManager));
210
184
  }
211
- case 'claude_code':
212
- case 'claude-code':
213
- // Per-account: spawn `claude` with this account's CLAUDE_CONFIG_DIR.
214
- return traced(provider, new ClaudeCliBackend(opts.claudeConfigDir
215
- ? { env: { ...process.env, CLAUDE_CONFIG_DIR: opts.claudeConfigDir } }
216
- : undefined));
217
- case 'claude_code_direct':
218
- case 'claude-code-direct': {
219
- // Per-account: read this account's .credentials.json (default ~/.claude when
220
- // unset). For a POOLED account, suppress the ambient CLAUDE_CODE_OAUTH_TOKEN
221
- // (envToken: null) — loadCredentialsSync prefers an env token over the file,
222
- // so a stray global token would override every account with one identity —
223
- // AND suppress the shared macOS keychain (keychainReader: () => undefined):
224
- // a pooled account with no isolated creds must fail closed, not fall back to
225
- // the one ambient keychain identity every pooled account would share. The
226
- // ambient (non-pooled) path keeps env-token + keychain precedence unchanged.
227
- const authManager = new ClaudeCodeAuthManager(opts.claudeCredsFilePath
228
- ? { credentialsFilePath: opts.claudeCredsFilePath, envToken: null, keychainReader: () => undefined }
229
- : (opts.keychainReader ? { keychainReader: opts.keychainReader } : undefined));
230
- authManager.loadCredentialsSync();
231
- return traced(provider, new ClaudeCodeAuthBackend(authManager, opts.apiEndpoint));
232
- }
233
185
  case 'kimi_code':
234
186
  case 'kimi-code': {
235
187
  // Per-account: read this account's kimi-code.json (default ~/.kimi-code
@@ -21,7 +21,7 @@ export declare const KIMI_CODE_AUTH_SENTINEL = "kimi-code-oauth";
21
21
  /**
22
22
  * A refresh the server rejected as dead (401/403/invalid_grant). Carries the
23
23
  * HTTP status so classifyFailover() maps it to the 'auth' failover kind and
24
- * the rotation engine cools the account instead of hard-failing the turn.
24
+ * the turn asks for a new sign-in instead of failing with an opaque error.
25
25
  */
26
26
  export declare class OAuthUnauthorizedError extends Error {
27
27
  readonly status: number;
@@ -40,7 +40,7 @@ const DEFAULT_TOKEN_EXPIRES_IN_SECONDS = 3600;
40
40
  /**
41
41
  * A refresh the server rejected as dead (401/403/invalid_grant). Carries the
42
42
  * HTTP status so classifyFailover() maps it to the 'auth' failover kind and
43
- * the rotation engine cools the account instead of hard-failing the turn.
43
+ * the turn asks for a new sign-in instead of failing with an opaque error.
44
44
  */
45
45
  export class OAuthUnauthorizedError extends Error {
46
46
  status;
@@ -352,7 +352,7 @@ export class KimiCodeAuthBackend {
352
352
  }
353
353
  }
354
354
  }
355
- /** Convert a 429 into the typed RateLimitError the rotation engine acts on. */
355
+ /** Convert a 429 into the typed RateLimitError, which says when the limit resets (see rate_limit.ts). */
356
356
  function rethrowKimiError(error) {
357
357
  if (error instanceof OpenAICompatibleApiError && error.status === 429) {
358
358
  const now = Date.now();
@@ -7,4 +7,9 @@ export declare function normalizeProviderId(provider: string): string;
7
7
  export declare function isCodexAppServerProvider(provider: string): boolean;
8
8
  export declare function isCodexLegacyProvider(provider: string): boolean;
9
9
  export declare function getProviderDisplayName(provider: string): string;
10
+ /**
11
+ * Providers that run on a subscription login on this machine (Codex, Kimi
12
+ * Code) rather than an API key. The one list every surface consults: they
13
+ * route direct, never through Zerg Router, and switch accounts in /accounts.
14
+ */
10
15
  export declare function isLocalSubscriptionProvider(provider: string): boolean;
@@ -37,7 +37,12 @@ export function getProviderDisplayName(provider) {
37
37
  return provider;
38
38
  }
39
39
  }
40
+ /**
41
+ * Providers that run on a subscription login on this machine (Codex, Kimi
42
+ * Code) rather than an API key. The one list every surface consults: they
43
+ * route direct, never through Zerg Router, and switch accounts in /accounts.
44
+ */
40
45
  export function isLocalSubscriptionProvider(provider) {
41
- return ['codex_app_server', 'codex_legacy', 'claude_code', 'claude-code', 'claude_code_direct', 'claude-code-direct', 'kimi_code', 'kimi-code']
46
+ return ['codex_app_server', 'codex_legacy', 'kimi_code', 'kimi-code']
42
47
  .includes(normalizeProviderId(provider));
43
48
  }