zcode-app-cli 3.11.2-24 → 3.12.3-26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +35 -8
  2. package/bin/zcode.js +265 -133
  3. package/docs/CONFIGURATION.md +387 -0
  4. package/docs/CONFIGURATION.zh-CN.md +324 -0
  5. package/docs/PROVIDER_CONFIG.md +271 -0
  6. package/docs/PROVIDER_CONFIG.zh-CN.md +245 -0
  7. package/package.json +15 -6
  8. package/provider.example.json +151 -0
  9. package/{config.example.json → setting.example.json} +0 -47
  10. package/vendor/cli-config.cjs +161 -0
  11. package/vendor/extraction.json +17 -4
  12. package/vendor/node_modules/@zcode/tui/dist/index.js +495 -1095
  13. package/vendor/packages/browser-use-plugin/dist/mcp/server.js +35543 -34422
  14. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +2 -2
  15. package/vendor/packages/document-skills-plugin/package.json +4 -4
  16. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +34 -0
  17. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +9 -0
  18. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +11 -0
  19. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +7 -0
  20. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +7 -0
  21. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +10 -1
  22. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +19 -4
  23. package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/env_check.sh +6 -2
  24. package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup.md +12 -3
  25. package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup_mac_linux.sh +9 -3
  26. package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup_windows.ps1 +8 -3
  27. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +30 -6
  28. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +9 -3
  29. package/vendor/packages/document-skills-plugin/skills/pptx/SKILL.md +33 -0
  30. package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup.md +29 -4
  31. package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup_mac_linux.sh +8 -3
  32. package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup_windows.ps1 +8 -3
  33. package/vendor/packages/document-skills-plugin/skills/xlsx/quality/pipeline.md +9 -0
  34. package/vendor/packages/document-skills-plugin/skills/xlsx/setup.sh +8 -3
  35. package/vendor/packages/document-skills-plugin/skills/xlsx/xlsx.py +15 -1
  36. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +13 -8
  37. package/vendor/provider/zcode-builtin.json +6296 -0
  38. package/vendor/zcode.cjs +1159 -840
  39. package/zcode-runtime.lock.json +3 -3
@@ -1,52 +1,17 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { spawn } from "node:child_process";
3
- import { accessSync, appendFileSync, closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
3
+ import { accessSync, appendFileSync, closeSync, constants, fstatSync, openSync, readFileSync, readSync } from "node:fs";
4
4
  import { constants as constants$1, homedir } from "node:os";
5
+ import { access, link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
5
6
  import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep, win32 } from "node:path";
6
- import { access, copyFile, link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
7
7
  import { randomUUID } from "node:crypto";
8
- import { isDeepStrictEqual } from "node:util";
9
8
  import { Box, CombinedAutocompleteProvider, Container, Editor, Image, Input, Markdown, ProcessTerminal, ScrollView, SelectList, Spacer, Text, TuiAltScreen, TuiMainScreen, VStack, decodeKittyPrintable, getKeybindings, isKeyRelease, isViewportTUI, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
9
+ import { isDeepStrictEqual } from "node:util";
10
10
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
11
11
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
12
12
  //#endregion
13
- //#region config.example.json
14
- var config_example_default = {
15
- provider: { "zai": {
16
- "kind": "anthropic",
17
- "name": "Z.AI Coding Plan",
18
- "options": {
19
- "apiKeyRequired": true,
20
- "baseURL": "https://api.z.ai/api/anthropic"
21
- },
22
- "headers": {},
23
- "models": {
24
- "glm-5.3": { "name": "GLM-5.3" },
25
- "glm-5.3-flash": {
26
- "name": "GLM-5.3-Flash",
27
- "limit": {
28
- "context": 1e6,
29
- "output": 128e3
30
- },
31
- "modalities": {
32
- "input": [
33
- "text",
34
- "image",
35
- "video"
36
- ],
37
- "output": ["text"]
38
- }
39
- },
40
- "glm-5.2": { "name": "GLM-5.2" },
41
- "glm-5.1": { "name": "GLM-5.1" },
42
- "glm-5-turbo": { "name": "GLM-5-Turbo" }
43
- }
44
- } },
45
- model: {
46
- "main": "zai/glm-5.2",
47
- "lite": "zai/glm-5-turbo"
48
- },
49
- modelCatalog: { "overrides": {} },
13
+ //#region setting.example.json
14
+ var setting_example_default = {
50
15
  modelStream: { "idleTimeoutMs": 6e4 },
51
16
  permission: {
52
17
  "mode": "build",
@@ -64,14 +29,11 @@ var config_example_default = {
64
29
  "compact": true,
65
30
  "rewind": true,
66
31
  "subagent": true,
67
- "memory": true,
68
32
  "skill": true,
69
33
  "mcp": true
70
34
  },
71
35
  subagents: { "autoBackgroundMs": 1e3 },
72
36
  memory: {
73
- "use": true,
74
- "write": true,
75
37
  "autoConsolidate": true,
76
38
  "summaryMaxBytes": 8192
77
39
  },
@@ -96,7 +58,6 @@ var config_example_default = {
96
58
  "format": "text"
97
59
  },
98
60
  ui: {
99
- "locale": "auto",
100
61
  "theme": "auto",
101
62
  "tuiMode": "regular",
102
63
  "copyOnSelect": true,
@@ -126,6 +87,41 @@ var config_example_default = {
126
87
  }
127
88
  };
128
89
  //#endregion
90
+ //#region src/config-paths.ts
91
+ function cliSettingsPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
92
+ const path = platform === "win32" ? win32 : posix;
93
+ const home = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim() || fallbackHome;
94
+ return path.join(home, ".zcode", "cli", "setting.json");
95
+ }
96
+ function desktopSettingsPath(env = process.env) {
97
+ return join(dirname(dirname(cliSettingsPath(env))), "v2", "setting.json");
98
+ }
99
+ function readDesktopSettings(env = process.env) {
100
+ try {
101
+ const value = JSON.parse(readFileSync(desktopSettingsPath(env), "utf8"));
102
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid settings object");
103
+ return value;
104
+ } catch (error) {
105
+ if (error.code === "ENOENT") return {};
106
+ throw new Error("Unable to read Desktop setting.json; the file was left unchanged.");
107
+ }
108
+ }
109
+ function sharedDataBaseDir(env = process.env, platform = process.platform, fallbackHome = homedir()) {
110
+ const home = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim() || fallbackHome;
111
+ const desktop = platform === process.platform ? readDesktopSettings(env).dataBaseDir : void 0;
112
+ return env.ZCODE_DATA_BASE_DIR?.trim() || typeof desktop === "string" && desktop.trim() || home;
113
+ }
114
+ function providerConfigPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
115
+ const path = platform === "win32" ? win32 : posix;
116
+ return env.ZCODE_PERSONAL_PROVIDER_CONFIG_FILE?.trim() || path.join(sharedDataBaseDir(env, platform, fallbackHome), ".zcode", "v2", "provider_config.json");
117
+ }
118
+ function legacyCliConfigPath(env = process.env) {
119
+ return join(dirname(cliSettingsPath(env)), "config.json");
120
+ }
121
+ function settingsMigrationMarkerPath(env = process.env) {
122
+ return join(dirname(cliSettingsPath(env)), "migrations", "settings-v1.json");
123
+ }
124
+ //#endregion
129
125
  //#region src/model-access.ts
130
126
  function isNodeError(error) {
131
127
  return error instanceof Error && "code" in error;
@@ -142,16 +138,27 @@ async function configFileExists(configPath) {
142
138
  throw error;
143
139
  }
144
140
  }
145
- function userConfigPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
146
- const path = platform === "win32" ? win32 : posix;
147
- const configuredHome = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim();
148
- return path.join(configuredHome || fallbackHome, ".zcode", "cli", "config.json");
141
+ function providerConfigPathHint(platform = process.platform) {
142
+ return platform === "win32" ? "%USERPROFILE%\\.zcode\\v2\\provider_config.json" : "~/.zcode/v2/provider_config.json";
149
143
  }
150
- function userConfigPathHint(platform = process.platform) {
151
- return platform === "win32" ? "%USERPROFILE%\\.zcode\\cli\\config.json" : "~/.zcode/cli/config.json";
144
+ async function finishSettingsMigration(env) {
145
+ const marker = settingsMigrationMarkerPath(env);
146
+ await mkdir(dirname(marker), {
147
+ recursive: true,
148
+ mode: 448
149
+ });
150
+ let file;
151
+ try {
152
+ file = await open(marker, "wx", 384);
153
+ await file.writeFile("{\"schemaVersion\":1}\n", "utf8");
154
+ } catch (error) {
155
+ if (!isNodeError(error) || error.code !== "EEXIST") throw error;
156
+ } finally {
157
+ await file?.close();
158
+ }
152
159
  }
153
- async function ensureUserConfig(env = process.env) {
154
- const configPath = userConfigPath(env);
160
+ async function ensureCliSettings(env = process.env) {
161
+ const configPath = cliSettingsPath(env);
155
162
  const configDirectory = dirname(configPath);
156
163
  try {
157
164
  await mkdir(configDirectory, {
@@ -161,15 +168,32 @@ async function ensureUserConfig(env = process.env) {
161
168
  } catch (error) {
162
169
  throw new Error(`Unable to create ZCode config directory ${configDirectory}: ${errorMessage$2(error)}`, { cause: error });
163
170
  }
164
- if (await configFileExists(configPath)) return {
165
- configPath,
166
- created: false
167
- };
171
+ if (await configFileExists(configPath)) {
172
+ await finishSettingsMigration(env);
173
+ return {
174
+ configPath,
175
+ created: false
176
+ };
177
+ }
178
+ let initial = setting_example_default;
179
+ let migrated = false;
180
+ try {
181
+ if (await configFileExists(settingsMigrationMarkerPath(env))) initial = setting_example_default;
182
+ else {
183
+ const legacy = JSON.parse(await readFile(legacyCliConfigPath(env), "utf8"));
184
+ if (!legacy || typeof legacy !== "object" || Array.isArray(legacy)) throw new Error("invalid legacy settings");
185
+ const { provider, model, modelCatalog, ...settings } = legacy;
186
+ initial = settings;
187
+ migrated = true;
188
+ }
189
+ } catch (error) {
190
+ if (!isNodeError(error) || error.code !== "ENOENT") throw new Error("Unable to migrate the old CLI config.json; the original file was preserved.");
191
+ }
168
192
  const temporaryPath = join(configDirectory, `.${basename(configPath)}.${process.pid}.${randomUUID()}.tmp`);
169
193
  let file;
170
194
  try {
171
195
  file = await open(temporaryPath, "wx", 384);
172
- await file.writeFile(`${JSON.stringify(config_example_default, null, 2)}\n`, "utf8");
196
+ await file.writeFile(`${JSON.stringify(initial, null, 2)}\n`, "utf8");
173
197
  await file.sync();
174
198
  } catch (error) {
175
199
  if (file) {
@@ -183,13 +207,16 @@ async function ensureUserConfig(env = process.env) {
183
207
  }
184
208
  try {
185
209
  await link(temporaryPath, configPath);
210
+ await finishSettingsMigration(env);
186
211
  return {
187
212
  configPath,
188
- created: true
213
+ created: true,
214
+ ...migrated ? { migrated: true } : {}
189
215
  };
190
216
  } catch (error) {
191
217
  if (isNodeError(error) && error.code === "EEXIST") {
192
218
  if (!await configFileExists(configPath)) throw new Error(`ZCode config path exists but is not a file: ${configPath}`);
219
+ await finishSettingsMigration(env);
193
220
  return {
194
221
  configPath,
195
222
  created: false
@@ -200,8 +227,8 @@ async function ensureUserConfig(env = process.env) {
200
227
  await rm(temporaryPath, { force: true }).catch(() => {});
201
228
  }
202
229
  }
203
- async function readUserConfig(env = process.env) {
204
- const { configPath } = await ensureUserConfig(env);
230
+ async function readCliSettings(env = process.env) {
231
+ const { configPath } = await ensureCliSettings(env);
205
232
  try {
206
233
  const value = JSON.parse(await readFile(configPath, "utf8"));
207
234
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("the root value must be a JSON object");
@@ -210,9 +237,9 @@ async function readUserConfig(env = process.env) {
210
237
  throw new Error(`Unable to read ZCode config ${configPath}: ${errorMessage$2(error)}`, { cause: error });
211
238
  }
212
239
  }
213
- async function updateUserConfig(update, env = process.env) {
214
- const configPath = userConfigPath(env);
215
- const config = await readUserConfig(env);
240
+ async function updateCliSettings(update, env = process.env) {
241
+ const configPath = cliSettingsPath(env);
242
+ const config = await readCliSettings(env);
216
243
  const before = JSON.stringify(config);
217
244
  update(config);
218
245
  if (JSON.stringify(config) === before) return configPath;
@@ -233,27 +260,56 @@ async function updateUserConfig(update, env = process.env) {
233
260
  await rm(temporaryPath, { force: true }).catch(() => {});
234
261
  }
235
262
  }
263
+ function record$5(value) {
264
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
265
+ }
266
+ /** Configuration presence only; the runtime owns credential decryption and authentication. */
236
267
  async function readConfiguredModelAccess(env = process.env) {
237
- const configPath = userConfigPath(env);
238
- let config;
268
+ const directory = join(sharedDataBaseDir(env), ".zcode", "v2");
269
+ const configPath = providerConfigPath(env);
270
+ let value;
239
271
  try {
240
- config = JSON.parse(await readFile(configPath, "utf8"));
241
- } catch {
272
+ value = JSON.parse(await readFile(configPath, "utf8"));
273
+ } catch (error) {
242
274
  return null;
243
275
  }
244
- const model = typeof config.model?.main === "string" ? config.model.main.trim() : "";
245
- const separator = model.indexOf("/");
246
- if (separator <= 0 || separator === model.length - 1) return null;
247
- const providerId = model.slice(0, separator);
248
- const modelId = model.slice(separator + 1);
249
- const provider = config.provider?.[providerId];
250
- const apiKey = provider?.options?.apiKey;
251
- if (!provider?.models?.[modelId] || typeof apiKey !== "string" || !apiKey.trim()) return null;
252
- return {
276
+ const root = record$5(value), config = record$5(root?.config);
277
+ if (root?.schemaVersion !== 1 || !config) return null;
278
+ const selection = record$5(config.defaultModelSelection);
279
+ const providerId = typeof selection?.providerId === "string" ? selection.providerId.trim() : "";
280
+ const modelId = typeof selection?.modelId === "string" ? selection.modelId.trim() : "";
281
+ if (!providerId || !modelId) return null;
282
+ const result = {
253
283
  configPath,
254
- model,
284
+ model: `${providerId}/${modelId}`,
255
285
  providerId
256
286
  };
287
+ if (providerId.startsWith("account:")) try {
288
+ const credentials = record$5(JSON.parse(await readFile(join(directory, "credentials.json"), "utf8")));
289
+ const identity = credentials?.[`account-provider:${providerId}:identity`];
290
+ const keyPrefix = `account-provider:coding-plan:${providerId}:account:`;
291
+ return typeof identity === "string" && identity.length > 0 && Object.entries(credentials ?? {}).some(([key, secret]) => key.startsWith(keyPrefix) && key.endsWith(":api-key") && typeof secret === "string" && secret.length > 0) ? result : null;
292
+ } catch {
293
+ return null;
294
+ }
295
+ const rules = record$5(config.providerConfigRules)?.providerRules;
296
+ if (!Array.isArray(rules)) return null;
297
+ const settings = record$5(rules.map(record$5).find((rule) => rule?.providerId === providerId)?.config), access = record$5(settings?.access);
298
+ return settings?.visibility !== "hidden" && typeof access?.apiKey === "string" && access.apiKey.trim() && (!Array.isArray(settings?.personalModelIds) || settings.personalModelIds.includes(modelId)) ? result : null;
299
+ }
300
+ /** A native personal provider can be usable without a saved default selection. */
301
+ async function hasConfiguredProviderAccess(env = process.env) {
302
+ if (await readConfiguredModelAccess(env)) return true;
303
+ try {
304
+ const value = record$5(JSON.parse(await readFile(providerConfigPath(env), "utf8")));
305
+ const rules = record$5(record$5(value?.config)?.providerConfigRules)?.providerRules;
306
+ return value?.schemaVersion === 1 && Array.isArray(rules) && rules.some((raw) => {
307
+ const rule = record$5(raw), config = record$5(rule?.config), access = record$5(config?.access);
308
+ return rule?.enabled !== false && config?.visibility !== "hidden" && typeof access?.apiKey === "string" && access.apiKey.trim().length > 0 && (typeof rule?.templateId === "string" || Array.isArray(config?.personalModelIds) && config.personalModelIds.length > 0);
309
+ });
310
+ } catch {
311
+ return false;
312
+ }
257
313
  }
258
314
  function setupPendingPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
259
315
  const path = platform === "win32" ? win32 : posix;
@@ -302,472 +358,28 @@ async function missingCodingPlanKey(options = {}) {
302
358
  if (parent === directory) break;
303
359
  directory = parent;
304
360
  }
305
- let config;
306
- try {
307
- config = record$4(JSON.parse(await readFile(userConfigPath(env), "utf8")));
308
- } catch {
309
- return;
310
- }
311
- const model = options.model ?? record$4(config?.model)?.main;
312
- if (typeof model !== "string") return void 0;
313
- const providerId = model.split("/", 1)[0];
314
- if (providerId !== "zai" && providerId !== "bigmodel") return void 0;
315
- const provider = record$4(record$4(config?.provider)?.[providerId]);
316
- const settings = record$4(provider?.options);
317
- const expectedUrl = providerId === "zai" ? "https://api.z.ai/api/anthropic" : "https://open.bigmodel.cn/api/anthropic";
318
- if (provider?.kind !== "anthropic" || settings?.baseURL !== expectedUrl || settings?.apiKeyRequired !== true || typeof settings.apiKey === "string" && settings.apiKey.trim() || settings.apiKey !== void 0 && typeof settings.apiKey !== "string" || Object.keys(record$4(provider.headers) ?? {}).length > 0) return void 0;
319
- return `Model access is not configured for ${providerId}. Run /login or /setup in zcode, or configure its API key before sending a prompt. No model request was sent.`;
320
- }
321
- //#endregion
322
- //#region src/model-catalog-refresh.ts
323
- const MODEL_CATALOG_REFRESH_TTL_MS = 360 * 60 * 1e3;
324
- const MODEL_CATALOG_URL_PATH = "/api/v1/client/configs";
325
- const DEFAULT_TIMEOUT_MS = 5e3;
326
- const PROVIDER_BASE_URLS = {
327
- zai: "https://api.z.ai/api/anthropic",
328
- bigmodel: "https://open.bigmodel.cn/api/anthropic"
329
- };
330
- const MODALITIES = /* @__PURE__ */ new Set([
331
- "text",
332
- "audio",
333
- "image",
334
- "video",
335
- "pdf"
336
- ]);
337
- const EFFORTS = /* @__PURE__ */ new Set([
338
- "low",
339
- "medium",
340
- "high",
341
- "xhigh",
342
- "max"
343
- ]);
344
- function enabledEnvironmentFlag$1(value) {
345
- if (value === void 0) return false;
346
- return ![
347
- "",
348
- "0",
349
- "false",
350
- "no",
351
- "off"
352
- ].includes(value.trim().toLowerCase());
353
- }
354
- function modelCatalogRefreshDisabled(env = process.env) {
355
- return enabledEnvironmentFlag$1(env.CI) || enabledEnvironmentFlag$1(env.ZCODE_DISABLE_MODEL_CATALOG_REFRESH);
356
- }
357
- function modelCatalogCachePath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
358
- const path = platform === "win32" ? win32 : posix;
359
- const configuredHome = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim();
360
- return path.join(configuredHome || fallbackHome, ".zcode", "cli", "model-catalog.json");
361
- }
362
- function resolveModelCatalogEndpoint(baseUrl, env = process.env, platform = process.platform, arch = process.arch) {
363
- const url = new URL(baseUrl);
364
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error("Model catalog endpoint must use HTTP or HTTPS.");
365
- url.pathname = `${url.pathname.replace(/\/+$/u, "")}${MODEL_CATALOG_URL_PATH}`;
366
- url.hash = "";
367
- url.searchParams.set("platform", `${platform}-${arch}`);
368
- const appVersion = env.ZCODE_APP_CLI_VERSION?.trim() || "";
369
- if (appVersion) url.searchParams.set("app_version", appVersion);
370
- return url.toString();
371
- }
372
- function catalogEndpoint(options) {
373
- const env = options.env ?? process.env;
374
- return resolveModelCatalogEndpoint(options.baseUrl, {
375
- ...env,
376
- ZCODE_APP_CLI_VERSION: env.ZCODE_APP_CLI_VERSION?.trim() || options.currentVersion
377
- });
378
- }
379
- function toModelId(value) {
380
- return value.trim().toLowerCase();
381
- }
382
- function isRecord$2(value) {
383
- return typeof value === "object" && value !== null && !Array.isArray(value);
384
- }
385
- function modelId(value) {
386
- return typeof value === "string" && /^[a-z0-9][a-z0-9._-]*$/iu.test(value.trim());
387
- }
388
- function positiveInteger$1(value) {
389
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
390
- }
391
- function parseModalities(value) {
392
- if (!Array.isArray(value)) return void 0;
393
- const valid = value.filter((item) => typeof item === "string" && MODALITIES.has(item));
394
- return valid.length > 0 || value.length === 0 ? [...new Set(valid)] : void 0;
395
- }
396
- function parseCatalog(data) {
397
- if (!isRecord$2(data)) return {};
398
- const builtinModels = [];
399
- const builtinProviders = [];
400
- const candidates = Array.isArray(data.builtinModels) ? [...data.builtinModels] : [];
401
- for (const provider of Array.isArray(data.providers) ? data.providers : []) {
402
- if (!isRecord$2(provider) || provider.schema !== "anthropic" || !Array.isArray(provider.models)) continue;
403
- const family = provider.id === "z-ai" ? "zai" : provider.id === "bigmodel" ? "bigmodel" : void 0;
404
- if (!family || typeof provider.baseUrl !== "string" || provider.baseUrl.trim().replace(/\/+$/u, "") !== PROVIDER_BASE_URLS[family]) continue;
405
- candidates.push(...provider.models);
406
- builtinProviders.push({
407
- id: `builtin:${family}-coding-plan`,
408
- schema: "anthropic",
409
- models: provider.models.flatMap((model) => isRecord$2(model) && modelId(model.modelId) ? [model.modelId] : [])
410
- });
411
- }
412
- const seen = /* @__PURE__ */ new Set();
413
- for (const value of candidates) {
414
- if (!isRecord$2(value) || !modelId(value.modelId)) continue;
415
- const id = toModelId(value.modelId);
416
- if (seen.has(id)) continue;
417
- seen.add(id);
418
- const model = {
419
- modelId: value.modelId.trim(),
420
- name: typeof value.name === "string" && value.name.trim() ? value.name.trim() : value.modelId.trim()
421
- };
422
- if (positiveInteger$1(value.contextWindow)) model.contextWindow = value.contextWindow;
423
- if (positiveInteger$1(value.maxCompletionTokens)) model.maxCompletionTokens = value.maxCompletionTokens;
424
- if (isRecord$2(value.modalities)) {
425
- const input = parseModalities(value.modalities.input);
426
- const output = parseModalities(value.modalities.output);
427
- if (input || output) model.modalities = {
428
- ...input ? { input } : {},
429
- ...output ? { output } : {}
430
- };
431
- }
432
- if (isRecord$2(value.reasoning) && isRecord$2(value.reasoning.levels)) model.reasoning = {
433
- levels: value.reasoning.levels,
434
- ...typeof value.reasoning.defaultLevel === "string" ? { defaultLevel: value.reasoning.defaultLevel } : {}
435
- };
436
- builtinModels.push(model);
437
- }
438
- for (const value of Array.isArray(data.builtinProviders) ? data.builtinProviders : []) {
439
- if (!isRecord$2(value) || typeof value.id !== "string" || !Array.isArray(value.models)) continue;
440
- builtinProviders.push({
441
- id: value.id,
442
- ...typeof value.schema === "string" ? { schema: value.schema } : {},
443
- models: value.models.filter(modelId).map((id) => id.trim())
444
- });
445
- }
446
- return {
447
- builtinModels,
448
- builtinProviders
449
- };
450
- }
451
- function usableCatalog(catalog) {
452
- const ids = new Set(catalog.builtinModels?.map((model) => toModelId(model.modelId)));
453
- return catalog.builtinProviders?.some((provider) => providerFamilyForBuiltinId(provider.id) !== void 0 && (provider.schema === void 0 || provider.schema === "anthropic") && provider.models.some((id) => ids.has(toModelId(id)))) ?? false;
454
- }
455
- function completeModelList(value) {
456
- return Array.isArray(value) && value.every((model) => isRecord$2(model) && modelId(model.modelId));
457
- }
458
- function completeBuiltinLists(value) {
459
- return completeModelList(value.builtinModels) && Array.isArray(value.builtinProviders) && value.builtinProviders.every((provider) => isRecord$2(provider) && typeof provider.id === "string" && Array.isArray(provider.models) && provider.models.every(modelId));
460
- }
461
- async function readCatalogCache(cachePath, endpoint) {
462
- try {
463
- const value = JSON.parse(await readFile(cachePath, "utf8"));
464
- if (!isRecord$2(value) || value.endpoint !== endpoint) return void 0;
465
- const lastFetchedAt = typeof value.lastFetchedAt === "string" ? value.lastFetchedAt : void 0;
466
- if (!lastFetchedAt || !Number.isFinite(Date.parse(lastFetchedAt))) return void 0;
467
- const catalog = parseCatalog(value);
468
- if (!usableCatalog(catalog)) return void 0;
469
- return {
470
- endpoint,
471
- lastFetchedAt,
472
- retirementSafe: value.retirementSafe === true && completeBuiltinLists(value),
473
- builtinModels: catalog.builtinModels,
474
- builtinProviders: catalog.builtinProviders
475
- };
476
- } catch {
477
- return;
478
- }
479
- }
480
- async function writePrivateJson(path, value) {
481
- const directory = dirname(path);
482
- const temporaryPath = join(directory, `.model-catalog.${process.pid}.${randomUUID()}.tmp`);
483
- await mkdir(directory, {
484
- recursive: true,
485
- mode: 448
486
- });
487
- try {
488
- await writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, {
489
- encoding: "utf8",
490
- flag: "wx",
491
- mode: 384
492
- });
493
- await rename(temporaryPath, path);
494
- } finally {
495
- await rm(temporaryPath, { force: true }).catch(() => {});
496
- }
497
- }
498
- function parseRemoteClientConfigs(body) {
499
- if (!isRecord$2(body) || body.code !== 0) return {};
500
- const data = body.data;
501
- const catalog = parseCatalog(data);
502
- catalog.retirementSafe = isRecord$2(data) && completeBuiltinLists(data) && Array.isArray(data.providers) && data.providers.every((provider) => isRecord$2(provider) && typeof provider.id === "string" && typeof provider.schema === "string" && typeof provider.baseUrl === "string" && completeModelList(provider.models));
503
- return catalog;
504
- }
505
- async function fetchRemoteModelCatalog(options) {
506
- if (options.signal?.aborted) return {};
507
- const controller = new AbortController();
508
- const abort = () => controller.abort(options.signal?.reason);
509
- if (options.signal?.aborted) abort();
510
- else options.signal?.addEventListener("abort", abort, { once: true });
511
- const timeout = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Model catalog refresh timed out.")), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
361
+ const message = (providerId) => `Model access is not configured${providerId ? ` for ${providerId}` : ""}. Run /login or /setup in zcode, or configure its API key before sending a prompt. No model request was sent.`;
362
+ let root;
512
363
  try {
513
- const url = catalogEndpoint(options);
514
- const response = await (options.fetcher ?? ((requestUrl, init) => fetch(requestUrl, init)))(url, {
515
- headers: {
516
- accept: "application/json",
517
- "user-agent": `zcode-app-cli/${options.currentVersion}`
518
- },
519
- signal: controller.signal
520
- });
521
- if (!response.ok) return {};
522
- return parseRemoteClientConfigs(await response.json());
523
- } catch {
524
- return {};
525
- } finally {
526
- clearTimeout(timeout);
527
- options.signal?.removeEventListener("abort", abort);
528
- }
529
- }
530
- async function refreshModelCatalog(options) {
531
- const env = options.env ?? process.env;
532
- const cachePath = modelCatalogCachePath(env);
533
- const now = options.now ?? Date.now();
534
- if (modelCatalogRefreshDisabled(env) || options.signal?.aborted) return {
535
- cachePath,
536
- refreshed: false,
537
- catalog: null
538
- };
539
- let endpoint;
540
- try {
541
- endpoint = catalogEndpoint(options);
542
- } catch {
543
- return {
544
- cachePath,
545
- refreshed: false,
546
- catalog: null
547
- };
364
+ root = record$4(JSON.parse(await readFile(providerConfigPath(env), "utf8")));
365
+ } catch (error) {
366
+ return error.code === "ENOENT" && !options.model ? message() : void 0;
548
367
  }
549
- const cached = await readCatalogCache(cachePath, endpoint);
550
- const existing = cached && Date.parse(cached.lastFetchedAt) <= now ? cached : void 0;
551
- const age = existing ? now - Date.parse(existing.lastFetchedAt) : Infinity;
552
- if (existing && age >= 0 && age < 216e5) return {
553
- cachePath,
554
- refreshed: false,
555
- catalog: existing
556
- };
557
- const remote = await fetchRemoteModelCatalog(options);
558
- if (options.signal?.aborted) return {
559
- cachePath,
560
- refreshed: false,
561
- catalog: null
562
- };
563
- if (!usableCatalog(remote)) return {
564
- cachePath,
565
- refreshed: false,
566
- catalog: existing ?? null
567
- };
568
- const cache = {
569
- endpoint,
570
- retirementSafe: remote.retirementSafe === true,
571
- lastFetchedAt: new Date(now).toISOString(),
572
- builtinModels: remote.builtinModels ?? [],
573
- builtinProviders: remote.builtinProviders ?? []
574
- };
575
- await writePrivateJson(cachePath, cache).catch(() => {});
576
- return {
577
- cachePath,
578
- refreshed: true,
579
- catalog: cache
580
- };
581
- }
582
- function providerFamilyForBuiltinId(builtinId) {
583
- if (builtinId === "builtin:zai-coding-plan") return "zai";
584
- if (builtinId === "builtin:bigmodel-coding-plan") return "bigmodel";
585
- }
586
- function buildReasoning(model) {
587
- const options = {};
588
- for (const [level, value] of Object.entries(model.reasoning?.levels ?? {})) {
589
- if (!modelId(level) || !isRecord$2(value) || !isRecord$2(value.anthropic)) continue;
590
- const operations = value.anthropic.set;
591
- if (!Array.isArray(operations) || operations.length !== 1 || value.anthropic.unset !== void 0) continue;
592
- const operation = operations[0];
593
- if (!isRecord$2(operation) || !Array.isArray(operation.path) || operation.path.length !== 2 || operation.path[0] !== "output_config" || operation.path[1] !== "effort" || typeof operation.value !== "string" || !EFFORTS.has(operation.value)) continue;
594
- options[level] = { anthropic: { effort: operation.value } };
595
- }
596
- const levels = Object.keys(options);
597
- if (!levels.length) return void 0;
598
- const defaultLevel = model.reasoning?.defaultLevel;
599
- return {
600
- enabled: true,
601
- levels,
602
- ...defaultLevel && levels.includes(defaultLevel) ? { defaultLevel } : {},
603
- providerOptionsByLevel: options
604
- };
605
- }
606
- function buildModelEntry(model) {
607
- const entry = { name: model.name };
608
- if (typeof model.contextWindow === "number") entry.limit = {
609
- context: model.contextWindow,
610
- ...typeof model.maxCompletionTokens === "number" ? { output: model.maxCompletionTokens } : {}
611
- };
612
- else if (typeof model.maxCompletionTokens === "number") entry.limit = { output: model.maxCompletionTokens };
613
- if (model.modalities && (model.modalities.input || model.modalities.output)) entry.modalities = {
614
- ...model.modalities.input ? { input: model.modalities.input } : {},
615
- ...model.modalities.output ? { output: model.modalities.output } : {}
616
- };
617
- const reasoning = buildReasoning(model);
618
- if (reasoning) entry.reasoning = reasoning;
619
- return entry;
620
- }
621
- function isOfficialProvider(provider, family) {
622
- if (provider.kind !== "anthropic" || !isRecord$2(provider.options)) return false;
623
- const baseURL = provider.options.baseURL;
624
- return typeof baseURL === "string" && baseURL.trim().replace(/\/+$/u, "") === PROVIDER_BASE_URLS[family];
625
- }
626
- function mergeModelEntry(entry, existing) {
627
- const merged = {
628
- ...entry,
629
- ...existing
630
- };
631
- for (const key of ["limit", "modalities"]) if (isRecord$2(entry[key]) && isRecord$2(existing[key])) merged[key] = {
632
- ...entry[key],
633
- ...existing[key]
634
- };
635
- return merged;
636
- }
637
- function catalogSource(endpoint) {
638
- if (!endpoint) return "";
639
- const url = new URL(endpoint);
640
- url.searchParams.delete("app_version");
641
- url.searchParams.delete("platform");
642
- return url.toString();
643
- }
644
- async function readManagedCatalog(path, endpoint) {
645
- try {
646
- const value = JSON.parse(await readFile(path, "utf8"));
647
- if (isRecord$2(value) && value.endpoint === endpoint && isRecord$2(value.models)) return {
648
- endpoint,
649
- models: Object.fromEntries(Object.entries(value.models).filter((entry) => isRecord$2(entry[1])))
650
- };
651
- } catch {}
652
- return {
653
- endpoint,
654
- models: {}
655
- };
656
- }
657
- async function applyRefreshedModelsToConfig(result, env = process.env, protectedModels = []) {
658
- const catalog = parseCatalog(result.catalog);
659
- if (!usableCatalog(catalog)) return;
660
- const age = Date.now() - Date.parse(result.catalog.lastFetchedAt);
661
- const retire = result.refreshed && result.catalog?.retirementSafe === true && age >= 0 && age < 216e5;
662
- const managedPath = join(dirname(modelCatalogCachePath(env)), "model-catalog-managed.json");
663
- const managed = await readManagedCatalog(managedPath, catalogSource(result.catalog?.endpoint ?? ""));
664
- const beforeManaged = JSON.stringify(managed);
665
- const modelsByFamily = /* @__PURE__ */ new Map();
666
- const incompleteFamilies = /* @__PURE__ */ new Set();
667
- const models = new Map(catalog.builtinModels.map((model) => [toModelId(model.modelId), model]));
668
- for (const provider of catalog.builtinProviders) {
669
- const family = providerFamilyForBuiltinId(provider.id);
670
- if (!family || provider.schema !== void 0 && provider.schema !== "anthropic") continue;
671
- const familyModels = modelsByFamily.get(family) ?? /* @__PURE__ */ new Map();
672
- if (!provider.models.length || provider.models.some((id) => !models.has(toModelId(id)))) {
673
- incompleteFamilies.add(family);
674
- continue;
675
- }
676
- for (const id of provider.models) {
677
- const model = models.get(toModelId(id));
678
- if (model) familyModels.set(toModelId(id), buildModelEntry(model));
679
- }
680
- modelsByFamily.set(family, familyModels);
681
- }
682
- await updateUserConfig((config) => {
683
- if (!isRecord$2(config.provider)) return;
684
- const providers = config.provider;
685
- const selected = new Set(protectedModels.map(toModelId));
686
- if (typeof config.model === "string") selected.add(toModelId(config.model));
687
- if (isRecord$2(config.model)) {
688
- for (const value of Object.values(config.model)) if (typeof value === "string") selected.add(toModelId(value));
689
- }
690
- const overrides = isRecord$2(config.modelCatalog) && isRecord$2(config.modelCatalog.overrides) ? config.modelCatalog.overrides : {};
691
- for (const [providerId, familyModels] of modelsByFamily) {
692
- const current = providers[providerId];
693
- if (!isRecord$2(current) || !isOfficialProvider(current, providerId)) continue;
694
- const currentModels = isRecord$2(current.models) ? current.models : {};
695
- const merged = { ...currentModels };
696
- const existingIds = new Map(Object.keys(currentModels).map((id) => [toModelId(id), id]));
697
- for (const [id, existing] of Object.entries(currentModels)) {
698
- const reference = `${providerId}/${id}`;
699
- if (retire && !incompleteFamilies.has(providerId) && !familyModels.has(toModelId(id)) && !selected.has(toModelId(reference)) && !Object.hasOwn(overrides, reference) && isDeepStrictEqual(existing, managed.models[reference])) {
700
- delete merged[id];
701
- delete managed.models[reference];
702
- }
703
- }
704
- for (const [modelId, entry] of familyModels) {
705
- const id = existingIds.get(modelId) ?? modelId;
706
- const existing = merged[id];
707
- if (Object.hasOwn(merged, id) && !isRecord$2(existing)) continue;
708
- const reference = `${providerId}/${id}`;
709
- const owned = !Object.hasOwn(merged, id) || isDeepStrictEqual(existing, managed.models[reference]);
710
- merged[id] = owned ? entry : mergeModelEntry(entry, existing);
711
- if (owned) managed.models[reference] = entry;
712
- }
713
- providers[providerId] = {
714
- ...current,
715
- models: merged
716
- };
717
- }
718
- config.provider = providers;
719
- }, env);
720
- if (JSON.stringify(managed) !== beforeManaged) await writePrivateJson(managedPath, managed);
368
+ const config = record$4(root?.config);
369
+ if (root?.schemaVersion !== 1 || !config) return void 0;
370
+ const selection = record$4(config.defaultModelSelection);
371
+ const model = options.model ?? (typeof selection?.providerId === "string" && typeof selection.modelId === "string" ? `${selection.providerId}/${selection.modelId}` : void 0);
372
+ if (!model) return await hasConfiguredProviderAccess(env) ? void 0 : message();
373
+ const separator = model.indexOf("/");
374
+ if (separator <= 0) return void 0;
375
+ const providerId = model.slice(0, separator), modelId = model.slice(separator + 1);
376
+ if (providerId.startsWith("account:")) return void 0;
377
+ const rules = record$4(config.providerConfigRules)?.providerRules;
378
+ if (!Array.isArray(rules)) return void 0;
379
+ const settings = record$4(rules.map(record$4).find((rule) => rule?.providerId === providerId)?.config), auth = record$4(settings?.access), api = record$4(settings?.api);
380
+ if (!settings || !["api-key", "zhipu-coding-plan-api-key"].includes(String(auth?.type)) || typeof auth?.apiKey === "string" && auth.apiKey.trim() || auth?.apiKey !== void 0 && typeof auth.apiKey !== "string" || Object.keys(record$4(api?.headers) ?? {}).length > 0 || Array.isArray(settings.personalModelIds) && !settings.personalModelIds.includes(modelId)) return void 0;
381
+ return message(providerId);
721
382
  }
722
- /** Download in the background; sync only at a model-selection boundary. */
723
- var ModelCatalogRefresh = class {
724
- options;
725
- controller = new AbortController();
726
- pending;
727
- result;
728
- nextRefreshAt = 0;
729
- timer;
730
- constructor(options) {
731
- this.options = options;
732
- }
733
- start() {
734
- if (this.controller.signal.aborted || this.pending || Date.now() < this.nextRefreshAt || modelCatalogRefreshDisabled(this.options.env)) return;
735
- clearTimeout(this.timer);
736
- this.pending = refreshModelCatalog({
737
- ...this.options,
738
- signal: this.controller.signal
739
- }).then((result) => {
740
- if (!this.controller.signal.aborted) {
741
- if (result.catalog) this.result = result;
742
- else if (this.result) this.result = {
743
- ...this.result,
744
- refreshed: false
745
- };
746
- }
747
- this.nextRefreshAt = result.catalog ? Math.max(Date.now() + 6e4, Date.parse(result.catalog.lastFetchedAt) + MODEL_CATALOG_REFRESH_TTL_MS) : Date.now() + 6e4;
748
- }).catch(() => {
749
- if (this.result) this.result = {
750
- ...this.result,
751
- refreshed: false
752
- };
753
- this.nextRefreshAt = Date.now() + 6e4;
754
- }).finally(() => {
755
- this.pending = void 0;
756
- if (!this.controller.signal.aborted) {
757
- this.timer = setTimeout(() => this.start(), Math.max(1, this.nextRefreshAt - Date.now()));
758
- this.timer.unref?.();
759
- }
760
- });
761
- }
762
- async apply(protectedModels = []) {
763
- this.start();
764
- if (this.result && !this.controller.signal.aborted && !modelCatalogRefreshDisabled(this.options.env)) await applyRefreshedModelsToConfig(this.result, this.options.env, protectedModels);
765
- }
766
- stop() {
767
- clearTimeout(this.timer);
768
- this.controller.abort();
769
- }
770
- };
771
383
  //#endregion
772
384
  //#region packages/zcode-tui/src/prompt-preflight.ts
773
385
  /** Preserve rejected input without replacing a draft typed during validation. */
@@ -784,217 +396,6 @@ async function preflightSubmission(options) {
784
396
  return false;
785
397
  }
786
398
  //#endregion
787
- //#region src/desktop-migration.ts
788
- const desktopConfigDirectory = "v2";
789
- const knownFamilies = ["zai", "bigmodel"];
790
- function isRecord$1(value) {
791
- return typeof value === "object" && value !== null && !Array.isArray(value);
792
- }
793
- function desktopProviderFamilyScore(providerId, family) {
794
- if (providerId === `builtin:${family}-coding-plan`) return 4;
795
- if (providerId === family || providerId === `builtin:${family}`) return 3;
796
- if (providerId.endsWith(`:${family}`)) return 2;
797
- if (providerId.startsWith(`builtin:${family}-`)) return 1;
798
- }
799
- function desktopHome(env, platform, fallbackHome) {
800
- return (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim() || fallbackHome;
801
- }
802
- function desktopConfigPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
803
- return (platform === "win32" ? win32 : posix).join(desktopHome(env, platform, fallbackHome), ".zcode", desktopConfigDirectory, "config.json");
804
- }
805
- function desktopSettingPath(env, platform, fallbackHome) {
806
- return (platform === "win32" ? win32 : posix).join(desktopHome(env, platform, fallbackHome), ".zcode", desktopConfigDirectory, "setting.json");
807
- }
808
- async function fileExists(path) {
809
- try {
810
- return (await stat(path)).isFile();
811
- } catch {
812
- return false;
813
- }
814
- }
815
- async function readJsonObject(path) {
816
- const value = JSON.parse(await readFile(path, "utf8"));
817
- if (!isRecord$1(value)) throw new Error("the root value must be a JSON object");
818
- return value;
819
- }
820
- function desktopModels(provider) {
821
- const models = [];
822
- for (const [id, raw] of Object.entries(provider.models ?? {})) {
823
- if (typeof id !== "string" || id.length === 0) continue;
824
- const detail = isRecord$1(raw) && typeof raw.name === "string" && raw.name.length > 0 ? raw.name : id;
825
- models.push({
826
- id,
827
- name: detail
828
- });
829
- }
830
- return models;
831
- }
832
- function readSelectedFamily(setting) {
833
- if (!setting) return void 0;
834
- const selected = setting.modelProviderFamilySelectedKeys;
835
- if (!isRecord$1(selected)) return void 0;
836
- const domain = setting.providerFamilyDomain;
837
- if (typeof domain === "string" && knownFamilies.includes(domain)) return domain;
838
- for (const family of knownFamilies) {
839
- const value = selected[family];
840
- if (typeof value === "string" && value.length > 0) return family;
841
- }
842
- }
843
- function baseURLFromOptions(options) {
844
- if (!isRecord$1(options)) return void 0;
845
- const baseURL = options.baseURL;
846
- return typeof baseURL === "string" && baseURL.trim().length > 0 ? baseURL.trim() : void 0;
847
- }
848
- function buildMigrationPlan(desktopConfig, setting) {
849
- const providers = desktopConfig.provider ?? {};
850
- const families = /* @__PURE__ */ new Map();
851
- for (const [providerId, provider] of Object.entries(providers)) {
852
- if (!isRecord$1(provider)) continue;
853
- let bestFamily;
854
- let bestScore = 0;
855
- for (const family of knownFamilies) {
856
- const score = desktopProviderFamilyScore(providerId, family);
857
- if (score !== void 0 && score > bestScore) {
858
- bestFamily = family;
859
- bestScore = score;
860
- }
861
- }
862
- if (!bestFamily) continue;
863
- const models = desktopModels(provider);
864
- if (models.length === 0) continue;
865
- const existing = families.get(bestFamily);
866
- if (existing && existing.score >= bestScore) continue;
867
- const name = typeof provider.name === "string" && provider.name.length > 0 ? provider.name : `${bestFamily} coding plan`;
868
- families.set(bestFamily, {
869
- score: bestScore,
870
- plan: {
871
- family: bestFamily,
872
- providerName: name,
873
- models,
874
- baseURL: baseURLFromOptions(provider.options)
875
- }
876
- });
877
- }
878
- const ordered = [];
879
- for (const family of knownFamilies) {
880
- const entry = families.get(family);
881
- if (entry) ordered.push(entry.plan);
882
- }
883
- return {
884
- families: ordered,
885
- defaultFamily: readSelectedFamily(setting)
886
- };
887
- }
888
- async function detectDesktopInstallation(env = process.env, platform = process.platform, fallbackHome = homedir()) {
889
- const configPath = desktopConfigPath(env, platform, fallbackHome);
890
- if (!await fileExists(configPath)) return null;
891
- let desktopConfig;
892
- let setting;
893
- try {
894
- desktopConfig = await readJsonObject(configPath);
895
- } catch {
896
- return null;
897
- }
898
- const settingPath = desktopSettingPath(env, platform, fallbackHome);
899
- if (await fileExists(settingPath)) try {
900
- setting = await readJsonObject(settingPath);
901
- } catch {
902
- setting = void 0;
903
- }
904
- const plan = buildMigrationPlan(desktopConfig, setting);
905
- if (plan.families.length === 0) return null;
906
- return {
907
- configPath,
908
- plan
909
- };
910
- }
911
- function mergeModels(current, migrated) {
912
- const merged = { ...current };
913
- for (const model of migrated) {
914
- const existing = isRecord$1(merged[model.id]) ? merged[model.id] : void 0;
915
- merged[model.id] = isRecord$1(existing) ? {
916
- ...existing,
917
- name: model.name
918
- } : { name: model.name };
919
- }
920
- return merged;
921
- }
922
- function normalizeModelId(id) {
923
- return id.trim().toLowerCase();
924
- }
925
- function modelIdInCandidates(candidateIds, preferredId) {
926
- if (!preferredId) return void 0;
927
- const normalized = preferredId.trim();
928
- if (normalized.length === 0) return void 0;
929
- if (candidateIds.includes(normalized)) return normalized;
930
- const preferredKey = normalizeModelId(normalized);
931
- return candidateIds.find((id) => normalizeModelId(id) === preferredKey);
932
- }
933
- function preferredOrFirstModel(candidateIds, preferredId, fallbackIds) {
934
- const preferred = modelIdInCandidates(candidateIds, preferredId);
935
- if (preferred) return preferred;
936
- for (const fallbackId of fallbackIds) {
937
- const fallback = modelIdInCandidates(candidateIds, fallbackId);
938
- if (fallback) return fallback;
939
- }
940
- return candidateIds[0];
941
- }
942
- function selectMainModel(family, candidateIds, previousMain) {
943
- return `${family}/${preferredOrFirstModel(candidateIds, previousMain?.split("/")[1] ?? previousMain, ["glm-5.2", "glm-5.3"])}`;
944
- }
945
- function selectLiteModel(family, candidateIds, mainModel, previousLite) {
946
- return `${family}/${modelIdInCandidates(candidateIds, previousLite?.split("/")[1] ?? previousLite) ?? modelIdInCandidates(candidateIds, "glm-5-turbo") ?? mainModel.split("/")[1]}`;
947
- }
948
- async function applyDesktopMigration(plan, options = {}) {
949
- const env = options.env ?? process.env;
950
- const family = options.family ?? plan.defaultFamily ?? plan.families[0]?.family;
951
- if (!family) throw new Error("No desktop provider families are available to migrate.");
952
- const familyPlanEntry = plan.families.find((entry) => entry.family === family);
953
- if (!familyPlanEntry) throw new Error(`Desktop settings contain no migratable ${family} provider.`);
954
- const configPath = userConfigPath(env);
955
- const previous = JSON.parse(await readFile(configPath, "utf8"));
956
- const previousModel = isRecord$1(previous.model) ? previous.model : {};
957
- const previousMain = typeof previousModel.main === "string" ? previousModel.main : void 0;
958
- const previousLite = typeof previousModel.lite === "string" ? previousModel.lite : void 0;
959
- const backupPath = `${configPath}.pre-migration.bak`;
960
- try {
961
- await copyFile(configPath, backupPath);
962
- } catch (error) {
963
- throw new Error(`Unable to back up ${configPath} to ${basename(backupPath)} before importing desktop settings: ` + (error instanceof Error ? error.message : String(error)), { cause: error });
964
- }
965
- await updateUserConfig((config) => {
966
- const providers = isRecord$1(config.provider) ? config.provider : {};
967
- const current = isRecord$1(providers[family]) ? providers[family] : {};
968
- const currentOptions = isRecord$1(current.options) ? current.options : {};
969
- const currentApiKey = typeof currentOptions.apiKey === "string" && currentOptions.apiKey.trim() ? currentOptions.apiKey : void 0;
970
- providers[family] = {
971
- ...current,
972
- kind: "anthropic",
973
- name: familyPlanEntry.providerName,
974
- options: {
975
- ...currentOptions,
976
- apiKeyRequired: true,
977
- ...familyPlanEntry.baseURL ? { baseURL: familyPlanEntry.baseURL } : {},
978
- ...currentApiKey ? { apiKey: currentApiKey } : {}
979
- },
980
- models: mergeModels(isRecord$1(current.models) ? current.models : void 0, familyPlanEntry.models)
981
- };
982
- config.provider = providers;
983
- const migratedProvider = providers[family];
984
- const mergedModelIds = Object.keys(isRecord$1(migratedProvider.models) ? migratedProvider.models : {});
985
- const main = selectMainModel(family, mergedModelIds, previousMain);
986
- config.model = {
987
- ...isRecord$1(config.model) ? config.model : {},
988
- main,
989
- lite: selectLiteModel(family, mergedModelIds, main, previousLite)
990
- };
991
- }, env);
992
- return {
993
- configPath,
994
- backupPath
995
- };
996
- }
997
- //#endregion
998
399
  //#region scripts/release-version.ts
999
400
  const releaseVersionPattern = /^(\d+\.\d+\.\d+)-([1-9]\d*)$/u;
1000
401
  function parseReleaseVersion(version) {
@@ -1033,7 +434,7 @@ function updateCheckDisabled(env = process.env) {
1033
434
  }
1034
435
  function updateCachePath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
1035
436
  const path = platform === "win32" ? win32 : posix;
1036
- return path.join(path.dirname(userConfigPath(env, platform, fallbackHome)), "version.json");
437
+ return path.join(path.dirname(cliSettingsPath(env, platform, fallbackHome)), "version.json");
1037
438
  }
1038
439
  function parseUpdateCache(value) {
1039
440
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -158688,7 +158089,7 @@ function responseText(value) {
158688
158089
  if (!isRecord(value)) return void 0;
158689
158090
  return asString(value.response) ?? asString(value.message) ?? asString(value.text);
158690
158091
  }
158691
- function modelLabel$1(value) {
158092
+ function modelLabel(value) {
158692
158093
  if (typeof value === "string") return value;
158693
158094
  if (!isRecord(value)) return "default";
158694
158095
  const model = asString(value.modelId) ?? asString(value.id) ?? asString(value.name);
@@ -158875,6 +158276,10 @@ function restoredMessages(value) {
158875
158276
  const rawRole = asString(item.role) ?? (info && asString(info.role));
158876
158277
  const role = rawRole === "user" ? "user" : rawRole === "assistant" || rawRole === "agent" ? "assistant" : "system";
158877
158278
  const direct = asString(item.text) ?? asString(item.content);
158279
+ const model = modelReference(item.model) ?? modelReference({
158280
+ providerId: item.providerId ?? item.providerID ?? (info && (info.providerId ?? info.providerID)),
158281
+ modelId: item.modelId ?? item.modelID ?? (info && (info.modelId ?? info.modelID))
158282
+ });
158878
158283
  const structured = Array.isArray(item.parts) ? item.parts.map(normalizeRestoredPart).filter((part) => Boolean(part)) : [];
158879
158284
  const hasTextPart = structured.some((part) => part.type === "text");
158880
158285
  const parts = direct && !hasTextPart ? [{
@@ -158883,6 +158288,7 @@ function restoredMessages(value) {
158883
158288
  }, ...structured] : structured;
158884
158289
  if (parts.length > 0) messages.push({
158885
158290
  messageId: asString(item.messageId) ?? asString(item.messageID) ?? (info && (asString(info.messageId) ?? asString(info.id))),
158291
+ ...model ? { model } : {},
158886
158292
  role,
158887
158293
  parts
158888
158294
  });
@@ -158982,6 +158388,29 @@ function buildExitSummary(options) {
158982
158388
  };
158983
158389
  }
158984
158390
  //#endregion
158391
+ //#region packages/zcode-tui/src/plan-editor.ts
158392
+ /** Decorate the existing border without changing editor rows or cursor coordinates. */
158393
+ var PlanEditor = class extends Editor {
158394
+ planEnabled = false;
158395
+ planColor = (text) => text;
158396
+ planHint = "Research and plan before making changes";
158397
+ hintColor = (text) => text;
158398
+ render(width) {
158399
+ const lines = super.render(width);
158400
+ if (!this.planEnabled || width < 4 || !lines[0]) return lines;
158401
+ const label = width >= 10 ? " Plan ──" : "Plan";
158402
+ const prefixWidth = width - visibleWidth(label);
158403
+ const prefix = truncateToWidth(lines[0], prefixWidth, "");
158404
+ lines[0] = prefix + this.borderColor("─".repeat(Math.max(0, prefixWidth - visibleWidth(prefix)))) + this.planColor(label);
158405
+ if (!this.getText() && lines[1] && width > 2) {
158406
+ const cursor = truncateToWidth(lines[1], 2, "");
158407
+ const hint = truncateToWidth(this.planHint, width - 2, "");
158408
+ lines[1] = cursor + this.hintColor(hint) + " ".repeat(Math.max(0, width - 2 - visibleWidth(hint)));
158409
+ }
158410
+ return lines;
158411
+ }
158412
+ };
158413
+ //#endregion
158985
158414
  //#region packages/zcode-tui/src/footer-bar.ts
158986
158415
  const horizontalPadding = 1;
158987
158416
  const sectionGap = 2;
@@ -159351,7 +158780,9 @@ var StatusDetailView = class {
159351
158780
  ["CLI version", this.data.cliVersion],
159352
158781
  ["Runtime version", this.data.version],
159353
158782
  ["Model", this.data.model],
159354
- ["Mode", [this.data.mode, this.data.effort].filter(Boolean).join(" · ")],
158783
+ ["Mode", this.data.mode],
158784
+ ["Plan", this.data.planEnabled ? "on" : "off"],
158785
+ ["Reasoning effort", this.data.effort],
159355
158786
  ["Workspace", this.data.workspace],
159356
158787
  ["Git branch", this.data.branch],
159357
158788
  ["Session", projection?.sessionId],
@@ -162141,10 +161572,41 @@ var AppServerRequestError = class extends Error {
162141
161572
  this.name = "AppServerRequestError";
162142
161573
  }
162143
161574
  };
162144
- function cancellationError() {
162145
- const error = /* @__PURE__ */ new Error("App-server request cancelled.");
162146
- error.name = "AbortError";
162147
- return error;
161575
+ var AppServerProcessError = class extends Error {
161576
+ exitCode;
161577
+ constructor(message, exitCode) {
161578
+ super(message);
161579
+ this.exitCode = exitCode;
161580
+ this.name = "AppServerProcessError";
161581
+ }
161582
+ };
161583
+ var AppServerCancellationError = class extends Error {
161584
+ exitCode;
161585
+ constructor(exitCode) {
161586
+ super("App-server request cancelled.");
161587
+ this.exitCode = exitCode;
161588
+ this.name = "AbortError";
161589
+ }
161590
+ };
161591
+ function signalExitCode$1(signal) {
161592
+ if (!signal) return 1;
161593
+ const number = constants$1.signals[signal];
161594
+ return typeof number === "number" ? 128 + number : 1;
161595
+ }
161596
+ function abortSignalName(signal) {
161597
+ const reason = signal?.reason;
161598
+ return reason === "SIGINT" || reason === "SIGTERM" || reason === "SIGHUP" ? reason : void 0;
161599
+ }
161600
+ function cancellationError(signal) {
161601
+ const signalName = abortSignalName(signal);
161602
+ if (signalName) return new AppServerCancellationError(signalExitCode$1(signalName));
161603
+ return new AppServerCancellationError(130);
161604
+ }
161605
+ function terminationSignal(signal) {
161606
+ return abortSignalName(signal) ?? "SIGTERM";
161607
+ }
161608
+ function processError(message, code) {
161609
+ return new AppServerProcessError(message, code);
162148
161610
  }
162149
161611
  async function readBounded(stream, onOverflow) {
162150
161612
  if (!stream) return "";
@@ -162174,7 +161636,7 @@ function responseEnvelope(stdout) {
162174
161636
  }
162175
161637
  }
162176
161638
  async function requestAppServer(request) {
162177
- if (request.signal?.aborted) throw cancellationError();
161639
+ if (request.signal?.aborted) throw cancellationError(request.signal);
162178
161640
  const child = spawn(request.transport.command, request.transport.args, {
162179
161641
  cwd: request.transport.cwd,
162180
161642
  env: request.transport.env,
@@ -162199,7 +161661,7 @@ async function requestAppServer(request) {
162199
161661
  launchError = error;
162200
161662
  finish(1);
162201
161663
  });
162202
- child.once("close", (code) => finish(code ?? 1));
161664
+ child.once("close", (code, signal) => finish(code ?? signalExitCode$1(signal)));
162203
161665
  });
162204
161666
  const terminateForOverflow = () => {
162205
161667
  overflow = true;
@@ -162207,7 +161669,7 @@ async function requestAppServer(request) {
162207
161669
  };
162208
161670
  const onAbort = () => {
162209
161671
  if (child.exitCode !== null || child.signalCode !== null) return;
162210
- child.kill("SIGTERM");
161672
+ child.kill(terminationSignal(request.signal));
162211
161673
  forceTerminationTimer = setTimeout(() => {
162212
161674
  if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
162213
161675
  }, forceTerminationDelayMilliseconds);
@@ -162227,12 +161689,12 @@ async function requestAppServer(request) {
162227
161689
  readBounded(child.stdout, terminateForOverflow),
162228
161690
  readBounded(child.stderr, terminateForOverflow)
162229
161691
  ]);
162230
- if (request.signal?.aborted) throw cancellationError();
161692
+ if (request.signal?.aborted) throw cancellationError(request.signal);
162231
161693
  if (overflow) throw new Error(`App-server output exceeded ${maximumOutputBytes} bytes.`);
162232
161694
  if (launchError) throw launchError;
162233
161695
  const envelope = responseEnvelope(stdout);
162234
161696
  if (envelope?.error) throw new AppServerRequestError(envelope.error.message?.trim() || "App-server request failed.", envelope.error.code, envelope.error.data);
162235
- if (code !== 0) throw new Error(stderr.trim() || `App-server exited with status ${code}.`);
161697
+ if (code !== 0) throw processError(stderr.trim() || `App-server exited with status ${code}.`, code);
162236
161698
  if (!envelope || !("result" in envelope)) throw new Error(stderr.trim() || "App-server did not return a response envelope.");
162237
161699
  return envelope.result;
162238
161700
  } finally {
@@ -162563,13 +162025,13 @@ function notificationSettings(env = process.env, config) {
162563
162025
  };
162564
162026
  }
162565
162027
  async function readNotificationSettings(env = process.env) {
162566
- return notificationSettings(env, await readUserConfig(env));
162028
+ return notificationSettings(env, await readCliSettings(env));
162567
162029
  }
162568
162030
  async function readStoredNotificationSettings(env = process.env) {
162569
- return notificationSettings({}, await readUserConfig(env));
162031
+ return notificationSettings({}, await readCliSettings(env));
162570
162032
  }
162571
162033
  async function writeNotificationSettings(settings, env = process.env) {
162572
- return await updateUserConfig((config) => {
162034
+ return await updateCliSettings((config) => {
162573
162035
  const ui = record$2(config.ui) ?? {};
162574
162036
  ui.notifications = { ...settings };
162575
162037
  config.ui = ui;
@@ -162838,10 +162300,10 @@ function resolveTuiMode(env = process.env, config) {
162838
162300
  return tuiMode(env.ZCODE_TUI_MODE) ?? tuiMode(configuredTuiMode(config)) ?? "regular";
162839
162301
  }
162840
162302
  async function readTuiMode(env = process.env) {
162841
- return resolveTuiMode(env, await readUserConfig(env));
162303
+ return resolveTuiMode(env, await readCliSettings(env));
162842
162304
  }
162843
162305
  async function writeTuiMode(mode, env = process.env) {
162844
- return await updateUserConfig((config) => {
162306
+ return await updateCliSettings((config) => {
162845
162307
  const ui = record$1(config.ui) ?? {};
162846
162308
  ui.tuiMode = mode;
162847
162309
  config.ui = ui;
@@ -162857,16 +162319,51 @@ function configuredCopyOnSelect(config) {
162857
162319
  return typeof value === "boolean" ? value : void 0;
162858
162320
  }
162859
162321
  async function readCopyOnSelect(env = process.env) {
162860
- return configuredCopyOnSelect(await readUserConfig(env)) ?? true;
162322
+ return configuredCopyOnSelect(await readCliSettings(env)) ?? true;
162861
162323
  }
162862
162324
  async function writeCopyOnSelect(enabled, env = process.env) {
162863
- return await updateUserConfig((config) => {
162325
+ return await updateCliSettings((config) => {
162864
162326
  const ui = record(config.ui) ?? {};
162865
162327
  ui.copyOnSelect = enabled;
162866
162328
  config.ui = ui;
162867
162329
  }, env);
162868
162330
  }
162869
162331
  //#endregion
162332
+ //#region packages/zcode-tui/src/session-title.ts
162333
+ const SESSION_TITLE_PREFIX = "ZC | ";
162334
+ const sessionTitleSpinnerFrames = [
162335
+ "⠋",
162336
+ "⠙",
162337
+ "⠹",
162338
+ "⠸",
162339
+ "⠼",
162340
+ "⠴",
162341
+ "⠦",
162342
+ "⠧",
162343
+ "⠇",
162344
+ "⠏"
162345
+ ];
162346
+ function sessionTitleSpinnerFrame(elapsedMilliseconds, animated = true) {
162347
+ if (!animated) return sessionTitleSpinnerFrames[0];
162348
+ const frame = Math.floor(Math.max(0, elapsedMilliseconds) / 120);
162349
+ return sessionTitleSpinnerFrames[frame % sessionTitleSpinnerFrames.length] ?? sessionTitleSpinnerFrames[0];
162350
+ }
162351
+ function normalizeSessionTitle(title) {
162352
+ return sanitizeTerminalText(title).replace(/\s+/gu, " ").trim();
162353
+ }
162354
+ function sessionTitleFromFirstMessage(message) {
162355
+ const normalized = normalizeSessionTitle(message);
162356
+ if (!normalized) return null;
162357
+ const characters = Array.from(normalized);
162358
+ if (characters.length <= 50) return normalized;
162359
+ return `${characters.slice(0, 49).join("")}…`;
162360
+ }
162361
+ function emitSessionTerminalTitle(stream, title) {
162362
+ if (!stream?.isTTY) return;
162363
+ const safeTitle = normalizeSessionTitle(title);
162364
+ stream.write(safeTitle ? `\x1b]0;${SESSION_TITLE_PREFIX}${safeTitle}\x07` : "\x1B]0;\x07");
162365
+ }
162366
+ //#endregion
162870
162367
  //#region packages/zcode-tui/src/selectors.ts
162871
162368
  function pickerRequest(input, commands) {
162872
162369
  const match = /^\/([^\s]+)(?:\s+(.*))?$/u.exec(input.trim());
@@ -162884,12 +162381,15 @@ function modePicker(currentMode, availableModes) {
162884
162381
  const items = (availableModes?.length ? availableModes : [
162885
162382
  "build",
162886
162383
  "edit",
162887
- "yolo",
162888
- "plan"
162889
- ]).map((mode) => ({
162384
+ "yolo"
162385
+ ]).filter((mode) => [
162386
+ "build",
162387
+ "edit",
162388
+ "yolo"
162389
+ ].includes(mode)).map((mode) => ({
162890
162390
  value: mode,
162891
162391
  label: mode.charAt(0).toUpperCase() + mode.slice(1),
162892
- description: mode === currentMode ? "current" : void 0,
162392
+ description: [mode === "build" ? "Ask before changes" : mode === "edit" ? "Edit automatically" : "Full access", mode === currentMode ? "current" : void 0].filter(Boolean).join(" · "),
162893
162393
  command: `/mode ${mode}`
162894
162394
  }));
162895
162395
  const currentIndex = items.findIndex((item) => item.value === currentMode);
@@ -162907,7 +162407,7 @@ function modePicker(currentMode, availableModes) {
162907
162407
  function explicitModelRequest(input) {
162908
162408
  const argument = /^\/model\s+(\S+)$/iu.exec(input.trim())?.[1];
162909
162409
  if (!argument || argument.toLowerCase() === "list") return void 0;
162910
- if (/^(?:main|lite|sonnet|opus|haiku)$/iu.test(argument)) return argument;
162410
+ if (argument.toLowerCase() === "main") return "main";
162911
162411
  const separator = argument.indexOf("/");
162912
162412
  if (separator <= 0 || separator === argument.length - 1) return void 0;
162913
162413
  return argument;
@@ -162915,116 +162415,37 @@ function explicitModelRequest(input) {
162915
162415
  function isEffortPickerRequest(input) {
162916
162416
  return pickerRequest(input, /* @__PURE__ */ new Set(["effort", "variant"]));
162917
162417
  }
162418
+ /**
162419
+ * Parse a `/rename <title>` request into the normalized title. Returns `""`
162420
+ * for an empty title and undefined for any other command or conversation text.
162421
+ */
162422
+ function sessionRenameRequest(input) {
162423
+ const match = /^\/rename(?:\s+([\s\S]+))?$/iu.exec(input.trim());
162424
+ if (!match) return void 0;
162425
+ return normalizeSessionTitle(match[1] ?? "");
162426
+ }
162918
162427
  function extractModelId(record, raw) {
162919
162428
  const direct = asString(record?.id);
162920
162429
  if (direct) return direct;
162921
- const modelId = asString(record?.modelId);
162430
+ const ref = isRecord(record?.ref) ? record.ref : record;
162431
+ const modelId = asString(ref?.modelId);
162922
162432
  if (modelId) {
162923
- const providerId = asString(record?.providerId);
162433
+ const providerId = asString(ref?.providerId);
162924
162434
  return providerId ? `${providerId}/${modelId}` : modelId;
162925
162435
  }
162926
162436
  return asString(raw);
162927
162437
  }
162928
- function parseModelRef(id) {
162929
- const separator = id.indexOf("/");
162930
- if (separator <= 0 || separator === id.length - 1) return void 0;
162931
- return {
162932
- providerId: id.slice(0, separator),
162933
- modelId: id.slice(separator + 1)
162934
- };
162935
- }
162936
- function extractModelOption(option) {
162937
- const record = isRecord(option) ? option : void 0;
162938
- const id = extractModelId(record, option);
162939
- if (!id) return void 0;
162940
- const parsed = parseModelRef(id);
162941
- if (!parsed) return void 0;
162942
- return {
162943
- id,
162944
- providerId: parsed.providerId,
162945
- modelId: parsed.modelId,
162946
- name: asString(record?.name) ?? asString(record?.label),
162947
- providerLabel: asString(record?.providerLabel) ?? asString(record?.providerName)
162948
- };
162949
- }
162950
- function modelLabel(option) {
162951
- return option.name && option.name !== option.modelId ? option.name : option.modelId;
162952
- }
162953
- function describeModel(option, currentModel) {
162954
- const details = [option.name && option.name !== option.modelId ? option.name : void 0, option.id === currentModel ? "current" : void 0].filter((value) => Boolean(value));
162955
- return details.length > 0 ? details.join(" · ") : void 0;
162956
- }
162957
- function providerLabel(option) {
162958
- return option.providerLabel ?? option.providerId;
162959
- }
162960
- /**
162961
- * Group the runtime's flat `modelOptions` list by provider, producing a
162962
- * three-level cascade: provider → main model → lite model.
162963
- *
162964
- * The runtime passes each option as `{ modelId, providerId, ... }` (from
162965
- * `listModels()`/`RXr`), but tests and some callers use `{ id, name }` — both
162966
- * forms are accepted.
162967
- */
162968
- function providerModelPicker(options, currentModel) {
162969
- const byProvider = /* @__PURE__ */ new Map();
162970
- const seen = /* @__PURE__ */ new Set();
162971
- for (const option of options) {
162972
- const parsed = extractModelOption(option);
162973
- if (!parsed) continue;
162974
- if (seen.has(parsed.id)) continue;
162975
- seen.add(parsed.id);
162976
- const group = byProvider.get(parsed.providerId) ?? [];
162977
- group.push(parsed);
162978
- byProvider.set(parsed.providerId, group);
162979
- }
162980
- if (byProvider.size === 0) return null;
162981
- const groups = [];
162982
- for (const [providerId, models] of byProvider) {
162983
- const label = providerLabel(models[0]);
162984
- const items = models.map((model) => ({
162985
- value: model.id,
162986
- label: modelLabel(model),
162987
- description: describeModel(model, currentModel),
162988
- command: `/model ${model.id}`
162989
- }));
162990
- const currentIndex = items.findIndex((item) => item.value === currentModel);
162991
- groups.push({
162992
- providerId,
162993
- label,
162994
- models: {
162995
- items,
162996
- selectedIndex: currentIndex >= 0 ? currentIndex : 0
162997
- }
162998
- });
162999
- }
163000
- const providerItems = groups.map((group) => {
163001
- const currentInGroup = group.models.items.some((item) => item.value === currentModel);
163002
- const currentModelId = group.models.items.find((item) => item.value === currentModel)?.label;
163003
- return {
163004
- value: group.providerId,
163005
- label: group.label,
163006
- description: [`${group.models.items.length} model${group.models.items.length === 1 ? "" : "s"}`, currentInGroup && currentModelId ? `current: ${currentModelId}` : void 0].filter((value) => Boolean(value)).join(" · "),
163007
- command: ""
163008
- };
163009
- });
163010
- return {
163011
- providers: {
163012
- items: providerItems,
163013
- selectedIndex: providerItems.findIndex((item) => groups[providerItems.indexOf(item)].models.items.some((m) => m.value === currentModel))
163014
- },
163015
- groups
163016
- };
163017
- }
163018
162438
  function modelPicker(options, currentModel) {
163019
162439
  const items = [];
163020
162440
  const seen = /* @__PURE__ */ new Set();
163021
162441
  for (const option of options) {
163022
162442
  const record = isRecord(option) ? option : void 0;
163023
- const id = asString(record?.id) ?? asString(option);
162443
+ const id = extractModelId(record, option);
163024
162444
  if (!id || seen.has(id)) continue;
163025
162445
  seen.add(id);
162446
+ const name = asString(record?.name) ?? asString(record?.label);
163026
162447
  const details = [
163027
- asString(record?.name) !== id ? asString(record?.name) : void 0,
162448
+ name !== id ? name : void 0,
163028
162449
  asString(record?.alias),
163029
162450
  id === currentModel ? "current" : void 0
163030
162451
  ].filter((value) => Boolean(value));
@@ -163687,6 +163108,7 @@ function normalizeRuntimeProjection(value) {
163687
163108
  sessionId: stringField(projection, "sessionId", "sessionID", "id"),
163688
163109
  status: stringField(projection, "status"),
163689
163110
  mode: stringField(projection, "mode"),
163111
+ planEnabled: typeof projection.planEnabled === "boolean" ? projection.planEnabled : void 0,
163690
163112
  turnCount: nonNegativeInteger(projection.turnCount),
163691
163113
  totalTokenCount: nonNegativeInteger(projection.totalTokenCount),
163692
163114
  currentTurnId: stringField(projection, "currentTurnId", "currentTurnID"),
@@ -163923,37 +163345,6 @@ function redactSecrets(message, secrets) {
163923
163345
  return secrets.reduce((redacted, secret) => secret ? redacted.replaceAll(secret, "[redacted]") : redacted, message);
163924
163346
  }
163925
163347
  //#endregion
163926
- //#region packages/zcode-tui/src/session-title.ts
163927
- const SESSION_TITLE_PREFIX = "ZC | ";
163928
- const sessionTitleSpinnerFrames = [
163929
- "⠋",
163930
- "⠙",
163931
- "⠹",
163932
- "⠸",
163933
- "⠼",
163934
- "⠴",
163935
- "⠦",
163936
- "⠧",
163937
- "⠇",
163938
- "⠏"
163939
- ];
163940
- function sessionTitleSpinnerFrame(elapsedMilliseconds, animated = true) {
163941
- if (!animated) return sessionTitleSpinnerFrames[0];
163942
- const frame = Math.floor(Math.max(0, elapsedMilliseconds) / 120);
163943
- return sessionTitleSpinnerFrames[frame % sessionTitleSpinnerFrames.length] ?? sessionTitleSpinnerFrames[0];
163944
- }
163945
- function sessionTitleFromFirstMessage(message) {
163946
- const normalized = sanitizeTerminalText(message).replace(/\s+/gu, " ").trim();
163947
- if (!normalized) return null;
163948
- const characters = Array.from(normalized);
163949
- if (characters.length <= 50) return normalized;
163950
- return `${characters.slice(0, 49).join("")}…`;
163951
- }
163952
- function emitSessionTerminalTitle(stream, title) {
163953
- if (!stream?.isTTY) return;
163954
- stream.write(title ? `\x1b]0;${SESSION_TITLE_PREFIX}${title}\x07` : "\x1B]0;\x07");
163955
- }
163956
- //#endregion
163957
163348
  //#region packages/zcode-tui/src/skills.ts
163958
163349
  const skillCacheMilliseconds = 2e3;
163959
163350
  const skillDescriptionLimit = 140;
@@ -164082,15 +163473,14 @@ function skillDescription(candidate) {
164082
163473
  const modes = [
164083
163474
  "build",
164084
163475
  "edit",
164085
- "yolo",
164086
- "plan"
163476
+ "yolo"
164087
163477
  ];
164088
163478
  function normalizedMode(mode, fallback = "build") {
164089
163479
  const candidate = mode;
164090
163480
  return modes.includes(candidate) ? candidate : fallback;
164091
163481
  }
164092
163482
  function nextMode(currentMode) {
164093
- const currentIndex = modes.indexOf(normalizedMode(currentMode));
163483
+ const currentIndex = modes.indexOf(currentMode);
164094
163484
  return modes[(currentIndex + 1) % modes.length] ?? modes[0];
164095
163485
  }
164096
163486
  function settingTargetForCommand(input) {
@@ -164148,6 +163538,12 @@ var StatusLine = class {
164148
163538
  if (!removable) break;
164149
163539
  fields.splice(removable.index, 1);
164150
163540
  }
163541
+ for (const field of fields) {
163542
+ const overflow = this.width(fields) - availableWidth;
163543
+ if (overflow <= 0) break;
163544
+ if (field.minWidth === void 0) continue;
163545
+ field.renderedText = truncateToWidth(field.renderedText, Math.max(field.minWidth, visibleWidth(field.renderedText) - overflow), "…");
163546
+ }
164151
163547
  return [` ${truncateToWidth(fields.map((field) => field.renderedText).join(this.separator), availableWidth, "…")}`];
164152
163548
  }
164153
163549
  invalidate() {}
@@ -166621,6 +166017,8 @@ var ZCodeTui = class {
166621
166017
  pendingAttachments = [];
166622
166018
  editorHistory = [];
166623
166019
  mode;
166020
+ planEnabled = false;
166021
+ executionStateRevision = 0;
166624
166022
  model;
166625
166023
  tuiMode;
166626
166024
  copyOnSelect = true;
@@ -166677,7 +166075,6 @@ var ZCodeTui = class {
166677
166075
  backgroundDrainScheduled = false;
166678
166076
  backgroundHandoffInterruptInFlight = false;
166679
166077
  updateCheckAbortController;
166680
- modelCatalogRefresh;
166681
166078
  loginRequired;
166682
166079
  removeStreamErrorGuards;
166683
166080
  constructor(options) {
@@ -166700,8 +166097,9 @@ var ZCodeTui = class {
166700
166097
  loginRequired: options.loginRequired === true,
166701
166098
  includeIdentity: true
166702
166099
  });
166703
- this.mode = normalizedMode(options.initialMode);
166704
- this.model = modelLabel$1(options.initialModel);
166100
+ this.mode = options.initialMode ?? "build";
166101
+ this.planEnabled = options.initialPlanEnabled ?? false;
166102
+ this.model = modelLabel(options.initialModel);
166705
166103
  this.thoughtLevel = options.initialThoughtLevel;
166706
166104
  this.modelOptions = [...options.modelOptions ?? []];
166707
166105
  this.effortOptions = [...options.effortOptions ?? []];
@@ -166794,6 +166192,7 @@ var ZCodeTui = class {
166794
166192
  this.buildLayout();
166795
166193
  if (notificationConfigError) this.addNotice(`Unable to load notification settings: ${notificationConfigError}`, "warning");
166796
166194
  await this.restoreInitialTranscript();
166195
+ await this.refreshExecutionState();
166797
166196
  if (this.transcript.blockCount > 0) this.enterSessionRail(true);
166798
166197
  if (updateCheck?.availableVersion && this.distributionVersion) this.addUpdateAvailable(this.distributionVersion, updateCheck.availableVersion);
166799
166198
  this.bindInput();
@@ -166803,16 +166202,9 @@ var ZCodeTui = class {
166803
166202
  this.updateTurnStatus();
166804
166203
  this.ui.requestRender(true);
166805
166204
  this.startUpdateRefresh(updateCheck);
166806
- if (this.options.reloadModelOptions) {
166807
- this.modelCatalogRefresh = new ModelCatalogRefresh({
166808
- baseUrl: process.env.ZCODE_BASE_URL?.trim() || "https://zcode.z.ai",
166809
- currentVersion: this.distributionVersion || this.options.version || "0.0.0"
166810
- });
166811
- this.modelCatalogRefresh.start();
166812
- }
166813
166205
  if (!this.loginRequired) this.refreshGoal();
166814
166206
  if (!this.loginRequired) this.refreshSessionUsage();
166815
- if (await readSetupPending().catch(() => false)) if (await readConfiguredModelAccess().catch(() => null)) await clearSetupPending().catch(() => {});
166207
+ if (await readSetupPending().catch(() => false)) if (await hasConfiguredProviderAccess().catch(() => false)) await clearSetupPending().catch(() => {});
166816
166208
  else this.runFirstRunSetup();
166817
166209
  this.scheduleRuntimePoll(0);
166818
166210
  this.loadHistory();
@@ -167033,10 +166425,14 @@ var ZCodeTui = class {
167033
166425
  this.ui.addChild(this.composerHost);
167034
166426
  }
167035
166427
  createEditor(tui) {
167036
- const editor = new Editor(tui, this.theme.editor, {
166428
+ const editor = new PlanEditor(tui, this.theme.editor, {
167037
166429
  paddingX: 1,
167038
166430
  autocompleteMaxVisible: 7
167039
166431
  });
166432
+ editor.planEnabled = this.planEnabled;
166433
+ editor.planColor = this.theme.accent;
166434
+ editor.hintColor = this.theme.muted;
166435
+ if (this.options.locale?.startsWith("zh")) editor.planHint = "先调研与规划,再开始修改";
167040
166436
  for (const input of [...this.editorHistory].reverse()) editor.addToHistory(input);
167041
166437
  const commands = this.autocompleteCommands();
167042
166438
  const workspaceDirectory = this.options.workspaceDirectory ?? process.cwd();
@@ -167227,6 +166623,11 @@ var ZCodeTui = class {
167227
166623
  });
167228
166624
  }
167229
166625
  for (const command of [
166626
+ {
166627
+ name: "plan",
166628
+ description: "Toggle planning independently of permissions",
166629
+ argumentHint: "[on|off]"
166630
+ },
167230
166631
  {
167231
166632
  name: "cls",
167232
166633
  description: "Clear the visible transcript (the runtime's /clear starts a new session)"
@@ -167265,6 +166666,11 @@ var ZCodeTui = class {
167265
166666
  name: "status",
167266
166667
  description: "Inspect detailed runtime and session status"
167267
166668
  },
166669
+ {
166670
+ name: "rename",
166671
+ description: "Rename the current session",
166672
+ argumentHint: "<title>"
166673
+ },
167268
166674
  {
167269
166675
  name: "config",
167270
166676
  description: "Configure ZCode TUI settings"
@@ -167519,6 +166925,11 @@ var ZCodeTui = class {
167519
166925
  await this.showStatusDetails();
167520
166926
  return;
167521
166927
  }
166928
+ const renameRequest = sessionRenameRequest(input);
166929
+ if (renameRequest !== void 0) {
166930
+ await this.handleSessionRename(renameRequest);
166931
+ return;
166932
+ }
167522
166933
  if (input === "/config" || input === "/settings") {
167523
166934
  await this.showConfiguration();
167524
166935
  return;
@@ -167530,6 +166941,18 @@ var ZCodeTui = class {
167530
166941
  if (isMcpPickerRequest(input) && await this.showMcpPicker()) return;
167531
166942
  if (isModelPickerRequest(input) && await this.showModelPicker()) return;
167532
166943
  if (isModePickerRequest(input) && await this.showModePicker()) return;
166944
+ if (/^\/mode(?:\s|$)/iu.test(input)) {
166945
+ const mode = input.slice(5).trim().toLowerCase();
166946
+ if (!modes.includes(mode)) this.addNotice("Choose /mode build, edit or yolo. Use /plan on or /plan off for planning.", "warning");
166947
+ else await this.applyModeShortcut(mode, true);
166948
+ return;
166949
+ }
166950
+ if (/^\/plan(?:\s|$)/iu.test(input)) {
166951
+ const argument = input.slice(5).trim().toLowerCase();
166952
+ if (argument && argument !== "on" && argument !== "off") this.addNotice("Use /plan to toggle, or /plan on and /plan off.", "warning");
166953
+ else await this.switchPlan(argument === "on" ? true : argument === "off" ? false : void 0);
166954
+ return;
166955
+ }
167533
166956
  const explicitModel = explicitModelRequest(input);
167534
166957
  if (explicitModel) {
167535
166958
  this.addUserMessage(submission.displayInput);
@@ -167866,6 +167289,7 @@ var ZCodeTui = class {
167866
167289
  async handleResult(result, renderResponse = true, settingTarget) {
167867
167290
  if (!isRecord(result)) return;
167868
167291
  if (result.resetSessionProjection === true) {
167292
+ this.executionStateRevision++;
167869
167293
  this.clearTranscriptProjection();
167870
167294
  this.workflowView = void 0;
167871
167295
  this.sessionId = void 0;
@@ -167875,6 +167299,7 @@ var ZCodeTui = class {
167875
167299
  this.emittedSessionTerminalTitle = "";
167876
167300
  emitSessionTerminalTitle(this.options.stdout ?? process.stdout, "");
167877
167301
  this.sessionMetrics = {};
167302
+ await this.restoreCustomSessionTitle();
167878
167303
  this.restoreTranscript(restoredMessages(result.restoredMessages));
167879
167304
  if (this.transcript.blockCount > 0) this.enterSessionRail(true);
167880
167305
  }
@@ -167883,8 +167308,9 @@ var ZCodeTui = class {
167883
167308
  this.completeThinking();
167884
167309
  this.recordAssistantText(this.assistantStream.reconcile(response));
167885
167310
  }
167886
- if (appliesToSetting(settingTarget, "mode") && typeof result.mode === "string") this.mode = normalizedMode(result.mode, this.mode);
167887
- if (appliesToSetting(settingTarget, "model") && result.model !== void 0) this.model = modelLabel$1(result.model);
167311
+ if (appliesToSetting(settingTarget, "mode") && typeof result.mode === "string") this.mode = result.mode;
167312
+ if (typeof result.planEnabled === "boolean") this.planEnabled = result.planEnabled;
167313
+ if (appliesToSetting(settingTarget, "model") && result.model !== void 0) this.model = modelLabel(result.model);
167888
167314
  if (typeof result.loginRequired === "boolean") {
167889
167315
  this.setLoginRequired(result.loginRequired);
167890
167316
  if (!result.loginRequired && result.model === void 0 && appliesToSetting(settingTarget, "model")) {
@@ -167903,6 +167329,19 @@ var ZCodeTui = class {
167903
167329
  this.ui.requestRender();
167904
167330
  if (isRecord(result.workflowPanel)) await this.showWorkflowPanel(result.workflowPanel);
167905
167331
  if (isRecord(result.selection)) await this.showSelection(result.selection);
167332
+ if (result.resetSessionProjection === true) {
167333
+ await this.refreshExecutionState();
167334
+ try {
167335
+ const persistedModel = await this.options.readSessionModel?.();
167336
+ if (isRecord(persistedModel) && typeof persistedModel.model === "string") {
167337
+ this.model = persistedModel.model;
167338
+ this.thoughtLevel = asString(persistedModel.thoughtLevel);
167339
+ if (Array.isArray(persistedModel.effortOptions)) this.effortOptions = persistedModel.effortOptions;
167340
+ }
167341
+ } catch {}
167342
+ this.updateMetadata();
167343
+ this.ui.requestRender();
167344
+ }
167906
167345
  }
167907
167346
  onEvent(value, turnEpoch) {
167908
167347
  this.debugEvent("session", value);
@@ -168053,6 +167492,7 @@ var ZCodeTui = class {
168053
167492
  const event = normalizeEvent(value);
168054
167493
  if (!event || this.isForeignSessionEvent(event)) return;
168055
167494
  this.applyBackgroundTaskEvent(event);
167495
+ this.scheduleRuntimeRefresh();
168056
167496
  }
168057
167497
  isForeignSessionEvent(event) {
168058
167498
  return Boolean(this.sessionId && event.sessionId && event.sessionId !== this.sessionId);
@@ -168718,6 +168158,7 @@ var ZCodeTui = class {
168718
168158
  }
168719
168159
  restoreTranscript(messages) {
168720
168160
  let firstUserMessageText;
168161
+ let lastAssistantModel;
168721
168162
  for (const message of messages) {
168722
168163
  this.currentToolGroup = void 0;
168723
168164
  this.currentToolGroupBlockId = void 0;
@@ -168731,6 +168172,7 @@ var ZCodeTui = class {
168731
168172
  }
168732
168173
  continue;
168733
168174
  }
168175
+ if (message.role === "assistant" && message.model) lastAssistantModel = message.model;
168734
168176
  const hiddenToolIds = message.role === "assistant" ? backgroundToolPartIds(message.parts) : /* @__PURE__ */ new Set();
168735
168177
  const coordinatesBackgroundAgents = message.parts.some(backgroundAgentPart);
168736
168178
  for (const part of message.parts) {
@@ -168754,6 +168196,7 @@ var ZCodeTui = class {
168754
168196
  this.currentToolGroupBlockId = void 0;
168755
168197
  this.currentToolGroupMessageId = void 0;
168756
168198
  this.assistantStream.breakSegment();
168199
+ if (lastAssistantModel) this.model = lastAssistantModel;
168757
168200
  }
168758
168201
  restorePart(part, role, fallbackMessageId) {
168759
168202
  const messageId = part.messageId ?? fallbackMessageId;
@@ -169149,7 +168592,7 @@ var ZCodeTui = class {
169149
168592
  });
169150
168593
  if (commands.some((command) => /^\/login\s+(?:zai|bigmodel)-/u.test(command.command))) commands.push({
169151
168594
  command: customProviderHelpCommand,
169152
- description: "Configure any supported endpoint in config.json without signing in",
168595
+ description: "Configure any supported endpoint in provider_config.json without signing in",
169153
168596
  label: "Custom provider"
169154
168597
  });
169155
168598
  const items = commands.map((parsed) => ({
@@ -169168,8 +168611,7 @@ var ZCodeTui = class {
169168
168611
  }))?.payload;
169169
168612
  if (!command?.command) return;
169170
168613
  if (command.command === customProviderHelpCommand) {
169171
- const configPath = userConfigPathHint();
169172
- this.addNotice(`Custom providers do not require login. Copy config.example.json to ${configPath}, set provider kind, baseURL, apiKey and model IDs, then run /new. See README: Custom provider without login.`, "muted");
168614
+ this.addNotice(`Configure custom providers in ${providerConfigPathHint()} (or ZCODE_PERSONAL_PROVIDER_CONFIG_FILE), then choose a model with /model. See provider.example.json for the schema.`, "muted");
169173
168615
  return;
169174
168616
  }
169175
168617
  if (!command.input) {
@@ -169225,7 +168667,7 @@ var ZCodeTui = class {
169225
168667
  if (picker.items.length === 0) return false;
169226
168668
  const mode = (await this.showChoice({
169227
168669
  title: "Select mode",
169228
- prompt: `Current mode: ${this.mode}. Controls tool permission behavior.`,
168670
+ prompt: `Current mode: ${this.mode}. Plan ${this.planEnabled ? "on" : "off"} · toggle with /plan`,
169229
168671
  help: "Up/Down choose · Enter switch · Esc cancel",
169230
168672
  items: picker.items.map((item) => ({
169231
168673
  ...item,
@@ -169239,21 +168681,15 @@ var ZCodeTui = class {
169239
168681
  }
169240
168682
  /** All model selectors re-read the catalog, including after first-run login. */
169241
168683
  async refreshModelOptions() {
169242
- const load = this.options.reloadModelOptions ?? this.options.listModelOptions;
168684
+ const load = this.options.reloadModelOptions;
169243
168685
  if (load) try {
169244
- await this.modelCatalogRefresh?.apply([this.model]).catch(() => {});
169245
168686
  const refreshed = await load();
169246
168687
  if (Array.isArray(refreshed)) this.modelOptions = [...refreshed];
169247
168688
  } catch (error) {
169248
168689
  this.addNotice(`Could not load model options: ${error instanceof Error ? error.message : String(error)}`, "warning");
169249
168690
  }
169250
168691
  }
169251
- /**
169252
- * Quick session-level model switch via the flat picker. Uses the
169253
- * setTransientModel bridge so the runtime keeps the switch in-memory —
169254
- * config.json's model.main stays untouched. For persistent main/lite
169255
- * configuration use /settings → Model providers.
169256
- */
168692
+ /** Switch this session while preserving the shared default model. */
169257
168693
  async showModelPicker() {
169258
168694
  await this.refreshModelOptions();
169259
168695
  const picker = modelPicker(this.modelOptions, this.model);
@@ -169272,12 +168708,6 @@ var ZCodeTui = class {
169272
168708
  await this.switchTransientModel(modelId);
169273
168709
  return true;
169274
168710
  }
169275
- /**
169276
- * Session-only model switch. Requires the setTransientModel bridge; without
169277
- * it (older runtime) the only available switch path persists to config.json,
169278
- * which contradicts this feature's contract — refuse instead of silently
169279
- * rewriting saved defaults.
169280
- */
169281
168711
  async switchTransientModel(modelId) {
169282
168712
  if (!this.options.setTransientModel) {
169283
168713
  this.addNotice("Session model switching is unavailable in this runtime · use /settings → Model providers.", "muted");
@@ -169288,7 +168718,7 @@ var ZCodeTui = class {
169288
168718
  try {
169289
168719
  const previousModel = this.model;
169290
168720
  const result = await this.options.setTransientModel(modelId);
169291
- await this.handleResult(result, false, "model");
168721
+ await this.handleResult(result, false);
169292
168722
  const status = this.model === previousModel ? "already active" : "now";
169293
168723
  this.addNotice(`Session model ${status}: ${this.model} · saved defaults unchanged.`, "muted");
169294
168724
  } catch (error) {
@@ -169297,87 +168727,30 @@ var ZCodeTui = class {
169297
168727
  this.settingSwitchInFlight = false;
169298
168728
  }
169299
168729
  }
169300
- /**
169301
- * Three-level cascade (provider → main → lite) embedded in the /settings
169302
- * menu. Persists both selections to config.json and applies the main model
169303
- * to the current session. Esc at each sub-level returns to the previous
169304
- * level: lite → main → provider → settings menu.
169305
- *
169306
- * Defaults are based on the SAVED config (model.main), not the session
169307
- * model — a quick /model switch in the session must not silently change
169308
- * what this persistent-configurator preselects.
169309
- */
168730
+ /** Save the registry default for new sessions and apply it to this session. */
169310
168731
  async showModelProviderSettings() {
169311
168732
  await this.refreshModelOptions();
169312
- const savedModelConfig = await readUserConfig().then((config) => isRecord(config.model) ? config.model : void 0).catch(() => void 0);
169313
- const savedModel = typeof savedModelConfig?.main === "string" && savedModelConfig.main.trim() ? savedModelConfig.main : void 0;
169314
- const savedLite = typeof savedModelConfig?.lite === "string" && savedModelConfig.lite.trim() ? savedModelConfig.lite : void 0;
169315
- const cascade = providerModelPicker(this.modelOptions, savedModel ?? this.model);
169316
- if (!cascade || cascade.providers.items.length === 0) {
169317
- this.addNotice("No model providers available to configure.", "muted");
169318
- return;
169319
- }
169320
- let providerIndex = cascade.providers.selectedIndex;
169321
- while (!this.stopped) {
169322
- const providerChoice = await this.showChoice({
169323
- title: "Model providers",
169324
- prompt: "Configure the main and lite models for each provider.",
169325
- help: "Up/Down choose · Enter select · Esc back to settings",
169326
- items: cascade.providers.items,
169327
- selectedIndex: providerIndex
169328
- });
169329
- if (!providerChoice) return;
169330
- providerIndex = cascade.providers.items.findIndex((item) => item.value === providerChoice.value);
169331
- const group = cascade.groups.find((g) => g.providerId === providerChoice.value);
169332
- if (!group) continue;
169333
- let confirmed = false;
169334
- let mainIndex = group.models.items.findIndex((item) => item.value === savedModel);
169335
- if (mainIndex < 0) mainIndex = group.models.selectedIndex;
169336
- while (!this.stopped && !confirmed) {
169337
- const mainChoice = await this.showChoice({
169338
- title: `Select main model · ${group.label}`,
169339
- prompt: "The main model handles agent turns.",
169340
- help: "Up/Down choose · Enter confirm · Esc back to provider",
169341
- items: group.models.items,
169342
- selectedIndex: mainIndex
169343
- });
169344
- if (!mainChoice) break;
169345
- mainIndex = group.models.items.findIndex((item) => item.value === mainChoice.value);
169346
- const liteCandidates = group.models.items.filter((item) => item.value !== mainChoice.value).map((item) => ({
169347
- ...item,
169348
- description: void 0
169349
- }));
169350
- const sameAsMainItem = {
169351
- value: mainChoice.value,
169352
- label: "Same as main",
169353
- description: `default · ${mainChoice.label}`
169354
- };
169355
- const liteItems = [...liteCandidates, sameAsMainItem];
169356
- const savedLiteIndex = liteItems.findIndex((item) => item.value === savedLite && item.value !== mainChoice.value);
169357
- const liteChoice = await this.showChoice({
169358
- title: `Select lite model · ${group.label}`,
169359
- prompt: "The lite model handles quick tasks and tool summaries.",
169360
- help: "Up/Down choose · Enter confirm · Esc back to main",
169361
- items: liteItems,
169362
- selectedIndex: savedLiteIndex >= 0 ? savedLiteIndex : liteItems.length - 1
169363
- });
169364
- if (!liteChoice) continue;
169365
- try {
169366
- await updateUserConfig((config) => {
169367
- const model = isRecord(config.model) ? config.model : {};
169368
- model.main = mainChoice.value;
169369
- model.lite = liteChoice.value;
169370
- config.model = model;
169371
- });
169372
- } catch (error) {
169373
- this.addNotice(`Could not save model config: ${error instanceof Error ? error.message : String(error)}`, "error");
169374
- continue;
169375
- }
169376
- this.addNotice(`Model config saved: main=${mainChoice.label}, lite=${liteChoice.label}.`, "muted");
169377
- await this.applySettingCommand(`/model ${mainChoice.value}`, "model");
169378
- confirmed = true;
168733
+ try {
168734
+ const saved = await this.options.readDefaultModel?.();
168735
+ const picker = modelPicker(this.modelOptions, saved);
168736
+ if (picker.items.length === 0) {
168737
+ this.addNotice("No model providers available to configure.", "muted");
168738
+ return;
169379
168739
  }
169380
- if (confirmed) return;
168740
+ const choice = await this.showChoice({
168741
+ title: "Default model",
168742
+ prompt: "Select the model used for new sessions.",
168743
+ help: "Up/Down choose · Enter save · Esc back to settings",
168744
+ items: picker.items,
168745
+ selectedIndex: picker.selectedIndex
168746
+ });
168747
+ if (!choice) return;
168748
+ if (!this.options.setDefaultModel) throw new Error("Saving the default model is unavailable.");
168749
+ const result = await this.options.setDefaultModel(choice.value);
168750
+ await this.handleResult(result, false);
168751
+ this.addNotice(`Default model saved: ${choice.value}.`, "muted");
168752
+ } catch (error) {
168753
+ this.addNotice(`Could not save model config: ${error instanceof Error ? error.message : String(error)}`, "error");
169381
168754
  }
169382
168755
  }
169383
168756
  async showConfiguration() {
@@ -169433,8 +168806,7 @@ var ZCodeTui = class {
169433
168806
  const methodOverride = Boolean(process.env.ZCODE_TUI_NOTIFICATION_METHOD?.trim());
169434
168807
  const conditionOverride = Boolean(process.env.ZCODE_TUI_NOTIFICATION_CONDITION?.trim());
169435
168808
  const tuiModeOverride = process.env.ZCODE_TUI_MODE?.trim().toLowerCase();
169436
- const savedConfig = await readUserConfig().then((config) => isRecord(config.model) ? config.model : void 0).catch(() => void 0);
169437
- const savedModelLabel = typeof savedConfig?.main === "string" && savedConfig.main.trim() ? savedConfig.main : void 0;
168809
+ const savedModelLabel = await this.options.readDefaultModel?.().catch(() => void 0);
169438
168810
  const setting = await this.showChoice({
169439
168811
  title: "ZCode settings",
169440
168812
  prompt: feedback,
@@ -169443,7 +168815,7 @@ var ZCodeTui = class {
169443
168815
  {
169444
168816
  value: "model-providers",
169445
168817
  label: "Model providers",
169446
- description: this.model === savedModelLabel || !savedModelLabel ? `Saved: ${savedModelLabel ?? this.model}` : `Session: ${this.model} · Saved: ${savedModelLabel}`
168818
+ description: savedModelLabel ? this.model === savedModelLabel ? `Saved: ${savedModelLabel}` : `Session: ${this.model} · Saved: ${savedModelLabel}` : `Session: ${this.model} · No saved default`
169447
168819
  },
169448
168820
  {
169449
168821
  value: "notification-method",
@@ -169599,24 +168971,10 @@ var ZCodeTui = class {
169599
168971
  }
169600
168972
  }
169601
168973
  async runFirstRunSetup(manual = false) {
169602
- let desktop = null;
169603
- try {
169604
- desktop = await detectDesktopInstallation();
169605
- } catch {
169606
- desktop = null;
169607
- }
169608
168974
  const access = await readConfiguredModelAccess().catch(() => null);
169609
168975
  const statusHint = access ? `Model access is already configured (${access.model}).` : "Model access is not configured yet.";
169610
168976
  while (!this.stopped) {
169611
168977
  const items = [];
169612
- if (desktop) {
169613
- const families = desktop.plan.families.map((entry) => entry.family).join("/");
169614
- items.push({
169615
- value: "import-desktop",
169616
- label: "Import settings from ZCode desktop",
169617
- description: `Copy desktop ${families} providers and model choices${desktop.plan.defaultFamily ? ` (selected: ${desktop.plan.defaultFamily})` : ""} · credentials are not copied`
169618
- });
169619
- }
169620
168978
  items.push({
169621
168979
  value: "sign-in",
169622
168980
  label: "Sign in (OAuth or API key)",
@@ -169624,7 +168982,7 @@ var ZCodeTui = class {
169624
168982
  }, {
169625
168983
  value: customProviderHelpCommand,
169626
168984
  label: "Custom provider",
169627
- description: "Configure any supported endpoint in config.json without signing in"
168985
+ description: "Configure any supported endpoint in provider_config.json without signing in"
169628
168986
  }, {
169629
168987
  value: "skip",
169630
168988
  label: "Skip for now",
@@ -169643,14 +169001,10 @@ var ZCodeTui = class {
169643
169001
  }
169644
169002
  if (selected.value === customProviderHelpCommand) {
169645
169003
  await clearSetupPending().catch(() => {});
169646
- const configPath = userConfigPathHint();
169647
- this.addNotice(`Custom providers do not require login. Copy config.example.json to ${configPath}, set provider kind, baseURL, apiKey and model IDs, then run /new. See README: Custom provider without login.`, "muted");
169004
+ this.addNotice(`Configure custom providers in ${providerConfigPathHint()} (or ZCODE_PERSONAL_PROVIDER_CONFIG_FILE), then choose a model with /model. See provider.example.json for the schema.`, "muted");
169648
169005
  return;
169649
169006
  }
169650
- if (selected.value === "import-desktop" && desktop) {
169651
- if (!await this.importDesktopSettings(desktop)) continue;
169652
- }
169653
- if (selected.value === "sign-in" || selected.value === "import-desktop") await this.submit("/login");
169007
+ if (selected.value === "sign-in") await this.submit("/login");
169654
169008
  if (await readConfiguredModelAccess().catch(() => null)) {
169655
169009
  await clearSetupPending().catch(() => {});
169656
169010
  this.setLoginRequired(false);
@@ -169660,54 +169014,6 @@ var ZCodeTui = class {
169660
169014
  this.addNotice("Login did not produce model access · choose another method or skip.", "muted");
169661
169015
  }
169662
169016
  }
169663
- async importDesktopSettings(desktop) {
169664
- const plan = desktop.plan;
169665
- if (plan.families.length === 0) return false;
169666
- const family = plan.defaultFamily && plan.families.some((entry) => entry.family === plan.defaultFamily) ? plan.defaultFamily : plan.families[0].family;
169667
- const familyPlan = plan.families.find((entry) => entry.family === family);
169668
- const modelIds = familyPlan.models.map((model) => model.id).join(", ");
169669
- const confirmed = await this.showChoice({
169670
- title: "Import from ZCode desktop",
169671
- prompt: `Import the desktop ${family} provider (${familyPlan.models.length} models: ${modelIds}) into your CLI config? A backup of the current config is saved first.`,
169672
- help: "Enter import · Esc cancel",
169673
- items: [{
169674
- value: "import",
169675
- label: `Import ${family} settings`,
169676
- description: "Provider, baseURL and model list · no credentials"
169677
- }, {
169678
- value: "cancel",
169679
- label: "Cancel",
169680
- description: "Keep the current CLI configuration"
169681
- }]
169682
- });
169683
- if (!confirmed || confirmed.value !== "import") return false;
169684
- try {
169685
- const result = await applyDesktopMigration(plan, { family });
169686
- this.addNotice(`Imported desktop ${family} settings into ${result.configPath} (backup: ${basename(result.backupPath)}).`, "muted");
169687
- } catch (error) {
169688
- this.addNotice(`Desktop import failed: ${error instanceof Error ? error.message : String(error)}`, "error");
169689
- return false;
169690
- }
169691
- if ((await this.showChoice({
169692
- title: "Sign in to finish",
169693
- prompt: `Desktop credentials cannot be copied. Sign in with the ${family} Coding Plan now to complete setup?`,
169694
- help: "Enter select · Esc decide later",
169695
- items: [{
169696
- value: "now",
169697
- label: "Sign in now (recommended)",
169698
- description: "Opens the Coding Plan login picker"
169699
- }, {
169700
- value: "later",
169701
- label: "Later",
169702
- description: "Run /login whenever you are ready"
169703
- }]
169704
- }))?.value !== "now") {
169705
- await clearSetupPending().catch(() => {});
169706
- this.addNotice("Provider settings imported · run /login to sign in when ready.", "muted");
169707
- return false;
169708
- }
169709
- return true;
169710
- }
169711
169017
  handleRewindEscape() {
169712
169018
  if (this.rewindEscapePending) {
169713
169019
  this.clearRewindEscape();
@@ -169872,22 +169178,59 @@ var ZCodeTui = class {
169872
169178
  if (!this.shortcutAvailable()) return;
169873
169179
  await this.applyModeShortcut(nextMode(this.mode));
169874
169180
  }
169875
- async applyModeShortcut(requestedMode) {
169181
+ async applyModeShortcut(requestedMode, announce = false) {
169876
169182
  if (this.settingSwitchInFlight) return;
169877
169183
  if (!this.options.setMode) {
169878
169184
  this.addNotice("Mode switching is unavailable in this runtime.", "warning");
169879
169185
  return;
169880
169186
  }
169881
169187
  this.settingSwitchInFlight = true;
169188
+ this.executionStateRevision++;
169882
169189
  try {
169883
169190
  const result = await this.options.setMode(requestedMode);
169884
- const returnedMode = isRecord(result) ? asString(result.mode) : asString(result);
169885
- this.mode = normalizedMode(returnedMode, requestedMode);
169191
+ this.applyExecutionState(result);
169192
+ this.updateMetadata();
169193
+ if (announce) this.addNotice(`Mode switched to ${this.mode}.`, "muted");
169194
+ } catch (error) {
169195
+ this.addNotice(error instanceof Error ? error.message : String(error), "error");
169196
+ } finally {
169197
+ this.settingSwitchInFlight = false;
169198
+ this.executionStateRevision++;
169199
+ this.scheduleRuntimeRefresh(0);
169200
+ }
169201
+ }
169202
+ applyExecutionState(value) {
169203
+ if (!isRecord(value)) return;
169204
+ if (typeof value.mode === "string") this.mode = value.mode;
169205
+ if (typeof value.planEnabled === "boolean") this.planEnabled = value.planEnabled;
169206
+ }
169207
+ async refreshExecutionState() {
169208
+ if (this.loginRequired || !this.options.readExecutionState) return;
169209
+ try {
169210
+ this.applyExecutionState(await this.options.readExecutionState());
169211
+ } catch (error) {
169212
+ this.addNotice(`Could not read execution state: ${error instanceof Error ? error.message : String(error)}`, "warning");
169213
+ }
169214
+ }
169215
+ async switchPlan(enabled) {
169216
+ if (!this.shortcutAvailable()) return;
169217
+ if (!this.options.setPlanEnabled) {
169218
+ this.addNotice("Plan switching is unavailable in this runtime.", "warning");
169219
+ return;
169220
+ }
169221
+ this.settingSwitchInFlight = true;
169222
+ this.executionStateRevision++;
169223
+ try {
169224
+ if (this.options.readExecutionState) this.applyExecutionState(await this.options.readExecutionState());
169225
+ this.applyExecutionState(await this.options.setPlanEnabled(enabled ?? !this.planEnabled));
169886
169226
  this.updateMetadata();
169227
+ this.addNotice(`Plan ${this.planEnabled ? "enabled" : "disabled"} · permission mode: ${this.mode}.`, "muted");
169887
169228
  } catch (error) {
169888
169229
  this.addNotice(error instanceof Error ? error.message : String(error), "error");
169889
169230
  } finally {
169890
169231
  this.settingSwitchInFlight = false;
169232
+ this.executionStateRevision++;
169233
+ this.scheduleRuntimeRefresh(0);
169891
169234
  }
169892
169235
  }
169893
169236
  async switchModel() {
@@ -170183,6 +169526,7 @@ var ZCodeTui = class {
170183
169526
  version: this.options.version,
170184
169527
  model: this.model,
170185
169528
  mode: this.mode,
169529
+ planEnabled: this.planEnabled,
170186
169530
  effort: this.thoughtLevel,
170187
169531
  workspace: this.options.workspaceDirectory ?? process.cwd(),
170188
169532
  branch: this.options.workspaceGitBranch,
@@ -170200,6 +169544,36 @@ var ZCodeTui = class {
170200
169544
  }]
170201
169545
  });
170202
169546
  }
169547
+ /**
169548
+ * `/rename <title>`: persists a user-owned session title through the
169549
+ * runtime's setCustomSessionTitle capability, so the runtime's own title
169550
+ * generator will not replace it later. Older runtimes without the bridge
169551
+ * keep the previous title and say so.
169552
+ */
169553
+ async handleSessionRename(title) {
169554
+ if (!this.options.setCustomSessionTitle) {
169555
+ this.addNotice("Session renaming is unavailable in this runtime.", "warning");
169556
+ return;
169557
+ }
169558
+ if (!this.sessionId) {
169559
+ this.addNotice("No active session to rename yet.", "warning");
169560
+ return;
169561
+ }
169562
+ if (!title) {
169563
+ this.addNotice("Usage: /rename <new title>", "muted");
169564
+ return;
169565
+ }
169566
+ try {
169567
+ await this.options.setCustomSessionTitle({ title });
169568
+ } catch (error) {
169569
+ this.addNotice(`Rename failed: ${error instanceof Error ? error.message : String(error)}`, "error");
169570
+ return;
169571
+ }
169572
+ this.sessionTerminalTitle = title;
169573
+ this.sessionTitleEmitted = true;
169574
+ this.refreshSessionTerminalTitle();
169575
+ this.addNotice(`Session renamed to: ${title}`, "muted");
169576
+ }
170203
169577
  async readMcpSummary() {
170204
169578
  if (!this.options.listMcpServers) return void 0;
170205
169579
  try {
@@ -170590,25 +169964,46 @@ var ZCodeTui = class {
170590
169964
  this.editor.addToHistory(input);
170591
169965
  }
170592
169966
  }
170593
- async restoreInitialTranscript() {
170594
- if (!this.options.loadSessionTranscript) return;
169967
+ async restoreCustomSessionTitle() {
170595
169968
  try {
169969
+ const persistedTitle = await this.options.readCustomSessionTitle?.();
169970
+ const title = typeof persistedTitle === "string" ? normalizeSessionTitle(persistedTitle) : "";
169971
+ if (!title) return;
169972
+ this.sessionTerminalTitle = title;
169973
+ this.sessionTitleEmitted = true;
169974
+ this.refreshSessionTerminalTitle();
169975
+ } catch {}
169976
+ }
169977
+ async restoreInitialTranscript() {
169978
+ await this.restoreCustomSessionTitle();
169979
+ if (this.options.loadSessionTranscript) try {
170596
169980
  this.restoreTranscript(restoredMessages(await this.options.loadSessionTranscript()));
170597
169981
  } catch (error) {
170598
169982
  const message = error instanceof Error ? error.message : String(error);
170599
169983
  this.addNotice(`Unable to restore session transcript: ${message}`, "warning");
170600
169984
  }
169985
+ try {
169986
+ const persistedModel = await this.options.readSessionModel?.();
169987
+ if (isRecord(persistedModel) && typeof persistedModel.model === "string") {
169988
+ this.model = persistedModel.model;
169989
+ this.thoughtLevel = asString(persistedModel.thoughtLevel);
169990
+ if (Array.isArray(persistedModel.effortOptions)) this.effortOptions = persistedModel.effortOptions;
169991
+ }
169992
+ } catch {}
170601
169993
  }
170602
169994
  updateMetadata() {
169995
+ this.editor.planEnabled = this.planEnabled;
170603
169996
  const fields = [{
170604
169997
  text: this.theme.muted(`◈ ${this.model}`),
170605
- compactText: this.theme.muted(`◈ ${this.model}`),
169998
+ compactText: this.theme.muted(`◈ ${this.model.slice(this.model.indexOf("/") + 1)}`),
170606
169999
  priority: 100,
170607
- required: true
170000
+ required: true,
170001
+ minWidth: 3
170608
170002
  }, {
170609
170003
  text: this.theme.muted(`◉ ${this.mode}`),
170610
170004
  compactText: this.theme.muted(`◉ ${this.mode}`),
170611
- priority: 70
170005
+ priority: 100,
170006
+ required: true
170612
170007
  }];
170613
170008
  if (this.thoughtLevel) fields.push({
170614
170009
  text: this.theme.muted(`⚡ ${this.thoughtLevel}`),
@@ -170752,6 +170147,7 @@ var ZCodeTui = class {
170752
170147
  applyRuntimeProjection(projection) {
170753
170148
  if (!projection) return;
170754
170149
  this.runtimeProjection = projection;
170150
+ if (!this.settingSwitchInFlight) this.applyExecutionState(projection);
170755
170151
  this.noticeRestoredBackgroundTasks(projection);
170756
170152
  this.reconcileTurnTiming(projection);
170757
170153
  if (projection.sessionId) this.sessionId = projection.sessionId;
@@ -170810,11 +170206,16 @@ var ZCodeTui = class {
170810
170206
  try {
170811
170207
  do {
170812
170208
  this.runtimeRefreshPending = false;
170209
+ const executionStateRevision = this.executionStateRevision;
170813
170210
  const [projectionResult, todosResult, contextMessagesResult] = await Promise.allSettled([
170814
170211
  this.options.readRuntimeProjection?.(),
170815
170212
  this.options.readTodos?.(),
170816
170213
  this.options.readRuntimeProjection && this.options.loadSessionContextMessages ? this.options.loadSessionContextMessages() : Promise.resolve(void 0)
170817
170214
  ]);
170215
+ if (executionStateRevision !== this.executionStateRevision) {
170216
+ this.runtimeRefreshPending = true;
170217
+ continue;
170218
+ }
170818
170219
  const next = {
170819
170220
  projection: this.runtimeProjection,
170820
170221
  todos: this.todos,
@@ -170954,7 +170355,6 @@ var ZCodeTui = class {
170954
170355
  for (const controller of this.steerAbortControllers) controller.abort();
170955
170356
  this.steerAbortControllers.clear();
170956
170357
  this.updateCheckAbortController?.abort();
170957
- this.modelCatalogRefresh?.stop();
170958
170358
  if (this.turnTimer) clearInterval(this.turnTimer);
170959
170359
  this.stopSessionTitleSpinner();
170960
170360
  if (this.rewindEscapeTimer) clearTimeout(this.rewindEscapeTimer);