@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
@@ -1,5 +1,6 @@
1
1
  import type { RouterSessionStatus } from '../router_auth.js';
2
- import type { RouterCatalog } from '../utils/router_catalog.js';
2
+ import { type DesktopRuntimeChoices } from '../ui/ratatui/protocol.js';
3
+ import { type RouterCatalog } from '../utils/router_catalog.js';
3
4
  /** How a provider choice is reached: through Zerg Router, or a credential on this machine. */
4
5
  export type ProviderRoute = 'zergrouter' | 'direct';
5
6
  /** Whether a choice can run now, needs a key or login first, or has no usable model on Zerg Router. */
@@ -36,3 +37,79 @@ export declare const NO_ROUTER_KEY = "No key on Zerg Router";
36
37
  * provider this pane runs on is always listed, as needing setup when it would otherwise be missing.
37
38
  */
38
39
  export declare function buildProviderChoices(input: ProviderChoicesInput): ProviderChoice[];
40
+ /** What a pane's ZTC gathers from its cached state for its header's provider and model menus (runtime_choices_source.ts). */
41
+ export interface RuntimeChoicesInput {
42
+ /** Router's catalog as cached for this login, whatever this pane's route. */
43
+ catalog?: RouterCatalog;
44
+ routerSession: RouterSessionStatus;
45
+ /** How current the catalog is: Router's last refresh failed (unavailable), was refused (rejected), or is running. */
46
+ catalogState: DesktopRuntimeChoices['router']['catalog'];
47
+ /** Direct providers with a key or login here (see modelRouteStatus). */
48
+ directReady: readonly string[];
49
+ /** What this pane runs on; routed when it goes through Zerg Router. */
50
+ selected: {
51
+ provider: string;
52
+ model: string;
53
+ routed: boolean;
54
+ };
55
+ /** A direct provider's models: the ones discovery last found, else ZTC's own list, with names where ZTC knows them. */
56
+ directModels?: ReadonlyArray<{
57
+ id: string;
58
+ name?: string;
59
+ }>;
60
+ modelsLoading: boolean;
61
+ /** The models this pane last ran with the selected provider, newest first. */
62
+ recentModels: readonly string[];
63
+ /** What new panes start on; `modelName` names a direct provider's model ZTC knows. */
64
+ newPane: {
65
+ provider: string;
66
+ model: string;
67
+ routed: boolean;
68
+ modelName?: string;
69
+ };
70
+ /** Zerg Router's Credentials page, for the person's own Router sign-in. */
71
+ credentialsUrl?: string;
72
+ }
73
+ /**
74
+ * The lists a pane header's provider and model menus show (desktop_runtime_choices_v1), from what the pane's ZTC has
75
+ * cached; the revision is the caller's (RuntimeChoicesPublication). Providers: Zerg Router's in Router's order, then
76
+ * your keys and logins, at most 48 with the selected one always in. Models: the selected provider's, at most 128 with
77
+ * the current model always in: recent (the current model, this pane's last three with the provider and Router's
78
+ * default), then all, then older versions (dated or preview ids). Text is cleaned and cut to the contract's limits.
79
+ * Undefined when the pane's provider or model can't be sent as it is, or the list would fail zterm's checks: the pane
80
+ * then sends no list, and the title-bar chip stays.
81
+ */
82
+ export declare function buildRuntimeChoices(input: RuntimeChoicesInput): Omit<DesktopRuntimeChoices, 'revision'> | undefined;
83
+ /**
84
+ * The list a pane last published and its revision, which moves only when the list's JSON does: usage and observed_at
85
+ * refreshes give the task-controls state a new revision but leave this one, so a click made against an older state with
86
+ * the same list still applies (see the select_runtime fence).
87
+ */
88
+ export declare class RuntimeChoicesPublication {
89
+ private published;
90
+ /** The list to send with the state about to take revision `nextRevision`; undefined when there is none to send. */
91
+ update(built: Omit<DesktopRuntimeChoices, 'revision'> | undefined, nextRevision: number): {
92
+ value: DesktopRuntimeChoices;
93
+ hash: string;
94
+ } | undefined;
95
+ }
96
+ /**
97
+ * A pane's task-controls signature, compared on every render to send a state only when it changed: the projection, and
98
+ * of its runtime_choices only their hash and revision, so a render never serializes the lists again.
99
+ */
100
+ export declare function desktopTaskSignature(projection: object, choices?: {
101
+ value: DesktopRuntimeChoices;
102
+ hash: string;
103
+ }): string;
104
+ /**
105
+ * Whether a header's select_runtime can be applied against `choices`, the lists the pane published: undefined when
106
+ * it can, else the reply. A provider no longer listed is stale; an unavailable one is blocked with its reason; a model
107
+ * named for a provider other than the pane's is invalid, and one not listed or not available to the account is stale.
108
+ */
109
+ export declare function checkRuntimeSelection(choices: Pick<DesktopRuntimeChoices, 'providers' | 'models' | 'selected_provider'>, request: {
110
+ provider_choice: string;
111
+ model?: string;
112
+ }): {
113
+ status: 'stale' | 'blocked' | 'invalid';
114
+ message: string;
115
+ } | undefined;
@@ -1,4 +1,9 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isLocalSubscriptionProvider } from '../agent/backends/provider_ids.js';
1
3
  import { canRouteThroughRouter, DIRECT_PROVIDER_CHOICES, describeDirectProvider, describeRouterRoute, PROVIDER_CHOICES, providerChoiceId, } from '../agent/commands/provider_choices.js';
4
+ import { DESKTOP_RUNTIME_MAX_CHOICE_DETAIL_BYTES, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES, DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES, DESKTOP_RUNTIME_MAX_MODEL_CHOICES, DESKTOP_RUNTIME_MAX_PROVIDER_CHOICES, isDesktopCredentialsUrl, isDesktopRuntimeChoices, } from '../ui/ratatui/protocol.js';
5
+ import { routerModelFacts } from '../utils/router_catalog_facts.js';
6
+ import { routerModelsForProvider } from '../utils/router_catalog.js';
2
7
  export { parseProviderChoiceId, providerChoiceId, ROUTER_CHOICE_PREFIX } from '../agent/commands/provider_choices.js';
3
8
  /** Router's provider slugs and ZTC's own provider ids: what can be typed after /provider and stored. */
4
9
  const PROVIDER_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/;
@@ -64,3 +69,227 @@ export function buildProviderChoices(input) {
64
69
  }
65
70
  return [...router, ...direct].map(choice => choice.id === selectedId ? { ...choice, selected: true } : choice);
66
71
  }
72
+ /** What a list never carries: C0 and C1 controls, and the bidi marks, embeddings and isolates. */
73
+ const FORBIDDEN = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/;
74
+ const FORBIDDEN_ALL = new RegExp(FORBIDDEN.source, 'g');
75
+ function bytes(text) {
76
+ return Buffer.byteLength(text, 'utf8');
77
+ }
78
+ /** An id the list can carry as it is: up to 256 bytes, nothing forbidden (an id can't be cleaned, it is applied). */
79
+ function sendableId(text) {
80
+ return text.length > 0 && bytes(text) <= 256 && !FORBIDDEN.test(text);
81
+ }
82
+ /**
83
+ * `text` without what a list never carries, in at most `max` bytes, cut on a character boundary: at the end, or for a
84
+ * chip, in the middle with an ellipsis, so both ends survive ("DeepSeek…Flash 1017").
85
+ */
86
+ function fit(text, max, middle = false) {
87
+ const clean = text.replace(FORBIDDEN_ALL, '');
88
+ if (bytes(clean) <= max)
89
+ return clean;
90
+ const chars = [...clean];
91
+ if (!middle) {
92
+ let out = '';
93
+ let used = 0;
94
+ for (const char of chars) {
95
+ if (used + bytes(char) > max)
96
+ break;
97
+ out += char;
98
+ used += bytes(char);
99
+ }
100
+ return out;
101
+ }
102
+ const budget = max - bytes('…');
103
+ let head = '';
104
+ let tail = '';
105
+ let headBytes = 0;
106
+ let tailBytes = 0;
107
+ for (let first = 0, last = chars.length - 1; first <= last;) {
108
+ const front = headBytes <= tailBytes;
109
+ const char = front ? chars[first] : chars[last];
110
+ if (headBytes + tailBytes + bytes(char) > budget)
111
+ break;
112
+ if (front) {
113
+ head += char;
114
+ headBytes += bytes(char);
115
+ first++;
116
+ }
117
+ else {
118
+ tail = char + tail;
119
+ tailBytes += bytes(char);
120
+ last--;
121
+ }
122
+ }
123
+ return `${head}…${tail}`;
124
+ }
125
+ /** Router ids carry their provider (morph/morph-kimik31); the provider is named beside them already. */
126
+ function withoutProvider(provider, model) {
127
+ return model.startsWith(`${provider}/`) ? model.slice(provider.length + 1) : model;
128
+ }
129
+ /** Whether `text`, in a model's trailing parentheses, names its provider: "(Modal Shared)", "(Morph)". */
130
+ function namesProvider(text, names) {
131
+ const key = (value) => (value ?? '').toLowerCase().replace(/[^a-z0-9]/g, '');
132
+ const said = key(text);
133
+ return said.length > 0 && names.some(name => { const known = key(name); return known.length > 0 && (known.startsWith(said) || said.startsWith(known)); });
134
+ }
135
+ /**
136
+ * A Router model's chip text: Router's name without a trailing parenthetical that names its provider ("Kimi K3 (Modal
137
+ * Shared)" is "Kimi K3"), else its id without the provider's prefix.
138
+ */
139
+ function routerModelShortLabel(row, provider) {
140
+ const name = row.display_name?.trim();
141
+ if (!name)
142
+ return withoutProvider(provider, row.id);
143
+ const named = /^(.*\S)\s*\(([^()]*)\)$/.exec(name);
144
+ return named && namesProvider(named[2], [provider, row.provider_display_name, knownLabel(provider)]) ? named[1] : name;
145
+ }
146
+ /** A dated id (`-2026-01-15`) or a preview one: shown under Older versions unless the pane used it lately. */
147
+ function olderVersion(id) {
148
+ return /-\d{4}-\d{2}-\d{2}$/.test(id) || id.toLowerCase().split(/[-_./:]/).includes('preview');
149
+ }
150
+ /** The rows to send: the first `max`, always including the one `kept` names. */
151
+ function bounded(rows, max, kept) {
152
+ const index = rows.findIndex(kept);
153
+ return index < max ? rows.slice(0, max) : [...rows.slice(0, max - 1), rows[index]];
154
+ }
155
+ function providerRow(choice) {
156
+ if (!sendableId(choice.id) || bytes(choice.provider) > 256 || FORBIDDEN.test(choice.provider))
157
+ return undefined;
158
+ const label = fit(choice.label, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES) || fit(choice.provider, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES);
159
+ const short = fit(choice.short_label, DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES, true) || fit(label, DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES, true);
160
+ return { id: choice.id, provider: choice.provider, route: choice.route === 'zergrouter' ? 'router' : 'direct',
161
+ label, short_label: short, detail: fit(choice.detail, DESKTOP_RUNTIME_MAX_CHOICE_DETAIL_BYTES) || null, state: choice.state };
162
+ }
163
+ /** The selected provider's models, as Router lists them for a routed pane, else as discovery or ZTC lists them. */
164
+ function modelEntries(input) {
165
+ const { provider, routed } = input.selected;
166
+ const entries = routed
167
+ ? (input.catalog ? routerModelsForProvider(input.catalog, provider) : []).map(row => ({ id: row.id,
168
+ label: row.display_name || row.id, short: routerModelShortLabel(row, provider), detail: routerModelFacts(row),
169
+ available: row.available !== false, routerDefault: row.is_default === true }))
170
+ : (input.directModels ?? []).map(model => ({ id: model.id, label: model.name || model.id, short: model.name || model.id,
171
+ detail: '', available: true, routerDefault: false }));
172
+ const seen = new Set();
173
+ return entries.filter(entry => sendableId(entry.id) && !seen.has(entry.id) && seen.add(entry.id) !== undefined);
174
+ }
175
+ function modelRow(entry, group) {
176
+ const label = fit(entry.label, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES) || fit(entry.id, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES);
177
+ return { id: entry.id, label,
178
+ short_label: fit(entry.short, DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES, true) || fit(label, DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES, true),
179
+ detail: fit(entry.detail, DESKTOP_RUNTIME_MAX_CHOICE_DETAIL_BYTES) || null, available: entry.available, group };
180
+ }
181
+ /** How a route reads after a model: through Zerg Router, or on what bills it here. */
182
+ function routeWord(provider, routed) {
183
+ if (routed)
184
+ return 'Zerg Router';
185
+ if (isLocalSubscriptionProvider(provider))
186
+ return 'local login';
187
+ return provider === 'openai_compatible' ? 'custom endpoint' : 'your key';
188
+ }
189
+ /** "Modal · DeepSeek V4.1 Flash (Zerg Router)": what new panes start on, as the menus' "Use for new panes" says it. */
190
+ function newPaneLabel(input) {
191
+ const { provider, model, routed, modelName } = input.newPane;
192
+ const row = routed && input.catalog ? routerModelsForProvider(input.catalog, provider).find(candidate => candidate.id === model) : undefined;
193
+ const providerName = knownLabel(provider) || row?.provider_display_name
194
+ || input.catalog?.models.find(candidate => candidate.owned_by === provider)?.provider_display_name || provider;
195
+ const sameDirect = !routed && !input.selected.routed && input.selected.provider === provider;
196
+ const name = row ? routerModelShortLabel(row, provider)
197
+ : routed ? withoutProvider(provider, model)
198
+ : modelName || (sameDirect ? input.directModels?.find(candidate => candidate.id === model)?.name : undefined) || model;
199
+ return fit(`${providerName} · ${name} (${routeWord(provider, routed)})`, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES);
200
+ }
201
+ /**
202
+ * The lists a pane header's provider and model menus show (desktop_runtime_choices_v1), from what the pane's ZTC has
203
+ * cached; the revision is the caller's (RuntimeChoicesPublication). Providers: Zerg Router's in Router's order, then
204
+ * your keys and logins, at most 48 with the selected one always in. Models: the selected provider's, at most 128 with
205
+ * the current model always in: recent (the current model, this pane's last three with the provider and Router's
206
+ * default), then all, then older versions (dated or preview ids). Text is cleaned and cut to the contract's limits.
207
+ * Undefined when the pane's provider or model can't be sent as it is, or the list would fail zterm's checks: the pane
208
+ * then sends no list, and the title-bar chip stays.
209
+ */
210
+ export function buildRuntimeChoices(input) {
211
+ const { provider, model, routed } = input.selected;
212
+ if (!sendableId(model) || bytes(provider) > 256 || FORBIDDEN.test(provider))
213
+ return undefined;
214
+ const selectedProvider = providerChoiceId(provider, routed ? 'zergrouter' : 'direct');
215
+ const rows = buildProviderChoices({ catalog: input.catalog, routerSession: input.routerSession, directReady: input.directReady,
216
+ selected: { provider, routed } }).flatMap(choice => { const row = providerRow(choice); return row ? [row] : []; });
217
+ if (!rows.some(row => row.id === selectedProvider))
218
+ return undefined;
219
+ const entries = modelEntries(input);
220
+ if (!entries.some(entry => entry.id === model)) {
221
+ entries.unshift({ id: model, label: model, short: withoutProvider(provider, model), detail: '', available: true, routerDefault: false });
222
+ }
223
+ const byId = new Map(entries.map(entry => [entry.id, entry]));
224
+ const routerDefault = entries.find(entry => entry.routerDefault)?.id;
225
+ const recent = [...new Set([model, ...input.recentModels.slice(0, 3), ...(routerDefault ? [routerDefault] : [])])]
226
+ .filter(id => byId.has(id));
227
+ const rest = entries.filter(entry => !recent.includes(entry.id));
228
+ const ordered = [
229
+ ...recent.map(id => modelRow(byId.get(id), 'recent')),
230
+ ...rest.filter(entry => !olderVersion(entry.id)).map(entry => modelRow(entry, 'all')),
231
+ ...rest.filter(entry => olderVersion(entry.id)).map(entry => modelRow(entry, 'older')),
232
+ ];
233
+ const newPane = providerChoiceId(input.newPane.provider, input.newPane.routed ? 'zergrouter' : 'direct');
234
+ if (!sendableId(newPane) || !sendableId(input.newPane.model))
235
+ return undefined;
236
+ const choices = {
237
+ selected_provider: selectedProvider,
238
+ selected_model: model,
239
+ new_pane_route: { provider_choice: newPane, model: input.newPane.model, label: newPaneLabel(input) },
240
+ providers: bounded(rows, DESKTOP_RUNTIME_MAX_PROVIDER_CHOICES, row => row.id === selectedProvider),
241
+ models: ordered.slice(0, DESKTOP_RUNTIME_MAX_MODEL_CHOICES),
242
+ models_complete: ordered.length <= DESKTOP_RUNTIME_MAX_MODEL_CHOICES,
243
+ models_loading: input.modelsLoading,
244
+ router: { session: input.routerSession, catalog: input.catalogState,
245
+ credentials_url: input.credentialsUrl && isDesktopCredentialsUrl(input.credentialsUrl) ? input.credentialsUrl : null },
246
+ };
247
+ // Never send a list zterm would drop: it would take the header menus with it.
248
+ return isDesktopRuntimeChoices({ revision: 0, ...choices }) ? choices : undefined;
249
+ }
250
+ /**
251
+ * The list a pane last published and its revision, which moves only when the list's JSON does: usage and observed_at
252
+ * refreshes give the task-controls state a new revision but leave this one, so a click made against an older state with
253
+ * the same list still applies (see the select_runtime fence).
254
+ */
255
+ export class RuntimeChoicesPublication {
256
+ published;
257
+ /** The list to send with the state about to take revision `nextRevision`; undefined when there is none to send. */
258
+ update(built, nextRevision) {
259
+ if (!built) {
260
+ this.published = undefined;
261
+ return undefined;
262
+ }
263
+ const json = JSON.stringify(built);
264
+ if (this.published?.json !== json) {
265
+ this.published = { json, hash: createHash('sha256').update(json).digest('hex').slice(0, 16), value: { revision: nextRevision, ...built } };
266
+ }
267
+ return { value: this.published.value, hash: this.published.hash };
268
+ }
269
+ }
270
+ /**
271
+ * A pane's task-controls signature, compared on every render to send a state only when it changed: the projection, and
272
+ * of its runtime_choices only their hash and revision, so a render never serializes the lists again.
273
+ */
274
+ export function desktopTaskSignature(projection, choices) {
275
+ return JSON.stringify([projection, choices ? [choices.hash, choices.value.revision] : null]);
276
+ }
277
+ /**
278
+ * Whether a header's select_runtime can be applied against `choices`, the lists the pane published: undefined when
279
+ * it can, else the reply. A provider no longer listed is stale; an unavailable one is blocked with its reason; a model
280
+ * named for a provider other than the pane's is invalid, and one not listed or not available to the account is stale.
281
+ */
282
+ export function checkRuntimeSelection(choices, request) {
283
+ const provider = choices.providers.find(row => row.id === request.provider_choice);
284
+ if (!provider)
285
+ return { status: 'stale', message: 'The provider list changed. Choose again.' };
286
+ if (provider.state === 'unavailable')
287
+ return { status: 'blocked', message: provider.detail ?? `${provider.short_label} can't be used yet.` };
288
+ if (request.model === undefined)
289
+ return undefined;
290
+ if (request.provider_choice !== choices.selected_provider) {
291
+ return { status: 'invalid', message: 'A model can be chosen only with the provider this pane runs on.' };
292
+ }
293
+ const model = choices.models.find(row => row.id === request.model);
294
+ return model?.available ? undefined : { status: 'stale', message: 'The model list changed. Choose again.' };
295
+ }
@@ -0,0 +1,45 @@
1
+ import type { ConfigController, ModelsController } from '../agent/commands/types.js';
2
+ import { type RouterCatalog } from '../utils/router_catalog.js';
3
+ import type { RuntimeChoicesInput } from './runtime_choices.js';
4
+ export type RuntimeChoicesConfig = Pick<ConfigController, 'getRouterSessionStatus' | 'hasDirectCredential' | 'getApiKey'> & {
5
+ getRouterCatalog(): RouterCatalog | undefined;
6
+ getPersonalRouterCredential(): {
7
+ origin: string;
8
+ } | undefined;
9
+ onChange(listener: () => void): () => void;
10
+ };
11
+ /** The parts of the builder's input the pane itself knows: its route, its recent models, what new panes start on. */
12
+ export type RuntimeChoicesPane = Pick<RuntimeChoicesInput, 'selected' | 'recentModels' | 'newPane'>;
13
+ /** ZTC's own list of a direct provider's models, with their names, for before discovery has run. */
14
+ export declare function staticDirectModels(provider: string): Array<{
15
+ id: string;
16
+ name?: string;
17
+ }>;
18
+ export declare class RuntimeChoicesSource {
19
+ private readonly config;
20
+ private readonly models;
21
+ private readonly now;
22
+ /** Direct providers with a key or login here, until the settings change. */
23
+ private ready;
24
+ private readonly discovered;
25
+ private readonly listing;
26
+ private routerLoading;
27
+ /** How Router's last refresh on request ended, when it didn't succeed. */
28
+ private routerOutcome;
29
+ private readonly stopFollowing;
30
+ constructor(config: RuntimeChoicesConfig, models: () => ModelsController, now?: () => number);
31
+ /** The builder's input for `pane`, from cached state only. */
32
+ input(pane: RuntimeChoicesPane): RuntimeChoicesInput;
33
+ /**
34
+ * Discovery, as a menu asks for it: Router's catalog while signed in, when `force` or older than 30 s (one fetch for
35
+ * the whole profile, shared with every other caller); the selected direct provider's models when `force` or older
36
+ * than 10 minutes. `changed` runs when loading starts and when it ends. Resolves when both are done.
37
+ */
38
+ refresh(force: boolean, selected: RuntimeChoicesPane['selected'], changed: () => void): Promise<void>;
39
+ dispose(): void;
40
+ private catalogState;
41
+ /** What discovery last found for `provider` here, named as ZTC names them, else ZTC's own list. */
42
+ private directModels;
43
+ private refreshRouter;
44
+ private discover;
45
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * What a pane's ZTC gathers for its header's provider and model menus (see buildRuntimeChoices).
3
+ *
4
+ * The 5 s projection tick reads only what is cached: Router's catalog as cached for this login (a stat-memoized read),
5
+ * the Router session, which providers have a key or login here (probed once, then kept until the settings change), and
6
+ * the models discovery last found. It never lists models or fetches: listing Codex CLI's models starts codex
7
+ * app-server, and a Router list older than 30 s starts a fetch. Discovery runs only when the menus ask (refresh_choices).
8
+ */
9
+ import { modelRouteStatus } from '../agent/commands/provider_choices.js';
10
+ import { MODEL_CATALOG } from '../panes/model_catalog.js';
11
+ import { RouterCatalogAuthenticationError } from '../utils/router_catalog.js';
12
+ /** Router's catalog is fresh for 30 s, as model lists are (app/model_catalog_cache.ts). */
13
+ const ROUTER_FRESH_MS = 30_000;
14
+ /** A direct provider's models are listed again at most every 10 minutes unless the menu asks for a refresh. */
15
+ const DIRECT_FRESH_MS = 10 * 60_000;
16
+ /** ZTC's own list of a direct provider's models, with their names, for before discovery has run. */
17
+ export function staticDirectModels(provider) {
18
+ return MODEL_CATALOG.find(group => group.provider === provider)?.models.map(model => ({ id: model.id, name: model.name })) ?? [];
19
+ }
20
+ export class RuntimeChoicesSource {
21
+ config;
22
+ models;
23
+ now;
24
+ /** Direct providers with a key or login here, until the settings change. */
25
+ ready;
26
+ discovered = new Map();
27
+ listing = new Set();
28
+ routerLoading = false;
29
+ /** How Router's last refresh on request ended, when it didn't succeed. */
30
+ routerOutcome;
31
+ stopFollowing;
32
+ constructor(config, models, now = () => Date.now()) {
33
+ this.config = config;
34
+ this.models = models;
35
+ this.now = now;
36
+ this.stopFollowing = config.onChange(() => { this.ready = undefined; });
37
+ }
38
+ /** The builder's input for `pane`, from cached state only. */
39
+ input(pane) {
40
+ const catalog = this.config.getRouterCatalog();
41
+ this.ready ??= modelRouteStatus(this.config).directProviders;
42
+ const { selected } = pane;
43
+ const origin = this.config.getPersonalRouterCredential()?.origin;
44
+ return {
45
+ catalog, routerSession: this.config.getRouterSessionStatus?.() ?? 'signed_out', catalogState: this.catalogState(catalog),
46
+ directReady: this.ready, selected,
47
+ ...(selected.routed ? {} : { directModels: this.directModels(selected.provider) }),
48
+ modelsLoading: selected.routed ? this.routerLoading : this.listing.has(selected.provider),
49
+ recentModels: pane.recentModels, newPane: pane.newPane,
50
+ ...(origin ? { credentialsUrl: `${origin.replace(/\/+$/, '')}/dashboard?tab=credentials` } : {}),
51
+ };
52
+ }
53
+ /**
54
+ * Discovery, as a menu asks for it: Router's catalog while signed in, when `force` or older than 30 s (one fetch for
55
+ * the whole profile, shared with every other caller); the selected direct provider's models when `force` or older
56
+ * than 10 minutes. `changed` runs when loading starts and when it ends. Resolves when both are done.
57
+ */
58
+ async refresh(force, selected, changed) {
59
+ const work = [];
60
+ const catalog = this.config.getRouterCatalog();
61
+ const age = catalog ? this.now() - catalog.fetchedAt : Infinity;
62
+ if (this.config.getRouterSessionStatus?.() === 'signed_in' && !this.routerLoading && (force || !(age >= 0 && age < ROUTER_FRESH_MS))) {
63
+ work.push(this.refreshRouter(changed));
64
+ }
65
+ const known = this.discovered.get(selected.provider);
66
+ if (!selected.routed && !this.listing.has(selected.provider)
67
+ && (force || !known || !(this.now() - known.at >= 0 && this.now() - known.at < DIRECT_FRESH_MS))) {
68
+ work.push(this.discover(selected.provider, changed));
69
+ }
70
+ await Promise.all(work);
71
+ }
72
+ dispose() {
73
+ this.stopFollowing();
74
+ }
75
+ catalogState(catalog) {
76
+ if (this.routerLoading)
77
+ return 'loading';
78
+ if (catalog?.authRequired || this.routerOutcome === 'rejected')
79
+ return 'rejected';
80
+ if (this.routerOutcome === 'unavailable')
81
+ return 'unavailable';
82
+ if (!catalog)
83
+ return 'absent';
84
+ const age = this.now() - catalog.fetchedAt;
85
+ return age >= 0 && age < ROUTER_FRESH_MS ? 'fresh' : 'cached';
86
+ }
87
+ /** What discovery last found for `provider` here, named as ZTC names them, else ZTC's own list. */
88
+ directModels(provider) {
89
+ const found = this.discovered.get(provider)?.models;
90
+ if (!found)
91
+ return staticDirectModels(provider);
92
+ const names = new Map(staticDirectModels(provider).map(model => [model.id, model.name]));
93
+ return found.map(id => ({ id, ...(names.get(id) ? { name: names.get(id) } : {}) }));
94
+ }
95
+ async refreshRouter(changed) {
96
+ this.routerLoading = true;
97
+ changed();
98
+ try {
99
+ const catalog = await this.models().catalog(undefined, { refresh: true });
100
+ // The catalog comes back as cached when Router couldn't be reached, and marked when it refused this login.
101
+ this.routerOutcome = catalog.authRequired ? 'rejected' : catalog.cached ? 'unavailable' : undefined;
102
+ }
103
+ catch (error) {
104
+ this.routerOutcome = error instanceof RouterCatalogAuthenticationError ? 'rejected' : 'unavailable';
105
+ }
106
+ finally {
107
+ this.routerLoading = false;
108
+ changed();
109
+ }
110
+ }
111
+ async discover(provider, changed) {
112
+ this.listing.add(provider);
113
+ changed();
114
+ try {
115
+ const models = await this.models().list(provider, { authMode: 'direct', refresh: true });
116
+ if (models.length > 0)
117
+ this.discovered.set(provider, { models, at: this.now() });
118
+ }
119
+ catch {
120
+ // Keeps what it had: a failed listing leaves the last list, or ZTC's own.
121
+ }
122
+ finally {
123
+ this.listing.delete(provider);
124
+ changed();
125
+ }
126
+ }
127
+ }
@@ -1,5 +1,5 @@
1
1
  import { routerModelIds, routerModelsForProvider, resolveRouterModel } from '../utils/router_catalog.js';
2
- import { formatPriceRange } from '../utils/openrouter_prices.js';
2
+ import { routerModelFacts } from '../utils/router_catalog_facts.js';
3
3
  import { reasoningCommandChoices, reasoningEnabled } from '../utils/reasoning.js';
4
4
  import { MODEL_CATALOG } from '../panes/model_catalog.js';
5
5
  import { canRouteThroughRouter, canonicalProvider, canonicalRoute, describeDirectProvider, describeDirectRoute, describeRouterRoute, DIRECT_PROVIDER_CHOICES, isLocalSubscription, isRouterOnlyProvider, MODEL_ROUTE_CHOICES, PROVIDER_CHOICES, } from '../agent/commands/provider_choices.js';
@@ -152,19 +152,6 @@ function routerProviderChoices(catalog) {
152
152
  id, label: provider.label, aliases: [], description: provider.keyed ? 'Key set' : 'No key',
153
153
  }));
154
154
  }
155
- /** What a Router model offers, for its row: context, reasoning, images, limits and its price across providers. */
156
- function routerModelFacts(row) {
157
- const capabilities = row.capabilities;
158
- const context = capabilities?.context_window;
159
- return [
160
- context ? `${context >= 1_000_000 ? `${Number((context / 1_000_000).toFixed(1))}M` : `${Math.round(context / 1000)}K`} context` : '',
161
- capabilities?.reasoning?.choices.some(choice => choice !== 'none') ? 'Reasoning' : '',
162
- capabilities?.images ? 'Images' : '',
163
- capabilities?.tools === false ? 'Chat only' : '',
164
- row.price_range ? formatPriceRange(row.price_range) : '',
165
- row.available === false ? 'Access unavailable' : '',
166
- ].filter(Boolean).join(' · ');
167
- }
168
155
  function commandSelections(commands) {
169
156
  return commands.map(command => ({
170
157
  value: command.name, label: `/${command.name}`, description: command.description,