@zergai/ztc 0.18.2-dev.202611110225 → 0.19.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 (39) hide show
  1. package/README.md +6 -3
  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-computer-darwin-arm64 +0 -0
  6. package/bin/ztc-llm-darwin-arm64 +0 -0
  7. package/bin/ztc-tts-darwin-arm64 +0 -0
  8. package/bin/ztc-tui-darwin-arm64 +0 -0
  9. package/bin/zterm-darwin-arm64 +2 -2
  10. package/dist/agent/commands/index.js +2 -1
  11. package/dist/agent/commands/model.js +19 -11
  12. package/dist/agent/commands/models.js +21 -4
  13. package/dist/agent/commands/provider.d.ts +22 -0
  14. package/dist/agent/commands/provider.js +285 -0
  15. package/dist/agent/commands/provider_choices.d.ts +12 -0
  16. package/dist/agent/commands/provider_choices.js +15 -0
  17. package/dist/agent/commands/provider_selection.d.ts +18 -0
  18. package/dist/agent/commands/provider_selection.js +77 -13
  19. package/dist/agent/commands/runtime_model.d.ts +16 -1
  20. package/dist/agent/commands/runtime_model.js +24 -3
  21. package/dist/agent/commands/settings.js +39 -14
  22. package/dist/agent/commands/types.d.ts +25 -1
  23. package/dist/app/command_context.js +31 -15
  24. package/dist/app/model_catalog_cache.d.ts +5 -0
  25. package/dist/app/model_catalog_cache.js +13 -0
  26. package/dist/app/runtime_choices.d.ts +38 -0
  27. package/dist/app/runtime_choices.js +66 -0
  28. package/dist/app/selection_completion.d.ts +5 -0
  29. package/dist/app/selection_completion.js +35 -2
  30. package/dist/cli_ratatui.d.ts +26 -6
  31. package/dist/cli_ratatui.js +98 -43
  32. package/dist/config/provider_models.d.ts +22 -0
  33. package/dist/config/provider_models.js +83 -0
  34. package/dist/config.d.ts +22 -1
  35. package/dist/config.js +64 -5
  36. package/dist/headless.js +4 -1
  37. package/dist/panes/ztc_launch.js +3 -2
  38. package/dist/zlm-embed.mjs +69 -18
  39. package/package.json +24 -8
package/README.md CHANGED
@@ -1410,9 +1410,12 @@ credentials. Panes need zmux (plain `ztc`) or the desktop app.
1410
1410
  test`); text that starts with a flag goes to the CLI as its arguments
1411
1411
  (`/claude --continue`, `/codex -m gpt-5 "review the diff"`).
1412
1412
  - Ctrl+B c offers Claude Code and Codex next to bash and ZTC when they are
1413
- installed. In the desktop app, the tab strip's + opens a menu: New ZTC Pane,
1414
- New Claude Code Pane, New Codex Pane, New Shell Pane. Cmd+T still opens a ZTC
1415
- tab directly.
1413
+ installed. In the desktop app, the tab strip's + opens a ZTC tab, as Cmd+T
1414
+ does. The ▾ beside it, or a right-click or Ctrl-click on +, opens New tab and
1415
+ Split focused pane, each for ZTC, Claude Code, Codex and Shell.
1416
+ Ctrl+Cmd+A and Ctrl+Cmd+O split the focused pane with Claude Code and Codex
1417
+ (Ctrl+Cmd+Z with ZTC, Cmd+D with a shell; Shift splits down), and Ctrl+Cmd+N
1418
+ opens the menu at the focused pane.
1416
1419
 
1417
1420
  Each of these panes starts with ZTC's workspace MCP server (`ztc
1418
1421
  workspace-mcp`) attached for that session only, through Claude Code's
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/zterm-darwin-arm64
3
- size: 33730352 bytes
4
- sha256: d9b491a5c2e99773b153ebd23b926f3e9d5bd1663641fa65ca0586d20cb5d6c9
3
+ size: 33779680 bytes
4
+ sha256: 32f57ab167ced380d2b07fb1875d85be10cd2964ccb32b32cb5544f36c276dce
@@ -16,6 +16,7 @@ import { shellCommand, cdCommand } from './shell.js';
16
16
  import { clipboardCommand } from './clipboard.js';
17
17
  import { modelsCommand } from './models.js';
18
18
  import { modelCommand } from './model.js';
19
+ import { providerCommand } from './provider.js';
19
20
  import { permissionsCommand } from './permissions.js';
20
21
  import { resourcesCommand } from './resources.js';
21
22
  import { skillsCommand } from './skills.js';
@@ -84,7 +85,7 @@ import { effortCommand, thinkingCommand, reasoningCommand, fastCommand } from '.
84
85
  import { runtimePluginRegistry } from '../../plugin/runtime_registry.js';
85
86
  const commandList = [];
86
87
  const helpCommand = makeHelpCommand(() => commandList);
87
- commandList.push(helpCommand, authCommand, loginCommand, logoutCommand, accountsCommand, zergCommand, zergsCommand, configCommand, debugCommand, clearCommand, handoffCommand, statusCommand, runtimeCommand, environmentCommand, jobCommand, shareCommand, hooksCommand, emulationCommand, shellCommand, cdCommand, clipboardCommand, modelsCommand, modelCommand, permissionsCommand, resourcesCommand, initCommand, forkCommand, sideCommand, claudeCommand, codexCommand, subsCommand, diffCommand, rawCommand, themeCommand, doctorCommand, intentCommand, profileCommand, skillsCommand, runbooksCommand, keybindingsCommand, keymapCommand, shortcutsCommand, updateCommand, desktopCommand, layoutCommand, setupCommand, connectCommand, keysCommand, restartCommand, reloadCommand, inputModeCommand, retryCommand, dictationStatusCommand, embeddedCommand, benchCommand, voiceCommand, sfxCommand, compactCommand, automodeCommand, sessionsCommand, resumeCommand, rewindCommand, renameCommand, labelCommand, inboxCommand, attentionCommand, contextCommand, evidenceCommand, boardCommand, usageCommand, shannonRunnerCommand, planCommand, executeCommand, modeCommand, modeListCommand, exitModeCommand, validateCommand, previewCommand, saveCommand, dcaigCommand, manifestCommand, swarmCommand, swarmStopCommand, swarmStatusCommand, superviseCommand, superviseStopCommand, superviseStatusCommand, zlickyCommand, zlickyStopCommand, zlickyStatusCommand, zlickyActCommand, zlickyPresenceCommand, zlickyPttCommand, simCommand, simStopCommand, simStatusCommand, simRunCommand, simCheckpointCommand, simResumeCommand, evolveCommand, evolveStopCommand, evolveStatusCommand, evolveBestCommand, optimizeCommand, batchCommand, batchStatusCommand, batchStopCommand, workflowsCommand, mirrorCommand, settingsCommand, mcpCommand, loopCommand, goalCommand, effortCommand, thinkingCommand, reasoningCommand, fastCommand, exitCommand);
88
+ commandList.push(helpCommand, authCommand, loginCommand, logoutCommand, accountsCommand, zergCommand, zergsCommand, configCommand, debugCommand, clearCommand, handoffCommand, statusCommand, runtimeCommand, environmentCommand, jobCommand, shareCommand, hooksCommand, emulationCommand, shellCommand, cdCommand, clipboardCommand, modelsCommand, modelCommand, providerCommand, permissionsCommand, resourcesCommand, initCommand, forkCommand, sideCommand, claudeCommand, codexCommand, subsCommand, diffCommand, rawCommand, themeCommand, doctorCommand, intentCommand, profileCommand, skillsCommand, runbooksCommand, keybindingsCommand, keymapCommand, shortcutsCommand, updateCommand, desktopCommand, layoutCommand, setupCommand, connectCommand, keysCommand, restartCommand, reloadCommand, inputModeCommand, retryCommand, dictationStatusCommand, embeddedCommand, benchCommand, voiceCommand, sfxCommand, compactCommand, automodeCommand, sessionsCommand, resumeCommand, rewindCommand, renameCommand, labelCommand, inboxCommand, attentionCommand, contextCommand, evidenceCommand, boardCommand, usageCommand, shannonRunnerCommand, planCommand, executeCommand, modeCommand, modeListCommand, exitModeCommand, validateCommand, previewCommand, saveCommand, dcaigCommand, manifestCommand, swarmCommand, swarmStopCommand, swarmStatusCommand, superviseCommand, superviseStopCommand, superviseStatusCommand, zlickyCommand, zlickyStopCommand, zlickyStatusCommand, zlickyActCommand, zlickyPresenceCommand, zlickyPttCommand, simCommand, simStopCommand, simStatusCommand, simRunCommand, simCheckpointCommand, simResumeCommand, evolveCommand, evolveStopCommand, evolveStatusCommand, evolveBestCommand, optimizeCommand, batchCommand, batchStatusCommand, batchStopCommand, workflowsCommand, mirrorCommand, settingsCommand, mcpCommand, loopCommand, goalCommand, effortCommand, thinkingCommand, reasoningCommand, fastCommand, exitCommand);
88
89
  export const commands = commandList;
89
90
  export function refreshPluginCommands() {
90
91
  const existing = new Set(commandList.map(command => command.name));
@@ -1,10 +1,12 @@
1
1
  import { configCommand } from './config.js';
2
2
  import { modelsCommand } from './models.js';
3
3
  import { canRouteThroughRouter, canonicalProvider, canonicalRoute, describeDirectRoute, describeRouterRoute, isRouterOnlyProvider, modelRouteStatus, } from './provider_choices.js';
4
- import { selectProviderModel } from './provider_selection.js';
4
+ import { refreshRouterModels, selectProviderModel } from './provider_selection.js';
5
+ import { switchProvider } from './provider.js';
5
6
  import { getEffectiveModel } from './runtime_model.js';
6
7
  import { normalizeProviderId } from '../backends/provider_ids.js';
7
8
  import { isModelAvailableForProvider, resolveModelAndProvider } from '../../panes/model_catalog.js';
9
+ import { resolveRouterModel } from '../../utils/router_catalog.js';
8
10
  import { isRetiredModel, isRetiredProvider, retiredModelMessage, retiredProviderMessage } from '../../config/retired_routes.js';
9
11
  const MODEL_SUBCOMMANDS = ['list', 'latest', 'set'];
10
12
  /** Bare `/model`: the active route, the two routes to choose from, and current models. */
@@ -81,6 +83,18 @@ function otherProvidersSelection(modelId, ctx) {
81
83
  return undefined;
82
84
  return routedNow(ctx) && canRouteThroughRouter(owner) ? ['zergrouter', owner, model] : [owner, model];
83
85
  }
86
+ /**
87
+ * `/model <name>` for a provider Zerg Router's cached catalog lists (morph), when no model of the provider in use goes
88
+ * by that name: the provider, as /provider <name> chooses it, rather than a model of the current provider.
89
+ */
90
+ function routerListsProvider(name, ctx) {
91
+ const catalog = ctx.config.getRouterCatalog?.();
92
+ const owner = name.trim().toLowerCase();
93
+ if (!catalog?.models.some(row => row.owned_by === owner && (catalog.version === 0 || row.capabilities?.chat)))
94
+ return false;
95
+ const current = normalizeProviderId(ctx.config.getProvider());
96
+ return !isModelAvailableForProvider(current, name) && !resolveRouterModel(catalog, current, name);
97
+ }
84
98
  export const modelCommand = {
85
99
  name: 'model',
86
100
  description: 'Select provider and model, or set a model on the current provider',
@@ -88,16 +102,8 @@ export const modelCommand = {
88
102
  agentRunnable: true,
89
103
  category: 'config',
90
104
  handler: async (args, ctx) => {
91
- if (args[0] === 'refresh' && ctx.models.catalog) {
92
- try {
93
- const catalog = await ctx.models.catalog(undefined, { refresh: true });
94
- ctx.addMessage({ role: 'system', content: `${catalog.authRequired ? 'Router authentication rejected. Run ztc auth login again. Showing cached catalog' : catalog.cached ? 'Router unavailable. Showing cached catalog' : 'Router catalog refreshed'}: ${catalog.models.length} models. Active responses continue with their current selection.` });
95
- }
96
- catch (error) {
97
- ctx.addMessage({ role: 'system', content: `Could not refresh Router models: ${error.message}` });
98
- }
99
- return;
100
- }
105
+ if (args[0] === 'refresh' && ctx.models.catalog)
106
+ return refreshRouterModels(ctx);
101
107
  if (args.length > 0 && MODEL_SUBCOMMANDS.includes(args[0].toLowerCase())) {
102
108
  return modelsCommand.handler(args, ctx);
103
109
  }
@@ -113,6 +119,8 @@ export const modelCommand = {
113
119
  if (args.length > 1 || (args.length === 1 && (canonicalProvider(args[0]) || canonicalRoute(args[0])))) {
114
120
  return selectProviderModel(args, ctx, { offerReasoning: true });
115
121
  }
122
+ if (args.length === 1 && routerListsProvider(args[0], ctx))
123
+ return switchProvider(args, ctx);
116
124
  // Another provider's model selects that provider too, so its key is the
117
125
  // one asked for and the model is never saved under the current provider.
118
126
  const selection = otherProvidersSelection(args[0], ctx);
@@ -1,7 +1,9 @@
1
- import { applyRuntimeModelSelection } from './runtime_model.js';
1
+ import { applyRuntimeModelSelection, paneRoute } from './runtime_model.js';
2
2
  import { isCodexAppServerProvider, isCodexLegacyProvider, normalizeProviderId } from '../backends/provider_ids.js';
3
3
  import { isBuildableResolvedConfig, unbuildableSelectionMessage } from './config.js';
4
4
  import { promptForMissingDirectKey } from './direct_credential_prompt.js';
5
+ import { canonicalProvider } from './provider_choices.js';
6
+ import { selectProviderModel } from './provider_selection.js';
5
7
  const LATEST_TAGS = ['latest', 'current', 'default'];
6
8
  function filterModelsForProvider(models, provider) {
7
9
  const normalizedProvider = provider.toLowerCase();
@@ -101,17 +103,32 @@ export function pickLatestModel(models, provider) {
101
103
  return candidateModels.slice().sort((a, b) => compareVariantPreference(a, b, provider))[0];
102
104
  }
103
105
  /**
104
- * `/models set <id>` on the active provider. A missing direct key is asked for
106
+ * `/models set <id>` on the provider this pane runs on, saved with that provider and its route, so the saved
107
+ * provider and model stay a pair: a pane running another provider than the profile's once saved its model beside
108
+ * the profile's provider. Key and login prompts, and Zerg Router's catalog check, are selectProviderModel's.
109
+ */
110
+ async function setModel(value, ctx) {
111
+ // The main pane's route can be the web mirror's choice for it alone, not the configuration's.
112
+ const { provider, routed } = paneRoute(ctx);
113
+ if (routed)
114
+ return selectProviderModel(['zergrouter', provider, value], ctx);
115
+ // A provider /model doesn't name (Bedrock) keeps the model-only change.
116
+ if (!canonicalProvider(provider))
117
+ return setModelOnly(value, ctx);
118
+ return selectProviderModel(['direct', provider, value], ctx);
119
+ }
120
+ /**
121
+ * The model alone, on the active provider. A missing direct key is asked for
105
122
  * once; `credentialPrompted` marks the retry after it is saved.
106
123
  */
107
- async function setModel(value, ctx, credentialPrompted = false) {
124
+ async function setModelOnly(value, ctx, credentialPrompted = false) {
108
125
  const provider = ctx.config.getProvider();
109
126
  // Verify the selection builds a backend BEFORE persisting so an unbuildable
110
127
  // choice never lands in config.json nor earns a false "✓".
111
128
  // Checked as it will be once chosen: saving it ends any wait for a route choice.
112
129
  const llm = ctx.config.resolveLLMBackendConfig({ provider, model: value, asChosen: true });
113
130
  if (!isBuildableResolvedConfig(llm)) {
114
- if (!credentialPrompted && promptForMissingDirectKey(llm, ctx, () => setModel(value, ctx, true)))
131
+ if (!credentialPrompted && promptForMissingDirectKey(llm, ctx, () => setModelOnly(value, ctx, true)))
115
132
  return;
116
133
  ctx.addMessage({ role: 'system', content: unbuildableSelectionMessage(provider, llm, ctx.config) });
117
134
  return;
@@ -0,0 +1,22 @@
1
+ import type { Command, CommandContext } from './types.js';
2
+ /**
3
+ * `/provider [zergrouter|direct] <name> [model]`, and `/model <name>` for a provider Zerg Router lists. The model is
4
+ * the one named, else the one last used with that provider while it is still offered, else the provider's default.
5
+ */
6
+ export declare function switchProvider(args: string[], ctx: CommandContext): Promise<void>;
7
+ /**
8
+ * The desktop app's model chip: "Choose provider" first, Zerg Router's from the cached catalog whatever route this
9
+ * pane runs on, then the person's own keys, and then that provider's models; the current provider goes straight to
10
+ * its models. The choice applies as `/provider <choice> <model>` does, setting the default and switching this pane.
11
+ * `run` runs a slash command as the renderer does.
12
+ */
13
+ export declare function pickProviderAndModel(ctx: CommandContext, current: {
14
+ provider: string;
15
+ model: string;
16
+ }, run: (command: string, args: string[]) => Promise<void>): Promise<void>;
17
+ /**
18
+ * Whether `/provider <args>` switches, rebuilding this pane's agent, rather than listing the providers or refreshing
19
+ * Router's list: like /model, a switch waits for an agent turn to end.
20
+ */
21
+ export declare function switchesProvider(args: readonly string[]): boolean;
22
+ export declare const providerCommand: Command;
@@ -0,0 +1,285 @@
1
+ /**
2
+ * `/provider`: the providers this pane can run on, Zerg Router's and the person's own keys and logins, each with what
3
+ * it needs; and a switch to one, which sets the default for new panes and switches this pane in one step.
4
+ */
5
+ import { buildProviderChoices } from '../../app/runtime_choices.js';
6
+ import { isLocalSubscriptionProvider, normalizeProviderId } from '../backends/provider_ids.js';
7
+ import { canonicalProvider, canonicalRoute, isRouterOnlyProvider, modelRouteStatus, routerServesProvider, } from './provider_choices.js';
8
+ import { profileDirectory, refreshRouterModels, selectProviderModel } from './provider_selection.js';
9
+ import { paneRoute } from './runtime_model.js';
10
+ import { rememberedModel } from '../../config/provider_models.js';
11
+ import { defaultRouterModel, routerModelsForProvider } from '../../utils/router_catalog.js';
12
+ const USAGE = 'Usage: /provider [<provider> [model] | zergrouter <provider> [model] | direct <provider> [model] | refresh]';
13
+ /** The choices from what is cached here: Router's catalog for this login, and this machine's keys and logins. */
14
+ function choicesFor(ctx, current) {
15
+ const status = modelRouteStatus(ctx.config);
16
+ return buildProviderChoices({ catalog: ctx.config.getRouterCatalog?.(), routerSession: status.routerSession,
17
+ directReady: status.directProviders, selected: { provider: current.provider, routed: current.routed } });
18
+ }
19
+ /** Router's Credentials page, where a provider key is added: only for the person's own Router sign-in. */
20
+ function credentialsUrl(ctx) {
21
+ const origin = ctx.config.getPersonalRouterCredential?.()?.origin;
22
+ return origin ? `${origin.replace(/\/+$/, '')}/dashboard?tab=credentials` : undefined;
23
+ }
24
+ function detail(choice, url) {
25
+ return choice.state === 'unavailable' && url ? `${choice.detail} · add it at ${url}` : choice.detail;
26
+ }
27
+ /** How a route reads after the provider's name. */
28
+ function routePhrase(provider, routed) {
29
+ if (routed)
30
+ return 'via Zerg Router';
31
+ if (isLocalSubscriptionProvider(provider))
32
+ return 'with your local login';
33
+ return provider === 'openai_compatible' ? 'at your custom endpoint' : 'with your key';
34
+ }
35
+ /** Router ids carry their provider (morph/morph-kimik31); the provider is already named. */
36
+ function modelName(provider, model) {
37
+ return model.startsWith(`${provider}/`) ? model.slice(provider.length + 1) : model;
38
+ }
39
+ function describeCurrent(current, choices) {
40
+ const label = choices.find(choice => choice.selected)?.short_label ?? current.provider;
41
+ return `${label} ${routePhrase(current.provider, current.routed)} · ${modelName(current.provider, current.model)}`;
42
+ }
43
+ /** Providers both lists offer: their bare name picks a route (see resolveChoice), so the route can be named too. */
44
+ function onBothRoutes(choices) {
45
+ const routed = new Set(choices.filter(choice => choice.route === 'zergrouter').map(choice => choice.provider));
46
+ return choices.filter(choice => choice.route === 'direct' && routed.has(choice.provider)).map(choice => choice.provider);
47
+ }
48
+ function listing(ctx, current, choices) {
49
+ const url = credentialsUrl(ctx);
50
+ const session = ctx.config.getRouterSessionStatus?.() ?? 'signed_out';
51
+ const router = choices.filter(choice => choice.route === 'zergrouter');
52
+ const nameWidth = Math.max(...choices.map(choice => choice.provider.length));
53
+ const labelWidth = Math.max(...choices.map(choice => choice.short_label.length));
54
+ const row = (choice) => ` ${choice.selected ? '✓' : ' '} ${choice.provider.padEnd(nameWidth)} `
55
+ + `${choice.short_label.padEnd(labelWidth)} ${detail(choice, url)}`.trimEnd();
56
+ const both = onBothRoutes(choices);
57
+ return [
58
+ `Provider: ${describeCurrent(current, choices)}`,
59
+ `Zerg Router · ${session === 'signed_in' ? 'signed in' : session === 'expired' ? 'ZergAI session expired · /auth login' : 'not signed in · /auth login'}`,
60
+ ...(router.length > 0 ? router.map(row) : [' Log in with ZergAI (/auth login) to list Zerg Router\'s providers.']),
61
+ 'Your keys',
62
+ ...choices.filter(choice => choice.route === 'direct').map(row),
63
+ ...(both.length > 0 ? [`On both lists (${both.join(', ')}): /provider zergrouter <name> or /provider direct <name> picks the route.`] : []),
64
+ '/provider <name> switches this pane and the default for new panes. /provider refresh reloads Zerg Router\'s list.',
65
+ ].join('\n');
66
+ }
67
+ /** Bare /provider: a choice to pick where someone can pick one, otherwise the list as text. */
68
+ async function showProviders(ctx) {
69
+ const current = paneRoute(ctx);
70
+ const choices = choicesFor(ctx, current);
71
+ if (ctx.commandOrigin === 'agent' || ctx.prompt?.interactive === false || !ctx.select?.showSelect) {
72
+ ctx.addMessage({ role: 'system', content: listing(ctx, current, choices) });
73
+ return;
74
+ }
75
+ const url = credentialsUrl(ctx);
76
+ const selected = choices.find(choice => choice.selected);
77
+ ctx.select.showSelect({
78
+ title: 'Choose provider', type: 'select', defaultValue: selected.id, silentCancel: true,
79
+ question: `This pane and new panes run on the provider you choose. Now: ${describeCurrent(current, choices)}.`,
80
+ options: choices.map(choice => ({ value: choice.id,
81
+ label: choice.route === 'zergrouter' ? `${choice.short_label} · Zerg Router` : choice.label,
82
+ ...(detail(choice, url) ? { description: detail(choice, url) } : {}) })),
83
+ }, async (value) => {
84
+ const chosen = choices.find(choice => choice.id === value);
85
+ if (chosen && !chosen.selected)
86
+ await applyChoice({ provider: chosen.provider, route: chosen.route, choice: chosen }, undefined, ctx);
87
+ });
88
+ }
89
+ /**
90
+ * The choice a typed name means: a Zerg Router choice id typed in full (zergrouter:morph); else a name ZTC knows for
91
+ * a provider, or one Router's cached catalog lists. When both routes offer it, the current route if it can run it,
92
+ * else the one that can, else Zerg Router. (A direct choice's id is its bare provider name, so it takes this rule
93
+ * too.) A Router provider whose row is withheld while signed out is a Router choice, which asks for the login.
94
+ */
95
+ function resolveChoice(name, route, ctx, current) {
96
+ const choices = choicesFor(ctx, current);
97
+ const exact = choices.find(choice => choice.route === 'zergrouter' && choice.id === name && route !== 'direct');
98
+ if (exact)
99
+ return { provider: exact.provider, route: exact.route, choice: exact };
100
+ const provider = canonicalProvider(name) ?? normalizeProviderId(name);
101
+ const offered = choices.filter(choice => choice.provider === provider && (!route || choice.route === route));
102
+ const currentRouteName = current.routed ? 'zergrouter' : 'direct';
103
+ const pick = offered.length < 2 ? offered[0]
104
+ : offered.find(choice => choice.route === currentRouteName && choice.state === 'ready')
105
+ ?? offered.find(choice => choice.state === 'ready') ?? offered.find(choice => choice.route === 'zergrouter');
106
+ if (pick)
107
+ return { provider: pick.provider, route: pick.route, choice: pick };
108
+ // A provider only Zerg Router serves, asked for with your own key: /model direct says where it runs.
109
+ if (route === 'direct' && isRouterOnlyProvider(provider))
110
+ return { provider, route: 'direct' };
111
+ const signedIn = ctx.config.getRouterSessionStatus?.() === 'signed_in';
112
+ if (!signedIn && route !== 'direct' && (route === 'zergrouter' || routerServesProvider(provider, undefined, ctx.config.getRouterCatalog?.()))) {
113
+ return { provider, route: 'zergrouter' };
114
+ }
115
+ return undefined;
116
+ }
117
+ async function applyChoice(resolved, model, ctx) {
118
+ const { provider, route, choice } = resolved;
119
+ if (choice?.state === 'unavailable') {
120
+ const url = credentialsUrl(ctx);
121
+ ctx.addMessage({ role: 'system', content: `${choice.short_label} has no key on Zerg Router yet. `
122
+ + `${url ? `Add it at ${url}` : 'Add it on Zerg Router\'s Credentials page'}, then run /provider refresh.` });
123
+ return;
124
+ }
125
+ const confirm = (applied, kept) => {
126
+ const choices = choicesFor(ctx, applied);
127
+ const session = ctx.config.getConfigScope?.() === 'session';
128
+ if (kept) {
129
+ // This pane couldn't rebuild on the choice (it said why) and runs on what it ran on.
130
+ const still = describeCurrent(kept, choicesFor(ctx, kept));
131
+ return session ? `This session keeps ${still}.` : `New panes start on ${describeCurrent(applied, choices)}; this pane keeps ${still}.`;
132
+ }
133
+ const scope = session ? 'This session' : 'This pane and new panes';
134
+ const alsoDirect = choices.some(entry => entry.route === 'direct' && entry.provider === applied.provider);
135
+ const alsoRouter = choices.some(entry => entry.route === 'zergrouter' && entry.provider === applied.provider);
136
+ const other = applied.routed
137
+ ? alsoDirect ? ` /provider direct ${applied.provider} would use your own key.` : ''
138
+ : alsoRouter ? ` /provider zergrouter ${applied.provider} would go through Zerg Router.` : '';
139
+ return `✓ ${scope}: ${describeCurrent(applied, choices)}.${other}`;
140
+ };
141
+ await selectProviderModel([route, provider, ...(model ? [model] : [])], ctx, { confirm });
142
+ }
143
+ /**
144
+ * `/provider [zergrouter|direct] <name> [model]`, and `/model <name>` for a provider Zerg Router lists. The model is
145
+ * the one named, else the one last used with that provider while it is still offered, else the provider's default.
146
+ */
147
+ export async function switchProvider(args, ctx) {
148
+ const route = args[0] ? canonicalRoute(args[0]) : undefined;
149
+ const [name, model] = route ? args.slice(1) : args;
150
+ if (!name)
151
+ return showProviders(ctx);
152
+ if (args.length > (route ? 3 : 2)) {
153
+ ctx.addMessage({ role: 'system', content: USAGE });
154
+ return;
155
+ }
156
+ const current = paneRoute(ctx);
157
+ let resolved = resolveChoice(name, route, ctx, current);
158
+ if (!resolved && ctx.config.getRouterSessionStatus?.() === 'signed_in' && ctx.models.catalog) {
159
+ // A provider Router added since its list was cached: ask Router once.
160
+ await ctx.models.catalog(undefined, { refresh: true }).catch(() => undefined);
161
+ resolved = resolveChoice(name, route, ctx, current);
162
+ }
163
+ if (!resolved) {
164
+ ctx.addMessage({ role: 'system', content: `Unknown provider: ${name}. Run /provider to see the choices.` });
165
+ return;
166
+ }
167
+ await applyChoice(resolved, model, ctx);
168
+ }
169
+ /** A choice from `ctx.select`, or null when it is dismissed. */
170
+ function choose(ctx, options) {
171
+ return new Promise(resolve => ctx.select.showSelect(options, value => resolve(typeof value === 'string' ? value : null)));
172
+ }
173
+ /**
174
+ * The model to switch to with another provider: one picked from that provider's list, null when the list is
175
+ * dismissed, or undefined for no list. A choice that isn't ready gets none, so /provider refuses it, or asks for its
176
+ * key or login, and then lands on its remembered or default model.
177
+ */
178
+ async function chooseModelFor(choice, ctx) {
179
+ if (choice.state !== 'ready')
180
+ return undefined;
181
+ const profile = profileDirectory(ctx);
182
+ const remembered = profile ? rememberedModel(choice.id, profile) : undefined;
183
+ if (choice.route === 'zergrouter') {
184
+ const catalog = ctx.config.getRouterCatalog?.();
185
+ const rows = catalog?.version === 1 ? routerModelsForProvider(catalog, choice.provider) : [];
186
+ if (rows.length === 0)
187
+ return undefined;
188
+ const kept = rows.find(row => row.id === remembered && row.available !== false);
189
+ return choose(ctx, {
190
+ title: 'Choose model', type: 'select', allowOther: false, defaultValue: (kept ?? defaultRouterModel(rows))?.id,
191
+ question: `Select a ${choice.short_label} model through Zerg Router. Conversation and tools are retained; context limits may change.`,
192
+ options: rows.map(row => ({ value: row.id, label: row.display_name || row.id,
193
+ ...(row.available === false ? { description: 'Not available to your account' } : {}) })),
194
+ });
195
+ }
196
+ const models = await ctx.models.list(choice.provider, { authMode: 'direct' }).catch(() => []);
197
+ if (models.length === 0)
198
+ return undefined;
199
+ return choose(ctx, {
200
+ title: 'Choose model', type: 'select', allowOther: false,
201
+ defaultValue: remembered && models.includes(remembered) ? remembered : models[0],
202
+ question: `Select a ${choice.label} model. Conversation and tools are retained; context limits may change.`,
203
+ options: models.map(value => ({ value, label: value })),
204
+ });
205
+ }
206
+ /**
207
+ * The desktop app's model chip: "Choose provider" first, Zerg Router's from the cached catalog whatever route this
208
+ * pane runs on, then the person's own keys, and then that provider's models; the current provider goes straight to
209
+ * its models. The choice applies as `/provider <choice> <model>` does, setting the default and switching this pane.
210
+ * `run` runs a slash command as the renderer does.
211
+ */
212
+ export async function pickProviderAndModel(ctx, current, run) {
213
+ let routed;
214
+ let provider = current.provider;
215
+ try {
216
+ const llm = ctx.config.resolveLLMBackendConfig({ provider: current.provider, model: current.model });
217
+ routed = llm.useProxy;
218
+ provider = llm.provider;
219
+ }
220
+ catch {
221
+ routed = ctx.config.getAuthMode?.() === 'zrouter';
222
+ }
223
+ const route = { provider, model: current.model, routed: routed || isRouterOnlyProvider(provider) };
224
+ const choices = choicesFor(ctx, route);
225
+ const url = credentialsUrl(ctx);
226
+ const picked = await choose(ctx, {
227
+ title: 'Choose provider', type: 'select', defaultValue: choices.find(choice => choice.selected).id,
228
+ question: `Choose a provider, then one of its models. Now: ${describeCurrent(route, choices)}.`,
229
+ options: choices.map(choice => ({ value: choice.id,
230
+ label: choice.route === 'zergrouter' ? `${choice.short_label} · Zerg Router` : choice.label,
231
+ ...(detail(choice, url) ? { description: detail(choice, url) } : {}) })),
232
+ });
233
+ const chosen = choices.find(choice => choice.id === picked);
234
+ if (!chosen)
235
+ return;
236
+ if (chosen.selected) {
237
+ const models = await ctx.models.list(current.provider);
238
+ if (models.length === 0)
239
+ throw new Error('No supported models were returned. Keep the current model and retry discovery.');
240
+ const model = await choose(ctx, {
241
+ title: 'Choose model', question: `Select a model for ${current.provider}. Conversation and tools are retained; context limits may change.`,
242
+ type: 'select', options: models.map(value => ({ value, label: value })), defaultValue: current.model, allowOther: false,
243
+ });
244
+ if (model === null)
245
+ return;
246
+ // Saved with the provider and route the pane runs on, which the owner's live choice can make differ from the
247
+ // saved provider /model set would use; a provider /provider doesn't name keeps /model set.
248
+ if (chosen.route === 'zergrouter' || canonicalProvider(chosen.provider))
249
+ await run('provider', [chosen.route, chosen.provider, model]);
250
+ else
251
+ await run('model', ['set', model]);
252
+ return;
253
+ }
254
+ const model = await chooseModelFor(chosen, ctx);
255
+ if (model === null)
256
+ return;
257
+ await run('provider', [chosen.route, chosen.provider, ...(model ? [model] : [])]);
258
+ }
259
+ /**
260
+ * Whether `/provider <args>` switches, rebuilding this pane's agent, rather than listing the providers or refreshing
261
+ * Router's list: like /model, a switch waits for an agent turn to end.
262
+ */
263
+ export function switchesProvider(args) {
264
+ return args.length > 0 && args[0].toLowerCase() !== 'refresh' && !(args.length === 1 && canonicalRoute(args[0]));
265
+ }
266
+ export const providerCommand = {
267
+ name: 'provider',
268
+ description: 'Choose the provider this pane and new panes run on: Zerg Router\'s, or your own keys',
269
+ usage: '[<provider> [model] | zergrouter <provider> [model] | direct <provider> [model] | refresh]',
270
+ agentRunnable: true,
271
+ category: 'config',
272
+ handler: async (args, ctx) => {
273
+ if (args[0]?.toLowerCase() === 'refresh')
274
+ return refreshRouterModels(ctx);
275
+ if (!switchesProvider(args))
276
+ return showProviders(ctx);
277
+ // Listing is the agent's; the switch changes the default for every new pane, which is the person's choice.
278
+ if (ctx.commandOrigin === 'agent') {
279
+ const current = paneRoute(ctx);
280
+ ctx.addMessage({ role: 'system', content: `Only you can switch providers: /provider changes this pane and the default for new panes. Keeping ${describeCurrent(current, choicesFor(ctx, current))}.` });
281
+ return;
282
+ }
283
+ return switchProvider(args, ctx);
284
+ },
285
+ };
@@ -134,6 +134,18 @@ export declare function currentRouterOnlyModelError(config: Pick<ConfigControlle
134
134
  useProxy: boolean;
135
135
  authMode: ZTCAuthMode;
136
136
  }): RouterOnlyModelError | undefined;
137
+ /** The value /settings' Provider row uses for a Zerg Router choice: `zergrouter:<provider>`. */
138
+ export declare const ROUTER_CHOICE_PREFIX = "zergrouter:";
139
+ /**
140
+ * The id a provider choice goes by in lists and in remembered models: `zergrouter:<provider>` through Zerg Router,
141
+ * otherwise the provider id.
142
+ */
143
+ export declare function providerChoiceId(provider: string, route: 'zergrouter' | 'direct'): string;
144
+ /** A choice id's provider and route; a bare provider id is a direct choice. */
145
+ export declare function parseProviderChoiceId(id: string): {
146
+ provider: string;
147
+ route: 'zergrouter' | 'direct';
148
+ };
137
149
  export declare function canonicalRoute(value: string): ModelRoute | undefined;
138
150
  export declare function describeRouterRoute(session: RouterSessionStatus): string;
139
151
  export declare function describeDirectRoute(readyProviders: readonly string[]): string;
@@ -166,6 +166,21 @@ export function currentRouterOnlyModelError(config, route) {
166
166
  return undefined;
167
167
  }
168
168
  }
169
+ /** The value /settings' Provider row uses for a Zerg Router choice: `zergrouter:<provider>`. */
170
+ export const ROUTER_CHOICE_PREFIX = 'zergrouter:';
171
+ /**
172
+ * The id a provider choice goes by in lists and in remembered models: `zergrouter:<provider>` through Zerg Router,
173
+ * otherwise the provider id.
174
+ */
175
+ export function providerChoiceId(provider, route) {
176
+ return route === 'zergrouter' ? `${ROUTER_CHOICE_PREFIX}${provider}` : provider;
177
+ }
178
+ /** A choice id's provider and route; a bare provider id is a direct choice. */
179
+ export function parseProviderChoiceId(id) {
180
+ return id.startsWith(ROUTER_CHOICE_PREFIX)
181
+ ? { provider: id.slice(ROUTER_CHOICE_PREFIX.length), route: 'zergrouter' }
182
+ : { provider: id, route: 'direct' };
183
+ }
169
184
  export function canonicalRoute(value) {
170
185
  const normalized = value.trim().toLowerCase();
171
186
  return MODEL_ROUTE_CHOICES.find(route => route.id === normalized
@@ -1,10 +1,28 @@
1
1
  import type { CommandContext } from './types.js';
2
+ import { type PaneRoute } from './runtime_model.js';
3
+ /**
4
+ * Where this configuration keeps its profile: the models remembered per provider live beside its config.json. A
5
+ * configuration without a file (a renderer's stand-in) remembers nothing.
6
+ */
7
+ export declare function profileDirectory(ctx: CommandContext): string | undefined;
2
8
  /** Local providers with their credential state, configured ones first. */
3
9
  export declare function formatDirectProviders(readyProviders: readonly string[]): string;
10
+ /** `/model refresh` and `/provider refresh`: Zerg Router's catalog again, without changing the selection. */
11
+ export declare function refreshRouterModels(ctx: CommandContext): Promise<void>;
12
+ /**
13
+ * Whether `model` is still one `provider` offers on your own key or login: the models discovery last listed for it
14
+ * include it, or none were listed yet, so nothing says it is gone.
15
+ */
16
+ export declare function stillListed(ctx: CommandContext, provider: string, model: string): Promise<boolean>;
4
17
  /** How a provider and model selection runs; see selectProviderModel. */
5
18
  export interface SelectionOptions {
6
19
  credentialPrompted?: boolean;
7
20
  offerReasoning?: boolean;
21
+ /**
22
+ * The confirmation to show once the selection is saved, instead of /model's. `kept` is the route this pane went on
23
+ * running when its rebuild on the selection failed (it said why), so only new panes start on the selection.
24
+ */
25
+ confirm?: (applied: PaneRoute, kept?: PaneRoute) => string;
8
26
  }
9
27
  /**
10
28
  * Apply a provider and optional model in one validated config transition. A