@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,11 +1,12 @@
1
1
  /**
2
- * Typed rate-limit signal for the account-rotation engine (S2).
2
+ * Typed rate-limit signal.
3
3
  *
4
- * Each backend that can hit a subscription usage/rate limit throws a
5
- * {@link RateLimitError} so the {@link RotatingBackend} can cool the offending
6
- * account and fail over to the next ready one. Keeping this in its own module
7
- * keeps it dependency-free (no backend/config imports) so every backend and the
8
- * pool can import it without a cycle.
4
+ * Each backend that can hit a subscription usage/rate limit (Codex, Kimi Code)
5
+ * throws a {@link RateLimitError} carrying when the limit resets, so callers
6
+ * can say when to retry and worker model pools (model_pool.ts, failover.ts)
7
+ * can skip a limited model for a cooldown. Accounts never switch on their own.
8
+ * Keeping this in its own module keeps it dependency-free (no backend/config
9
+ * imports) so every backend can import it without a cycle.
9
10
  */
10
11
  export interface RateLimitInfo {
11
12
  /** Provider id of the backend that was limited. */
@@ -41,13 +42,3 @@ export declare function parseResetAt(opts: {
41
42
  resetEpochSeconds?: number | null;
42
43
  resetEpochMs?: number | null;
43
44
  }): number | undefined;
44
- /**
45
- * Best-effort reset + weekly-cap hint from an Anthropic/Claude error body. The
46
- * 429 body is the only signal available on AnthropicApiError (no headers), so we
47
- * probe the documented-ish fields and fall through to undefined (default
48
- * cooldown) when none parse. `weekly` is inferred from the message text.
49
- */
50
- export declare function anthropicRateLimitHint(body: string, now: number): {
51
- resetAt?: number;
52
- weekly: boolean;
53
- };
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Typed rate-limit signal for the account-rotation engine (S2).
2
+ * Typed rate-limit signal.
3
3
  *
4
- * Each backend that can hit a subscription usage/rate limit throws a
5
- * {@link RateLimitError} so the {@link RotatingBackend} can cool the offending
6
- * account and fail over to the next ready one. Keeping this in its own module
7
- * keeps it dependency-free (no backend/config imports) so every backend and the
8
- * pool can import it without a cycle.
4
+ * Each backend that can hit a subscription usage/rate limit (Codex, Kimi Code)
5
+ * throws a {@link RateLimitError} carrying when the limit resets, so callers
6
+ * can say when to retry and worker model pools (model_pool.ts, failover.ts)
7
+ * can skip a limited model for a cooldown. Accounts never switch on their own.
8
+ * Keeping this in its own module keeps it dependency-free (no backend/config
9
+ * imports) so every backend can import it without a cycle.
9
10
  */
10
11
  export class RateLimitError extends Error {
11
12
  provider;
@@ -47,26 +48,3 @@ export function parseResetAt(opts) {
47
48
  }
48
49
  return undefined;
49
50
  }
50
- /**
51
- * Best-effort reset + weekly-cap hint from an Anthropic/Claude error body. The
52
- * 429 body is the only signal available on AnthropicApiError (no headers), so we
53
- * probe the documented-ish fields and fall through to undefined (default
54
- * cooldown) when none parse. `weekly` is inferred from the message text.
55
- */
56
- export function anthropicRateLimitHint(body, now) {
57
- let resetAt;
58
- try {
59
- const data = JSON.parse(body);
60
- const retryAfter = Number(data?.error?.retry_after ?? data?.retry_after);
61
- const resetsAt = Number(data?.error?.resets_at ?? data?.resets_at);
62
- resetAt = parseResetAt({
63
- now,
64
- retryAfterSeconds: Number.isFinite(retryAfter) ? retryAfter : undefined,
65
- resetEpochSeconds: Number.isFinite(resetsAt) ? resetsAt : undefined,
66
- });
67
- }
68
- catch {
69
- // Non-JSON body (e.g. the CLI's plain-text usage-limit line) -> default cooldown.
70
- }
71
- return { resetAt, weekly: /week/i.test(body) };
72
- }
@@ -203,11 +203,6 @@ export interface BackendRequest {
203
203
  * The agent aborts this for BOTH a user cancel AND a per-attempt inactivity
204
204
  * timeout, so its aborted-ness alone can't tell the two apart. */
205
205
  signal?: AbortSignal;
206
- /** The caller's cancel signal, distinct from {@link signal}: aborted ONLY on a
207
- * real user cancel, never on the inactivity-timeout watchdog. Rotation uses it
208
- * to skip failover on a cancel while still rotating away from a hung account on
209
- * a timeout. */
210
- userSignal?: AbortSignal;
211
206
  /** Optional per-request timeout, used by the agent watchdog. */
212
207
  timeoutMs?: number;
213
208
  /**
@@ -1,13 +1,17 @@
1
1
  /**
2
- * `/accounts` — manage the pool of switchable Claude Code + Codex subscription
2
+ * `/accounts` — manage the pool of switchable Codex and Kimi Code subscription
3
3
  * accounts. ztc stores only ids/labels/paths; tokens live in each account's own
4
- * credential dir, written by the official CLI's own login. Subcommands:
4
+ * credential dir, written by the official CLI's own login. Accounts switch only
5
+ * when the user chooses one. Subcommands:
5
6
  *
6
7
  * /accounts open the account manager (or list in plain output)
7
8
  * /accounts add <provider> <id> [label…] [--path <dir>]
8
9
  * /accounts use <id> make an account the live one for its provider
9
10
  * /accounts login <id> run the official CLI login at the account's dir
10
11
  * /accounts remove <id> drop an account from the pool
12
+ *
13
+ * Claude accounts are Claude Code sign-in profiles now (/subs, /claude @name):
14
+ * the old Claude verbs answer with where that account went.
11
15
  */
12
16
  import { Command, CommandContext } from './types.js';
13
17
  /**
@@ -1,25 +1,52 @@
1
1
  /**
2
- * `/accounts` — manage the pool of switchable Claude Code + Codex subscription
2
+ * `/accounts` — manage the pool of switchable Codex and Kimi Code subscription
3
3
  * accounts. ztc stores only ids/labels/paths; tokens live in each account's own
4
- * credential dir, written by the official CLI's own login. Subcommands:
4
+ * credential dir, written by the official CLI's own login. Accounts switch only
5
+ * when the user chooses one. Subcommands:
5
6
  *
6
7
  * /accounts open the account manager (or list in plain output)
7
8
  * /accounts add <provider> <id> [label…] [--path <dir>]
8
9
  * /accounts use <id> make an account the live one for its provider
9
10
  * /accounts login <id> run the official CLI login at the account's dir
10
11
  * /accounts remove <id> drop an account from the pool
12
+ *
13
+ * Claude accounts are Claude Code sign-in profiles now (/subs, /claude @name):
14
+ * the old Claude verbs answer with where that account went.
11
15
  */
16
+ import { homedir } from 'node:os';
17
+ import { isAbsolute } from 'node:path';
12
18
  import { configStore } from '../../config.js';
13
19
  import { canonicalAccountProvider, defaultAccountDir, defaultSourceFor, findCodexHomeCollision, isAccountProvider, probeAccountUsable, sourceDir, } from '../backends/account_pool.js';
14
20
  import { codexStatusCache } from '../backends/codex_account_status.js';
15
- import { applyAccountOp } from '../../web/accounts_mirror.js';
21
+ import { isRetiredProvider } from '../../config/retired_ids.js';
22
+ import { expandHomePath } from '../../config/retired_routes.js';
23
+ import { ensureAgentProfile, isProfileName, listAgentProfiles } from '../../panes/agent_profiles.js';
24
+ import { applyAccountOp, CLAUDE_ACCOUNTS_MOVED } from '../../web/accounts_mirror.js';
25
+ import { subsCommand } from './subs.js';
16
26
  const PROVIDER_LABELS = {
17
- claude_code: 'Claude Code (claude CLI)',
18
27
  codex_app_server: 'Codex (codex app-server)',
19
28
  codex_legacy: 'Codex (direct chatgpt.com)',
20
- claude_code_direct: 'Claude Code (direct Anthropic)',
21
29
  kimi_code: 'Kimi Code (subscription)',
22
30
  };
31
+ /** Accounts never switch on their own, for any provider: switching the account that pays is the user's choice. */
32
+ const ACCOUNTS_SWITCH_ON_CHOICE = 'Accounts switch only when you choose one: automatic rotation is gone for every provider, Codex and Kimi Code included.';
33
+ const ROTATION_RETIRED = 'Automatic account rotation is retired: accounts switch only when you choose one (/accounts use <id>).';
34
+ /**
35
+ * The Claude Code profile an old Claude account id names now: the profile the
36
+ * move made from that account (its name may differ), else a profile of that name.
37
+ */
38
+ function claudeProfileFor(id) {
39
+ const panes = configStore.get().panes;
40
+ const profiles = listAgentProfiles('claude', undefined, panes?.agentProfileDirs?.claude ?? {});
41
+ const moved = panes?.agentProfileAccountIds?.claude?.[id];
42
+ if (moved && profiles.includes(moved))
43
+ return moved;
44
+ return profiles.includes(id) ? id : undefined;
45
+ }
46
+ function claudeProfileRedirect(id, profile) {
47
+ const now = profile === id ? `"${id}" is a Claude Code sign-in profile now` : `"${id}" is the Claude Code sign-in profile @${profile} now`;
48
+ return `${now}: /claude @${profile} opens it in a pane, and /subs use claude ${profile} makes new Claude Code panes start on it.`;
49
+ }
23
50
  function say(ctx, content) {
24
51
  ctx.addMessage({ role: 'system', content });
25
52
  }
@@ -32,9 +59,10 @@ function usage() {
32
59
  ' /accounts use <id> switch the live account for its provider',
33
60
  ' /accounts login <id> sign in an account (official CLI or device flow)',
34
61
  ' /accounts remove <id> remove an account',
35
- ' /accounts rotation [on|off|mode …|subagents …] view/configure auto-rotate',
36
62
  '',
37
63
  `Providers: ${Object.keys(PROVIDER_LABELS).join(', ')}`,
64
+ ACCOUNTS_SWITCH_ON_CHOICE,
65
+ 'Claude accounts are Claude Code sign-in profiles: /subs, and /claude @<name> to open one.',
38
66
  ].join('\n');
39
67
  }
40
68
  /**
@@ -92,8 +120,7 @@ async function renderList(ctx) {
92
120
  lines.push(` ${account.source.kind}: ${account.source.path}`);
93
121
  }
94
122
  }
95
- const rotation = configStore.getRotation();
96
- lines.push('', `* = live account for that provider. Auto-rotate (Claude/Kimi only): ${rotation.enabled ? `ON (${rotation.mode})` : 'off'}. Codex switches only when you choose an account.`);
123
+ lines.push('', '* = live account for that provider. Accounts switch only when you choose one.');
97
124
  say(ctx, lines.join('\n'));
98
125
  }
99
126
  function parseAdd(args) {
@@ -113,11 +140,38 @@ function parseAdd(args) {
113
140
  const [provider, id, ...labelParts] = positional;
114
141
  if (!provider || !id)
115
142
  return `Missing provider or id.\n\n${usage()}`;
143
+ if (isRetiredProvider(provider))
144
+ return { claudeProfile: { id, path } };
116
145
  if (!isAccountProvider(provider)) {
117
146
  return `Unknown provider "${provider}". One of: ${Object.keys(PROVIDER_LABELS).join(', ')}.`;
118
147
  }
119
148
  return { provider, id, label: labelParts.join(' ') || id, path };
120
149
  }
150
+ /**
151
+ * `/accounts add claude_code <id> [--path <dir>]`: a Claude account is a Claude
152
+ * Code sign-in profile now, so make that profile, on the given Claude Code
153
+ * config directory when there is one, and say how to open it.
154
+ */
155
+ async function addClaudeProfile(id, path, ctx) {
156
+ if (!isProfileName(id)) {
157
+ return `${CLAUDE_ACCOUNTS_MOVED}\n"${id}" can't be a profile name: use letters, digits, ".", "_" or "-", up to 32.`;
158
+ }
159
+ const panes = ctx.config.get().panes ?? {};
160
+ const registered = panes.agentProfileDirs?.claude ?? {};
161
+ if (path === undefined) {
162
+ ensureAgentProfile('claude', id, undefined, registered);
163
+ return `${CLAUDE_ACCOUNTS_MOVED}\nMade the "${id}" profile: open it with /claude @${id} and sign in there the first time.`;
164
+ }
165
+ const dir = expandHomePath(path.trim(), homedir());
166
+ if (!isAbsolute(dir)) {
167
+ return `"${path}" is not a full path: give the full path of the Claude Code config directory, for example ~/claude-work.`;
168
+ }
169
+ const claude = { ...registered, [id]: dir };
170
+ ensureAgentProfile('claude', id, undefined, claude);
171
+ ctx.config.set('panes', { ...panes, agentProfileDirs: { ...panes.agentProfileDirs, claude } });
172
+ await ctx.config.save();
173
+ return `${CLAUDE_ACCOUNTS_MOVED}\nMade the "${id}" profile on ${dir}: open it with /claude @${id}; Claude Code keeps any sign-in it has there.`;
174
+ }
121
175
  /** All mutating CLI and terminal-panel actions use the same owner admission and
122
176
  * canonical operation as the mirror. The owner callback holds its runtime lease. */
123
177
  async function applyOperation(body, ctx) {
@@ -147,6 +201,10 @@ async function handleAdd(args, ctx) {
147
201
  say(ctx, parsed);
148
202
  return;
149
203
  }
204
+ if ('claudeProfile' in parsed) {
205
+ say(ctx, await addClaudeProfile(parsed.claudeProfile.id, parsed.claudeProfile.path, ctx));
206
+ return;
207
+ }
150
208
  const result = await addAccount(parsed, ctx);
151
209
  if ('error' in result) {
152
210
  say(ctx, result.message);
@@ -169,6 +227,12 @@ async function handleUse(args, ctx) {
169
227
  say(ctx, 'Usage: /accounts use <id>');
170
228
  return;
171
229
  }
230
+ // An old Claude account id names a Claude Code profile now.
231
+ const profile = configStore.getAccount(id) ? undefined : claudeProfileFor(id);
232
+ if (profile) {
233
+ say(ctx, claudeProfileRedirect(id, profile));
234
+ return;
235
+ }
172
236
  showOperationResult(await applyOperation({ op: 'use', id }, ctx), ctx);
173
237
  }
174
238
  async function handleLogin(args, ctx) {
@@ -177,61 +241,15 @@ async function handleLogin(args, ctx) {
177
241
  say(ctx, 'Usage: /accounts login <id>');
178
242
  return;
179
243
  }
244
+ const profile = configStore.getAccount(id) ? undefined : claudeProfileFor(id);
245
+ if (profile) {
246
+ say(ctx, `${claudeProfileRedirect(id, profile)} Claude Code asks you to sign in there the first time.`);
247
+ return;
248
+ }
180
249
  // The canonical operation returns pending while the official/device login
181
250
  // runs. Completion notification and idle-safe reload belong to the owner.
182
251
  showOperationResult(await applyOperation({ op: 'login', id }, ctx), ctx);
183
252
  }
184
- function describeRotation() {
185
- const r = configStore.getRotation();
186
- const hours = (ms) => `${Math.round((ms / 3_600_000) * 10) / 10}h`;
187
- return [
188
- `Auto-rotate (Claude/Kimi): ${r.enabled ? 'ON' : 'off'}`,
189
- ' Codex: manual selection only',
190
- ` mode: ${r.mode}`,
191
- ` subagents: ${r.subagentInheritance}`,
192
- ` cooldowns: default ${hours(r.defaultCooldownMs)}, weekly ${hours(r.weeklyCooldownMs)}`,
193
- '',
194
- 'Change: /accounts rotation on|off · mode failover|round_robin · subagents inherit|pool',
195
- ].join('\n');
196
- }
197
- async function handleRotation(args, ctx) {
198
- const [field, value] = args;
199
- if (!field) {
200
- say(ctx, describeRotation());
201
- return;
202
- }
203
- const patch = { op: 'rotation' };
204
- switch (field) {
205
- case 'on':
206
- patch.enabled = true;
207
- break;
208
- case 'off':
209
- patch.enabled = false;
210
- break;
211
- case 'mode':
212
- if (value !== 'failover' && value !== 'round_robin') {
213
- say(ctx, 'Usage: /accounts rotation mode failover|round_robin');
214
- return;
215
- }
216
- patch.mode = value;
217
- break;
218
- case 'subagents':
219
- if (value !== 'inherit' && value !== 'pool') {
220
- say(ctx, 'Usage: /accounts rotation subagents inherit|pool');
221
- return;
222
- }
223
- patch.subagentInheritance = value;
224
- break;
225
- default:
226
- say(ctx, `Unknown rotation field "${field}".\n\n${describeRotation()}`);
227
- return;
228
- }
229
- const result = await applyOperation(patch, ctx);
230
- if (!result.ok)
231
- showOperationResult(result, ctx);
232
- else
233
- say(ctx, describeRotation());
234
- }
235
253
  async function handleRemove(args, ctx) {
236
254
  const id = args[0];
237
255
  if (!id) {
@@ -242,16 +260,12 @@ async function handleRemove(args, ctx) {
242
260
  }
243
261
  // --- interactive terminal settings page (text list in non-interactive output) ---
244
262
  function accountFamily(provider) {
245
- if (provider.startsWith('claude_code'))
246
- return 'Claude';
247
- if (provider.startsWith('codex_'))
248
- return 'Codex';
249
- return 'Kimi';
263
+ return provider.startsWith('codex_') ? 'Codex' : 'Kimi';
250
264
  }
251
265
  function interactiveAddPage(ctx, provider, onBack) {
252
266
  const selected = configStore.getProvider();
253
267
  const draft = {
254
- provider: provider ?? (isAccountProvider(selected) ? selected : 'claude_code'),
268
+ provider: provider ?? (isAccountProvider(selected) ? selected : 'codex_app_server'),
255
269
  id: '', label: '', path: '',
256
270
  };
257
271
  const originalFamily = provider ? accountFamily(provider) : undefined;
@@ -366,7 +380,6 @@ export function openAccountsManager(ctx, options = {}) {
366
380
  async function runInteractive(ctx, focus, onBack) {
367
381
  const accounts = configStore.listAccounts();
368
382
  const families = [
369
- { name: 'Claude', provider: 'claude_code', matches: account => account.provider.startsWith('claude_code') },
370
383
  { name: 'Codex', provider: 'codex_app_server', matches: account => account.provider.startsWith('codex_') },
371
384
  { name: 'Kimi', provider: 'kimi_code', matches: account => account.provider === 'kimi_code' },
372
385
  ];
@@ -447,10 +460,24 @@ async function runInteractive(ctx, focus, onBack) {
447
460
  ],
448
461
  };
449
462
  }));
463
+ // Where Claude accounts went: Claude Code sign-in profiles, listed by /subs.
464
+ categories.push({
465
+ name: 'Claude',
466
+ settings: [{
467
+ name: 'claudeProfiles',
468
+ label: 'Claude Code → profiles',
469
+ value: '/subs',
470
+ type: 'text',
471
+ description: `${CLAUDE_ACCOUNTS_MOVED} Enter lists them (/subs).`,
472
+ onActivate: () => {
473
+ ctx.settingsPanel?.closeSettingsPanel?.();
474
+ void subsCommand.handler([], ctx);
475
+ },
476
+ }],
477
+ });
450
478
  const provider = configStore.getProvider();
451
479
  const defaultFocus = provider.startsWith('codex_') ? 'Codex'
452
- : provider.startsWith('claude_code') ? 'Claude'
453
- : provider === 'kimi_code' ? 'Kimi' : undefined;
480
+ : provider === 'kimi_code' ? 'Kimi' : undefined;
454
481
  ctx.settingsPanel?.showSettingsPanel({
455
482
  title: 'Accounts', categories, initialCategory: focus ?? defaultFocus,
456
483
  onSettingChange: () => { },
@@ -459,7 +486,7 @@ async function runInteractive(ctx, focus, onBack) {
459
486
  }
460
487
  export const accountsCommand = {
461
488
  name: 'accounts',
462
- description: 'Manage switchable Claude Code + Codex + Kimi subscription accounts',
489
+ description: 'Manage switchable Codex and Kimi Code accounts (Claude Code profiles: /subs)',
463
490
  usage: '[add|use|login|remove] …',
464
491
  handler: async (args, ctx) => {
465
492
  const [sub, ...rest] = args;
@@ -503,7 +530,7 @@ export const accountsCommand = {
503
530
  return;
504
531
  case 'rotation':
505
532
  case 'rotate':
506
- await handleRotation(rest, ctx);
533
+ say(ctx, ROTATION_RETIRED);
507
534
  return;
508
535
  case 'help':
509
536
  say(ctx, usage());
@@ -54,9 +54,11 @@ export const compactCommand = {
54
54
  role: 'system',
55
55
  content: `Compacting conversation (${Math.round(status.percentage)}% -> ${shownTarget}% target)...`,
56
56
  });
57
- // Determine summarizer based on provider and API key availability
57
+ // Determine summarizer based on provider and API key availability. A
58
+ // profile waiting for a route choice has none to summarize on, so the
59
+ // local summarizer runs (see ConfigStore.getRequestApiKey).
58
60
  const provider = ctx.config.getProvider();
59
- const apiKey = ctx.config.getApiKey(provider);
61
+ const apiKey = ctx.config.getRequestApiKey ? ctx.config.getRequestApiKey(provider) : ctx.config.getApiKey(provider);
60
62
  const summarizer = async (msgs) => {
61
63
  if (apiKey) {
62
64
  return smartSummarizer(msgs, { provider, apiKey });
@@ -7,7 +7,8 @@ import { contextProgressBarConfig, normalizeBarColor, publishContextProgressBar,
7
7
  import { compatEndpoint, DEFAULT_CONTEXT_PROGRESS_BAR, maskApiKey } from '../../config.js';
8
8
  import { parseGoalTurnCap } from './goal.js';
9
9
  import { getSupportedCodexReasoningEfforts, isCodexReasoningEffortSupported, unsupportedEffortMessage, } from '../../utils/models.js';
10
- import { modelForProviderSwitch, resolveModelForProviderChange } from './provider_model_defaults.js';
10
+ import { modelForProviderSwitch } from './provider_model_defaults.js';
11
+ import { CLAUDE_CODE_TOKEN_MESSAGE, isClaudeCodeToken, isRetiredProvider, retiredProviderMessage } from '../../config/retired_routes.js';
11
12
  import { applyRuntimeModelSelection, getEffectiveModel } from './runtime_model.js';
12
13
  import { shutdownAndClearWorkflowRegistry } from '../../workflows/registry_handle.js';
13
14
  import { formatRate } from '../../utils/openrouter_prices.js';
@@ -145,14 +146,15 @@ function pickKeyProvider(ctx) {
145
146
  }
146
147
  /**
147
148
  * Put a key just saved to use: the running agent rebuilds when it belongs to
148
- * the active provider; otherwise, with no model connected, ZTC offers to
149
- * switch to that provider.
149
+ * the active provider and its route can use it; otherwise, with no model
150
+ * connected (another provider, or this one on a route that waits for a ZergAI
151
+ * login), ZTC offers to switch to that provider with the key.
150
152
  */
151
153
  function useSavedKey(provider, ctx) {
154
+ if (offerKeyedProviderSwitch(provider, ctx))
155
+ return;
152
156
  if (normalizeProviderId(provider) === normalizeProviderId(ctx.config.getProvider()))
153
157
  ctx.reloadAgent();
154
- else
155
- offerKeyedProviderSwitch(provider, ctx);
156
158
  }
157
159
  /**
158
160
  * After the key choices of `/config key`: a key or a set variable is put to
@@ -172,6 +174,10 @@ function useKeyChange(provider, ctx, change) {
172
174
  * once it is saved, switches; `credentialPrompted` keeps that retry from asking twice.
173
175
  */
174
176
  async function setConfigProvider(value, ctx, credentialPrompted = false) {
177
+ if (isRetiredProvider(value)) {
178
+ ctx.addMessage({ role: 'system', content: retiredProviderMessage(value, ctx.config.getProvider()) });
179
+ return;
180
+ }
175
181
  const provider = canonicalProvider(value) ?? value;
176
182
  // Verify the target actually builds a backend BEFORE persisting — an
177
183
  // unbuildable provider written to config.json makes the NEXT boot start
@@ -182,7 +188,8 @@ async function setConfigProvider(value, ctx, credentialPrompted = false) {
182
188
  const currentModel = getEffectiveModel(ctx);
183
189
  const model = modelForProviderSwitch(provider, previousProvider, currentModel);
184
190
  if (provider !== 'openai_compatible') {
185
- const llm = ctx.config.resolveLLMBackendConfig({ provider, model });
191
+ // Checked as it will be once chosen: saving it ends any wait for a route choice.
192
+ const llm = ctx.config.resolveLLMBackendConfig({ provider, model, asChosen: true });
186
193
  if (!isBuildableResolvedConfig(llm)) {
187
194
  if (!credentialPrompted && promptForMissingDirectKey(llm, ctx, () => setConfigProvider(provider, ctx, true)))
188
195
  return;
@@ -190,15 +197,11 @@ async function setConfigProvider(value, ctx, credentialPrompted = false) {
190
197
  return;
191
198
  }
192
199
  }
193
- const resetModel = resolveModelForProviderChange(provider, currentModel);
194
200
  ctx.config.setProvider(provider);
195
201
  ctx.config.set('model', model);
196
202
  await ctx.config.save();
197
203
  applyRuntimeModelSelection(ctx, provider, model);
198
- ctx.addMessage({
199
- role: 'system',
200
- content: `✓ Provider updated: ${provider}${resetModel ? `\n Model reset to ${resetModel} for Claude Code.` : ''}`
201
- });
204
+ ctx.addMessage({ role: 'system', content: `✓ Provider updated: ${provider}` });
202
205
  // Auto-launch the wizard the first time the user picks openai_compatible
203
206
  // (Ollama / vLLM / LM Studio / custom). Skip if a base URL is already set
204
207
  // — they can re-run via `/config openai-compat` to change anything.
@@ -222,7 +225,7 @@ async function setConfigModel(value, ctx, credentialPrompted = false) {
222
225
  // Verify the selection builds a backend BEFORE persisting so an
223
226
  // unbuildable choice never lands in config.json nor earns a false "✓".
224
227
  const activeProvider = ctx.config.getProvider();
225
- const llm = ctx.config.resolveLLMBackendConfig({ provider: activeProvider, model: value });
228
+ const llm = ctx.config.resolveLLMBackendConfig({ provider: activeProvider, model: value, asChosen: true });
226
229
  if (!isBuildableResolvedConfig(llm)) {
227
230
  if (!credentialPrompted && promptForMissingDirectKey(llm, ctx, () => setConfigModel(value, ctx, true)))
228
231
  return;
@@ -232,7 +235,8 @@ async function setConfigModel(value, ctx, credentialPrompted = false) {
232
235
  ctx.config.set('model', value);
233
236
  await ctx.config.save();
234
237
  applyRuntimeModelSelection(ctx, activeProvider, value);
235
- const envPinnedModel = process.env.ZTC_MODEL || process.env.LLM_MODEL;
238
+ // A model variable ignored as a retired Claude Code route pins nothing.
239
+ const envPinnedModel = ctx.config.getEnvironmentModel?.();
236
240
  ctx.addMessage({
237
241
  role: 'system',
238
242
  content: `✓ Model updated: ${value} (${ctx.config.getConfigScope?.() || 'global'} scope)${envPinnedModel ? `\n Deployment currently pins model=${envPinnedModel}; this override may reset on refresh or restart.` : ''}`
@@ -460,7 +464,17 @@ Usage:
460
464
  });
461
465
  return;
462
466
  }
467
+ // A retired Claude Code route takes no key, and a Claude Code sign-in
468
+ // token is never saved as anyone's key.
469
+ if (isRetiredProvider(rest[0])) {
470
+ ctx.addMessage({ role: 'system', content: retiredProviderMessage(rest[0], ctx.config.getProvider()) });
471
+ return;
472
+ }
463
473
  const { provider, apiKey } = parseConfigKeyArgs(rest, ctx.config.getProvider());
474
+ if (isClaudeCodeToken(apiKey)) {
475
+ ctx.addMessage({ role: 'system', content: CLAUDE_CODE_TOKEN_MESSAGE });
476
+ return;
477
+ }
464
478
  if (provider === 'modal' || provider === 'zergrouter' || isLocalSubscription(provider)) {
465
479
  ctx.addMessage({ role: 'system', content: provider === 'modal' || provider === 'zergrouter'
466
480
  ? `${provider} runs through Zerg Router with your ZergAI login. Run /auth login; /config key cannot configure this provider.`
@@ -3,6 +3,8 @@ import { canAskForCredential, promptForDirectCredential } from './direct_credent
3
3
  import { canonicalProvider, canonicalRoute, DIRECT_PROVIDER_CHOICES, describeDirectProvider, isLocalSubscription, modelRouteStatus, } from './provider_choices.js';
4
4
  import { currentRouteReady, formatDirectProviders, selectProviderModel } from './provider_selection.js';
5
5
  import { LOCAL_API_KEYS_LABEL, ZERGAI_LOGIN_BENEFITS, ZERGAI_LOGIN_LABEL, } from '../../onboarding/zergai_login.js';
6
+ import { readProviderApiKeyEnv } from '../../config/provider_api_key_env.js';
7
+ import { isClaudeCodeToken } from '../../config/retired_routes.js';
6
8
  const ROUTE_OPTIONS = [
7
9
  {
8
10
  value: 'zergrouter',
@@ -13,10 +15,72 @@ const ROUTE_OPTIONS = [
13
15
  {
14
16
  value: 'direct',
15
17
  label: LOCAL_API_KEYS_LABEL,
16
- description: 'Paste a provider API key, or use a local Claude Code, Codex or Kimi Code login.',
18
+ description: 'Paste a provider API key, or use a local Codex or Kimi Code login.',
17
19
  },
18
20
  ];
19
21
  const CONNECT_LATER = 'Run /connect any time to log in with ZergAI or use your local API keys.';
22
+ /**
23
+ * Choices that use a key found in the environment (`environment_key:<provider>`),
24
+ * or the Anthropic key the move off the retired Claude Code routes kept apart.
25
+ */
26
+ const ENVIRONMENT_KEY_PREFIX = 'environment_key:';
27
+ const KEPT_KEY_CHOICE = 'kept_key:anthropic';
28
+ /**
29
+ * An Anthropic API key found in the environment, offered as a choice of its
30
+ * own. ZTC never moves a route onto such a key by itself, because it bills per
31
+ * token; choosing it here is what puts it to use. A Claude Code sign-in token
32
+ * in that variable is not a key and is not offered.
33
+ */
34
+ function environmentKeyChoice() {
35
+ const found = readProviderApiKeyEnv('anthropic');
36
+ if (!found || isClaudeCodeToken(found.value))
37
+ return undefined;
38
+ return {
39
+ value: `${ENVIRONMENT_KEY_PREFIX}anthropic`,
40
+ label: `Use ${found.name}`,
41
+ description: 'Your Anthropic API key from the environment, for Claude models · billed per token',
42
+ };
43
+ }
44
+ /**
45
+ * The Anthropic API key the move off the retired Claude Code routes found filed
46
+ * under one of them and kept apart, offered as a choice of its own for the same
47
+ * reason as an environment key: nothing uses it until it is chosen here.
48
+ */
49
+ function keptKeyChoice(ctx) {
50
+ const kept = ctx.config.get().keptAnthropicKey;
51
+ if (!kept?.key || isClaudeCodeToken(kept.key))
52
+ return undefined;
53
+ return {
54
+ value: KEPT_KEY_CHOICE,
55
+ label: `Use the Anthropic API key you saved for ${kept.from}`,
56
+ description: 'Kept from your settings before the move, for Claude models · billed per token',
57
+ };
58
+ }
59
+ /** Use a provider's API key: the direct route, chosen as local keys are. */
60
+ async function connectKey(provider, ctx, flow) {
61
+ const previous = ctx.config.get().onboarding;
62
+ ctx.config.set('onboarding', { ...previous, connectChoice: 'direct' });
63
+ await ctx.config.save();
64
+ await selectProviderModel([provider], ctx, { credentialPrompted: true });
65
+ flow?.finish();
66
+ }
67
+ /** The kept key, chosen: it becomes the Anthropic key (and is no longer offered apart), then runs as any key does. */
68
+ async function connectKeptKey(ctx, flow) {
69
+ const kept = ctx.config.get().keptAnthropicKey;
70
+ if (kept?.key)
71
+ ctx.config.setApiKey(kept.key, 'anthropic');
72
+ ctx.config.set('keptAnthropicKey', undefined);
73
+ await connectKey('anthropic', ctx, flow);
74
+ }
75
+ /** The last row of the local list: where a Claude subscription runs now. */
76
+ const CLAUDE_SUBSCRIPTION_OPTION = {
77
+ value: 'claude_subscription',
78
+ label: 'Claude Code (your subscription)',
79
+ description: 'Runs in its own pane, not as ZTC\'s model · /claude',
80
+ };
81
+ const CLAUDE_SUBSCRIPTION_HELP = 'Your Claude subscription runs in Claude Code itself: open it in a pane with /claude '
82
+ + '(on a sign-in profile with /claude @<name>; /subs lists them). Anthropic\'s terms reserve subscription sign-in for '
83
+ + 'Claude Code, so ZTC\'s own model needs Zerg Router or an API key: /connect when you want one.';
20
84
  const NOTHING_CONNECTED = 'No model is connected. Run /connect to log in with ZergAI or use your local API keys.';
21
85
  async function connectProvider(provider, ready, ctx, flow) {
22
86
  if (ready) {
@@ -68,7 +132,12 @@ async function connectRoute(route, ctx, noBrowser, flow) {
68
132
  .sort((a, b) => Number(ready.has(b.id)) - Number(ready.has(a.id)))
69
133
  .map(choice => ({ value: choice.id, label: choice.label, description: describeDirectProvider(choice.id, ready.has(choice.id)) }));
70
134
  const showProviders = () => ctx.select.showSelect({ title: LOCAL_API_KEYS_LABEL,
71
- question: 'Which provider should ZTC call?', type: 'select', options, silentCancel: true, compact: true }, async (value) => {
135
+ question: 'Which provider should ZTC call?', type: 'select', options: [...options, CLAUDE_SUBSCRIPTION_OPTION], silentCancel: true, compact: true }, async (value) => {
136
+ if (value === CLAUDE_SUBSCRIPTION_OPTION.value) {
137
+ ctx.addMessage({ role: 'system', content: CLAUDE_SUBSCRIPTION_HELP });
138
+ flow?.finish();
139
+ return;
140
+ }
72
141
  if (typeof value === 'string' && options.some(option => option.value === value)) {
73
142
  // Leaving a key choice comes back here.
74
143
  return connectProvider(value, ready.has(value), ctx, flow && { back: showProviders, finish: flow.finish });
@@ -137,13 +206,20 @@ export function showConnectPrompt(ctx, { launch = false, noBrowser = false, onFi
137
206
  const flow = launch
138
207
  ? { back: () => showConnectPrompt(ctx, { launch, noBrowser, onFinished: finish }), finish }
139
208
  : undefined;
209
+ const keyChoices = [keptKeyChoice(ctx), environmentKeyChoice()].filter((choice) => choice !== undefined);
210
+ const options = [ROUTE_OPTIONS[0], ...keyChoices, ...ROUTE_OPTIONS.slice(1)];
140
211
  ctx.select.showSelect({
141
212
  title: 'Connect a model', type: 'select',
142
213
  question: `${expired ? 'Your ZergAI session expired. ' : ''}How should ZTC reach a model?`,
143
- options: ROUTE_OPTIONS, defaultValue: 'zergrouter', silentCancel: true, compact: true, ...(launch ? { required: true } : {}),
214
+ options, defaultValue: 'zergrouter', silentCancel: true, compact: true, ...(launch ? { required: true } : {}),
144
215
  }, value => {
145
216
  if (value === 'zergrouter' || value === 'direct')
146
217
  return connectRoute(value, ctx, noBrowser, flow);
218
+ if (value === KEPT_KEY_CHOICE && keyChoices.some(choice => choice.value === KEPT_KEY_CHOICE))
219
+ return connectKeptKey(ctx, flow);
220
+ const key = keyChoices.find(choice => choice.value === value);
221
+ if (key)
222
+ return connectKey(key.value.slice(ENVIRONMENT_KEY_PREFIX.length), ctx, flow);
147
223
  ctx.addMessage({ role: 'system', content: CONNECT_LATER });
148
224
  flow?.finish();
149
225
  });
@@ -12,6 +12,8 @@ export interface ActiveRoute {
12
12
  error?: string;
13
13
  /** The error is a missing or expired ZergAI login. */
14
14
  signIn?: boolean;
15
+ /** The profile waits for a route choice, so there is no route (see ConfigStore.routeAwaitingChoice). */
16
+ awaitingChoice?: boolean;
15
17
  }
16
18
  export declare function describeActiveRoute(config: ConfigController): ActiveRoute;
17
19
  /**