zcode-app-cli 3.11.2-25 → 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.
- package/README.md +22 -8
- package/bin/zcode.js +194 -111
- package/docs/CONFIGURATION.md +387 -0
- package/docs/CONFIGURATION.zh-CN.md +324 -0
- package/docs/PROVIDER_CONFIG.md +271 -0
- package/docs/PROVIDER_CONFIG.zh-CN.md +245 -0
- package/package.json +8 -3
- package/provider.example.json +151 -0
- package/{config.example.json → setting.example.json} +0 -47
- package/vendor/cli-config.cjs +161 -0
- package/vendor/extraction.json +17 -4
- package/vendor/node_modules/@zcode/tui/dist/index.js +436 -1086
- package/vendor/packages/browser-use-plugin/dist/mcp/server.js +35543 -34422
- package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +2 -2
- package/vendor/packages/document-skills-plugin/package.json +4 -4
- package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +34 -0
- package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +9 -0
- package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +11 -0
- package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +7 -0
- package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +7 -0
- package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +10 -1
- package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +19 -4
- package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/env_check.sh +6 -2
- package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup.md +12 -3
- package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup_mac_linux.sh +9 -3
- package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup_windows.ps1 +8 -3
- package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +30 -6
- package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +9 -3
- package/vendor/packages/document-skills-plugin/skills/pptx/SKILL.md +33 -0
- package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup.md +29 -4
- package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup_mac_linux.sh +8 -3
- package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup_windows.ps1 +8 -3
- package/vendor/packages/document-skills-plugin/skills/xlsx/quality/pipeline.md +9 -0
- package/vendor/packages/document-skills-plugin/skills/xlsx/setup.sh +8 -3
- package/vendor/packages/document-skills-plugin/skills/xlsx/xlsx.py +15 -1
- package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +13 -8
- package/vendor/provider/zcode-builtin.json +6296 -0
- package/vendor/zcode.cjs +1159 -840
- 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
|
|
14
|
-
var
|
|
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
|
|
146
|
-
|
|
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
|
|
151
|
-
|
|
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
|
|
154
|
-
const configPath =
|
|
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))
|
|
165
|
-
|
|
166
|
-
|
|
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(
|
|
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
|
|
204
|
-
const { configPath } = await
|
|
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
|
|
214
|
-
const configPath =
|
|
215
|
-
const config = await
|
|
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
|
|
238
|
-
|
|
268
|
+
const directory = join(sharedDataBaseDir(env), ".zcode", "v2");
|
|
269
|
+
const configPath = providerConfigPath(env);
|
|
270
|
+
let value;
|
|
239
271
|
try {
|
|
240
|
-
|
|
241
|
-
} catch {
|
|
272
|
+
value = JSON.parse(await readFile(configPath, "utf8"));
|
|
273
|
+
} catch (error) {
|
|
242
274
|
return null;
|
|
243
275
|
}
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
const providerId =
|
|
248
|
-
const modelId =
|
|
249
|
-
|
|
250
|
-
const
|
|
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
|
-
|
|
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;
|
|
306
363
|
try {
|
|
307
|
-
|
|
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);
|
|
512
|
-
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
|
|
550
|
-
|
|
551
|
-
const
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
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(
|
|
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
|
|
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);
|
|
@@ -158987,6 +158388,29 @@ function buildExitSummary(options) {
|
|
|
158987
158388
|
};
|
|
158988
158389
|
}
|
|
158989
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
|
|
158990
158414
|
//#region packages/zcode-tui/src/footer-bar.ts
|
|
158991
158415
|
const horizontalPadding = 1;
|
|
158992
158416
|
const sectionGap = 2;
|
|
@@ -159356,7 +158780,9 @@ var StatusDetailView = class {
|
|
|
159356
158780
|
["CLI version", this.data.cliVersion],
|
|
159357
158781
|
["Runtime version", this.data.version],
|
|
159358
158782
|
["Model", this.data.model],
|
|
159359
|
-
["Mode",
|
|
158783
|
+
["Mode", this.data.mode],
|
|
158784
|
+
["Plan", this.data.planEnabled ? "on" : "off"],
|
|
158785
|
+
["Reasoning effort", this.data.effort],
|
|
159360
158786
|
["Workspace", this.data.workspace],
|
|
159361
158787
|
["Git branch", this.data.branch],
|
|
159362
158788
|
["Session", projection?.sessionId],
|
|
@@ -162599,13 +162025,13 @@ function notificationSettings(env = process.env, config) {
|
|
|
162599
162025
|
};
|
|
162600
162026
|
}
|
|
162601
162027
|
async function readNotificationSettings(env = process.env) {
|
|
162602
|
-
return notificationSettings(env, await
|
|
162028
|
+
return notificationSettings(env, await readCliSettings(env));
|
|
162603
162029
|
}
|
|
162604
162030
|
async function readStoredNotificationSettings(env = process.env) {
|
|
162605
|
-
return notificationSettings({}, await
|
|
162031
|
+
return notificationSettings({}, await readCliSettings(env));
|
|
162606
162032
|
}
|
|
162607
162033
|
async function writeNotificationSettings(settings, env = process.env) {
|
|
162608
|
-
return await
|
|
162034
|
+
return await updateCliSettings((config) => {
|
|
162609
162035
|
const ui = record$2(config.ui) ?? {};
|
|
162610
162036
|
ui.notifications = { ...settings };
|
|
162611
162037
|
config.ui = ui;
|
|
@@ -162874,10 +162300,10 @@ function resolveTuiMode(env = process.env, config) {
|
|
|
162874
162300
|
return tuiMode(env.ZCODE_TUI_MODE) ?? tuiMode(configuredTuiMode(config)) ?? "regular";
|
|
162875
162301
|
}
|
|
162876
162302
|
async function readTuiMode(env = process.env) {
|
|
162877
|
-
return resolveTuiMode(env, await
|
|
162303
|
+
return resolveTuiMode(env, await readCliSettings(env));
|
|
162878
162304
|
}
|
|
162879
162305
|
async function writeTuiMode(mode, env = process.env) {
|
|
162880
|
-
return await
|
|
162306
|
+
return await updateCliSettings((config) => {
|
|
162881
162307
|
const ui = record$1(config.ui) ?? {};
|
|
162882
162308
|
ui.tuiMode = mode;
|
|
162883
162309
|
config.ui = ui;
|
|
@@ -162893,16 +162319,51 @@ function configuredCopyOnSelect(config) {
|
|
|
162893
162319
|
return typeof value === "boolean" ? value : void 0;
|
|
162894
162320
|
}
|
|
162895
162321
|
async function readCopyOnSelect(env = process.env) {
|
|
162896
|
-
return configuredCopyOnSelect(await
|
|
162322
|
+
return configuredCopyOnSelect(await readCliSettings(env)) ?? true;
|
|
162897
162323
|
}
|
|
162898
162324
|
async function writeCopyOnSelect(enabled, env = process.env) {
|
|
162899
|
-
return await
|
|
162325
|
+
return await updateCliSettings((config) => {
|
|
162900
162326
|
const ui = record(config.ui) ?? {};
|
|
162901
162327
|
ui.copyOnSelect = enabled;
|
|
162902
162328
|
config.ui = ui;
|
|
162903
162329
|
}, env);
|
|
162904
162330
|
}
|
|
162905
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
|
|
162906
162367
|
//#region packages/zcode-tui/src/selectors.ts
|
|
162907
162368
|
function pickerRequest(input, commands) {
|
|
162908
162369
|
const match = /^\/([^\s]+)(?:\s+(.*))?$/u.exec(input.trim());
|
|
@@ -162920,12 +162381,15 @@ function modePicker(currentMode, availableModes) {
|
|
|
162920
162381
|
const items = (availableModes?.length ? availableModes : [
|
|
162921
162382
|
"build",
|
|
162922
162383
|
"edit",
|
|
162923
|
-
"yolo"
|
|
162924
|
-
|
|
162925
|
-
|
|
162384
|
+
"yolo"
|
|
162385
|
+
]).filter((mode) => [
|
|
162386
|
+
"build",
|
|
162387
|
+
"edit",
|
|
162388
|
+
"yolo"
|
|
162389
|
+
].includes(mode)).map((mode) => ({
|
|
162926
162390
|
value: mode,
|
|
162927
162391
|
label: mode.charAt(0).toUpperCase() + mode.slice(1),
|
|
162928
|
-
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(" · "),
|
|
162929
162393
|
command: `/mode ${mode}`
|
|
162930
162394
|
}));
|
|
162931
162395
|
const currentIndex = items.findIndex((item) => item.value === currentMode);
|
|
@@ -162943,7 +162407,7 @@ function modePicker(currentMode, availableModes) {
|
|
|
162943
162407
|
function explicitModelRequest(input) {
|
|
162944
162408
|
const argument = /^\/model\s+(\S+)$/iu.exec(input.trim())?.[1];
|
|
162945
162409
|
if (!argument || argument.toLowerCase() === "list") return void 0;
|
|
162946
|
-
if (
|
|
162410
|
+
if (argument.toLowerCase() === "main") return "main";
|
|
162947
162411
|
const separator = argument.indexOf("/");
|
|
162948
162412
|
if (separator <= 0 || separator === argument.length - 1) return void 0;
|
|
162949
162413
|
return argument;
|
|
@@ -162951,116 +162415,37 @@ function explicitModelRequest(input) {
|
|
|
162951
162415
|
function isEffortPickerRequest(input) {
|
|
162952
162416
|
return pickerRequest(input, /* @__PURE__ */ new Set(["effort", "variant"]));
|
|
162953
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
|
+
}
|
|
162954
162427
|
function extractModelId(record, raw) {
|
|
162955
162428
|
const direct = asString(record?.id);
|
|
162956
162429
|
if (direct) return direct;
|
|
162957
|
-
const
|
|
162430
|
+
const ref = isRecord(record?.ref) ? record.ref : record;
|
|
162431
|
+
const modelId = asString(ref?.modelId);
|
|
162958
162432
|
if (modelId) {
|
|
162959
|
-
const providerId = asString(
|
|
162433
|
+
const providerId = asString(ref?.providerId);
|
|
162960
162434
|
return providerId ? `${providerId}/${modelId}` : modelId;
|
|
162961
162435
|
}
|
|
162962
162436
|
return asString(raw);
|
|
162963
162437
|
}
|
|
162964
|
-
function parseModelRef(id) {
|
|
162965
|
-
const separator = id.indexOf("/");
|
|
162966
|
-
if (separator <= 0 || separator === id.length - 1) return void 0;
|
|
162967
|
-
return {
|
|
162968
|
-
providerId: id.slice(0, separator),
|
|
162969
|
-
modelId: id.slice(separator + 1)
|
|
162970
|
-
};
|
|
162971
|
-
}
|
|
162972
|
-
function extractModelOption(option) {
|
|
162973
|
-
const record = isRecord(option) ? option : void 0;
|
|
162974
|
-
const id = extractModelId(record, option);
|
|
162975
|
-
if (!id) return void 0;
|
|
162976
|
-
const parsed = parseModelRef(id);
|
|
162977
|
-
if (!parsed) return void 0;
|
|
162978
|
-
return {
|
|
162979
|
-
id,
|
|
162980
|
-
providerId: parsed.providerId,
|
|
162981
|
-
modelId: parsed.modelId,
|
|
162982
|
-
name: asString(record?.name) ?? asString(record?.label),
|
|
162983
|
-
providerLabel: asString(record?.providerLabel) ?? asString(record?.providerName)
|
|
162984
|
-
};
|
|
162985
|
-
}
|
|
162986
|
-
function modelLabel(option) {
|
|
162987
|
-
return option.name && option.name !== option.modelId ? option.name : option.modelId;
|
|
162988
|
-
}
|
|
162989
|
-
function describeModel(option, currentModel) {
|
|
162990
|
-
const details = [option.name && option.name !== option.modelId ? option.name : void 0, option.id === currentModel ? "current" : void 0].filter((value) => Boolean(value));
|
|
162991
|
-
return details.length > 0 ? details.join(" · ") : void 0;
|
|
162992
|
-
}
|
|
162993
|
-
function providerLabel(option) {
|
|
162994
|
-
return option.providerLabel ?? option.providerId;
|
|
162995
|
-
}
|
|
162996
|
-
/**
|
|
162997
|
-
* Group the runtime's flat `modelOptions` list by provider, producing a
|
|
162998
|
-
* three-level cascade: provider → main model → lite model.
|
|
162999
|
-
*
|
|
163000
|
-
* The runtime passes each option as `{ modelId, providerId, ... }` (from
|
|
163001
|
-
* `listModels()`/`RXr`), but tests and some callers use `{ id, name }` — both
|
|
163002
|
-
* forms are accepted.
|
|
163003
|
-
*/
|
|
163004
|
-
function providerModelPicker(options, currentModel) {
|
|
163005
|
-
const byProvider = /* @__PURE__ */ new Map();
|
|
163006
|
-
const seen = /* @__PURE__ */ new Set();
|
|
163007
|
-
for (const option of options) {
|
|
163008
|
-
const parsed = extractModelOption(option);
|
|
163009
|
-
if (!parsed) continue;
|
|
163010
|
-
if (seen.has(parsed.id)) continue;
|
|
163011
|
-
seen.add(parsed.id);
|
|
163012
|
-
const group = byProvider.get(parsed.providerId) ?? [];
|
|
163013
|
-
group.push(parsed);
|
|
163014
|
-
byProvider.set(parsed.providerId, group);
|
|
163015
|
-
}
|
|
163016
|
-
if (byProvider.size === 0) return null;
|
|
163017
|
-
const groups = [];
|
|
163018
|
-
for (const [providerId, models] of byProvider) {
|
|
163019
|
-
const label = providerLabel(models[0]);
|
|
163020
|
-
const items = models.map((model) => ({
|
|
163021
|
-
value: model.id,
|
|
163022
|
-
label: modelLabel(model),
|
|
163023
|
-
description: describeModel(model, currentModel),
|
|
163024
|
-
command: `/model ${model.id}`
|
|
163025
|
-
}));
|
|
163026
|
-
const currentIndex = items.findIndex((item) => item.value === currentModel);
|
|
163027
|
-
groups.push({
|
|
163028
|
-
providerId,
|
|
163029
|
-
label,
|
|
163030
|
-
models: {
|
|
163031
|
-
items,
|
|
163032
|
-
selectedIndex: currentIndex >= 0 ? currentIndex : 0
|
|
163033
|
-
}
|
|
163034
|
-
});
|
|
163035
|
-
}
|
|
163036
|
-
const providerItems = groups.map((group) => {
|
|
163037
|
-
const currentInGroup = group.models.items.some((item) => item.value === currentModel);
|
|
163038
|
-
const currentModelId = group.models.items.find((item) => item.value === currentModel)?.label;
|
|
163039
|
-
return {
|
|
163040
|
-
value: group.providerId,
|
|
163041
|
-
label: group.label,
|
|
163042
|
-
description: [`${group.models.items.length} model${group.models.items.length === 1 ? "" : "s"}`, currentInGroup && currentModelId ? `current: ${currentModelId}` : void 0].filter((value) => Boolean(value)).join(" · "),
|
|
163043
|
-
command: ""
|
|
163044
|
-
};
|
|
163045
|
-
});
|
|
163046
|
-
return {
|
|
163047
|
-
providers: {
|
|
163048
|
-
items: providerItems,
|
|
163049
|
-
selectedIndex: providerItems.findIndex((item) => groups[providerItems.indexOf(item)].models.items.some((m) => m.value === currentModel))
|
|
163050
|
-
},
|
|
163051
|
-
groups
|
|
163052
|
-
};
|
|
163053
|
-
}
|
|
163054
162438
|
function modelPicker(options, currentModel) {
|
|
163055
162439
|
const items = [];
|
|
163056
162440
|
const seen = /* @__PURE__ */ new Set();
|
|
163057
162441
|
for (const option of options) {
|
|
163058
162442
|
const record = isRecord(option) ? option : void 0;
|
|
163059
|
-
const id =
|
|
162443
|
+
const id = extractModelId(record, option);
|
|
163060
162444
|
if (!id || seen.has(id)) continue;
|
|
163061
162445
|
seen.add(id);
|
|
162446
|
+
const name = asString(record?.name) ?? asString(record?.label);
|
|
163062
162447
|
const details = [
|
|
163063
|
-
|
|
162448
|
+
name !== id ? name : void 0,
|
|
163064
162449
|
asString(record?.alias),
|
|
163065
162450
|
id === currentModel ? "current" : void 0
|
|
163066
162451
|
].filter((value) => Boolean(value));
|
|
@@ -163723,6 +163108,7 @@ function normalizeRuntimeProjection(value) {
|
|
|
163723
163108
|
sessionId: stringField(projection, "sessionId", "sessionID", "id"),
|
|
163724
163109
|
status: stringField(projection, "status"),
|
|
163725
163110
|
mode: stringField(projection, "mode"),
|
|
163111
|
+
planEnabled: typeof projection.planEnabled === "boolean" ? projection.planEnabled : void 0,
|
|
163726
163112
|
turnCount: nonNegativeInteger(projection.turnCount),
|
|
163727
163113
|
totalTokenCount: nonNegativeInteger(projection.totalTokenCount),
|
|
163728
163114
|
currentTurnId: stringField(projection, "currentTurnId", "currentTurnID"),
|
|
@@ -163959,37 +163345,6 @@ function redactSecrets(message, secrets) {
|
|
|
163959
163345
|
return secrets.reduce((redacted, secret) => secret ? redacted.replaceAll(secret, "[redacted]") : redacted, message);
|
|
163960
163346
|
}
|
|
163961
163347
|
//#endregion
|
|
163962
|
-
//#region packages/zcode-tui/src/session-title.ts
|
|
163963
|
-
const SESSION_TITLE_PREFIX = "ZC | ";
|
|
163964
|
-
const sessionTitleSpinnerFrames = [
|
|
163965
|
-
"⠋",
|
|
163966
|
-
"⠙",
|
|
163967
|
-
"⠹",
|
|
163968
|
-
"⠸",
|
|
163969
|
-
"⠼",
|
|
163970
|
-
"⠴",
|
|
163971
|
-
"⠦",
|
|
163972
|
-
"⠧",
|
|
163973
|
-
"⠇",
|
|
163974
|
-
"⠏"
|
|
163975
|
-
];
|
|
163976
|
-
function sessionTitleSpinnerFrame(elapsedMilliseconds, animated = true) {
|
|
163977
|
-
if (!animated) return sessionTitleSpinnerFrames[0];
|
|
163978
|
-
const frame = Math.floor(Math.max(0, elapsedMilliseconds) / 120);
|
|
163979
|
-
return sessionTitleSpinnerFrames[frame % sessionTitleSpinnerFrames.length] ?? sessionTitleSpinnerFrames[0];
|
|
163980
|
-
}
|
|
163981
|
-
function sessionTitleFromFirstMessage(message) {
|
|
163982
|
-
const normalized = sanitizeTerminalText(message).replace(/\s+/gu, " ").trim();
|
|
163983
|
-
if (!normalized) return null;
|
|
163984
|
-
const characters = Array.from(normalized);
|
|
163985
|
-
if (characters.length <= 50) return normalized;
|
|
163986
|
-
return `${characters.slice(0, 49).join("")}…`;
|
|
163987
|
-
}
|
|
163988
|
-
function emitSessionTerminalTitle(stream, title) {
|
|
163989
|
-
if (!stream?.isTTY) return;
|
|
163990
|
-
stream.write(title ? `\x1b]0;${SESSION_TITLE_PREFIX}${title}\x07` : "\x1B]0;\x07");
|
|
163991
|
-
}
|
|
163992
|
-
//#endregion
|
|
163993
163348
|
//#region packages/zcode-tui/src/skills.ts
|
|
163994
163349
|
const skillCacheMilliseconds = 2e3;
|
|
163995
163350
|
const skillDescriptionLimit = 140;
|
|
@@ -164118,15 +163473,14 @@ function skillDescription(candidate) {
|
|
|
164118
163473
|
const modes = [
|
|
164119
163474
|
"build",
|
|
164120
163475
|
"edit",
|
|
164121
|
-
"yolo"
|
|
164122
|
-
"plan"
|
|
163476
|
+
"yolo"
|
|
164123
163477
|
];
|
|
164124
163478
|
function normalizedMode(mode, fallback = "build") {
|
|
164125
163479
|
const candidate = mode;
|
|
164126
163480
|
return modes.includes(candidate) ? candidate : fallback;
|
|
164127
163481
|
}
|
|
164128
163482
|
function nextMode(currentMode) {
|
|
164129
|
-
const currentIndex = modes.indexOf(
|
|
163483
|
+
const currentIndex = modes.indexOf(currentMode);
|
|
164130
163484
|
return modes[(currentIndex + 1) % modes.length] ?? modes[0];
|
|
164131
163485
|
}
|
|
164132
163486
|
function settingTargetForCommand(input) {
|
|
@@ -164184,6 +163538,12 @@ var StatusLine = class {
|
|
|
164184
163538
|
if (!removable) break;
|
|
164185
163539
|
fields.splice(removable.index, 1);
|
|
164186
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
|
+
}
|
|
164187
163547
|
return [` ${truncateToWidth(fields.map((field) => field.renderedText).join(this.separator), availableWidth, "…")}`];
|
|
164188
163548
|
}
|
|
164189
163549
|
invalidate() {}
|
|
@@ -166657,6 +166017,8 @@ var ZCodeTui = class {
|
|
|
166657
166017
|
pendingAttachments = [];
|
|
166658
166018
|
editorHistory = [];
|
|
166659
166019
|
mode;
|
|
166020
|
+
planEnabled = false;
|
|
166021
|
+
executionStateRevision = 0;
|
|
166660
166022
|
model;
|
|
166661
166023
|
tuiMode;
|
|
166662
166024
|
copyOnSelect = true;
|
|
@@ -166713,7 +166075,6 @@ var ZCodeTui = class {
|
|
|
166713
166075
|
backgroundDrainScheduled = false;
|
|
166714
166076
|
backgroundHandoffInterruptInFlight = false;
|
|
166715
166077
|
updateCheckAbortController;
|
|
166716
|
-
modelCatalogRefresh;
|
|
166717
166078
|
loginRequired;
|
|
166718
166079
|
removeStreamErrorGuards;
|
|
166719
166080
|
constructor(options) {
|
|
@@ -166736,8 +166097,9 @@ var ZCodeTui = class {
|
|
|
166736
166097
|
loginRequired: options.loginRequired === true,
|
|
166737
166098
|
includeIdentity: true
|
|
166738
166099
|
});
|
|
166739
|
-
this.mode =
|
|
166740
|
-
this.
|
|
166100
|
+
this.mode = options.initialMode ?? "build";
|
|
166101
|
+
this.planEnabled = options.initialPlanEnabled ?? false;
|
|
166102
|
+
this.model = modelLabel(options.initialModel);
|
|
166741
166103
|
this.thoughtLevel = options.initialThoughtLevel;
|
|
166742
166104
|
this.modelOptions = [...options.modelOptions ?? []];
|
|
166743
166105
|
this.effortOptions = [...options.effortOptions ?? []];
|
|
@@ -166830,6 +166192,7 @@ var ZCodeTui = class {
|
|
|
166830
166192
|
this.buildLayout();
|
|
166831
166193
|
if (notificationConfigError) this.addNotice(`Unable to load notification settings: ${notificationConfigError}`, "warning");
|
|
166832
166194
|
await this.restoreInitialTranscript();
|
|
166195
|
+
await this.refreshExecutionState();
|
|
166833
166196
|
if (this.transcript.blockCount > 0) this.enterSessionRail(true);
|
|
166834
166197
|
if (updateCheck?.availableVersion && this.distributionVersion) this.addUpdateAvailable(this.distributionVersion, updateCheck.availableVersion);
|
|
166835
166198
|
this.bindInput();
|
|
@@ -166839,16 +166202,9 @@ var ZCodeTui = class {
|
|
|
166839
166202
|
this.updateTurnStatus();
|
|
166840
166203
|
this.ui.requestRender(true);
|
|
166841
166204
|
this.startUpdateRefresh(updateCheck);
|
|
166842
|
-
if (this.options.reloadModelOptions) {
|
|
166843
|
-
this.modelCatalogRefresh = new ModelCatalogRefresh({
|
|
166844
|
-
baseUrl: process.env.ZCODE_BASE_URL?.trim() || "https://zcode.z.ai",
|
|
166845
|
-
currentVersion: this.distributionVersion || this.options.version || "0.0.0"
|
|
166846
|
-
});
|
|
166847
|
-
this.modelCatalogRefresh.start();
|
|
166848
|
-
}
|
|
166849
166205
|
if (!this.loginRequired) this.refreshGoal();
|
|
166850
166206
|
if (!this.loginRequired) this.refreshSessionUsage();
|
|
166851
|
-
if (await readSetupPending().catch(() => false)) if (await
|
|
166207
|
+
if (await readSetupPending().catch(() => false)) if (await hasConfiguredProviderAccess().catch(() => false)) await clearSetupPending().catch(() => {});
|
|
166852
166208
|
else this.runFirstRunSetup();
|
|
166853
166209
|
this.scheduleRuntimePoll(0);
|
|
166854
166210
|
this.loadHistory();
|
|
@@ -167069,10 +166425,14 @@ var ZCodeTui = class {
|
|
|
167069
166425
|
this.ui.addChild(this.composerHost);
|
|
167070
166426
|
}
|
|
167071
166427
|
createEditor(tui) {
|
|
167072
|
-
const editor = new
|
|
166428
|
+
const editor = new PlanEditor(tui, this.theme.editor, {
|
|
167073
166429
|
paddingX: 1,
|
|
167074
166430
|
autocompleteMaxVisible: 7
|
|
167075
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 = "先调研与规划,再开始修改";
|
|
167076
166436
|
for (const input of [...this.editorHistory].reverse()) editor.addToHistory(input);
|
|
167077
166437
|
const commands = this.autocompleteCommands();
|
|
167078
166438
|
const workspaceDirectory = this.options.workspaceDirectory ?? process.cwd();
|
|
@@ -167263,6 +166623,11 @@ var ZCodeTui = class {
|
|
|
167263
166623
|
});
|
|
167264
166624
|
}
|
|
167265
166625
|
for (const command of [
|
|
166626
|
+
{
|
|
166627
|
+
name: "plan",
|
|
166628
|
+
description: "Toggle planning independently of permissions",
|
|
166629
|
+
argumentHint: "[on|off]"
|
|
166630
|
+
},
|
|
167266
166631
|
{
|
|
167267
166632
|
name: "cls",
|
|
167268
166633
|
description: "Clear the visible transcript (the runtime's /clear starts a new session)"
|
|
@@ -167301,6 +166666,11 @@ var ZCodeTui = class {
|
|
|
167301
166666
|
name: "status",
|
|
167302
166667
|
description: "Inspect detailed runtime and session status"
|
|
167303
166668
|
},
|
|
166669
|
+
{
|
|
166670
|
+
name: "rename",
|
|
166671
|
+
description: "Rename the current session",
|
|
166672
|
+
argumentHint: "<title>"
|
|
166673
|
+
},
|
|
167304
166674
|
{
|
|
167305
166675
|
name: "config",
|
|
167306
166676
|
description: "Configure ZCode TUI settings"
|
|
@@ -167555,6 +166925,11 @@ var ZCodeTui = class {
|
|
|
167555
166925
|
await this.showStatusDetails();
|
|
167556
166926
|
return;
|
|
167557
166927
|
}
|
|
166928
|
+
const renameRequest = sessionRenameRequest(input);
|
|
166929
|
+
if (renameRequest !== void 0) {
|
|
166930
|
+
await this.handleSessionRename(renameRequest);
|
|
166931
|
+
return;
|
|
166932
|
+
}
|
|
167558
166933
|
if (input === "/config" || input === "/settings") {
|
|
167559
166934
|
await this.showConfiguration();
|
|
167560
166935
|
return;
|
|
@@ -167566,6 +166941,18 @@ var ZCodeTui = class {
|
|
|
167566
166941
|
if (isMcpPickerRequest(input) && await this.showMcpPicker()) return;
|
|
167567
166942
|
if (isModelPickerRequest(input) && await this.showModelPicker()) return;
|
|
167568
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
|
+
}
|
|
167569
166956
|
const explicitModel = explicitModelRequest(input);
|
|
167570
166957
|
if (explicitModel) {
|
|
167571
166958
|
this.addUserMessage(submission.displayInput);
|
|
@@ -167902,6 +167289,7 @@ var ZCodeTui = class {
|
|
|
167902
167289
|
async handleResult(result, renderResponse = true, settingTarget) {
|
|
167903
167290
|
if (!isRecord(result)) return;
|
|
167904
167291
|
if (result.resetSessionProjection === true) {
|
|
167292
|
+
this.executionStateRevision++;
|
|
167905
167293
|
this.clearTranscriptProjection();
|
|
167906
167294
|
this.workflowView = void 0;
|
|
167907
167295
|
this.sessionId = void 0;
|
|
@@ -167911,6 +167299,7 @@ var ZCodeTui = class {
|
|
|
167911
167299
|
this.emittedSessionTerminalTitle = "";
|
|
167912
167300
|
emitSessionTerminalTitle(this.options.stdout ?? process.stdout, "");
|
|
167913
167301
|
this.sessionMetrics = {};
|
|
167302
|
+
await this.restoreCustomSessionTitle();
|
|
167914
167303
|
this.restoreTranscript(restoredMessages(result.restoredMessages));
|
|
167915
167304
|
if (this.transcript.blockCount > 0) this.enterSessionRail(true);
|
|
167916
167305
|
}
|
|
@@ -167919,8 +167308,9 @@ var ZCodeTui = class {
|
|
|
167919
167308
|
this.completeThinking();
|
|
167920
167309
|
this.recordAssistantText(this.assistantStream.reconcile(response));
|
|
167921
167310
|
}
|
|
167922
|
-
if (appliesToSetting(settingTarget, "mode") && typeof result.mode === "string") this.mode =
|
|
167923
|
-
if (
|
|
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);
|
|
167924
167314
|
if (typeof result.loginRequired === "boolean") {
|
|
167925
167315
|
this.setLoginRequired(result.loginRequired);
|
|
167926
167316
|
if (!result.loginRequired && result.model === void 0 && appliesToSetting(settingTarget, "model")) {
|
|
@@ -167940,9 +167330,14 @@ var ZCodeTui = class {
|
|
|
167940
167330
|
if (isRecord(result.workflowPanel)) await this.showWorkflowPanel(result.workflowPanel);
|
|
167941
167331
|
if (isRecord(result.selection)) await this.showSelection(result.selection);
|
|
167942
167332
|
if (result.resetSessionProjection === true) {
|
|
167333
|
+
await this.refreshExecutionState();
|
|
167943
167334
|
try {
|
|
167944
167335
|
const persistedModel = await this.options.readSessionModel?.();
|
|
167945
|
-
if (typeof persistedModel === "string"
|
|
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
|
+
}
|
|
167946
167341
|
} catch {}
|
|
167947
167342
|
this.updateMetadata();
|
|
167948
167343
|
this.ui.requestRender();
|
|
@@ -168097,6 +167492,7 @@ var ZCodeTui = class {
|
|
|
168097
167492
|
const event = normalizeEvent(value);
|
|
168098
167493
|
if (!event || this.isForeignSessionEvent(event)) return;
|
|
168099
167494
|
this.applyBackgroundTaskEvent(event);
|
|
167495
|
+
this.scheduleRuntimeRefresh();
|
|
168100
167496
|
}
|
|
168101
167497
|
isForeignSessionEvent(event) {
|
|
168102
167498
|
return Boolean(this.sessionId && event.sessionId && event.sessionId !== this.sessionId);
|
|
@@ -169196,7 +168592,7 @@ var ZCodeTui = class {
|
|
|
169196
168592
|
});
|
|
169197
168593
|
if (commands.some((command) => /^\/login\s+(?:zai|bigmodel)-/u.test(command.command))) commands.push({
|
|
169198
168594
|
command: customProviderHelpCommand,
|
|
169199
|
-
description: "Configure any supported endpoint in
|
|
168595
|
+
description: "Configure any supported endpoint in provider_config.json without signing in",
|
|
169200
168596
|
label: "Custom provider"
|
|
169201
168597
|
});
|
|
169202
168598
|
const items = commands.map((parsed) => ({
|
|
@@ -169215,8 +168611,7 @@ var ZCodeTui = class {
|
|
|
169215
168611
|
}))?.payload;
|
|
169216
168612
|
if (!command?.command) return;
|
|
169217
168613
|
if (command.command === customProviderHelpCommand) {
|
|
169218
|
-
|
|
169219
|
-
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");
|
|
169220
168615
|
return;
|
|
169221
168616
|
}
|
|
169222
168617
|
if (!command.input) {
|
|
@@ -169272,7 +168667,7 @@ var ZCodeTui = class {
|
|
|
169272
168667
|
if (picker.items.length === 0) return false;
|
|
169273
168668
|
const mode = (await this.showChoice({
|
|
169274
168669
|
title: "Select mode",
|
|
169275
|
-
prompt: `Current mode: ${this.mode}.
|
|
168670
|
+
prompt: `Current mode: ${this.mode}. Plan ${this.planEnabled ? "on" : "off"} · toggle with /plan`,
|
|
169276
168671
|
help: "Up/Down choose · Enter switch · Esc cancel",
|
|
169277
168672
|
items: picker.items.map((item) => ({
|
|
169278
168673
|
...item,
|
|
@@ -169286,21 +168681,15 @@ var ZCodeTui = class {
|
|
|
169286
168681
|
}
|
|
169287
168682
|
/** All model selectors re-read the catalog, including after first-run login. */
|
|
169288
168683
|
async refreshModelOptions() {
|
|
169289
|
-
const load = this.options.reloadModelOptions
|
|
168684
|
+
const load = this.options.reloadModelOptions;
|
|
169290
168685
|
if (load) try {
|
|
169291
|
-
await this.modelCatalogRefresh?.apply([this.model]).catch(() => {});
|
|
169292
168686
|
const refreshed = await load();
|
|
169293
168687
|
if (Array.isArray(refreshed)) this.modelOptions = [...refreshed];
|
|
169294
168688
|
} catch (error) {
|
|
169295
168689
|
this.addNotice(`Could not load model options: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
169296
168690
|
}
|
|
169297
168691
|
}
|
|
169298
|
-
/**
|
|
169299
|
-
* Quick session-level model switch via the flat picker. Uses the
|
|
169300
|
-
* setTransientModel bridge so the runtime keeps the switch in-memory —
|
|
169301
|
-
* config.json's model.main stays untouched. For persistent main/lite
|
|
169302
|
-
* configuration use /settings → Model providers.
|
|
169303
|
-
*/
|
|
168692
|
+
/** Switch this session while preserving the shared default model. */
|
|
169304
168693
|
async showModelPicker() {
|
|
169305
168694
|
await this.refreshModelOptions();
|
|
169306
168695
|
const picker = modelPicker(this.modelOptions, this.model);
|
|
@@ -169319,12 +168708,6 @@ var ZCodeTui = class {
|
|
|
169319
168708
|
await this.switchTransientModel(modelId);
|
|
169320
168709
|
return true;
|
|
169321
168710
|
}
|
|
169322
|
-
/**
|
|
169323
|
-
* Session-only model switch. Requires the setTransientModel bridge; without
|
|
169324
|
-
* it (older runtime) the only available switch path persists to config.json,
|
|
169325
|
-
* which contradicts this feature's contract — refuse instead of silently
|
|
169326
|
-
* rewriting saved defaults.
|
|
169327
|
-
*/
|
|
169328
168711
|
async switchTransientModel(modelId) {
|
|
169329
168712
|
if (!this.options.setTransientModel) {
|
|
169330
168713
|
this.addNotice("Session model switching is unavailable in this runtime · use /settings → Model providers.", "muted");
|
|
@@ -169335,7 +168718,7 @@ var ZCodeTui = class {
|
|
|
169335
168718
|
try {
|
|
169336
168719
|
const previousModel = this.model;
|
|
169337
168720
|
const result = await this.options.setTransientModel(modelId);
|
|
169338
|
-
await this.handleResult(result, false
|
|
168721
|
+
await this.handleResult(result, false);
|
|
169339
168722
|
const status = this.model === previousModel ? "already active" : "now";
|
|
169340
168723
|
this.addNotice(`Session model ${status}: ${this.model} · saved defaults unchanged.`, "muted");
|
|
169341
168724
|
} catch (error) {
|
|
@@ -169344,87 +168727,30 @@ var ZCodeTui = class {
|
|
|
169344
168727
|
this.settingSwitchInFlight = false;
|
|
169345
168728
|
}
|
|
169346
168729
|
}
|
|
169347
|
-
/**
|
|
169348
|
-
* Three-level cascade (provider → main → lite) embedded in the /settings
|
|
169349
|
-
* menu. Persists both selections to config.json and applies the main model
|
|
169350
|
-
* to the current session. Esc at each sub-level returns to the previous
|
|
169351
|
-
* level: lite → main → provider → settings menu.
|
|
169352
|
-
*
|
|
169353
|
-
* Defaults are based on the SAVED config (model.main), not the session
|
|
169354
|
-
* model — a quick /model switch in the session must not silently change
|
|
169355
|
-
* what this persistent-configurator preselects.
|
|
169356
|
-
*/
|
|
168730
|
+
/** Save the registry default for new sessions and apply it to this session. */
|
|
169357
168731
|
async showModelProviderSettings() {
|
|
169358
168732
|
await this.refreshModelOptions();
|
|
169359
|
-
|
|
169360
|
-
|
|
169361
|
-
|
|
169362
|
-
|
|
169363
|
-
|
|
169364
|
-
|
|
169365
|
-
return;
|
|
169366
|
-
}
|
|
169367
|
-
let providerIndex = cascade.providers.selectedIndex;
|
|
169368
|
-
while (!this.stopped) {
|
|
169369
|
-
const providerChoice = await this.showChoice({
|
|
169370
|
-
title: "Model providers",
|
|
169371
|
-
prompt: "Configure the main and lite models for each provider.",
|
|
169372
|
-
help: "Up/Down choose · Enter select · Esc back to settings",
|
|
169373
|
-
items: cascade.providers.items,
|
|
169374
|
-
selectedIndex: providerIndex
|
|
169375
|
-
});
|
|
169376
|
-
if (!providerChoice) return;
|
|
169377
|
-
providerIndex = cascade.providers.items.findIndex((item) => item.value === providerChoice.value);
|
|
169378
|
-
const group = cascade.groups.find((g) => g.providerId === providerChoice.value);
|
|
169379
|
-
if (!group) continue;
|
|
169380
|
-
let confirmed = false;
|
|
169381
|
-
let mainIndex = group.models.items.findIndex((item) => item.value === savedModel);
|
|
169382
|
-
if (mainIndex < 0) mainIndex = group.models.selectedIndex;
|
|
169383
|
-
while (!this.stopped && !confirmed) {
|
|
169384
|
-
const mainChoice = await this.showChoice({
|
|
169385
|
-
title: `Select main model · ${group.label}`,
|
|
169386
|
-
prompt: "The main model handles agent turns.",
|
|
169387
|
-
help: "Up/Down choose · Enter confirm · Esc back to provider",
|
|
169388
|
-
items: group.models.items,
|
|
169389
|
-
selectedIndex: mainIndex
|
|
169390
|
-
});
|
|
169391
|
-
if (!mainChoice) break;
|
|
169392
|
-
mainIndex = group.models.items.findIndex((item) => item.value === mainChoice.value);
|
|
169393
|
-
const liteCandidates = group.models.items.filter((item) => item.value !== mainChoice.value).map((item) => ({
|
|
169394
|
-
...item,
|
|
169395
|
-
description: void 0
|
|
169396
|
-
}));
|
|
169397
|
-
const sameAsMainItem = {
|
|
169398
|
-
value: mainChoice.value,
|
|
169399
|
-
label: "Same as main",
|
|
169400
|
-
description: `default · ${mainChoice.label}`
|
|
169401
|
-
};
|
|
169402
|
-
const liteItems = [...liteCandidates, sameAsMainItem];
|
|
169403
|
-
const savedLiteIndex = liteItems.findIndex((item) => item.value === savedLite && item.value !== mainChoice.value);
|
|
169404
|
-
const liteChoice = await this.showChoice({
|
|
169405
|
-
title: `Select lite model · ${group.label}`,
|
|
169406
|
-
prompt: "The lite model handles quick tasks and tool summaries.",
|
|
169407
|
-
help: "Up/Down choose · Enter confirm · Esc back to main",
|
|
169408
|
-
items: liteItems,
|
|
169409
|
-
selectedIndex: savedLiteIndex >= 0 ? savedLiteIndex : liteItems.length - 1
|
|
169410
|
-
});
|
|
169411
|
-
if (!liteChoice) continue;
|
|
169412
|
-
try {
|
|
169413
|
-
await updateUserConfig((config) => {
|
|
169414
|
-
const model = isRecord(config.model) ? config.model : {};
|
|
169415
|
-
model.main = mainChoice.value;
|
|
169416
|
-
model.lite = liteChoice.value;
|
|
169417
|
-
config.model = model;
|
|
169418
|
-
});
|
|
169419
|
-
} catch (error) {
|
|
169420
|
-
this.addNotice(`Could not save model config: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
169421
|
-
continue;
|
|
169422
|
-
}
|
|
169423
|
-
this.addNotice(`Model config saved: main=${mainChoice.label}, lite=${liteChoice.label}.`, "muted");
|
|
169424
|
-
await this.applySettingCommand(`/model ${mainChoice.value}`, "model");
|
|
169425
|
-
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;
|
|
169426
168739
|
}
|
|
169427
|
-
|
|
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");
|
|
169428
168754
|
}
|
|
169429
168755
|
}
|
|
169430
168756
|
async showConfiguration() {
|
|
@@ -169480,8 +168806,7 @@ var ZCodeTui = class {
|
|
|
169480
168806
|
const methodOverride = Boolean(process.env.ZCODE_TUI_NOTIFICATION_METHOD?.trim());
|
|
169481
168807
|
const conditionOverride = Boolean(process.env.ZCODE_TUI_NOTIFICATION_CONDITION?.trim());
|
|
169482
168808
|
const tuiModeOverride = process.env.ZCODE_TUI_MODE?.trim().toLowerCase();
|
|
169483
|
-
const
|
|
169484
|
-
const savedModelLabel = typeof savedConfig?.main === "string" && savedConfig.main.trim() ? savedConfig.main : void 0;
|
|
168809
|
+
const savedModelLabel = await this.options.readDefaultModel?.().catch(() => void 0);
|
|
169485
168810
|
const setting = await this.showChoice({
|
|
169486
168811
|
title: "ZCode settings",
|
|
169487
168812
|
prompt: feedback,
|
|
@@ -169490,7 +168815,7 @@ var ZCodeTui = class {
|
|
|
169490
168815
|
{
|
|
169491
168816
|
value: "model-providers",
|
|
169492
168817
|
label: "Model providers",
|
|
169493
|
-
description: this.model === savedModelLabel
|
|
168818
|
+
description: savedModelLabel ? this.model === savedModelLabel ? `Saved: ${savedModelLabel}` : `Session: ${this.model} · Saved: ${savedModelLabel}` : `Session: ${this.model} · No saved default`
|
|
169494
168819
|
},
|
|
169495
168820
|
{
|
|
169496
168821
|
value: "notification-method",
|
|
@@ -169646,24 +168971,10 @@ var ZCodeTui = class {
|
|
|
169646
168971
|
}
|
|
169647
168972
|
}
|
|
169648
168973
|
async runFirstRunSetup(manual = false) {
|
|
169649
|
-
let desktop = null;
|
|
169650
|
-
try {
|
|
169651
|
-
desktop = await detectDesktopInstallation();
|
|
169652
|
-
} catch {
|
|
169653
|
-
desktop = null;
|
|
169654
|
-
}
|
|
169655
168974
|
const access = await readConfiguredModelAccess().catch(() => null);
|
|
169656
168975
|
const statusHint = access ? `Model access is already configured (${access.model}).` : "Model access is not configured yet.";
|
|
169657
168976
|
while (!this.stopped) {
|
|
169658
168977
|
const items = [];
|
|
169659
|
-
if (desktop) {
|
|
169660
|
-
const families = desktop.plan.families.map((entry) => entry.family).join("/");
|
|
169661
|
-
items.push({
|
|
169662
|
-
value: "import-desktop",
|
|
169663
|
-
label: "Import settings from ZCode desktop",
|
|
169664
|
-
description: `Copy desktop ${families} providers and model choices${desktop.plan.defaultFamily ? ` (selected: ${desktop.plan.defaultFamily})` : ""} · credentials are not copied`
|
|
169665
|
-
});
|
|
169666
|
-
}
|
|
169667
168978
|
items.push({
|
|
169668
168979
|
value: "sign-in",
|
|
169669
168980
|
label: "Sign in (OAuth or API key)",
|
|
@@ -169671,7 +168982,7 @@ var ZCodeTui = class {
|
|
|
169671
168982
|
}, {
|
|
169672
168983
|
value: customProviderHelpCommand,
|
|
169673
168984
|
label: "Custom provider",
|
|
169674
|
-
description: "Configure any supported endpoint in
|
|
168985
|
+
description: "Configure any supported endpoint in provider_config.json without signing in"
|
|
169675
168986
|
}, {
|
|
169676
168987
|
value: "skip",
|
|
169677
168988
|
label: "Skip for now",
|
|
@@ -169690,14 +169001,10 @@ var ZCodeTui = class {
|
|
|
169690
169001
|
}
|
|
169691
169002
|
if (selected.value === customProviderHelpCommand) {
|
|
169692
169003
|
await clearSetupPending().catch(() => {});
|
|
169693
|
-
|
|
169694
|
-
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");
|
|
169695
169005
|
return;
|
|
169696
169006
|
}
|
|
169697
|
-
if (selected.value === "
|
|
169698
|
-
if (!await this.importDesktopSettings(desktop)) continue;
|
|
169699
|
-
}
|
|
169700
|
-
if (selected.value === "sign-in" || selected.value === "import-desktop") await this.submit("/login");
|
|
169007
|
+
if (selected.value === "sign-in") await this.submit("/login");
|
|
169701
169008
|
if (await readConfiguredModelAccess().catch(() => null)) {
|
|
169702
169009
|
await clearSetupPending().catch(() => {});
|
|
169703
169010
|
this.setLoginRequired(false);
|
|
@@ -169707,54 +169014,6 @@ var ZCodeTui = class {
|
|
|
169707
169014
|
this.addNotice("Login did not produce model access · choose another method or skip.", "muted");
|
|
169708
169015
|
}
|
|
169709
169016
|
}
|
|
169710
|
-
async importDesktopSettings(desktop) {
|
|
169711
|
-
const plan = desktop.plan;
|
|
169712
|
-
if (plan.families.length === 0) return false;
|
|
169713
|
-
const family = plan.defaultFamily && plan.families.some((entry) => entry.family === plan.defaultFamily) ? plan.defaultFamily : plan.families[0].family;
|
|
169714
|
-
const familyPlan = plan.families.find((entry) => entry.family === family);
|
|
169715
|
-
const modelIds = familyPlan.models.map((model) => model.id).join(", ");
|
|
169716
|
-
const confirmed = await this.showChoice({
|
|
169717
|
-
title: "Import from ZCode desktop",
|
|
169718
|
-
prompt: `Import the desktop ${family} provider (${familyPlan.models.length} models: ${modelIds}) into your CLI config? A backup of the current config is saved first.`,
|
|
169719
|
-
help: "Enter import · Esc cancel",
|
|
169720
|
-
items: [{
|
|
169721
|
-
value: "import",
|
|
169722
|
-
label: `Import ${family} settings`,
|
|
169723
|
-
description: "Provider, baseURL and model list · no credentials"
|
|
169724
|
-
}, {
|
|
169725
|
-
value: "cancel",
|
|
169726
|
-
label: "Cancel",
|
|
169727
|
-
description: "Keep the current CLI configuration"
|
|
169728
|
-
}]
|
|
169729
|
-
});
|
|
169730
|
-
if (!confirmed || confirmed.value !== "import") return false;
|
|
169731
|
-
try {
|
|
169732
|
-
const result = await applyDesktopMigration(plan, { family });
|
|
169733
|
-
this.addNotice(`Imported desktop ${family} settings into ${result.configPath} (backup: ${basename(result.backupPath)}).`, "muted");
|
|
169734
|
-
} catch (error) {
|
|
169735
|
-
this.addNotice(`Desktop import failed: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
169736
|
-
return false;
|
|
169737
|
-
}
|
|
169738
|
-
if ((await this.showChoice({
|
|
169739
|
-
title: "Sign in to finish",
|
|
169740
|
-
prompt: `Desktop credentials cannot be copied. Sign in with the ${family} Coding Plan now to complete setup?`,
|
|
169741
|
-
help: "Enter select · Esc decide later",
|
|
169742
|
-
items: [{
|
|
169743
|
-
value: "now",
|
|
169744
|
-
label: "Sign in now (recommended)",
|
|
169745
|
-
description: "Opens the Coding Plan login picker"
|
|
169746
|
-
}, {
|
|
169747
|
-
value: "later",
|
|
169748
|
-
label: "Later",
|
|
169749
|
-
description: "Run /login whenever you are ready"
|
|
169750
|
-
}]
|
|
169751
|
-
}))?.value !== "now") {
|
|
169752
|
-
await clearSetupPending().catch(() => {});
|
|
169753
|
-
this.addNotice("Provider settings imported · run /login to sign in when ready.", "muted");
|
|
169754
|
-
return false;
|
|
169755
|
-
}
|
|
169756
|
-
return true;
|
|
169757
|
-
}
|
|
169758
169017
|
handleRewindEscape() {
|
|
169759
169018
|
if (this.rewindEscapePending) {
|
|
169760
169019
|
this.clearRewindEscape();
|
|
@@ -169919,22 +169178,59 @@ var ZCodeTui = class {
|
|
|
169919
169178
|
if (!this.shortcutAvailable()) return;
|
|
169920
169179
|
await this.applyModeShortcut(nextMode(this.mode));
|
|
169921
169180
|
}
|
|
169922
|
-
async applyModeShortcut(requestedMode) {
|
|
169181
|
+
async applyModeShortcut(requestedMode, announce = false) {
|
|
169923
169182
|
if (this.settingSwitchInFlight) return;
|
|
169924
169183
|
if (!this.options.setMode) {
|
|
169925
169184
|
this.addNotice("Mode switching is unavailable in this runtime.", "warning");
|
|
169926
169185
|
return;
|
|
169927
169186
|
}
|
|
169928
169187
|
this.settingSwitchInFlight = true;
|
|
169188
|
+
this.executionStateRevision++;
|
|
169929
169189
|
try {
|
|
169930
169190
|
const result = await this.options.setMode(requestedMode);
|
|
169931
|
-
|
|
169932
|
-
this.mode = normalizedMode(returnedMode, requestedMode);
|
|
169191
|
+
this.applyExecutionState(result);
|
|
169933
169192
|
this.updateMetadata();
|
|
169193
|
+
if (announce) this.addNotice(`Mode switched to ${this.mode}.`, "muted");
|
|
169934
169194
|
} catch (error) {
|
|
169935
169195
|
this.addNotice(error instanceof Error ? error.message : String(error), "error");
|
|
169936
169196
|
} finally {
|
|
169937
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));
|
|
169226
|
+
this.updateMetadata();
|
|
169227
|
+
this.addNotice(`Plan ${this.planEnabled ? "enabled" : "disabled"} · permission mode: ${this.mode}.`, "muted");
|
|
169228
|
+
} catch (error) {
|
|
169229
|
+
this.addNotice(error instanceof Error ? error.message : String(error), "error");
|
|
169230
|
+
} finally {
|
|
169231
|
+
this.settingSwitchInFlight = false;
|
|
169232
|
+
this.executionStateRevision++;
|
|
169233
|
+
this.scheduleRuntimeRefresh(0);
|
|
169938
169234
|
}
|
|
169939
169235
|
}
|
|
169940
169236
|
async switchModel() {
|
|
@@ -170230,6 +169526,7 @@ var ZCodeTui = class {
|
|
|
170230
169526
|
version: this.options.version,
|
|
170231
169527
|
model: this.model,
|
|
170232
169528
|
mode: this.mode,
|
|
169529
|
+
planEnabled: this.planEnabled,
|
|
170233
169530
|
effort: this.thoughtLevel,
|
|
170234
169531
|
workspace: this.options.workspaceDirectory ?? process.cwd(),
|
|
170235
169532
|
branch: this.options.workspaceGitBranch,
|
|
@@ -170247,6 +169544,36 @@ var ZCodeTui = class {
|
|
|
170247
169544
|
}]
|
|
170248
169545
|
});
|
|
170249
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
|
+
}
|
|
170250
169577
|
async readMcpSummary() {
|
|
170251
169578
|
if (!this.options.listMcpServers) return void 0;
|
|
170252
169579
|
try {
|
|
@@ -170637,7 +169964,18 @@ var ZCodeTui = class {
|
|
|
170637
169964
|
this.editor.addToHistory(input);
|
|
170638
169965
|
}
|
|
170639
169966
|
}
|
|
169967
|
+
async restoreCustomSessionTitle() {
|
|
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
|
+
}
|
|
170640
169977
|
async restoreInitialTranscript() {
|
|
169978
|
+
await this.restoreCustomSessionTitle();
|
|
170641
169979
|
if (this.options.loadSessionTranscript) try {
|
|
170642
169980
|
this.restoreTranscript(restoredMessages(await this.options.loadSessionTranscript()));
|
|
170643
169981
|
} catch (error) {
|
|
@@ -170646,19 +169984,26 @@ var ZCodeTui = class {
|
|
|
170646
169984
|
}
|
|
170647
169985
|
try {
|
|
170648
169986
|
const persistedModel = await this.options.readSessionModel?.();
|
|
170649
|
-
if (typeof persistedModel === "string"
|
|
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
|
+
}
|
|
170650
169992
|
} catch {}
|
|
170651
169993
|
}
|
|
170652
169994
|
updateMetadata() {
|
|
169995
|
+
this.editor.planEnabled = this.planEnabled;
|
|
170653
169996
|
const fields = [{
|
|
170654
169997
|
text: this.theme.muted(`◈ ${this.model}`),
|
|
170655
|
-
compactText: this.theme.muted(`◈ ${this.model}`),
|
|
169998
|
+
compactText: this.theme.muted(`◈ ${this.model.slice(this.model.indexOf("/") + 1)}`),
|
|
170656
169999
|
priority: 100,
|
|
170657
|
-
required: true
|
|
170000
|
+
required: true,
|
|
170001
|
+
minWidth: 3
|
|
170658
170002
|
}, {
|
|
170659
170003
|
text: this.theme.muted(`◉ ${this.mode}`),
|
|
170660
170004
|
compactText: this.theme.muted(`◉ ${this.mode}`),
|
|
170661
|
-
priority:
|
|
170005
|
+
priority: 100,
|
|
170006
|
+
required: true
|
|
170662
170007
|
}];
|
|
170663
170008
|
if (this.thoughtLevel) fields.push({
|
|
170664
170009
|
text: this.theme.muted(`⚡ ${this.thoughtLevel}`),
|
|
@@ -170802,6 +170147,7 @@ var ZCodeTui = class {
|
|
|
170802
170147
|
applyRuntimeProjection(projection) {
|
|
170803
170148
|
if (!projection) return;
|
|
170804
170149
|
this.runtimeProjection = projection;
|
|
170150
|
+
if (!this.settingSwitchInFlight) this.applyExecutionState(projection);
|
|
170805
170151
|
this.noticeRestoredBackgroundTasks(projection);
|
|
170806
170152
|
this.reconcileTurnTiming(projection);
|
|
170807
170153
|
if (projection.sessionId) this.sessionId = projection.sessionId;
|
|
@@ -170860,11 +170206,16 @@ var ZCodeTui = class {
|
|
|
170860
170206
|
try {
|
|
170861
170207
|
do {
|
|
170862
170208
|
this.runtimeRefreshPending = false;
|
|
170209
|
+
const executionStateRevision = this.executionStateRevision;
|
|
170863
170210
|
const [projectionResult, todosResult, contextMessagesResult] = await Promise.allSettled([
|
|
170864
170211
|
this.options.readRuntimeProjection?.(),
|
|
170865
170212
|
this.options.readTodos?.(),
|
|
170866
170213
|
this.options.readRuntimeProjection && this.options.loadSessionContextMessages ? this.options.loadSessionContextMessages() : Promise.resolve(void 0)
|
|
170867
170214
|
]);
|
|
170215
|
+
if (executionStateRevision !== this.executionStateRevision) {
|
|
170216
|
+
this.runtimeRefreshPending = true;
|
|
170217
|
+
continue;
|
|
170218
|
+
}
|
|
170868
170219
|
const next = {
|
|
170869
170220
|
projection: this.runtimeProjection,
|
|
170870
170221
|
todos: this.todos,
|
|
@@ -171004,7 +170355,6 @@ var ZCodeTui = class {
|
|
|
171004
170355
|
for (const controller of this.steerAbortControllers) controller.abort();
|
|
171005
170356
|
this.steerAbortControllers.clear();
|
|
171006
170357
|
this.updateCheckAbortController?.abort();
|
|
171007
|
-
this.modelCatalogRefresh?.stop();
|
|
171008
170358
|
if (this.turnTimer) clearInterval(this.turnTimer);
|
|
171009
170359
|
this.stopSessionTitleSpinner();
|
|
171010
170360
|
if (this.rewindEscapeTimer) clearTimeout(this.rewindEscapeTimer);
|