@zergai/ztc 0.20.0-beta.1 → 0.21.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 (43) hide show
  1. package/bin/zmux-darwin-arm64 +0 -0
  2. package/bin/ztc-audio-darwin-arm64 +0 -0
  3. package/bin/ztc-capture-darwin-arm64 +0 -0
  4. package/bin/ztc-tui-darwin-arm64 +0 -0
  5. package/bin/zterm-darwin-arm64 +2 -2
  6. package/dist/agent/commands/config.js +7 -1
  7. package/dist/agent/commands/model.js +9 -5
  8. package/dist/agent/commands/models.js +2 -4
  9. package/dist/agent/commands/provider.d.ts +12 -0
  10. package/dist/agent/commands/provider.js +38 -2
  11. package/dist/agent/commands/provider_selection.d.ts +24 -1
  12. package/dist/agent/commands/provider_selection.js +70 -36
  13. package/dist/agent/commands/runtime_model.d.ts +11 -2
  14. package/dist/agent/commands/runtime_model.js +23 -5
  15. package/dist/agent/commands/settings.js +12 -3
  16. package/dist/agent/commands/types.d.ts +24 -4
  17. package/dist/app/runtime_choices.d.ts +78 -1
  18. package/dist/app/runtime_choices.js +229 -0
  19. package/dist/app/runtime_choices_source.d.ts +45 -0
  20. package/dist/app/runtime_choices_source.js +127 -0
  21. package/dist/app/selection_completion.js +1 -14
  22. package/dist/cli_ratatui.d.ts +94 -16
  23. package/dist/cli_ratatui.js +510 -124
  24. package/dist/config/provider_models.d.ts +15 -0
  25. package/dist/config/provider_models.js +28 -0
  26. package/dist/config.d.ts +114 -4
  27. package/dist/config.js +306 -62
  28. package/dist/headless.js +13 -5
  29. package/dist/panes/pane_registry.d.ts +16 -1
  30. package/dist/panes/pane_registry.js +17 -0
  31. package/dist/panes/types.d.ts +14 -0
  32. package/dist/panes/ztc_launch.d.ts +3 -0
  33. package/dist/panes/ztc_launch.js +10 -7
  34. package/dist/simulation/toolkit/dynamic_meetings.d.ts +2 -2
  35. package/dist/simulation/toolkit/dynamic_story_review.d.ts +3 -3
  36. package/dist/ui/ratatui/pane_relay.d.ts +22 -1
  37. package/dist/ui/ratatui/pane_relay.js +57 -6
  38. package/dist/ui/ratatui/protocol.d.ts +97 -1
  39. package/dist/ui/ratatui/protocol.js +136 -6
  40. package/dist/utils/router_catalog_facts.d.ts +3 -0
  41. package/dist/utils/router_catalog_facts.js +14 -0
  42. package/dist/zlm-embed.mjs +275 -52
  43. package/package.json +16 -16
@@ -32,7 +32,7 @@ import { beginSimTurn } from './agent/tools/sim_turn_budget.js';
32
32
  import { randomUUID } from 'crypto';
33
33
  import { appendFileSync, existsSync, writeFileSync } from 'fs';
34
34
  import { tmpdir, homedir } from 'os';
35
- import { join } from 'path';
35
+ import { dirname, join } from 'path';
36
36
  import { execFile, spawnSync } from 'child_process';
37
37
  import { promisify, isDeepStrictEqual } from 'util';
38
38
  import { configStore, resolveTerminalInteractionSettings } from './config.js';
@@ -73,8 +73,11 @@ import { EvidenceLedger } from './agent/runtime/evidence.js';
73
73
  import { runtimePluginRegistry } from './plugin/runtime_registry.js';
74
74
  import { getMirrorCommandUsages, isRichSlashUsage } from './agent/commands/mirror_usages.js';
75
75
  import { createModeContext } from './agent/commands/mode_commands.js';
76
- import { currentRouterOnlyModelError, isLocalSubscription, isRouterOnlyProvider, modelRouteStatus, RouterOnlyModelError, } from './agent/commands/provider_choices.js';
77
- import { pickProviderAndModel, switchesProvider } from './agent/commands/provider.js';
76
+ import { currentRouterOnlyModelError, isLocalSubscription, isRouterOnlyProvider, modelRouteStatus, parseProviderChoiceId, providerChoiceId, RouterOnlyModelError, } from './agent/commands/provider_choices.js';
77
+ import { newPanesConfirmation, paneSwitchConfirmation, pickProviderAndModel, switchesProvider } from './agent/commands/provider.js';
78
+ import { newPaneRoute } from './agent/commands/runtime_model.js';
79
+ import { selectProviderModel } from './agent/commands/provider_selection.js';
80
+ import { runAuthAction } from './agent/commands/auth.js';
78
81
  import { isBuildableResolvedConfig } from './agent/commands/config.js';
79
82
  import { promptForMissingDirectKey } from './agent/commands/direct_credential_prompt.js';
80
83
  import { showConnectPrompt } from './agent/commands/connect.js';
@@ -86,9 +89,12 @@ import { allocatePlanArtifact, askPlanApproval, findPlanContent, generatePlanPat
86
89
  import { setTodoUpdateCallback, clearTodoUpdateCallback, setPaneToolsTuiProcess, clearPaneToolsTuiProcess, setPaneToolsOwnId, setPaneToolsExitCallback, setPaneToolsMirrorCallback, setPaneToolsZdeLiteCallback, setPaneToolsPendingLaunchCallback, clearPaneToolsPendingLaunchCallback, setSupervisionManager, clearSupervisionManager, setBusTransport, clearBusTransport, setEvolutionTuiProcess, clearEvolutionTuiProcess, resetAskUserTurnFlag } from './agent/tools/index.js';
87
90
  import { shutdownLSPManager } from './lsp/index.js';
88
91
  import { MAX_CORRELATED_TURNS, correlatedInputDigest, projectCorrelatedTurns, restoreCorrelatedTurns, restoreCorrelatedTurnHistory } from './app/correlated_turn.js';
92
+ import { buildRuntimeChoices, checkRuntimeSelection, desktopTaskSignature, RuntimeChoicesPublication } from './app/runtime_choices.js';
93
+ import { RuntimeChoicesSource } from './app/runtime_choices_source.js';
94
+ import { PaneModelMemory } from './config/provider_models.js';
89
95
  import { zmuxKeymapPayload } from './config/keybindings.js';
90
96
  import { customPaneOptions } from './config/panes.js';
91
- import { CAPABILITY_DESKTOP_UPDATE_RESTART, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_ROUTER_CHROME, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_KITTY_GRAPHICS, isDesktopSessionShareAction, CAPABILITY_SCROLLBACK_ANCHOR, CAPABILITY_TERMINAL_INTERACTION, } from './ui/ratatui/protocol.js';
97
+ import { CAPABILITY_DESKTOP_UPDATE_RESTART, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_ROUTER_CHROME, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CHOICES, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_KITTY_GRAPHICS, isDesktopSessionShareAction, CAPABILITY_SCROLLBACK_ANCHOR, CAPABILITY_TERMINAL_INTERACTION, } from './ui/ratatui/protocol.js';
92
98
  import { writeClipboard } from './utils/clipboard.js';
93
99
  import { saveClipboardImagePng } from './utils/clipboard_image.js';
94
100
  import { loadEmulationProfiles, getEmulationProfile } from './emulation/catalog.js';
@@ -148,7 +154,7 @@ import { createWorkspaceLayoutController } from './app/workspace_layout_controll
148
154
  import { linkWorkspaceAgentSessions, resolveWorkspaceAgentSession } from './workspace_agent.js';
149
155
  import { hostedSessionSettingsEqual, hostedSettingsConfigPatch, isHostedMuxCommandAllowed, parseHostedSessionSettings, } from './hosted/session_settings.js';
150
156
  import { registerHostedAgentToolBridge } from './hosted/tool_bridge.js';
151
- import { PaneRegistry, mergeSessionPaneSpecs } from './panes/pane_registry.js';
157
+ import { PaneRegistry, isNativeZtcPane, mergeSessionPaneSpecs, nativeLaunchRouterOrigin } from './panes/pane_registry.js';
152
158
  import { buildZtcPaneLaunchCommand, createZtcLaunchSpec } from './panes/ztc_launch.js';
153
159
  import { preparePaneInitialInput, loadPaneInitialInput, readSavedPaneInitialInput, acknowledgePaneInitialInput, waitForPaneInitialInput, cleanupPaneInitialInput } from './panes/initial_input.js';
154
160
  import { getProviderForModel, isCatalogModelForProvider, isPaneProvider, resolveModelAndProvider } from './panes/model_catalog.js';
@@ -408,6 +414,10 @@ export function shouldProcessPostCommandBackgroundEvents(batch, workflows) {
408
414
  const workflowActive = workflows ? (workflows.hasUnsettledRuns() || workflows.hasPendingEvents()) : false;
409
415
  return batchActive || workflowActive;
410
416
  }
417
+ /** Whether two routes run the same provider and model the same way (the Router origin aside). */
418
+ function sameRoute(a, b) {
419
+ return normalizeProviderId(a.provider) === normalizeProviderId(b.provider) && a.model === b.model && a.authMode === b.authMode;
420
+ }
411
421
  export class RatatuiApp {
412
422
  tui;
413
423
  headlessMirror = false;
@@ -545,6 +555,23 @@ export class RatatuiApp {
545
555
  desktopTaskSignature = null;
546
556
  desktopTaskState = null;
547
557
  runtimeMutationInFlight = false;
558
+ /** What this pane's header menus list, gathered from cached state (see runtimeChoicesFor); made when first needed. */
559
+ runtimeChoicesSource = null;
560
+ /** Stops marking the lists stale on saved settings; set with the source. */
561
+ stopFollowingChoiceSettings = null;
562
+ /** Stops telling ConfigStore the directory this pane works in (ConfigStore.followRouteDirectory). */
563
+ stopFollowingRouteDirectory = null;
564
+ runtimeChoicesPublication = new RuntimeChoicesPublication();
565
+ publishedRuntimeChoices;
566
+ runtimeChoicesBuiltAt = 0;
567
+ /** Set when what the lists show may have changed (a switch, a saved setting, discovery); the next sync rebuilds them. */
568
+ runtimeChoicesStale = true;
569
+ /** The models this pane ran with each provider, for its model menu's Recent group and a switch back to a provider. */
570
+ paneModels = new PaneModelMemory(() => dirname(configStore.getConfigPath()));
571
+ /** Slash commands running now; while any runs, the profile isn't reloaded under it (see refreshSettingsFromElsewhere). */
572
+ commandsRunning = 0;
573
+ /** Runtime changes nested in one another, each holding runtimeMutationInFlight (see withRuntimeMutation). */
574
+ runtimeMutationDepth = 0;
548
575
  accountReloadPending = false;
549
576
  runtimeAccounts = null;
550
577
  runtimeUsage = null;
@@ -851,10 +878,6 @@ export class RatatuiApp {
851
878
  pendingPaneReplacements = new Map();
852
879
  paneRegistry = new PaneRegistry();
853
880
  resumedPaneSpecs = [];
854
- /** Overseer-only model override from the web mirror dropdown.
855
- * Stored separately from configStore CLI overrides so it doesn't
856
- * leak to new child panes (which should use configStore.getModel()). */
857
- overseerModelOverride = null;
858
881
  paneMode = false;
859
882
  /**
860
883
  * Another ZTC launched this one into one of its panes (ZTC_PARENT_PID or ZTC_COLONY_CHILD, see launchedByAnotherZtc):
@@ -938,8 +961,8 @@ export class RatatuiApp {
938
961
  const renderWindowMs = this.renderFirstSentAt > 0 ? Math.max(1, now - this.renderFirstSentAt) : 1;
939
962
  return {
940
963
  uptimeMs: now - this.startedAt,
941
- provider: this.overseerModelOverride?.provider || configStore.getProvider(),
942
- model: this.overseerModelOverride?.model || configStore.getModel(),
964
+ provider: configStore.getProvider(),
965
+ model: configStore.getModel(),
943
966
  renderCount: this.renderCount,
944
967
  renderRatePerSec: this.renderCount > 0 ? (this.renderCount * 1000) / renderWindowMs : 0,
945
968
  lastRenderAt: this.lastRenderSentAt > 0 ? new Date(this.lastRenderSentAt).toISOString() : null,
@@ -1283,6 +1306,10 @@ export class RatatuiApp {
1283
1306
  this.desktopMode = options?.desktop ?? false;
1284
1307
  this.desktopRuntime = options?.desktopRuntime;
1285
1308
  this.paneMode = options?.pane ?? false;
1309
+ // A pane another ZTC launched runs its launch route flags for itself alone (ConfigStore.markLaunchedByParent).
1310
+ configStore.markLaunchedByParent(this.paneMode);
1311
+ // A repository's model where this pane works counts in the route a reload keeps (ConfigStore.followRouteDirectory).
1312
+ this.stopFollowingRouteDirectory = configStore.followRouteDirectory(() => this.shellCwd || process.cwd());
1286
1313
  this.computerUseMode = options?.computerUse ?? false;
1287
1314
  this.mlMode = options?.ml ?? false;
1288
1315
  this.embeddedSystemName = options?.embeddedSystemName ?? null;
@@ -1843,6 +1870,22 @@ export class RatatuiApp {
1843
1870
  this.dispatchPendingAgentWork();
1844
1871
  }
1845
1872
  }
1873
+ /**
1874
+ * Bring in what another ZTC on this profile saved since this one read it (a default chosen in another pane, a key,
1875
+ * a Router login), unless a command or a runtime change is running here, which may still save its own settings.
1876
+ * This pane keeps the route it runs on (ConfigStore.refreshIfChangedElsewhere). True when the profile was reloaded.
1877
+ */
1878
+ async refreshSettingsFromElsewhere(options = {}) {
1879
+ if (this.exiting || this.commandsRunning > 0 || (this.runtimeMutationInFlight && !options.duringOwnChange))
1880
+ return false;
1881
+ try {
1882
+ return await configStore.refreshIfChangedElsewhere();
1883
+ }
1884
+ catch (error) {
1885
+ debugLog(`[config] Reloading settings saved elsewhere failed: ${String(error)}`);
1886
+ return false;
1887
+ }
1888
+ }
1846
1889
  refreshRuntimeProjection() {
1847
1890
  const sessionId = this.sessionId;
1848
1891
  const cwd = this.shellCwd || process.cwd();
@@ -1851,6 +1894,8 @@ export class RatatuiApp {
1851
1894
  return;
1852
1895
  this.runtimeProjectionRefreshAt = Date.now();
1853
1896
  this.runtimeProjectionRefreshScope = { sessionId, cwd };
1897
+ // The 5 s tick also notices settings another pane saved.
1898
+ void this.refreshSettingsFromElsewhere();
1854
1899
  this.runtimeProjectionRefresh = Promise.all([
1855
1900
  getAccountsPayloadWithCodexStatus(configStore),
1856
1901
  collectUsageViews(cwd, sessionId, this.ensureSessionManager().getUsageSnapshot()),
@@ -1872,8 +1917,8 @@ export class RatatuiApp {
1872
1917
  }
1873
1918
  desktopRuntimeProjection() {
1874
1919
  this.refreshRuntimeProjection();
1875
- const provider = this.overseerModelOverride?.provider || configStore.getProvider();
1876
- const model = this.overseerModelOverride?.model || configStore.getModel();
1920
+ const provider = configStore.getProvider();
1921
+ const model = configStore.getModel();
1877
1922
  const bound = (text) => new TextDecoder('utf-8', { ignoreBOM: true })
1878
1923
  .decode(Buffer.from(text.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')).subarray(0, 256), { stream: true });
1879
1924
  const family = (name) => name.startsWith('codex_') ? 'codex' : name;
@@ -1902,9 +1947,70 @@ export class RatatuiApp {
1902
1947
  context_notice: bound('Idle switches retain conversation and tools; model limits may change. Usage is a retained minimum; some costs and historical accounts are unknown. Quota is account-wide; project is the working directory.'),
1903
1948
  };
1904
1949
  }
1950
+ /**
1951
+ * The lists this pane's header menus show, for a renderer that draws them (desktop_runtime_choices_v1), and never for
1952
+ * a hosted runtime. They are rebuilt from cached state on the 5 s tick, or at once after a switch, a saved setting or
1953
+ * discovery; their revision moves only when they change (RuntimeChoicesPublication). Undefined sends none.
1954
+ */
1955
+ runtimeChoicesFor() {
1956
+ if (!this.paneActivityTransport().hasCapability(CAPABILITY_DESKTOP_RUNTIME_CHOICES) || this.isHostedRuntime())
1957
+ return undefined;
1958
+ const now = Date.now();
1959
+ if (this.runtimeChoicesStale || !(now - this.runtimeChoicesBuiltAt >= 0 && now - this.runtimeChoicesBuiltAt < 5_000)) {
1960
+ this.runtimeChoicesStale = false;
1961
+ this.runtimeChoicesBuiltAt = now;
1962
+ let built;
1963
+ try {
1964
+ built = buildRuntimeChoices(this.ensureRuntimeChoicesSource().input(this.runtimeChoicePane()));
1965
+ }
1966
+ catch (error) {
1967
+ debugLog(`[runtime-choices] Could not build the header menus' lists: ${String(error)}`);
1968
+ }
1969
+ // A new list takes the revision of the state it first goes out with.
1970
+ this.publishedRuntimeChoices = this.runtimeChoicesPublication.update(built, this.desktopTaskRevision + 1);
1971
+ }
1972
+ return this.publishedRuntimeChoices;
1973
+ }
1974
+ ensureRuntimeChoicesSource() {
1975
+ if (!this.runtimeChoicesSource) {
1976
+ this.runtimeChoicesSource = new RuntimeChoicesSource(configStore, () => buildModelsController(configStore));
1977
+ // A saved setting (a key, a login, a route) can change what the lists show.
1978
+ this.stopFollowingChoiceSettings = configStore.onChange(() => { this.runtimeChoicesStale = true; });
1979
+ }
1980
+ return this.runtimeChoicesSource;
1981
+ }
1982
+ /** The route this pane runs on, as its header shows it; routed when it goes through Zerg Router. */
1983
+ currentPaneRoute() {
1984
+ try {
1985
+ const llm = configStore.resolveLLMBackendConfig({ cwd: this.shellCwd || process.cwd() });
1986
+ return { provider: llm.provider, model: llm.model, routed: llm.useProxy || isRouterOnlyProvider(llm.provider) };
1987
+ }
1988
+ catch {
1989
+ const provider = normalizeProviderId(configStore.getProvider());
1990
+ return { provider, model: configStore.getModel(), routed: configStore.getAuthMode() === 'zrouter' || isRouterOnlyProvider(provider) };
1991
+ }
1992
+ }
1993
+ /** What new panes start on, and whether that goes through Zerg Router. */
1994
+ newPaneChoice() {
1995
+ return newPaneRoute(configStore, configStore.getNewPaneRoute());
1996
+ }
1997
+ /** This pane runs its current model with its provider: a switch back to that provider lands on it. */
1998
+ rememberPaneModel() {
1999
+ const route = this.currentPaneRoute();
2000
+ this.paneModels.remember(providerChoiceId(route.provider, route.routed ? 'zergrouter' : 'direct'), route.model);
2001
+ }
2002
+ runtimeChoicePane() {
2003
+ const selected = this.currentPaneRoute();
2004
+ return { selected, newPane: this.newPaneChoice(),
2005
+ recentModels: this.paneModels.recall(providerChoiceId(selected.provider, selected.routed ? 'zergrouter' : 'direct')) };
2006
+ }
1905
2007
  async handleDesktopRuntimeAction(event) {
1906
2008
  if (!this.paneActivityTransport().hasCapability(CAPABILITY_DESKTOP_RUNTIME_CONTROLS))
1907
2009
  return;
2010
+ // The renderer sends every pane's action to the main ZTC, and the relay passes them to every child: each ZTC acts
2011
+ // on its own pane's alone, and keeps no record of another's.
2012
+ if (event.pane_id !== this.ownPaneId())
2013
+ return;
1908
2014
  const fingerprint = JSON.stringify(event);
1909
2015
  const existing = this.desktopRuntimeRequests.get(event.request_id);
1910
2016
  if (existing) {
@@ -1924,7 +2030,21 @@ export class RatatuiApp {
1924
2030
  request.result = { request_id: event.request_id, status, message };
1925
2031
  this.syncOwnPaneTaskControls(request.result);
1926
2032
  };
1927
- if (!state || event.pane_id !== this.ownPaneId() || event.session_id !== state.session_id
2033
+ switch (event.action) {
2034
+ case 'account_use':
2035
+ case 'open_models':
2036
+ break;
2037
+ case 'select_runtime':
2038
+ case 'refresh_choices':
2039
+ case 'router_login':
2040
+ case 'save_as_default':
2041
+ await this.handleRuntimeChoiceAction(event, reply);
2042
+ return;
2043
+ default:
2044
+ reply('invalid', `Unknown runtime action: ${String(event.action)}.`);
2045
+ return;
2046
+ }
2047
+ if (!state || event.session_id !== state.session_id
1928
2048
  || event.owner_id !== state.owner_id || event.revision !== state.revision) {
1929
2049
  reply('stale', 'Runtime controls changed. Review the current selection and try again.');
1930
2050
  return;
@@ -1939,34 +2059,181 @@ export class RatatuiApp {
1939
2059
  const result = await this.applyAccountOperation({ op: 'use', id: event.account_id });
1940
2060
  reply(result.ok ? 'applied' : result.blocked ? 'blocked' : 'invalid', result.message ?? result.error ?? 'Account selection completed.');
1941
2061
  }
1942
- else {
1943
- this.runtimeMutationInFlight = true;
1944
- this.syncOwnPaneTaskControls();
2062
+ else if (state.runtime_choices) {
2063
+ // More models… in a pane header, or the title-bar chip of a pane whose header shows none: the picker stays open
2064
+ // in the pane, which the renderer needn't wait for, and its choice switches this pane alone. Having answered,
2065
+ // the pane says itself what went wrong.
2066
+ reply('applied', '');
1945
2067
  try {
1946
- await this.openDesktopModelPicker();
1947
- reply('applied', 'Model palette completed.');
2068
+ await this.withRuntimeMutation(() => this.openDesktopModelPicker('pane'));
1948
2069
  }
1949
- finally {
1950
- this.runtimeMutationInFlight = false;
1951
- this.syncOwnPaneTaskControls();
1952
- this.dispatchPendingAgentWork();
2070
+ catch (error) {
2071
+ this.addSystemMessage(`Could not list this pane's models: ${error instanceof Error ? error.message : String(error)}`);
1953
2072
  }
1954
2073
  }
2074
+ else {
2075
+ await this.withRuntimeMutation(() => this.openDesktopModelPicker('profile'));
2076
+ reply('applied', 'Model palette completed.');
2077
+ }
1955
2078
  }
1956
2079
  catch (error) {
1957
2080
  reply('invalid', error instanceof Error ? error.message : String(error));
1958
2081
  }
1959
2082
  }
2083
+ /**
2084
+ * Run `change` as a runtime change: agent turns and the queue wait while it runs (runAgent, handleSubmit), the
2085
+ * desktop app greys out the runtime controls, and pending work runs once it ends. Changes nest: a pane switch inside
2086
+ * a picker holds the flag until the picker ends.
2087
+ */
2088
+ async withRuntimeMutation(change) {
2089
+ if (this.runtimeMutationDepth++ === 0) {
2090
+ this.runtimeMutationInFlight = true;
2091
+ this.syncOwnPaneTaskControls();
2092
+ }
2093
+ try {
2094
+ return await change();
2095
+ }
2096
+ finally {
2097
+ if (--this.runtimeMutationDepth === 0) {
2098
+ this.runtimeMutationInFlight = false;
2099
+ this.runtimeChoicesStale = true;
2100
+ this.syncOwnPaneTaskControls();
2101
+ this.dispatchPendingAgentWork();
2102
+ }
2103
+ }
2104
+ }
2105
+ /**
2106
+ * The actions a pane header's menus send (desktop_runtime_choices_v1), which zterm sends only for a pane whose state
2107
+ * carries `runtime_choices`. Each is checked against this pane's session and owner; a choice also against the lists
2108
+ * it was made from: the lists' revision up to the state's current one (a newer state with the same lists still
2109
+ * holds them).
2110
+ */
2111
+ async handleRuntimeChoiceAction(event, reply) {
2112
+ const state = this.desktopTaskState;
2113
+ const ours = state !== null && event.session_id === state.session_id && event.owner_id === state.owner_id;
2114
+ if (event.action === 'refresh_choices') {
2115
+ // Never answered: the lists that follow are the answer.
2116
+ if (ours)
2117
+ await this.refreshRuntimeChoices(event.force);
2118
+ return;
2119
+ }
2120
+ if (!ours || !state.runtime_choices) {
2121
+ reply('stale', 'The provider list changed. Choose again.');
2122
+ return;
2123
+ }
2124
+ if (event.action === 'router_login') {
2125
+ // The browser wait holds nothing: the pane stays usable, and the lists follow once the login lands.
2126
+ reply('applied', 'Log in in your browser; the code is in this pane.');
2127
+ void this.runRouterLogin();
2128
+ return;
2129
+ }
2130
+ if (event.revision < state.runtime_choices.revision || event.revision > state.revision) {
2131
+ reply('stale', 'The provider list changed. Choose again.');
2132
+ return;
2133
+ }
2134
+ const blocked = this.runtimeSwitchBlockedReason();
2135
+ if (blocked) {
2136
+ reply('blocked', blocked);
2137
+ return;
2138
+ }
2139
+ if (event.action === 'save_as_default') {
2140
+ await this.withRuntimeMutation(() => this.saveRouteAsDefault(reply));
2141
+ return;
2142
+ }
2143
+ const verdict = checkRuntimeSelection(state.runtime_choices, event);
2144
+ if (verdict) {
2145
+ reply(verdict.status, verdict.message);
2146
+ return;
2147
+ }
2148
+ await this.withRuntimeMutation(() => this.selectPaneRuntime(event, reply));
2149
+ }
2150
+ /**
2151
+ * A header's provider or model choice, for this pane alone. Settings another pane saved meanwhile (a key, a login)
2152
+ * count, and the choice is checked again against the lists as they are now; then it applies as /provider would,
2153
+ * asking for a missing key or login in this pane, and finishing once it is saved.
2154
+ */
2155
+ async selectPaneRuntime(event, reply) {
2156
+ if (await this.refreshSettingsFromElsewhere({ duringOwnChange: true }))
2157
+ this.runtimeChoicesStale = true;
2158
+ const current = this.runtimeChoicesFor()?.value;
2159
+ const verdict = current ? checkRuntimeSelection(current, event) : undefined;
2160
+ if (verdict) {
2161
+ reply(verdict.status, verdict.message);
2162
+ return;
2163
+ }
2164
+ const { provider, route } = parseProviderChoiceId(event.provider_choice);
2165
+ const context = this.buildCommandContext(message => this.controller.addMessage(message));
2166
+ const outcome = await selectProviderModel([route, provider, ...(event.model ? [event.model] : [])], context, {
2167
+ scope: 'pane',
2168
+ // Back to a provider, the model this pane last ran with it.
2169
+ preferredModel: event.model ? undefined : this.paneModels.recall(event.provider_choice)[0],
2170
+ confirm: applied => paneSwitchConfirmation(context, applied),
2171
+ });
2172
+ if (outcome.kind === 'applied')
2173
+ reply('applied', '');
2174
+ else if (outcome.kind === 'prompted')
2175
+ reply('applied', outcome.message);
2176
+ else
2177
+ reply(outcome.blocked ? 'blocked' : 'invalid', outcome.message);
2178
+ }
2179
+ /** "Use for new panes": this pane's route becomes the default, as /provider would set it. */
2180
+ async saveRouteAsDefault(reply) {
2181
+ const route = this.currentPaneRoute();
2182
+ const context = this.buildCommandContext(message => this.controller.addMessage(message));
2183
+ const outcome = await selectProviderModel([route.routed ? 'zergrouter' : 'direct', route.provider, route.model], context, { confirm: (applied, kept) => newPanesConfirmation(context, applied, kept) });
2184
+ reply(outcome.kind === 'refused' ? 'invalid' : 'applied', outcome.message);
2185
+ }
2186
+ /** Router's catalog and the pane's provider's models again, as a menu asks; the lists follow as they load. */
2187
+ async refreshRuntimeChoices(force) {
2188
+ // Settings another pane saved since (a login, a key) count before anything is asked for.
2189
+ if (await this.refreshSettingsFromElsewhere())
2190
+ this.runtimeChoicesStale = true;
2191
+ const changed = () => {
2192
+ this.runtimeChoicesStale = true;
2193
+ if (!this.exiting)
2194
+ this.syncOwnPaneTaskControls();
2195
+ };
2196
+ changed();
2197
+ try {
2198
+ await this.ensureRuntimeChoicesSource().refresh(force, this.currentPaneRoute(), changed);
2199
+ }
2200
+ catch (error) {
2201
+ debugLog(`[runtime-choices] Refreshing the header menus' lists failed: ${String(error)}`);
2202
+ }
2203
+ }
2204
+ /** A header's "Log in to Zerg Router…": the login runs in this pane, which shows its code; the lists follow. */
2205
+ async runRouterLogin() {
2206
+ // It runs as /auth login does: the profile isn't reloaded under it, so the login's own reload applies its route.
2207
+ this.commandsRunning++;
2208
+ try {
2209
+ await runAuthAction(['login'], this.buildCommandContext(message => this.controller.addMessage(message)));
2210
+ }
2211
+ catch (error) {
2212
+ this.addSystemMessage(`Zerg Router login failed: ${error instanceof Error ? error.message : String(error)}`);
2213
+ }
2214
+ finally {
2215
+ this.commandsRunning--;
2216
+ }
2217
+ await this.refreshRuntimeChoices(true);
2218
+ }
1960
2219
  /**
1961
2220
  * The model chip's picker: a provider first, Zerg Router's from the cached catalog whatever this pane's route, then
1962
2221
  * the person's own keys, and then that provider's models (see pickProviderAndModel). Nothing new crosses the wire,
1963
2222
  * so every zterm gets it.
1964
2223
  */
1965
- async openDesktopModelPicker() {
1966
- const provider = this.overseerModelOverride?.provider || configStore.getProvider();
1967
- const model = this.overseerModelOverride?.model || configStore.getModel();
2224
+ async openDesktopModelPicker(scope) {
2225
+ const provider = configStore.getProvider();
2226
+ const model = configStore.getModel();
1968
2227
  const context = this.buildCommandContext(message => this.controller.addMessage(message));
1969
- await pickProviderAndModel(context, { provider, model }, (command, args) => this.handleCommand(command, args, false));
2228
+ // A pane that publishes its header's lists switches alone; an older renderer's chip sets the default, as /provider.
2229
+ const run = scope === 'profile' ? (command, args) => this.handleCommand(command, args, false)
2230
+ : async (command, args) => {
2231
+ const here = this.currentPaneRoute();
2232
+ // A provider /provider can't name keeps the route it runs on (the picker's `/model set`).
2233
+ const selection = command === 'provider' ? args : [here.routed ? 'zergrouter' : 'direct', here.provider, args[1]];
2234
+ await selectProviderModel(selection, context, { scope: 'pane', confirm: applied => paneSwitchConfirmation(context, applied) });
2235
+ };
2236
+ await pickProviderAndModel(context, { provider, model }, run);
1970
2237
  await this.awaitAgentBind();
1971
2238
  this.runtimeProjectionRefreshAt = 0;
1972
2239
  }
@@ -2133,11 +2400,13 @@ export class RatatuiApp {
2133
2400
  };
2134
2401
  }),
2135
2402
  };
2136
- const signature = JSON.stringify(projection);
2403
+ // The header menus' lists, only with the runtime they describe; the signature carries their hash, not their text.
2404
+ const choices = projection.runtime ? this.runtimeChoicesFor() : undefined;
2405
+ const signature = desktopTaskSignature(projection, choices);
2137
2406
  const changed = signature !== this.desktopTaskSignature;
2138
2407
  if (changed) {
2139
2408
  this.desktopTaskSignature = signature;
2140
- this.desktopTaskState = { ...projection, revision: ++this.desktopTaskRevision };
2409
+ this.desktopTaskState = { ...projection, ...(choices ? { runtime_choices: choices.value } : {}), revision: ++this.desktopTaskRevision };
2141
2410
  }
2142
2411
  if ((!changed && !result) || this.desktopTaskState === null)
2143
2412
  return;
@@ -2377,7 +2646,6 @@ export class RatatuiApp {
2377
2646
  if (status !== 'idle' && status !== 'error') {
2378
2647
  throw new Error('Wait for the current turn to finish before switching profiles.');
2379
2648
  }
2380
- const previousOverseerOverride = this.overseerModelOverride;
2381
2649
  const previousConfig = configStore.get();
2382
2650
  const previousMcp = JSON.stringify(previousConfig.mcpServers ?? {});
2383
2651
  const previousColonyMcp = process.env.ZTC_COLONY_MCP;
@@ -2417,7 +2685,6 @@ export class RatatuiApp {
2417
2685
  if (mcpChanged)
2418
2686
  await reloadMcp();
2419
2687
  await reloadSkills();
2420
- this.overseerModelOverride = null;
2421
2688
  const nextAgent = this.createAgent({ allowUnavailableRouterAuth: true });
2422
2689
  this.replaceAgent(nextAgent);
2423
2690
  if (nextAgent)
@@ -2432,7 +2699,6 @@ export class RatatuiApp {
2432
2699
  await configStore.duplicateProfile(name, duplicateSource, activate);
2433
2700
  }
2434
2701
  catch (error) {
2435
- this.overseerModelOverride = previousOverseerOverride;
2436
2702
  if (previousColonyMcp === undefined)
2437
2703
  delete process.env.ZTC_COLONY_MCP;
2438
2704
  else
@@ -2592,15 +2858,26 @@ export class RatatuiApp {
2592
2858
  await this.switchConfigProfileInPlace(name, source);
2593
2859
  return name;
2594
2860
  },
2595
- getRuntimeRoute: () => ({ provider: this.overseerModelOverride?.provider || configStore.getProvider(),
2596
- model: this.overseerModelOverride?.model || configStore.getModel() }),
2597
2861
  setRuntimeModelOverride: (provider, model, authMode) => {
2598
- // The choice is this process's own route too, so --provider, --model and --auth-mode stop masking it.
2599
- const took = this.hotSwapModel(provider, model, { authMode, pinRoute: true });
2862
+ // The choice is the default for new panes and this pane's route: --provider, --model and --auth-mode stop
2863
+ // masking it (see hotSwapModel).
2864
+ this.rememberPaneModel();
2865
+ const took = this.hotSwapModel(provider, model, { authMode, setsDefault: true });
2600
2866
  this.hookLifecycle.ensureWatcher();
2601
- this.mirrorServer?.setPaneModel(0, model, provider);
2867
+ this.mirrorServer?.setPaneModel(0, configStore.getModel(), configStore.getProvider());
2602
2868
  return took;
2603
2869
  },
2870
+ applyPaneRoute: route => this.withRuntimeMutation(async () => {
2871
+ // A turn may have started while the choice waited for Router's catalog or a key.
2872
+ if (this.isAgentBusy() || this.pendingAgentTurn || this.pendingBusTrigger) {
2873
+ return { ok: false, blocked: true, message: 'An active agent turn or tool is running; wait before switching' };
2874
+ }
2875
+ this.rememberPaneModel();
2876
+ const ok = this.hotSwapModel(route.provider, route.model, { authMode: route.authMode });
2877
+ this.hookLifecycle.ensureWatcher();
2878
+ this.mirrorServer?.setPaneModel(0, configStore.getModel(), configStore.getProvider());
2879
+ return ok ? { ok } : { ok, message: 'This pane keeps the model it runs on; it says why above.' };
2880
+ }),
2604
2881
  restartZtc: () => this.restartZtc(),
2605
2882
  setDebug: (enabled) => this.controller.setDebug(enabled),
2606
2883
  retry: () => { },
@@ -2677,9 +2954,11 @@ export class RatatuiApp {
2677
2954
  else {
2678
2955
  const pane = this.paneRegistry.get(paneId);
2679
2956
  if (pane?.launchSpec?.kind === 'ztc') {
2957
+ // A pane with no route of its own on record started on the route new panes start on.
2958
+ const started = configStore.getNewPaneRoute();
2680
2959
  await setSessionLabels(pane.launchSpec.session.id, pane.launchSpec.cwd ?? this.shellCwd, labels, {
2681
- model: pane.effectiveModel ?? configStore.getModel(),
2682
- provider: pane.effectiveProvider ?? configStore.getProvider(),
2960
+ model: pane.effectiveModel ?? started.model,
2961
+ provider: pane.effectiveProvider ?? started.provider,
2683
2962
  });
2684
2963
  }
2685
2964
  }
@@ -4240,13 +4519,13 @@ export class RatatuiApp {
4240
4519
  }
4241
4520
  else {
4242
4521
  const headlessPaneModel = this.childPaneModels.get(event.pane_id)
4243
- || (event.pane_type === 'ztc' ? configStore.getModel() : null);
4522
+ || (event.pane_type === 'ztc' ? configStore.getNewPaneRoute().model : null);
4244
4523
  if (headlessPaneModel) {
4245
4524
  this.childPaneModels.set(event.pane_id, headlessPaneModel);
4246
4525
  }
4247
4526
  if (this.mirrorServer) {
4248
4527
  const headlessPaneProvider = this.paneRegistry.get(event.pane_id)?.effectiveProvider
4249
- || (event.pane_type === 'ztc' ? configStore.getProvider() : undefined);
4528
+ || (event.pane_type === 'ztc' ? configStore.getNewPaneRoute().provider : undefined);
4250
4529
  this.mirrorServer.registerPane(event.pane_id, event.title, event.pane_type, headlessPaneModel || undefined, headlessPaneProvider);
4251
4530
  if (event.pane_type === 'process' || event.pane_type === 'command') {
4252
4531
  this.mirrorServer.publish({
@@ -4359,7 +4638,7 @@ export class RatatuiApp {
4359
4638
  if (cmd.__ztc_cmd === 'set_effort') {
4360
4639
  if (cmd.model)
4361
4640
  configStore.setModelEffort(cmd.model, (cmd.effort ?? null));
4362
- this.hotSwapModel(cmd.provider || configStore.getProvider(), cmd.model || configStore.getModel());
4641
+ this.rebuildOnCurrentRoute();
4363
4642
  return;
4364
4643
  }
4365
4644
  if (cmd.__ztc_cmd === 'submit_input') {
@@ -4455,12 +4734,15 @@ export class RatatuiApp {
4455
4734
  // Both interactive (TuiProcess) and headless (HeadlessPaneManager) serve the relay.
4456
4735
  // This allows sub-panes spawned within colony cells to connect and use pane tools.
4457
4736
  this.paneRelay = new PaneRelayServer(this.tui, process.env.ZTC_PANE_RELAY);
4737
+ // A child's report of its own pane tells this process the route it runs on (see noteChildPaneReport).
4738
+ this.paneRelay.onChildCommand((command, announced) => this.noteChildPaneReport(command, announced));
4458
4739
  await this.paneRelay.start();
4459
4740
  this.assertStartupActive();
4460
4741
  debugLog(`[start] Pane relay server started: ${process.env.ZTC_PANE_RELAY}`);
4461
4742
  }
4462
4743
  else if (this.paneMode && process.env.ZTC_PANE_RELAY) {
4463
- this.paneRelayClient = new PaneRelayClient(process.env.ZTC_PANE_RELAY);
4744
+ // The relay learns which pane this connection speaks for, so the main ZTC can trust what it reports.
4745
+ this.paneRelayClient = new PaneRelayClient(process.env.ZTC_PANE_RELAY, { paneId: this.ownPaneId() ?? undefined });
4464
4746
  try {
4465
4747
  await this.paneRelayClient.connect();
4466
4748
  this.assertStartupActive();
@@ -5298,28 +5580,36 @@ export class RatatuiApp {
5298
5580
  return { command: built.command, args: built.args, cwd: built.cwd };
5299
5581
  }
5300
5582
  createZtcPaneSpec(options) {
5301
- const resolved = options?.model
5302
- ? resolveModelAndProvider(options.model, options.provider, configStore.getResolvedAuthMode())
5303
- : { model: undefined, provider: options?.provider };
5583
+ // A split starts on exactly the provider and model the pane it splits runs (its auth mode names that route), any
5584
+ // provider of the person's own included. Any other pane names its model against the route a new pane starts on.
5585
+ const ownRoute = options?.authMode !== undefined && !!options.provider && !!options.model;
5586
+ const route = options?.authMode ?? configStore.getNewPaneRoute().authMode;
5587
+ const resolved = options?.model && !ownRoute
5588
+ ? resolveModelAndProvider(options.model, options.provider, route)
5589
+ : { model: options?.model, provider: options?.provider };
5304
5590
  return createZtcLaunchSpec({
5305
5591
  sessionId: options?.sessionId,
5306
5592
  sessionMode: options?.sessionMode,
5307
5593
  cwd: options?.cwd ?? (this.shellCwd || process.cwd()),
5308
5594
  title: options?.title || 'ZTC',
5309
- providerOverride: isPaneProvider(resolved.provider, configStore.getResolvedAuthMode()) ? resolved.provider : undefined,
5595
+ providerOverride: ownRoute || isPaneProvider(resolved.provider, route) ? resolved.provider : undefined,
5310
5596
  modelOverride: resolved.model,
5597
+ ...(options?.authMode ? { authMode: options.authMode } : {}),
5598
+ ...(options?.routerOrigin ? { routerOrigin: options.routerOrigin } : {}),
5311
5599
  extraArgs: [],
5312
5600
  });
5313
5601
  }
5314
5602
  registerPaneSpec(paneId, paneType, title, launchSpec) {
5315
5603
  const isZtc = launchSpec?.kind === 'ztc' || paneType === 'ztc';
5604
+ // A ZTC pane that names no route of its own starts on the route new panes start on, never this pane's.
5605
+ const started = configStore.getNewPaneRoute();
5316
5606
  const effectiveModel = isZtc
5317
- ? (launchSpec?.kind === 'ztc' ? launchSpec.modelOverride : undefined) || configStore.getModel()
5607
+ ? (launchSpec?.kind === 'ztc' ? launchSpec.modelOverride : undefined) || started.model
5318
5608
  : undefined;
5319
- const configProvider = configStore.getProvider();
5609
+ const configProvider = started.provider;
5320
5610
  const providerOverride = launchSpec?.kind === 'ztc' ? launchSpec.providerOverride : undefined;
5321
5611
  const modelOverride = launchSpec?.kind === 'ztc' ? launchSpec.modelOverride : undefined;
5322
- const configuredPaneProvider = isPaneProvider(configProvider, configStore.getResolvedAuthMode()) ? configProvider : undefined;
5612
+ const configuredPaneProvider = isPaneProvider(configProvider, started.authMode) ? configProvider : undefined;
5323
5613
  const effectiveProvider = isZtc
5324
5614
  ? providerOverride
5325
5615
  || (!modelOverride ? configuredPaneProvider : undefined)
@@ -5342,6 +5632,52 @@ export class RatatuiApp {
5342
5632
  else
5343
5633
  this.childPaneSessionIds.delete(paneId);
5344
5634
  }
5635
+ /**
5636
+ * A child ZTC's report of its own pane, relayed: its runtime names the provider and model it runs on, and its header's
5637
+ * lists name the provider choice, through Zerg Router or not. Trusted only from the relay connection that named that
5638
+ * pane, and only for a ZTC child this process registered or a native ZTC pane (#860's More… → ZTC). The pane's record
5639
+ * follows it: the web mirror's badge, and the launch spec a restore or a split relaunches it from, auth mode included
5640
+ * (the Router origin is kept). A native ZTC pane's launch spec is its native record, which only the desktop's native
5641
+ * owner writes: its route is kept beside it, for a split.
5642
+ */
5643
+ noteChildPaneReport(command, announced) {
5644
+ if (command.type !== 'set_pane_task_controls' || announced === null || command.pane_id !== announced
5645
+ || announced === this.ownPaneId())
5646
+ return;
5647
+ const pane = this.paneRegistry.get(announced);
5648
+ const native = isNativeZtcPane(pane);
5649
+ if (pane?.paneType !== 'ztc' && !native)
5650
+ return;
5651
+ const { provider, model } = command.state?.runtime ?? {};
5652
+ if (typeof provider !== 'string' || typeof model !== 'string' || !provider || !model
5653
+ || isRetiredProvider(provider) || isRetiredModel(model))
5654
+ return;
5655
+ // Only the header's lists say whether the pane runs through Zerg Router, so only a report that carries them names
5656
+ // its route whole. One without (a renderer that takes no lists, a pane whose lists couldn't be built) moves the
5657
+ // badge alone: a split or a restore never starts on its provider and model with an auth mode it didn't report.
5658
+ const selected = command.state.runtime_choices?.selected_provider;
5659
+ const authMode = typeof selected === 'string' ? (parseProviderChoiceId(selected).route === 'zergrouter' ? 'zrouter' : 'direct') : undefined;
5660
+ if (native) {
5661
+ if (authMode)
5662
+ pane.reportedRoute = { provider, model, authMode };
5663
+ return;
5664
+ }
5665
+ const spec = pane.launchSpec?.kind === 'ztc' ? pane.launchSpec : undefined;
5666
+ const specFollows = spec !== undefined && authMode !== undefined
5667
+ && !(spec.providerOverride === provider && spec.modelOverride === model && spec.authMode === authMode);
5668
+ if (pane.effectiveProvider === provider && pane.effectiveModel === model && !specFollows)
5669
+ return;
5670
+ pane.effectiveProvider = provider;
5671
+ pane.effectiveModel = model;
5672
+ this.childPaneModels.set(announced, model);
5673
+ this.mirrorServer?.setPaneModel(announced, model, provider);
5674
+ if (spec && specFollows) {
5675
+ spec.providerOverride = provider;
5676
+ spec.modelOverride = model;
5677
+ spec.authMode = authMode;
5678
+ }
5679
+ this.scheduleMuxPersistenceSave();
5680
+ }
5345
5681
  trackPendingPaneReplacement(paneId, requestId) {
5346
5682
  this.dailyDesktop?.paneClosed(paneId);
5347
5683
  this.pendingPaneReplacements.set(paneId, { requestId, sawClose: false, ignoreNextClose: false, createdAt: Date.now() });
@@ -5561,7 +5897,15 @@ export class RatatuiApp {
5561
5897
  delegatedSkillRoots: () => configStore.get().desktopDelegatedSkillRoots ?? [],
5562
5898
  select: (title, options) => this.dailySelect(title, options),
5563
5899
  input: (title, defaultValue) => new Promise(resolve => this.textInputWidget.show({ title, question: title, defaultValue, callback: resolve })),
5564
- track: record => { const clean = parseNativeRecords({ [record.paneId]: record })[String(record.paneId)]; this.registerPaneSpec(clean.paneId, clean.launch.mode === 'interactive' ? 'process' : 'feed', `${clean.launch.tool} ${clean.launch.mode}`, { kind: 'native_tool', title: clean.launch.tool, record: clean }); },
5900
+ track: record => {
5901
+ const clean = parseNativeRecords({ [record.paneId]: record })[String(record.paneId)];
5902
+ this.registerPaneSpec(clean.paneId, clean.launch.mode === 'interactive' ? 'process' : 'feed', `${clean.launch.tool} ${clean.launch.mode}`, { kind: 'native_tool', title: clean.launch.tool, record: clean });
5903
+ // The record kept is rebuilt from its recipe, with none of its launch flags: the Router a native ZTC pane was
5904
+ // launched or resumed on is kept beside it, for a split of it (see splitRouteFor).
5905
+ const registered = this.paneRegistry.get(clean.paneId);
5906
+ if (isNativeZtcPane(registered))
5907
+ registered.launchRouterOrigin = nativeLaunchRouterOrigin(record);
5908
+ },
5565
5909
  changed: () => { this.scheduleMuxPersistenceSave(100); this.syncOwnPaneTaskControls(); }, notify: message => this.controller.addMessage({ role: 'system', content: message }),
5566
5910
  });
5567
5911
  await daily.start();
@@ -6035,10 +6379,10 @@ export class RatatuiApp {
6035
6379
  this.publishPaneSystemMessage(command.pane_id, error);
6036
6380
  return { ok: false, error };
6037
6381
  }
6038
- // --- Overseer (pane 0): hot-swap directly in this process ---
6382
+ // --- Overseer (pane 0): hot-swap directly in this process, for this pane alone ---
6039
6383
  if (command.pane_id === 0) {
6040
6384
  this.hotSwapModel(nextOverride?.provider, nextOverride?.model);
6041
- this.mirrorServer?.setPaneModel(0, this.overseerModelOverride?.model || configStore.getModel(), this.overseerModelOverride?.provider || configStore.getProvider());
6385
+ this.mirrorServer?.setPaneModel(0, configStore.getModel(), configStore.getProvider());
6042
6386
  return { ok: true };
6043
6387
  }
6044
6388
  // --- Child panes: hot-swap via bus message ---
@@ -6080,9 +6424,10 @@ export class RatatuiApp {
6080
6424
  text: hotSwapPayload,
6081
6425
  });
6082
6426
  }
6083
- // Update parent-side tracking immediately.
6084
- const effectiveModel = nextOverride?.model || configStore.getModel();
6085
- const effectiveProvider = nextOverride?.provider || configStore.getProvider();
6427
+ // Update parent-side tracking immediately. A reset puts the pane back on the route new panes start on.
6428
+ const started = configStore.getNewPaneRoute();
6429
+ const effectiveModel = nextOverride?.model || started.model;
6430
+ const effectiveProvider = nextOverride?.provider || started.provider;
6086
6431
  this.childPaneModels.set(command.pane_id, effectiveModel);
6087
6432
  pane.effectiveModel = effectiveModel;
6088
6433
  pane.effectiveProvider = isPaneProvider(effectiveProvider, configStore.getResolvedAuthMode()) ? effectiveProvider : undefined;
@@ -6124,8 +6469,8 @@ export class RatatuiApp {
6124
6469
  configStore.setModelEffort(command.model, level);
6125
6470
  void configStore.save();
6126
6471
  if (command.pane_id === 0) {
6127
- // Overseer: rebuild in-process, preserving any active model override.
6128
- this.hotSwapModel(this.overseerModelOverride?.provider, this.overseerModelOverride?.model);
6472
+ // Overseer: rebuild in-process on the route it runs on, its own when it has one.
6473
+ this.rebuildOnCurrentRoute();
6129
6474
  return { ok: true };
6130
6475
  }
6131
6476
  // Child pane: carry the effort in a bus message; the child sets it on its
@@ -7342,7 +7687,7 @@ export class RatatuiApp {
7342
7687
  // Resolve display model: already-recorded child model → ztc default.
7343
7688
  // Tracked so the mirror UI shows the correct model badge.
7344
7689
  const paneModel = this.childPaneModels.get(event.pane_id)
7345
- || (event.pane_type === 'ztc' ? configStore.getModel() : null);
7690
+ || (event.pane_type === 'ztc' ? configStore.getNewPaneRoute().model : null);
7346
7691
  if (paneModel) {
7347
7692
  this.childPaneModels.set(event.pane_id, paneModel);
7348
7693
  }
@@ -7357,7 +7702,7 @@ export class RatatuiApp {
7357
7702
  }
7358
7703
  else if (this.mirrorServer) {
7359
7704
  const paneProvider = this.paneRegistry.get(event.pane_id)?.effectiveProvider
7360
- || (event.pane_type === 'ztc' ? configStore.getProvider() : undefined);
7705
+ || (event.pane_type === 'ztc' ? configStore.getNewPaneRoute().provider : undefined);
7361
7706
  this.mirrorServer.registerPane(event.pane_id, event.title, event.pane_type, paneModel || undefined, paneProvider);
7362
7707
  if (event.pane_type === 'process' || event.pane_type === 'command') {
7363
7708
  this.mirrorServer.publish({
@@ -9020,7 +9365,7 @@ export class RatatuiApp {
9020
9365
  if (cmd.model)
9021
9366
  configStore.setModelEffort(cmd.model, (cmd.effort ?? null));
9022
9367
  // Rebuild the agent with the same model so the new effort applies.
9023
- this.hotSwapModel(cmd.provider || configStore.getProvider(), cmd.model || configStore.getModel());
9368
+ this.rebuildOnCurrentRoute();
9024
9369
  return;
9025
9370
  }
9026
9371
  if (cmd.__ztc_cmd === 'widget_answer') {
@@ -9503,7 +9848,7 @@ export class RatatuiApp {
9503
9848
  resolveSendRoute() {
9504
9849
  let route;
9505
9850
  try {
9506
- route = configStore.resolveLLMBackendConfig({ cwd: this.shellCwd || process.cwd(), ...(this.overseerModelOverride ?? {}) });
9851
+ route = configStore.resolveLLMBackendConfig({ cwd: this.shellCwd || process.cwd() });
9507
9852
  }
9508
9853
  catch (error) {
9509
9854
  // A profile waiting for a route choice has no route, whatever a key or a
@@ -9611,8 +9956,8 @@ export class RatatuiApp {
9611
9956
  if (this.exiting)
9612
9957
  return;
9613
9958
  this.restoreComposerAfterRewind(prompt, []);
9614
- const provider = this.overseerModelOverride?.provider || configStore.getProvider();
9615
- const model = this.overseerModelOverride?.model || configStore.getModel();
9959
+ const provider = configStore.getProvider();
9960
+ const model = configStore.getModel();
9616
9961
  const note = `Your prompt is in the composer: press Enter to send it on ${provider}/${model}.`;
9617
9962
  this.controller.addMessage(createFirstRunLaunchMessage(note));
9618
9963
  this.mirror?.publishMessage('system', note);
@@ -10072,7 +10417,7 @@ export class RatatuiApp {
10072
10417
  ?? this.controller.getState().messages.find(message => message.role === 'user' && !message.metadata?.toolResult)?.content ?? '';
10073
10418
  const decision = classifyBusyInput({
10074
10419
  backendOptions: { config, cwd: this.shellCwd || process.cwd(), mode: this.getEffectiveAgentMode(),
10075
- ...(this.overseerModelOverride ?? {}), sessionId: routingSessionId },
10420
+ sessionId: routingSessionId },
10076
10421
  currentTask, inputText: input.text, hosted: this.isHostedRuntime(), signal: controller.signal,
10077
10422
  onUsage: receipt => {
10078
10423
  routingSession.restoreUsageSnapshot(recordUsageReceipt(createUsageSnapshot(), receipt));
@@ -12113,6 +12458,15 @@ export class RatatuiApp {
12113
12458
  * its panes reads from its terminal (see handleSubmit).
12114
12459
  */
12115
12460
  async handleCommand(cmd, cmdArgs, publishUserMessage = true, origin) {
12461
+ this.commandsRunning++;
12462
+ try {
12463
+ await this.runCommand(cmd, cmdArgs, publishUserMessage, origin);
12464
+ }
12465
+ finally {
12466
+ this.commandsRunning--;
12467
+ }
12468
+ }
12469
+ async runCommand(cmd, cmdArgs, publishUserMessage, origin) {
12116
12470
  if (cmd === 'pane' && cmdArgs[0] === 'stop' && this.dailyDesktop) {
12117
12471
  if (origin === 'relayed') {
12118
12472
  this.addSystemMessage('Native Stop requires a direct human command');
@@ -12326,25 +12680,24 @@ export class RatatuiApp {
12326
12680
  return next;
12327
12681
  }
12328
12682
  /**
12329
- * Hot-swap the model for this ZTC instance without restarting the process.
12330
- * Used by both the overseer (pane 0, called directly) and child panes
12331
- * (called via stdin JSON command from the parent).
12683
+ * Hot-swap the model for this ZTC instance without restarting the process: the main pane's (the web mirror's model
12684
+ * menu, a header choice) and a child pane's (its parent's set_model, a header choice) alike.
12332
12685
  *
12333
- * For the overseer: stores the override on this instance only, keeping
12334
- * configStore clean so new child panes still use the config default.
12335
- * For child panes: uses CLI overrides since each child is its own process.
12336
- * `pinRoute`, for a choice that also set the saved default, sets the CLI
12337
- * overrides on the overseer too, so its launch flags stop masking it.
12338
- * `authMode`, given when the choice names its route, moves with the provider
12339
- * and model: a pane's launch --auth-mode would otherwise keep the old route.
12340
- * A failed rebuild restores everything this set. False when this pane then
12341
- * runs on another route than the one asked for, which it says why.
12686
+ * The choice becomes this pane's own route in ConfigStore (setPaneRoute), which every reader of this pane's route
12687
+ * sees and nothing saves, so new panes still start on the configured route. No provider and model puts the pane
12688
+ * back on the configured route. `setsDefault`, for a choice just saved as the default for new panes (/provider,
12689
+ * /model, /settings), also drops this process's own launch flags (--provider, --model and --auth-mode, not
12690
+ * --router-url), which would otherwise outrank the new default for the panes it opens. `authMode`, given when the
12691
+ * choice names its route, moves with the provider and model: a pane's launch --auth-mode would otherwise keep the
12692
+ * old route. `keepsRoute` rebuilds on the route the pane runs on as it stands (its own, else the configured one with
12693
+ * the launch flags it was started with), as a changed effort needs. A failed rebuild keeps the pane on the route its
12694
+ * live agent was built on. False when this pane then runs on another route than the one asked for, which it says why.
12342
12695
  */
12343
12696
  hotSwapModel(provider, model, options = {}) {
12344
12697
  // A stale selection of a retired Claude Code route (an older parent, a
12345
12698
  // saved pane) keeps the current model, and says why in its own words.
12346
12699
  if (isRetiredProvider(provider) || isRetiredModel(model)) {
12347
- const current = `${this.overseerModelOverride?.provider || configStore.getProvider()}/${this.overseerModelOverride?.model || configStore.getModel()}`;
12700
+ const current = `${configStore.getProvider()}/${configStore.getModel()}`;
12348
12701
  this.addSystemMessage(isRetiredProvider(provider) ? retiredProviderMessage(provider, current) : retiredModelMessage(model));
12349
12702
  return false;
12350
12703
  }
@@ -12353,32 +12706,29 @@ export class RatatuiApp {
12353
12706
  // codex_* before login). Swapping that null in would kill the
12354
12707
  // in-flight turn while callers still report "✓ updated" — so on a null
12355
12708
  // rebuild we keep the working agent AND restore the recorded model.
12356
- const isOverseer = this.muxMode && !this.paneMode;
12357
- const setsOverrides = !isOverseer || options.pinRoute === true;
12358
- const prevOverseerOverride = this.overseerModelOverride;
12709
+ const previousPaneRoute = configStore.getPaneRoute();
12359
12710
  // A choice saved before this call already changed the configured route, so the live agent's own route is what a
12360
12711
  // failed rebuild keeps.
12361
12712
  const running = this.agent ? this.agentBuiltForRoute : null;
12362
12713
  const prevProvider = running?.provider ?? configStore.getProvider();
12363
12714
  const prevModel = running?.model ?? configStore.getModel();
12364
- const prevAuthMode = running?.authMode ?? configStore.getAuthMode();
12365
- if (isOverseer) {
12366
- // Overseer: store override locally; configStore only for a pinned choice.
12367
- this.overseerModelOverride = provider && model ? { provider, model } : null;
12368
- }
12369
- if (setsOverrides) {
12370
- // Child pane: use CLI overrides (each child is its own process).
12371
- if (provider && model) {
12372
- configStore.setCliOverride('provider', provider);
12373
- configStore.setCliOverride('model', model);
12374
- }
12375
- else {
12376
- configStore.setCliOverride('provider', '');
12377
- configStore.setCliOverride('model', '');
12378
- }
12379
- // The choice saved its route; only a launch --auth-mode that outranks the saved one needs replacing.
12380
- if (options.authMode && configStore.getAuthMode() !== options.authMode)
12381
- configStore.setCliOverride('authMode', options.authMode);
12715
+ const launch = configStore.getLaunchOverrides();
12716
+ if (options.setsDefault && configStore.getConfigScope() !== 'session') {
12717
+ for (const key of ['provider', 'model', 'authMode'])
12718
+ configStore.setCliOverride(key, undefined);
12719
+ }
12720
+ // Back to the default. A child pane drops the provider and model it was launched with, which its parent named
12721
+ // (a restored pane's, a split's); the main pane's own launch flags are this run's choice and stay.
12722
+ const reset = !options.keepsRoute && (!provider || !model);
12723
+ const dropsLaunchRoute = reset && !(this.muxMode && !this.paneMode);
12724
+ if (dropsLaunchRoute) {
12725
+ configStore.setCliOverride('provider', undefined);
12726
+ configStore.setCliOverride('model', undefined);
12727
+ }
12728
+ if (reset)
12729
+ configStore.setPaneRoute(undefined);
12730
+ else if (!options.keepsRoute && provider && model) {
12731
+ configStore.setPaneRoute({ provider, model, authMode: options.authMode ?? configStore.getAuthMode() });
12382
12732
  }
12383
12733
  let rebuilt = null;
12384
12734
  let awaitingChoice = false;
@@ -12395,19 +12745,20 @@ export class RatatuiApp {
12395
12745
  }
12396
12746
  if (!rebuilt) {
12397
12747
  // Roll back the half-applied selection and keep the working agent live —
12398
- // never dispose it or swap in null (that drops the running turn).
12399
- if (isOverseer)
12400
- this.overseerModelOverride = prevOverseerOverride;
12401
- if (setsOverrides) {
12402
- configStore.setCliOverride('provider', prevProvider);
12403
- configStore.setCliOverride('model', prevModel);
12404
- if (options.authMode && configStore.getAuthMode() !== prevAuthMode)
12405
- configStore.setCliOverride('authMode', prevAuthMode);
12406
- }
12748
+ // never dispose it or swap in null (that drops the running turn). When the configured route moved meanwhile
12749
+ // (a choice saved before this call), the pane keeps the route its live agent runs on as its own.
12750
+ configStore.setPaneRoute(previousPaneRoute);
12751
+ if (dropsLaunchRoute) {
12752
+ configStore.setCliOverride('provider', launch.provider);
12753
+ configStore.setCliOverride('model', launch.model);
12754
+ }
12755
+ if (running && !sameRoute(running, { provider: configStore.getProvider(), model: configStore.getModel(),
12756
+ authMode: configStore.getAuthMode() }))
12757
+ configStore.setPaneRoute(running);
12758
+ this.runtimeChoicesStale = true;
12407
12759
  const who = (provider && provider.trim()) || prevProvider || 'that provider';
12408
12760
  // With no agent built before, the route kept is the choice itself, saved by the caller.
12409
- const keptRoute = isOverseer && this.overseerModelOverride ? this.overseerModelOverride
12410
- : { provider: configStore.getProvider(), model: configStore.getModel() };
12761
+ const keptRoute = { provider: configStore.getProvider(), model: configStore.getModel() };
12411
12762
  const onChoice = !!provider && normalizeProviderId(keptRoute.provider) === normalizeProviderId(provider) && keptRoute.model === model;
12412
12763
  if (awaitingChoice) {
12413
12764
  // A profile waiting for a route choice has none for a pane's model either (see ConfigStore.routeAwaitingChoice).
@@ -12419,8 +12770,7 @@ export class RatatuiApp {
12419
12770
  const fix = isRouterOnlyProvider(who) ? (configStore.getAuthMode() === 'direct' ? 'set Routing to auto in /config' : 'log in with /auth login')
12420
12771
  : isLocalSubscription(who) ? 'sign in through /accounts' : `add a key with /config key ${who}`;
12421
12772
  // A caller may have saved the choice first; rolling back cannot undo that.
12422
- const kept = isOverseer ? this.overseerModelOverride?.provider ?? configStore.getProvider() : configStore.getProvider();
12423
- const selected = normalizeProviderId(kept) === normalizeProviderId(who);
12773
+ const selected = normalizeProviderId(keptRoute.provider) === normalizeProviderId(who);
12424
12774
  // A model only Zerg Router serves says why in its own words, as its turn would.
12425
12775
  this.addSystemMessage(routerOnly ? `⚠ ${routerOnly.message}${selected ? '' : ' Keeping the current model.'}`
12426
12776
  : selected ? `⚠ ${who} is selected but can't reach a model yet: ${fix}.`
@@ -12429,7 +12779,9 @@ export class RatatuiApp {
12429
12779
  return onChoice;
12430
12780
  }
12431
12781
  this.replaceAgent(rebuilt);
12432
- const effectiveModel = this.overseerModelOverride?.model || configStore.getModel();
12782
+ this.runtimeChoicesStale = true;
12783
+ this.rememberPaneModel();
12784
+ const effectiveModel = configStore.getModel();
12433
12785
  // The bar measures what is in use against the new model's window at once; it kept the old model's share (70%
12434
12786
  // of a 131K window on a 1M model) until the next answer (2026-10-27).
12435
12787
  const { agentState } = this.controller.getState();
@@ -12437,9 +12789,16 @@ export class RatatuiApp {
12437
12789
  const status = contextStatusFromUsed(agentState.contextTokens, effectiveModel, configStore.getModelContextWindow(effectiveModel));
12438
12790
  this.controller.dispatch({ type: 'SET_CONTEXT', length: agentState.contextTokens, estimated: agentState.tokensEstimated ?? false, status });
12439
12791
  }
12440
- debugLog(`[hot-swap] Model switched to ${this.overseerModelOverride?.provider || configStore.getProvider()}/${effectiveModel}`);
12792
+ debugLog(`[hot-swap] Model switched to ${configStore.getProvider()}/${effectiveModel}`);
12441
12793
  return true;
12442
12794
  }
12795
+ /**
12796
+ * Rebuild this pane's agent on the route it runs on, as a changed effort needs: its own when it has one, else the
12797
+ * configured one with the launch flags it was started with (a split's, a restored pane's), which stay.
12798
+ */
12799
+ rebuildOnCurrentRoute() {
12800
+ this.hotSwapModel(undefined, undefined, { keepsRoute: true });
12801
+ }
12443
12802
  /**
12444
12803
  * Rebuild the agent when the active mode differs from the mode it was built
12445
12804
  * for. Cheap no-op when they match (the common case). Fixes ZTC-24: a
@@ -12609,11 +12968,6 @@ export class RatatuiApp {
12609
12968
  mlMode: this.mlMode,
12610
12969
  evolveMode: isEvolveMode,
12611
12970
  tracer: this.promptTracer,
12612
- // Pass overseer-specific model override if set (from web mirror dropdown).
12613
- ...(this.overseerModelOverride ? {
12614
- provider: this.overseerModelOverride.provider,
12615
- model: this.overseerModelOverride.model,
12616
- } : {}),
12617
12971
  sessionId: this.sessionId,
12618
12972
  toolResponseStore: this.sessionToolResponseStore,
12619
12973
  paneId: this.getHookPaneId(),
@@ -12663,8 +13017,9 @@ export class RatatuiApp {
12663
13017
  this.agentBuiltForPlanFile = currentMode === 'plan'
12664
13018
  ? this.controller.getPlanFile()
12665
13019
  : null;
13020
+ const origin = configStore.get().zergProxyUrl;
12666
13021
  this.agentBuiltForRoute = { provider: configStore.getProvider(), model: configStore.getModel(),
12667
- authMode: configStore.getAuthMode() };
13022
+ authMode: configStore.getAuthMode(), ...(origin ? { routerOrigin: origin } : {}) };
12668
13023
  }
12669
13024
  return agent;
12670
13025
  }
@@ -14021,15 +14376,38 @@ export class RatatuiApp {
14021
14376
  return;
14022
14377
  }
14023
14378
  // No kind is a ZTC pane (+, Cmd+T, the new-pane menu's ZTC tab), native panes up or not: the New pane chooser
14024
- // opens only when it is asked for by name (show_new_pane_picker). The desktop app shows nothing of a pane that never
14025
- // opened, so the reason is said here, as for the kinds above.
14026
- void this.spawnZtcPane({ cwd: event.cwd, ...placement }).then((result) => {
14379
+ // opens only when it is asked for by name (show_new_pane_picker). A ZTC split starts on the route of the pane it
14380
+ // splits; a tab, on the default for new panes.
14381
+ const route = event.target === undefined ? undefined : this.splitRouteFor(event.target);
14382
+ // The desktop app shows nothing of a pane that never opened, so the reason is said here, as for the kinds above.
14383
+ void this.spawnZtcPane({ cwd: event.cwd, ...placement, ...(route ? { route } : {}) }).then((result) => {
14027
14384
  if (result.error) {
14028
14385
  debugLog(`[handleCreatePaneRequest] ${result.error}`);
14029
14386
  this.addSystemMessage(`Could not open a ZTC pane: ${result.error}`);
14030
14387
  }
14031
14388
  });
14032
14389
  }
14390
+ /**
14391
+ * The route a ZTC split of `target` starts on: this pane's own route when it splits itself, a ZTC child's or a native
14392
+ * ZTC pane's as it last reported it (see noteChildPaneReport), and otherwise none, so the split starts on the default
14393
+ * for new panes, as this pane does when it has no route of its own.
14394
+ */
14395
+ splitRouteFor(target) {
14396
+ if (target === this.ownPaneId())
14397
+ return configStore.getPaneRoute();
14398
+ const pane = this.paneRegistry.get(target);
14399
+ if (isNativeZtcPane(pane)) {
14400
+ const reported = pane.reportedRoute;
14401
+ const origin = pane.launchRouterOrigin;
14402
+ return reported && { provider: reported.provider, model: reported.model,
14403
+ authMode: reported.authMode ?? configStore.getNewPaneRoute().authMode, ...(origin ? { routerOrigin: origin } : {}) };
14404
+ }
14405
+ const spec = pane?.paneType === 'ztc' && pane.launchSpec?.kind === 'ztc' ? pane.launchSpec : undefined;
14406
+ if (!spec?.providerOverride || !spec.modelOverride)
14407
+ return undefined;
14408
+ return { provider: spec.providerOverride, model: spec.modelOverride, authMode: spec.authMode ?? configStore.getNewPaneRoute().authMode,
14409
+ ...(spec.routerOrigin ? { routerOrigin: spec.routerOrigin } : {}) };
14410
+ }
14033
14411
  /**
14034
14412
  * Open the user's own Claude Code or Codex in a pane: the chooser's and the
14035
14413
  * desktop menu's entry point. Returns what to tell the user (an error or a
@@ -14080,7 +14458,9 @@ export class RatatuiApp {
14080
14458
  const cwd = options?.cwd || this.shellCwd || process.cwd();
14081
14459
  const title = options?.title?.trim() || `ZTC ${this.childPaneIds.size + 1}`;
14082
14460
  const requestId = `ztc-pane-${generateSessionId()}`;
14083
- const launchSpec = this.createZtcPaneSpec({ sessionMode: 'new', cwd, title });
14461
+ const route = options?.route;
14462
+ const launchSpec = this.createZtcPaneSpec({ sessionMode: 'new', cwd, title, ...(route ? { provider: route.provider,
14463
+ model: route.model, authMode: route.authMode, ...(route.routerOrigin ? { routerOrigin: route.routerOrigin } : {}) } : {}) });
14084
14464
  let child;
14085
14465
  let captured = null;
14086
14466
  try {
@@ -14705,6 +15085,12 @@ export class RatatuiApp {
14705
15085
  await this.dailyDesktop?.close();
14706
15086
  this.supervisionManager = null;
14707
15087
  this.hookLifecycle.stop();
15088
+ this.stopFollowingChoiceSettings?.();
15089
+ this.stopFollowingChoiceSettings = null;
15090
+ this.stopFollowingRouteDirectory?.();
15091
+ this.stopFollowingRouteDirectory = null;
15092
+ this.runtimeChoicesSource?.dispose();
15093
+ this.runtimeChoicesSource = null;
14708
15094
  // Stop pane relay server/client
14709
15095
  if (this.paneRelay) {
14710
15096
  this.paneRelay.stop();