zcode-acp-server 0.90.1 → 0.92.0

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 (42) hide show
  1. package/README.md +1 -1
  2. package/dist/backend/resolve.d.ts +4 -1
  3. package/dist/backend/resolve.d.ts.map +1 -1
  4. package/dist/backend/resolve.js +132 -8
  5. package/dist/backend/resolve.js.map +1 -1
  6. package/dist/code-fingerprint.json +2 -2
  7. package/dist/config/account-provider.d.ts +64 -2
  8. package/dist/config/account-provider.d.ts.map +1 -1
  9. package/dist/config/account-provider.js +10 -4
  10. package/dist/config/account-provider.js.map +1 -1
  11. package/dist/config/model-cache.d.ts.map +1 -1
  12. package/dist/config/model-cache.js +11 -10
  13. package/dist/config/model-cache.js.map +1 -1
  14. package/dist/config/options.d.ts +75 -5
  15. package/dist/config/options.d.ts.map +1 -1
  16. package/dist/config/options.js +308 -28
  17. package/dist/config/options.js.map +1 -1
  18. package/dist/config/registry-context-window.d.ts +53 -0
  19. package/dist/config/registry-context-window.d.ts.map +1 -0
  20. package/dist/config/registry-context-window.js +305 -0
  21. package/dist/config/registry-context-window.js.map +1 -0
  22. package/dist/config/runtime-model.d.ts.map +1 -1
  23. package/dist/config/runtime-model.js +2 -2
  24. package/dist/config/runtime-model.js.map +1 -1
  25. package/dist/config/user-config.d.ts +9 -0
  26. package/dist/config/user-config.d.ts.map +1 -1
  27. package/dist/config/user-config.js +7 -0
  28. package/dist/config/user-config.js.map +1 -1
  29. package/dist/handlers/dispatch.js +9 -10
  30. package/dist/handlers/dispatch.js.map +1 -1
  31. package/dist/handlers/session.d.ts +20 -5
  32. package/dist/handlers/session.d.ts.map +1 -1
  33. package/dist/handlers/session.js +109 -36
  34. package/dist/handlers/session.js.map +1 -1
  35. package/dist/remote/settings-endpoint.d.ts.map +1 -1
  36. package/dist/remote/settings-endpoint.js +90 -11
  37. package/dist/remote/settings-endpoint.js.map +1 -1
  38. package/dist/settings/default-model.d.ts +36 -0
  39. package/dist/settings/default-model.d.ts.map +1 -0
  40. package/dist/settings/default-model.js +69 -0
  41. package/dist/settings/default-model.js.map +1 -0
  42. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"model-cache.js","sourceRoot":"","sources":["../../src/config/model-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,kBAAkB,EAClB,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAElC,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAGxD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,MAAsB,EACtB,QAAgB;IAEhB,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC/C,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC;IAC1B,IAAI,UAAU,GAAG,EAAE,CAAC;IACpB,IAAI,OAAO,GAAG,gBAAgB,CAAC;IAC/B,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACjD,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAA4B,CAAC;QAClE,MAAM,GAAG,GAAI,QAAQ,CAAC,KAAiE;YACrF,EAAE,OAAO,CAAC;QACZ,IAAI,GAAG,EAAE,UAAU;YAAE,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;QACjD,IAAI,GAAG,EAAE,OAAO;YAAE,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;IAC1C,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,GAAG,CAAC,qCAAqC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,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ACvE,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC,EAAE,EACxC,IAAI,CACL,CAAC;IACF,IAAI,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACpD,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAoB,CAAC;AAChD,CAAC"}
@@ -31,6 +31,15 @@ interface ProviderEntry {
31
31
  };
32
32
  models?: ProviderModelsJson;
33
33
  }
34
+ /**
35
+ * Positive evidence that a model is really gone — as opposed to merely absent
36
+ * from a registry list that may still be loading: the user switched it off in
37
+ * the desktop, or no local source (legacy config.json, the personal provider
38
+ * config, the provider table) knows it any more. A model that is merely
39
+ * missing from the backend's list is left alone until the backend itself
40
+ * refuses it (see repairUnavailableModel).
41
+ */
42
+ export declare function modelRetired(providerId: string, modelId: string): boolean;
34
43
  /**
35
44
  * A model's declaration from provider_config.json only — the lookup for
36
45
  * models that exist in the desktop's personal config but not (yet) in legacy
@@ -86,6 +95,47 @@ export declare function providerUnselectableReason(pid: string, p: ProviderEntry
86
95
  * provider, plus whole providers it describes and config.json does not.
87
96
  */
88
97
  export declare function loadAllModels(): ModelRef[];
98
+ /** A model the backend registry can run right now (`server.modelAvailability` entry). */
99
+ export interface UsableModel {
100
+ providerId?: string;
101
+ modelId?: string;
102
+ }
103
+ /** True when a provider-qualified model is in the usable set (dialect and case folded). */
104
+ export declare function isModelUsable(usable: readonly UsableModel[], providerId: string, modelId: string): boolean;
105
+ /** Whether two `providerId\modelId` values name the same model (dialect and case folded). */
106
+ export declare function sameModelValue(a: string, b: string): boolean;
107
+ /**
108
+ * The models to try, best first, when a session needs a default — the model a
109
+ * NEW session starts on, and the fallback when a session's own model is no
110
+ * longer runnable. Never a hardcoded id: a new upstream release is the default
111
+ * from the day it is usable, with nothing to change here (observed 2026-11-23:
112
+ * the hardcoded GLM-5.3 was switched off in the desktop on the day GLM-5.4
113
+ * shipped, and every new session tried to start on a model that no longer
114
+ * existed).
115
+ *
116
+ * 1. `ZCODE_PROVIDER` + `ZCODE_MODEL` — the per-process pin.
117
+ * 2. `session.defaultModel` in the user config — the manual choice, in any
118
+ * spelling `parseModelRefValue` reads (`providerId\modelId`,
119
+ * `providerId/modelId`, a bare modelId naming exactly one model).
120
+ * 3. `preferProviderId`'s newest model — a session keeps its own plan while
121
+ * that plan still runs anything (a coding-plan session is never moved to
122
+ * another plan while its own works).
123
+ * 4. The first provider in the user's own model-list order (the configured
124
+ * leader — what new sessions always started on), then the registry's
125
+ * first when no locally-known provider is runnable.
126
+ *
127
+ * The two explicit choices are tried even when the registry list lacks them:
128
+ * that list only names ENABLED models and may be stale (captured at resume) —
129
+ * the backend is the final authority, and a refusal falls through to the next
130
+ * candidate. The automatic choices only ever name models the list vouches for
131
+ * (without a list, the local model list stands in), so a fallback never lands
132
+ * on a model that was switched off.
133
+ */
134
+ export declare function defaultModelCandidates(usable?: readonly UsableModel[] | null, preferProviderId?: string): ModelRef[];
135
+ /** The first (best) entry of {@link defaultModelCandidates}. */
136
+ export declare function defaultModelRef(usable?: readonly UsableModel[] | null, preferProviderId?: string): ModelRef;
137
+ /** `defaultModelRef` as the `providerId\modelId` value the switch handler takes. */
138
+ export declare function defaultModelValue(usable?: readonly UsableModel[] | null, preferProviderId?: string): string;
89
139
  /** One provider entry in the ACP-facing `_meta.zcode.providers` list. */
90
140
  export interface ProviderMetadataEntry {
91
141
  /**
@@ -133,10 +183,29 @@ export declare function buildProviderMeta(currentProviderId: string, models?: Mo
133
183
  * config.json keeps the legacy `builtin:<family>-<plan>` — normalize before
134
184
  * lookup so both spellings resolve. */
135
185
  export declare function findProviderConfig(providerId: string): ProviderEntry | null;
136
- /** Read the context-window size for a provider+model: config.json first, then
137
- * the desktop's provider_config.json (models added there carry
138
- * `config.properties.contextWindow` and never reach config.json). */
186
+ /**
187
+ * The context-window size for a provider+model, 0 when no local source knows
188
+ * it. One ladder, most explicit first:
189
+ *
190
+ * 1. `config.json` `limit.context` — the user's per-model limit;
191
+ * 2. the desktop's `provider_config.json` rule (models added there carry
192
+ * `config.properties.contextWindow` and never reach config.json);
193
+ * 3. the registry's own answer (`registryContextWindow`) — the rule walk the
194
+ * backend resolves every table model through, and the only local source
195
+ * for a model that arrives through the provider table alone (GLM-5.4).
196
+ *
197
+ * An explicit value always wins, whichever is larger. Either provider dialect
198
+ * is accepted.
199
+ */
139
200
  export declare function modelContextWindow(providerId: string, modelId: string): number;
201
+ /**
202
+ * The context-gauge denominator (`usage_update.size`): the local ladder above,
203
+ * else the size the backend reported (the CLI's projection seeds a hardcoded
204
+ * 200K until its first usage event). Every emission site goes through here —
205
+ * initial usage, turn-time deltas, the post-switch refresh, the TUI's boot
206
+ * reading — so the gauge cannot flip-flop between sources.
207
+ */
208
+ export declare function usageWindowSize(providerId: string, modelId: string, backendSize: number | null | undefined): number;
140
209
  /** Builtin providerIds are prefixed with `builtin:` (e.g. `builtin:bigmodel`). */
141
210
  export declare function isBuiltinProvider(providerId: string): boolean;
142
211
  /**
@@ -219,8 +288,9 @@ export declare function rememberModelChoice(server: ZcodeAcpServer, acpSid: stri
219
288
  * broadcast or fail the handler — the switch already succeeded backend-side.
220
289
  *
221
290
  * For model switches, also emit a usage_update with the NEW model's context
222
- * window (from config.json) so the editor's context bar refreshes immediately
223
- * instead of waiting for the next turn's UsageDelta. */
291
+ * window (the context-window ladder, `usageWindowSize`) so the editor's
292
+ * context bar refreshes immediately instead of waiting for the next turn's
293
+ * UsageDelta. */
224
294
  export declare function emitConfigOptionUpdate(server: ZcodeAcpServer, cx: acp.AgentContext, acpSid: string, zcodeSid: string, kind: "model" | "mode" | "thought"): Promise<{
225
295
  options: acp.SessionConfigOption[];
226
296
  currentModeId?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../src/config/options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,KAAK,GAAG,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AAyB,CAC7C,MAAM,EAAE,cAAc,EACtB,YAAY,EAAE,OAAO,EACrB,MAAM,EAAE,iBAAiB,GAAG,IAAI,GAC/B,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,CAAC,CAqCpC;AAED;;;;;;GAMG;AACH,wBAAsB,eAAe,CACnC,MAAM,EAAE,cAAc,EACtB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC;IAAE,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CA2B9E;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,GAC1C,IAAI,CAWN;AAED;;;;;;;;;;;;;;;;;;;;;kBAqBkB;AAClB,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,cAAc,EACtB,EAAE,EAAE,GAAG,CAAC,YAAY,EACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,GACjC,OAAO,CAAC;IAAE,OAAO,EAAE,GAAG,CAAC,mBAAmB,EAAE,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CA4DzE"}
@@ -16,7 +16,10 @@ import { clientConnectionRoot, CONFIG_DISPATCH, CONFIG_META, log, warn, ZCODE_CR
16
16
  import { isBroadcastSource, sendSessionUpdate, sendSessionUpdateToOthers } from "../handlers/io.js";
17
17
  import { accountProviderIdFor, configProviderIdFor, entitledCodingPlanModels, readBuiltinTable, } from "./account-provider.js";
18
18
  import { readCredentialConfig } from "./bridge-accounts.js";
19
+ import { parseModelRefValue } from "./model-resolution.js";
20
+ import { registryContextWindow } from "./registry-context-window.js";
19
21
  import { initialSessionMode } from "./settings.js";
22
+ import { loadUserConfig } from "./user-config.js";
20
23
  /** Read the config.json contents (UTF-8). Throws on read/parse failure. */
21
24
  function readConfig() {
22
25
  return readCredentialConfig(ZCODE_CREDS_PATH);
@@ -42,14 +45,19 @@ function loadPersonalModels() {
42
45
  modelsByProvider: new Map(),
43
46
  contextByModel: new Map(),
44
47
  reasoningByModel: new Map(),
48
+ disabledByProvider: new Map(),
45
49
  providers: [],
46
50
  };
47
51
  for (const rule of modelRules) {
48
52
  if (!rule.providerId || !rule.modelId)
49
53
  continue;
50
- if (rule.config?.enabled === false)
51
- continue;
52
54
  const pid = configProviderIdFor(rule.providerId);
55
+ if (rule.config?.enabled === false) {
56
+ const disabled = out.disabledByProvider.get(pid) ?? new Set();
57
+ disabled.add(rule.modelId);
58
+ out.disabledByProvider.set(pid, disabled);
59
+ continue;
60
+ }
53
61
  const ids = out.modelsByProvider.get(pid) ?? [];
54
62
  if (!ids.includes(rule.modelId))
55
63
  ids.push(rule.modelId);
@@ -69,6 +77,25 @@ function loadPersonalModels() {
69
77
  }
70
78
  return out;
71
79
  }
80
+ /** True when the desktop's provider_config.json explicitly switches this model off. */
81
+ function personallyDisabled(personal, providerId, modelId) {
82
+ return personal?.disabledByProvider.get(configProviderIdFor(providerId))?.has(modelId) ?? false;
83
+ }
84
+ /**
85
+ * Positive evidence that a model is really gone — as opposed to merely absent
86
+ * from a registry list that may still be loading: the user switched it off in
87
+ * the desktop, or no local source (legacy config.json, the personal provider
88
+ * config, the provider table) knows it any more. A model that is merely
89
+ * missing from the backend's list is left alone until the backend itself
90
+ * refuses it (see repairUnavailableModel).
91
+ */
92
+ export function modelRetired(providerId, modelId) {
93
+ const personal = loadPersonalModels();
94
+ if (personallyDisabled(personal, providerId, modelId))
95
+ return true;
96
+ const model = modelId.toLowerCase();
97
+ return !loadAllModels().some((m) => sameProvider(m.providerId, providerId) && m.modelId.toLowerCase() === model);
98
+ }
72
99
  /**
73
100
  * A model's declaration from provider_config.json only — the lookup for
74
101
  * models that exist in the desktop's personal config but not (yet) in legacy
@@ -202,35 +229,51 @@ function appendPersonalOnlyProviders(out, personal, pinned) {
202
229
  }
203
230
  }
204
231
  /**
205
- * Append entitled coding-plan models (from the bundled table via the account
206
- * entitlement ladder) for any coding-plan provider not already added from
207
- * config.json. On 3.12+/3.15+ layouts where entitlement comes from OAuth
208
- * (`setting.json` + `credentials.json`), the encrypted store (#320), or a
209
- * manual coding-plan key in `provider_config.json` (#344), the plan's models
210
- * do not live in `config.json` — appending them here keeps them selectable
211
- * even when `config.json` still holds legacy entries or `provider_config.json`
212
- * also defines custom providers.
232
+ * Merge the entitled coding-plan models (the provider table's catalog, via the
233
+ * account entitlement ladder) into the dropdown.
234
+ *
235
+ * For a provider config.json already lists, the table's models are UNIONED in:
236
+ * config.json is a legacy file that stopped syncing, while the table is the
237
+ * catalog the backend registry builds from — and the desktop host refreshes it
238
+ * from the CDN independently of app updates (observed 2026-11-23: revision 47
239
+ * added GLM-5.4; a config.json still naming only GLM-5.3/5.3-Flash kept the
240
+ * new model out of the dropdown while the backend already served it).
241
+ *
242
+ * On 3.12+/3.15+ layouts where entitlement comes from OAuth (`setting.json` +
243
+ * `credentials.json`), the encrypted store (#320), or a manual coding-plan key
244
+ * in `provider_config.json` (#344), the plan's models do not live in
245
+ * `config.json` at all — the table is then the ONLY source that keeps them
246
+ * selectable even when `config.json` still holds legacy entries or
247
+ * `provider_config.json` also defines custom providers.
213
248
  */
214
249
  function appendEntitledCodingPlanModels(out, personal, pinned) {
215
- const known = new Set(out.map((m) => m.providerId));
250
+ const listed = new Set(out.map((m) => `${m.providerId}\0${m.modelId}`));
251
+ const names = new Map();
252
+ for (const m of out)
253
+ if (!names.has(m.providerId))
254
+ names.set(m.providerId, m.providerName);
216
255
  const byProvider = new Map();
217
256
  for (const m of entitledCodingPlanModels()) {
218
- if (known.has(m.providerId))
219
- continue;
220
257
  if (pinned && m.providerId !== pinned)
221
258
  continue;
259
+ if (personallyDisabled(personal, m.providerId, m.modelId))
260
+ continue;
222
261
  let group = byProvider.get(m.providerId);
223
262
  if (!group) {
224
- group = { providerName: m.providerName, models: new Set() };
263
+ // A provider config.json already lists keeps ITS display name.
264
+ group = { providerName: names.get(m.providerId) ?? m.providerName, models: new Set() };
225
265
  byProvider.set(m.providerId, group);
226
266
  }
227
267
  group.models.add(m.modelId);
228
268
  }
229
269
  for (const [pid, group] of byProvider) {
230
- for (const extra of personal?.modelsByProvider.get(pid) ?? []) {
270
+ for (const extra of personal?.modelsByProvider.get(pid) ?? [])
231
271
  group.models.add(extra);
232
- }
233
272
  for (const modelId of group.models) {
273
+ const key = `${pid}\0${modelId}`;
274
+ if (listed.has(key))
275
+ continue;
276
+ listed.add(key);
234
277
  out.push({ providerId: pid, providerName: group.providerName, modelId });
235
278
  }
236
279
  }
@@ -271,6 +314,11 @@ export function loadAllModels() {
271
314
  ? new Set(personalIds)
272
315
  : new Set([...Object.keys(p.models ?? {}), ...(personalIds ?? [])]);
273
316
  for (const modelId of ids) {
317
+ // A model the user switched off in the desktop is gone from the
318
+ // backend registry; legacy config.json keeps naming it, and listing
319
+ // it offered a choice every switch to which failed.
320
+ if (personallyDisabled(personal, pid, modelId))
321
+ continue;
274
322
  out.push({ providerId: pid, providerName, modelId });
275
323
  }
276
324
  }
@@ -316,6 +364,196 @@ function entitledOrDefaultModels(pinned) {
316
364
  },
317
365
  ];
318
366
  }
367
+ function sameProvider(a, b) {
368
+ return a === b || configProviderIdFor(a) === configProviderIdFor(b);
369
+ }
370
+ /** True when a provider-qualified model is in the usable set (dialect and case folded). */
371
+ export function isModelUsable(usable, providerId, modelId) {
372
+ const model = modelId.toLowerCase();
373
+ return usable.some((e) => e.providerId !== undefined &&
374
+ e.modelId?.toLowerCase() === model &&
375
+ sameProvider(e.providerId, providerId));
376
+ }
377
+ /** Whether two `providerId\modelId` values name the same model (dialect and case folded). */
378
+ export function sameModelValue(a, b) {
379
+ const pa = parseModelRefValue(a);
380
+ const pb = parseModelRefValue(b);
381
+ return (pa.modelId.toLowerCase() === pb.modelId.toLowerCase() &&
382
+ (!pa.providerId || !pb.providerId || sameProvider(pa.providerId, pb.providerId)));
383
+ }
384
+ /**
385
+ * An official ZCode plan (`builtin:` / `account:` provider ids) — a lineup in
386
+ * which "the newest model" is a real successor relation (GLM-5.4 follows
387
+ * GLM-5.3). A third-party provider may mix families in one list, so its
388
+ * version numbers are not comparable and the user's own order stays the rule.
389
+ */
390
+ function isOfficialPlan(providerId) {
391
+ const id = configProviderIdFor(providerId);
392
+ return isBuiltinProvider(id) || id.startsWith("account:");
393
+ }
394
+ /**
395
+ * The version a model id advertises, as a numeric chain: "GLM-5.4" → [5, 4],
396
+ * "glm-5-3-flash" → [5, 3], "GLM-5-Turbo" → [5]. The chain stops at the first
397
+ * non-numeric segment and before a date stamp ("GLM-4-Flash-250414" → [4]), so
398
+ * an id without a version ranks below every versioned one.
399
+ */
400
+ function modelVersion(modelId) {
401
+ const start = modelId.search(/\d/u);
402
+ if (start < 0)
403
+ return [];
404
+ const chain = /^v?\d+(?:[._-]\d+)*/iu.exec(modelId.slice(start))?.[0];
405
+ if (!chain)
406
+ return [];
407
+ const out = [];
408
+ for (const part of chain.split(/[._-]/u)) {
409
+ if (part.length >= 5)
410
+ break; // a date stamp, not a version
411
+ out.push(Number(part));
412
+ }
413
+ return out;
414
+ }
415
+ /** Sort order: the newer official model first — version, then fewer variant suffixes. */
416
+ function compareLatest(a, b) {
417
+ const va = modelVersion(a.modelId);
418
+ const vb = modelVersion(b.modelId);
419
+ for (let i = 0; i < Math.max(va.length, vb.length); i++) {
420
+ if (va[i] !== vb[i])
421
+ return (vb[i] ?? -1) - (va[i] ?? -1);
422
+ }
423
+ const variantSuffixes = (id) => {
424
+ const start = id.search(/\d/u);
425
+ const rest = start < 0 ? id : id.slice(start).replace(/^v?\d+(?:[._-]\d+)*/iu, "");
426
+ return rest.split(/[^a-z]+/iu).filter(Boolean).length;
427
+ };
428
+ return variantSuffixes(a.modelId) - variantSuffixes(b.modelId);
429
+ }
430
+ /**
431
+ * One provider's default model: the newest for an official plan, the
432
+ * first-listed everywhere else. `models` must all belong to that provider.
433
+ */
434
+ function providerDefault(models) {
435
+ const first = models[0];
436
+ if (!first)
437
+ return undefined;
438
+ return isOfficialPlan(first.providerId) ? [...models].sort(compareLatest)[0] : first;
439
+ }
440
+ /** The user's manual default (`session.defaultModel` in the user config), when set. */
441
+ function configuredDefaultModel() {
442
+ return loadUserConfig().session?.defaultModel?.trim() || undefined;
443
+ }
444
+ /**
445
+ * The models to try, best first, when a session needs a default — the model a
446
+ * NEW session starts on, and the fallback when a session's own model is no
447
+ * longer runnable. Never a hardcoded id: a new upstream release is the default
448
+ * from the day it is usable, with nothing to change here (observed 2026-11-23:
449
+ * the hardcoded GLM-5.3 was switched off in the desktop on the day GLM-5.4
450
+ * shipped, and every new session tried to start on a model that no longer
451
+ * existed).
452
+ *
453
+ * 1. `ZCODE_PROVIDER` + `ZCODE_MODEL` — the per-process pin.
454
+ * 2. `session.defaultModel` in the user config — the manual choice, in any
455
+ * spelling `parseModelRefValue` reads (`providerId\modelId`,
456
+ * `providerId/modelId`, a bare modelId naming exactly one model).
457
+ * 3. `preferProviderId`'s newest model — a session keeps its own plan while
458
+ * that plan still runs anything (a coding-plan session is never moved to
459
+ * another plan while its own works).
460
+ * 4. The first provider in the user's own model-list order (the configured
461
+ * leader — what new sessions always started on), then the registry's
462
+ * first when no locally-known provider is runnable.
463
+ *
464
+ * The two explicit choices are tried even when the registry list lacks them:
465
+ * that list only names ENABLED models and may be stale (captured at resume) —
466
+ * the backend is the final authority, and a refusal falls through to the next
467
+ * candidate. The automatic choices only ever name models the list vouches for
468
+ * (without a list, the local model list stands in), so a fallback never lands
469
+ * on a model that was switched off.
470
+ */
471
+ export function defaultModelCandidates(usable, preferProviderId) {
472
+ const local = loadAllModels();
473
+ const names = providerDisplayNames(local);
474
+ const nameOf = (providerId) => names.get(configProviderIdFor(providerId)) ?? names.get(providerId) ?? providerId;
475
+ const registryListed = Boolean(usable && usable.length > 0);
476
+ const listed = registryListed
477
+ ? usable
478
+ .filter((m) => m.providerId && m.modelId)
479
+ .map((m) => ({
480
+ providerId: m.providerId,
481
+ providerName: nameOf(m.providerId),
482
+ modelId: m.modelId,
483
+ }))
484
+ : local;
485
+ /** Every model of one provider (any dialect) inside a pool. */
486
+ const inPool = (pool, providerId) => pool.filter((m) => sameProvider(m.providerId, providerId));
487
+ /** An explicit pick as the list spells it, else as the local files do, else as written. */
488
+ const explicit = (providerId, modelId) => {
489
+ const model = modelId.toLowerCase();
490
+ const hit = (pool) => pool.find((m) => sameProvider(m.providerId, providerId) && m.modelId.toLowerCase() === model);
491
+ return hit(listed) ?? hit(local) ?? { providerId, providerName: nameOf(providerId), modelId };
492
+ };
493
+ const out = [];
494
+ const seen = new Set();
495
+ const push = (ref) => {
496
+ if (!ref)
497
+ return;
498
+ const key = `${configProviderIdFor(ref.providerId)}\0${ref.modelId.toLowerCase()}`;
499
+ if (seen.has(key))
500
+ return;
501
+ seen.add(key);
502
+ out.push(ref);
503
+ };
504
+ const pinnedProvider = process.env.ZCODE_PROVIDER?.trim();
505
+ const pinnedModel = process.env.ZCODE_MODEL?.trim();
506
+ if (pinnedProvider && pinnedModel)
507
+ push(explicit(pinnedProvider, pinnedModel));
508
+ const configured = configuredDefaultModel();
509
+ if (configured) {
510
+ const parsed = parseModelRefValue(configured);
511
+ if (parsed.providerId) {
512
+ push(explicit(parsed.providerId, parsed.modelId));
513
+ }
514
+ else {
515
+ // A bare id must name exactly one model — never guess between providers.
516
+ const model = parsed.modelId.toLowerCase();
517
+ const hits = listed.filter((c) => c.modelId.toLowerCase() === model);
518
+ const providers = new Set(hits.map((h) => configProviderIdFor(h.providerId)));
519
+ if (providers.size === 1)
520
+ push(hits[0]);
521
+ }
522
+ }
523
+ if (preferProviderId)
524
+ push(providerDefault(inPool(listed, preferProviderId)));
525
+ if (registryListed) {
526
+ // The user's own provider order decides which plan a default comes from;
527
+ // the registry list decides which of its models can run.
528
+ for (const m of local) {
529
+ const runnable = inPool(listed, m.providerId);
530
+ if (runnable.length > 0) {
531
+ push(providerDefault(runnable));
532
+ break;
533
+ }
534
+ }
535
+ // No locally-known provider runs anything: the registry's first one.
536
+ if (listed.length > 0)
537
+ push(providerDefault(inPool(listed, listed[0].providerId)));
538
+ }
539
+ else if (local.length > 0) {
540
+ push(providerDefault(inPool(local, local[0].providerId)));
541
+ }
542
+ return out;
543
+ }
544
+ /** The first (best) entry of {@link defaultModelCandidates}. */
545
+ export function defaultModelRef(usable, preferProviderId) {
546
+ return (defaultModelCandidates(usable, preferProviderId)[0] ?? {
547
+ providerId: DEFAULT_PROVIDER_ID,
548
+ providerName: DEFAULT_PROVIDER_NAME,
549
+ modelId: DEFAULT_MODEL_ID,
550
+ });
551
+ }
552
+ /** `defaultModelRef` as the `providerId\modelId` value the switch handler takes. */
553
+ export function defaultModelValue(usable, preferProviderId) {
554
+ const ref = defaultModelRef(usable, preferProviderId);
555
+ return formatModelValue(ref.providerId, ref.modelId);
556
+ }
319
557
  /**
320
558
  * The provider list ACP clients render a provider picker from (#400) —
321
559
  * without mirroring `providerSelectable` and the config scan in their own
@@ -390,9 +628,20 @@ export function findProviderConfig(providerId) {
390
628
  return null;
391
629
  }
392
630
  }
393
- /** Read the context-window size for a provider+model: config.json first, then
394
- * the desktop's provider_config.json (models added there carry
395
- * `config.properties.contextWindow` and never reach config.json). */
631
+ /**
632
+ * The context-window size for a provider+model, 0 when no local source knows
633
+ * it. One ladder, most explicit first:
634
+ *
635
+ * 1. `config.json` `limit.context` — the user's per-model limit;
636
+ * 2. the desktop's `provider_config.json` rule (models added there carry
637
+ * `config.properties.contextWindow` and never reach config.json);
638
+ * 3. the registry's own answer (`registryContextWindow`) — the rule walk the
639
+ * backend resolves every table model through, and the only local source
640
+ * for a model that arrives through the provider table alone (GLM-5.4).
641
+ *
642
+ * An explicit value always wins, whichever is larger. Either provider dialect
643
+ * is accepted.
644
+ */
396
645
  export function modelContextWindow(providerId, modelId) {
397
646
  const pid = configProviderIdFor(providerId);
398
647
  try {
@@ -405,7 +654,19 @@ export function modelContextWindow(providerId, modelId) {
405
654
  catch {
406
655
  // fall through to the personal config
407
656
  }
408
- return personalModelSpec(pid, modelId)?.contextWindow ?? 0;
657
+ return (personalModelSpec(pid, modelId)?.contextWindow ??
658
+ registryContextWindow(providerId, modelId) ??
659
+ 0);
660
+ }
661
+ /**
662
+ * The context-gauge denominator (`usage_update.size`): the local ladder above,
663
+ * else the size the backend reported (the CLI's projection seeds a hardcoded
664
+ * 200K until its first usage event). Every emission site goes through here —
665
+ * initial usage, turn-time deltas, the post-switch refresh, the TUI's boot
666
+ * reading — so the gauge cannot flip-flop between sources.
667
+ */
668
+ export function usageWindowSize(providerId, modelId, backendSize) {
669
+ return modelContextWindow(providerId, modelId) || backendSize || 0;
409
670
  }
410
671
  /** Builtin providerIds are prefixed with `builtin:` (e.g. `builtin:bigmodel`). */
411
672
  export function isBuiltinProvider(providerId) {
@@ -581,7 +842,10 @@ export async function buildConfigOptions(server, zcodeSid, receiverRoot) {
581
842
  // relays the options into a picker (Multica's effort selector) would
582
843
  // otherwise offer tokens the runtime rejects ("nothink" was fiction,
583
844
  // "low" was missing).
584
- const cur = loadAllModels()[0];
845
+ // The advertised current model is the DEFAULT a new session starts on
846
+ // (defaultModelRef: the manual choice, else the newest usable model) —
847
+ // the one the runtime is pinned to at materialization.
848
+ const cur = defaultModelRef();
585
849
  if (cur) {
586
850
  // The advertised current model follows the dropdown's leading entry
587
851
  // (the enabled provider's first model — what the runtime actually
@@ -751,9 +1015,21 @@ export async function buildConfigOptions(server, zcodeSid, receiverRoot) {
751
1015
  options: thoughtOptions,
752
1016
  },
753
1017
  ];
754
- // Do not invent a provider/model pair when a materialized read lacks identity.
755
- if (zcodeSid !== null && !currentProviderId)
756
- options.shift();
1018
+ // Do not invent a provider/model pair when a materialized read lacks
1019
+ // identity. An UNBOUND restore (a persisted selection the registry could
1020
+ // not bind — e.g. the model was switched off in the desktop) also reports
1021
+ // no current model, and hiding the model option there left the user with
1022
+ // no picker to switch back with (observed 2026-11-23): advertise the
1023
+ // default-model choice as the pending current instead, so the dropdown
1024
+ // exists and the repair/fallback path has a concrete value to apply.
1025
+ if (zcodeSid !== null && !currentProviderId && options[0]?.id === "model") {
1026
+ const modelOption = options[0];
1027
+ const fallback = defaultModelRef(snapshot);
1028
+ options[0] = {
1029
+ ...modelOption,
1030
+ currentValue: formatModelValue(fallback.providerId, fallback.modelId),
1031
+ };
1032
+ }
757
1033
  // Read-only quota pseudo-option (ADR-0021): martty-only, no category (never
758
1034
  // lands in a settings menu), string type per the probe-verified shape — the
759
1035
  // SDK's union stops at select/boolean, so the cast carries the agent-owned
@@ -942,8 +1218,9 @@ export function rememberModelChoice(server, acpSid, zcodeSid, patch) {
942
1218
  * broadcast or fail the handler — the switch already succeeded backend-side.
943
1219
  *
944
1220
  * For model switches, also emit a usage_update with the NEW model's context
945
- * window (from config.json) so the editor's context bar refreshes immediately
946
- * instead of waiting for the next turn's UsageDelta. */
1221
+ * window (the context-window ladder, `usageWindowSize`) so the editor's
1222
+ * context bar refreshes immediately instead of waiting for the next turn's
1223
+ * UsageDelta. */
947
1224
  export async function emitConfigOptionUpdate(server, cx, acpSid, zcodeSid, kind) {
948
1225
  const options = await buildConfigOptions(server, zcodeSid, clientConnectionRoot(cx));
949
1226
  const broadcastSource = isBroadcastSource(cx);
@@ -973,7 +1250,8 @@ export async function emitConfigOptionUpdate(server, cx, acpSid, zcodeSid, kind)
973
1250
  }
974
1251
  if (kind === "model") {
975
1252
  // Refresh the context bar: the backend's projection.contextWindow lags
976
- // behind a model switch, so read the new model's limit from config.json.
1253
+ // behind a model switch, so the new model's window comes from the local
1254
+ // ladder first.
977
1255
  try {
978
1256
  const read = await sessionRead(server, zcodeSid);
979
1257
  const proj = (read.projection ?? {});
@@ -984,7 +1262,9 @@ export async function emitConfigOptionUpdate(server, cx, acpSid, zcodeSid, kind)
984
1262
  // The rebuilt options[0] (model) currentValue is the just-switched value.
985
1263
  const modelOpt = options.find((o) => o.id === "model");
986
1264
  const { providerId, modelId } = parseModelValue(String(modelOpt?.currentValue ?? ""));
987
- const size = modelContextWindow(providerId, modelId);
1265
+ // The projection's contextWindow still names the PREVIOUS model here, so
1266
+ // it is only the last resort — for a model no local source knows.
1267
+ const size = usageWindowSize(providerId, modelId, proj.contextWindow);
988
1268
  await send({
989
1269
  sessionUpdate: "usage_update",
990
1270
  used,