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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +35 -8
  2. package/bin/zcode.js +265 -133
  3. package/docs/CONFIGURATION.md +387 -0
  4. package/docs/CONFIGURATION.zh-CN.md +324 -0
  5. package/docs/PROVIDER_CONFIG.md +271 -0
  6. package/docs/PROVIDER_CONFIG.zh-CN.md +245 -0
  7. package/package.json +15 -6
  8. package/provider.example.json +151 -0
  9. package/{config.example.json → setting.example.json} +0 -47
  10. package/vendor/cli-config.cjs +161 -0
  11. package/vendor/extraction.json +17 -4
  12. package/vendor/node_modules/@zcode/tui/dist/index.js +495 -1095
  13. package/vendor/packages/browser-use-plugin/dist/mcp/server.js +35543 -34422
  14. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +2 -2
  15. package/vendor/packages/document-skills-plugin/package.json +4 -4
  16. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +34 -0
  17. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +9 -0
  18. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +11 -0
  19. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +7 -0
  20. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +7 -0
  21. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +10 -1
  22. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +19 -4
  23. package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/env_check.sh +6 -2
  24. package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup.md +12 -3
  25. package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup_mac_linux.sh +9 -3
  26. package/vendor/packages/document-skills-plugin/skills/pdf/env_setup/setup_windows.ps1 +8 -3
  27. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +30 -6
  28. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +9 -3
  29. package/vendor/packages/document-skills-plugin/skills/pptx/SKILL.md +33 -0
  30. package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup.md +29 -4
  31. package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup_mac_linux.sh +8 -3
  32. package/vendor/packages/document-skills-plugin/skills/xlsx/env_setup/setup_windows.ps1 +8 -3
  33. package/vendor/packages/document-skills-plugin/skills/xlsx/quality/pipeline.md +9 -0
  34. package/vendor/packages/document-skills-plugin/skills/xlsx/setup.sh +8 -3
  35. package/vendor/packages/document-skills-plugin/skills/xlsx/xlsx.py +15 -1
  36. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +13 -8
  37. package/vendor/provider/zcode-builtin.json +6296 -0
  38. package/vendor/zcode.cjs +1159 -840
  39. package/zcode-runtime.lock.json +3 -3
package/bin/zcode.js CHANGED
@@ -4,47 +4,12 @@ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameS
4
4
  import { constants, homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, join, posix, resolve, sep, win32 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
8
8
  import { access, chmod, link, mkdir, mkdtemp, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
9
9
  import { createInterface } from "node:readline/promises";
10
10
  import { parseArgs } from "node:util";
11
- //#region config.example.json
12
- var config_example_default = {
13
- provider: { "zai": {
14
- "kind": "anthropic",
15
- "name": "Z.AI Coding Plan",
16
- "options": {
17
- "apiKeyRequired": true,
18
- "baseURL": "https://api.z.ai/api/anthropic"
19
- },
20
- "headers": {},
21
- "models": {
22
- "glm-5.3": { "name": "GLM-5.3" },
23
- "glm-5.3-flash": {
24
- "name": "GLM-5.3-Flash",
25
- "limit": {
26
- "context": 1e6,
27
- "output": 128e3
28
- },
29
- "modalities": {
30
- "input": [
31
- "text",
32
- "image",
33
- "video"
34
- ],
35
- "output": ["text"]
36
- }
37
- },
38
- "glm-5.2": { "name": "GLM-5.2" },
39
- "glm-5.1": { "name": "GLM-5.1" },
40
- "glm-5-turbo": { "name": "GLM-5-Turbo" }
41
- }
42
- } },
43
- model: {
44
- "main": "zai/glm-5.2",
45
- "lite": "zai/glm-5-turbo"
46
- },
47
- modelCatalog: { "overrides": {} },
11
+ //#region setting.example.json
12
+ var setting_example_default = {
48
13
  modelStream: { "idleTimeoutMs": 6e4 },
49
14
  permission: {
50
15
  "mode": "build",
@@ -62,14 +27,11 @@ var config_example_default = {
62
27
  "compact": true,
63
28
  "rewind": true,
64
29
  "subagent": true,
65
- "memory": true,
66
30
  "skill": true,
67
31
  "mcp": true
68
32
  },
69
33
  subagents: { "autoBackgroundMs": 1e3 },
70
34
  memory: {
71
- "use": true,
72
- "write": true,
73
35
  "autoConsolidate": true,
74
36
  "summaryMaxBytes": 8192
75
37
  },
@@ -94,7 +56,6 @@ var config_example_default = {
94
56
  "format": "text"
95
57
  },
96
58
  ui: {
97
- "locale": "auto",
98
59
  "theme": "auto",
99
60
  "tuiMode": "regular",
100
61
  "copyOnSelect": true,
@@ -124,6 +85,45 @@ var config_example_default = {
124
85
  }
125
86
  };
126
87
  //#endregion
88
+ //#region src/config-paths.ts
89
+ function cliSettingsPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
90
+ const path = platform === "win32" ? win32 : posix;
91
+ const home = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim() || fallbackHome;
92
+ return path.join(home, ".zcode", "cli", "setting.json");
93
+ }
94
+ function desktopSettingsPath(env = process.env) {
95
+ return join(dirname(dirname(cliSettingsPath(env))), "v2", "setting.json");
96
+ }
97
+ function readDesktopSettings(env = process.env) {
98
+ try {
99
+ const value = JSON.parse(readFileSync(desktopSettingsPath(env), "utf8"));
100
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid settings object");
101
+ return value;
102
+ } catch (error) {
103
+ if (error.code === "ENOENT") return {};
104
+ throw new Error("Unable to read Desktop setting.json; the file was left unchanged.");
105
+ }
106
+ }
107
+ function sharedDataBaseDir(env = process.env, platform = process.platform, fallbackHome = homedir()) {
108
+ const home = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim() || fallbackHome;
109
+ const desktop = platform === process.platform ? readDesktopSettings(env).dataBaseDir : void 0;
110
+ return env.ZCODE_DATA_BASE_DIR?.trim() || typeof desktop === "string" && desktop.trim() || home;
111
+ }
112
+ function providerConfigPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
113
+ const path = platform === "win32" ? win32 : posix;
114
+ return env.ZCODE_PERSONAL_PROVIDER_CONFIG_FILE?.trim() || path.join(sharedDataBaseDir(env, platform, fallbackHome), ".zcode", "v2", "provider_config.json");
115
+ }
116
+ function legacyCliConfigPath(env = process.env) {
117
+ return join(dirname(cliSettingsPath(env)), "config.json");
118
+ }
119
+ function settingsMigrationMarkerPath(env = process.env) {
120
+ return join(dirname(cliSettingsPath(env)), "migrations", "settings-v1.json");
121
+ }
122
+ function providerMigrationMarkerPath(env = process.env) {
123
+ const target = createHash("sha256").update(providerConfigPath(env)).digest("hex").slice(0, 16);
124
+ return join(dirname(cliSettingsPath(env)), "migrations", `provider-registry-${target}.json`);
125
+ }
126
+ //#endregion
127
127
  //#region src/model-access.ts
128
128
  function isNodeError(error) {
129
129
  return error instanceof Error && "code" in error;
@@ -140,13 +140,24 @@ async function configFileExists(configPath) {
140
140
  throw error;
141
141
  }
142
142
  }
143
- function userConfigPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
144
- const path = platform === "win32" ? win32 : posix;
145
- const configuredHome = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim();
146
- return path.join(configuredHome || fallbackHome, ".zcode", "cli", "config.json");
143
+ async function finishSettingsMigration(env) {
144
+ const marker = settingsMigrationMarkerPath(env);
145
+ await mkdir(dirname(marker), {
146
+ recursive: true,
147
+ mode: 448
148
+ });
149
+ let file;
150
+ try {
151
+ file = await open(marker, "wx", 384);
152
+ await file.writeFile("{\"schemaVersion\":1}\n", "utf8");
153
+ } catch (error) {
154
+ if (!isNodeError(error) || error.code !== "EEXIST") throw error;
155
+ } finally {
156
+ await file?.close();
157
+ }
147
158
  }
148
- async function ensureUserConfig(env = process.env) {
149
- const configPath = userConfigPath(env);
159
+ async function ensureCliSettings(env = process.env) {
160
+ const configPath = cliSettingsPath(env);
150
161
  const configDirectory = dirname(configPath);
151
162
  try {
152
163
  await mkdir(configDirectory, {
@@ -156,15 +167,32 @@ async function ensureUserConfig(env = process.env) {
156
167
  } catch (error) {
157
168
  throw new Error(`Unable to create ZCode config directory ${configDirectory}: ${errorMessage(error)}`, { cause: error });
158
169
  }
159
- if (await configFileExists(configPath)) return {
160
- configPath,
161
- created: false
162
- };
170
+ if (await configFileExists(configPath)) {
171
+ await finishSettingsMigration(env);
172
+ return {
173
+ configPath,
174
+ created: false
175
+ };
176
+ }
177
+ let initial = setting_example_default;
178
+ let migrated = false;
179
+ try {
180
+ if (await configFileExists(settingsMigrationMarkerPath(env))) initial = setting_example_default;
181
+ else {
182
+ const legacy = JSON.parse(await readFile(legacyCliConfigPath(env), "utf8"));
183
+ if (!legacy || typeof legacy !== "object" || Array.isArray(legacy)) throw new Error("invalid legacy settings");
184
+ const { provider, model, modelCatalog, ...settings } = legacy;
185
+ initial = settings;
186
+ migrated = true;
187
+ }
188
+ } catch (error) {
189
+ if (!isNodeError(error) || error.code !== "ENOENT") throw new Error("Unable to migrate the old CLI config.json; the original file was preserved.");
190
+ }
163
191
  const temporaryPath = join(configDirectory, `.${basename(configPath)}.${process.pid}.${randomUUID()}.tmp`);
164
192
  let file;
165
193
  try {
166
194
  file = await open(temporaryPath, "wx", 384);
167
- await file.writeFile(`${JSON.stringify(config_example_default, null, 2)}\n`, "utf8");
195
+ await file.writeFile(`${JSON.stringify(initial, null, 2)}\n`, "utf8");
168
196
  await file.sync();
169
197
  } catch (error) {
170
198
  if (file) {
@@ -178,13 +206,16 @@ async function ensureUserConfig(env = process.env) {
178
206
  }
179
207
  try {
180
208
  await link(temporaryPath, configPath);
209
+ await finishSettingsMigration(env);
181
210
  return {
182
211
  configPath,
183
- created: true
212
+ created: true,
213
+ ...migrated ? { migrated: true } : {}
184
214
  };
185
215
  } catch (error) {
186
216
  if (isNodeError(error) && error.code === "EEXIST") {
187
217
  if (!await configFileExists(configPath)) throw new Error(`ZCode config path exists but is not a file: ${configPath}`);
218
+ await finishSettingsMigration(env);
188
219
  return {
189
220
  configPath,
190
221
  created: false
@@ -195,27 +226,66 @@ async function ensureUserConfig(env = process.env) {
195
226
  await rm(temporaryPath, { force: true }).catch(() => {});
196
227
  }
197
228
  }
229
+ async function readCliSettings(env = process.env) {
230
+ const { configPath } = await ensureCliSettings(env);
231
+ try {
232
+ const value = JSON.parse(await readFile(configPath, "utf8"));
233
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("the root value must be a JSON object");
234
+ return value;
235
+ } catch (error) {
236
+ throw new Error(`Unable to read ZCode config ${configPath}: ${errorMessage(error)}`, { cause: error });
237
+ }
238
+ }
239
+ function record$1(value) {
240
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
241
+ }
242
+ /** Configuration presence only; the runtime owns credential decryption and authentication. */
198
243
  async function readConfiguredModelAccess(env = process.env) {
199
- const configPath = userConfigPath(env);
200
- let config;
244
+ const directory = join(sharedDataBaseDir(env), ".zcode", "v2");
245
+ const configPath = providerConfigPath(env);
246
+ let value;
201
247
  try {
202
- config = JSON.parse(await readFile(configPath, "utf8"));
203
- } catch {
248
+ value = JSON.parse(await readFile(configPath, "utf8"));
249
+ } catch (error) {
204
250
  return null;
205
251
  }
206
- const model = typeof config.model?.main === "string" ? config.model.main.trim() : "";
207
- const separator = model.indexOf("/");
208
- if (separator <= 0 || separator === model.length - 1) return null;
209
- const providerId = model.slice(0, separator);
210
- const modelId = model.slice(separator + 1);
211
- const provider = config.provider?.[providerId];
212
- const apiKey = provider?.options?.apiKey;
213
- if (!provider?.models?.[modelId] || typeof apiKey !== "string" || !apiKey.trim()) return null;
214
- return {
252
+ const root = record$1(value), config = record$1(root?.config);
253
+ if (root?.schemaVersion !== 1 || !config) return null;
254
+ const selection = record$1(config.defaultModelSelection);
255
+ const providerId = typeof selection?.providerId === "string" ? selection.providerId.trim() : "";
256
+ const modelId = typeof selection?.modelId === "string" ? selection.modelId.trim() : "";
257
+ if (!providerId || !modelId) return null;
258
+ const result = {
215
259
  configPath,
216
- model,
260
+ model: `${providerId}/${modelId}`,
217
261
  providerId
218
262
  };
263
+ if (providerId.startsWith("account:")) try {
264
+ const credentials = record$1(JSON.parse(await readFile(join(directory, "credentials.json"), "utf8")));
265
+ const identity = credentials?.[`account-provider:${providerId}:identity`];
266
+ const keyPrefix = `account-provider:coding-plan:${providerId}:account:`;
267
+ 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;
268
+ } catch {
269
+ return null;
270
+ }
271
+ const rules = record$1(config.providerConfigRules)?.providerRules;
272
+ if (!Array.isArray(rules)) return null;
273
+ const settings = record$1(rules.map(record$1).find((rule) => rule?.providerId === providerId)?.config), access = record$1(settings?.access);
274
+ return settings?.visibility !== "hidden" && typeof access?.apiKey === "string" && access.apiKey.trim() && (!Array.isArray(settings?.personalModelIds) || settings.personalModelIds.includes(modelId)) ? result : null;
275
+ }
276
+ /** A native personal provider can be usable without a saved default selection. */
277
+ async function hasConfiguredProviderAccess(env = process.env) {
278
+ if (await readConfiguredModelAccess(env)) return true;
279
+ try {
280
+ const value = record$1(JSON.parse(await readFile(providerConfigPath(env), "utf8")));
281
+ const rules = record$1(record$1(value?.config)?.providerConfigRules)?.providerRules;
282
+ return value?.schemaVersion === 1 && Array.isArray(rules) && rules.some((raw) => {
283
+ const rule = record$1(raw), config = record$1(rule?.config), access = record$1(config?.access);
284
+ 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);
285
+ });
286
+ } catch {
287
+ return false;
288
+ }
219
289
  }
220
290
  function setupPendingPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
221
291
  const path = platform === "win32" ? win32 : posix;
@@ -257,6 +327,11 @@ async function clearSetupPending(env = process.env) {
257
327
  await rm(setupPendingPath(env), { force: true }).catch(() => {});
258
328
  }
259
329
  //#endregion
330
+ //#region src/runtime-config-bridge.ts
331
+ function providerMigrationNeeded(env = process.env) {
332
+ return existsSync(legacyCliConfigPath(env)) && !existsSync(providerMigrationMarkerPath(env));
333
+ }
334
+ //#endregion
260
335
  //#region src/command.ts
261
336
  async function readText(stream) {
262
337
  if (!stream) return "";
@@ -690,10 +765,41 @@ var AppServerRequestError = class extends Error {
690
765
  this.name = "AppServerRequestError";
691
766
  }
692
767
  };
693
- function cancellationError() {
694
- const error = /* @__PURE__ */ new Error("App-server request cancelled.");
695
- error.name = "AbortError";
696
- return error;
768
+ var AppServerProcessError = class extends Error {
769
+ exitCode;
770
+ constructor(message, exitCode) {
771
+ super(message);
772
+ this.exitCode = exitCode;
773
+ this.name = "AppServerProcessError";
774
+ }
775
+ };
776
+ var AppServerCancellationError = class extends Error {
777
+ exitCode;
778
+ constructor(exitCode) {
779
+ super("App-server request cancelled.");
780
+ this.exitCode = exitCode;
781
+ this.name = "AbortError";
782
+ }
783
+ };
784
+ function signalExitCode$1(signal) {
785
+ if (!signal) return 1;
786
+ const number = constants.signals[signal];
787
+ return typeof number === "number" ? 128 + number : 1;
788
+ }
789
+ function abortSignalName$1(signal) {
790
+ const reason = signal?.reason;
791
+ return reason === "SIGINT" || reason === "SIGTERM" || reason === "SIGHUP" ? reason : void 0;
792
+ }
793
+ function cancellationError(signal) {
794
+ const signalName = abortSignalName$1(signal);
795
+ if (signalName) return new AppServerCancellationError(signalExitCode$1(signalName));
796
+ return new AppServerCancellationError(130);
797
+ }
798
+ function terminationSignal(signal) {
799
+ return abortSignalName$1(signal) ?? "SIGTERM";
800
+ }
801
+ function processError(message, code) {
802
+ return new AppServerProcessError(message, code);
697
803
  }
698
804
  async function readBounded(stream, onOverflow) {
699
805
  if (!stream) return "";
@@ -723,7 +829,7 @@ function responseEnvelope(stdout) {
723
829
  }
724
830
  }
725
831
  async function requestAppServer(request) {
726
- if (request.signal?.aborted) throw cancellationError();
832
+ if (request.signal?.aborted) throw cancellationError(request.signal);
727
833
  const child = spawn(request.transport.command, request.transport.args, {
728
834
  cwd: request.transport.cwd,
729
835
  env: request.transport.env,
@@ -748,7 +854,7 @@ async function requestAppServer(request) {
748
854
  launchError = error;
749
855
  finish(1);
750
856
  });
751
- child.once("close", (code) => finish(code ?? 1));
857
+ child.once("close", (code, signal) => finish(code ?? signalExitCode$1(signal)));
752
858
  });
753
859
  const terminateForOverflow = () => {
754
860
  overflow = true;
@@ -756,7 +862,7 @@ async function requestAppServer(request) {
756
862
  };
757
863
  const onAbort = () => {
758
864
  if (child.exitCode !== null || child.signalCode !== null) return;
759
- child.kill("SIGTERM");
865
+ child.kill(terminationSignal(request.signal));
760
866
  forceTerminationTimer = setTimeout(() => {
761
867
  if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
762
868
  }, forceTerminationDelayMilliseconds);
@@ -776,12 +882,12 @@ async function requestAppServer(request) {
776
882
  readBounded(child.stdout, terminateForOverflow),
777
883
  readBounded(child.stderr, terminateForOverflow)
778
884
  ]);
779
- if (request.signal?.aborted) throw cancellationError();
885
+ if (request.signal?.aborted) throw cancellationError(request.signal);
780
886
  if (overflow) throw new Error(`App-server output exceeded ${maximumOutputBytes} bytes.`);
781
887
  if (launchError) throw launchError;
782
888
  const envelope = responseEnvelope(stdout);
783
889
  if (envelope?.error) throw new AppServerRequestError(envelope.error.message?.trim() || "App-server request failed.", envelope.error.code, envelope.error.data);
784
- if (code !== 0) throw new Error(stderr.trim() || `App-server exited with status ${code}.`);
890
+ if (code !== 0) throw processError(stderr.trim() || `App-server exited with status ${code}.`, code);
785
891
  if (!envelope || !("result" in envelope)) throw new Error(stderr.trim() || "App-server did not return a response envelope.");
786
892
  return envelope.result;
787
893
  } finally {
@@ -1284,6 +1390,7 @@ async function runPluginCommand(args, options) {
1284
1390
  throw new Error(pluginUsage);
1285
1391
  } catch (error) {
1286
1392
  stderr.write(`Error: ${printableError(error)}\n`);
1393
+ if (error instanceof AppServerCancellationError || error instanceof AppServerProcessError) return error.exitCode;
1287
1394
  return error instanceof Error && error.name === "AbortError" ? 130 : 1;
1288
1395
  }
1289
1396
  }
@@ -1315,21 +1422,27 @@ async function missingCodingPlanKey(options = {}) {
1315
1422
  if (parent === directory) break;
1316
1423
  directory = parent;
1317
1424
  }
1318
- let config;
1425
+ 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.`;
1426
+ let root;
1319
1427
  try {
1320
- config = record(JSON.parse(await readFile(userConfigPath(env), "utf8")));
1321
- } catch {
1322
- return;
1428
+ root = record(JSON.parse(await readFile(providerConfigPath(env), "utf8")));
1429
+ } catch (error) {
1430
+ return error.code === "ENOENT" && !options.model ? message() : void 0;
1323
1431
  }
1324
- const model = options.model ?? record(config?.model)?.main;
1325
- if (typeof model !== "string") return void 0;
1326
- const providerId = model.split("/", 1)[0];
1327
- if (providerId !== "zai" && providerId !== "bigmodel") return void 0;
1328
- const provider = record(record(config?.provider)?.[providerId]);
1329
- const settings = record(provider?.options);
1330
- const expectedUrl = providerId === "zai" ? "https://api.z.ai/api/anthropic" : "https://open.bigmodel.cn/api/anthropic";
1331
- 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(provider.headers) ?? {}).length > 0) return void 0;
1332
- 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.`;
1432
+ const config = record(root?.config);
1433
+ if (root?.schemaVersion !== 1 || !config) return void 0;
1434
+ const selection = record(config.defaultModelSelection);
1435
+ const model = options.model ?? (typeof selection?.providerId === "string" && typeof selection.modelId === "string" ? `${selection.providerId}/${selection.modelId}` : void 0);
1436
+ if (!model) return await hasConfiguredProviderAccess(env) ? void 0 : message();
1437
+ const separator = model.indexOf("/");
1438
+ if (separator <= 0) return void 0;
1439
+ const providerId = model.slice(0, separator), modelId = model.slice(separator + 1);
1440
+ if (providerId.startsWith("account:")) return void 0;
1441
+ const rules = record(config.providerConfigRules)?.providerRules;
1442
+ if (!Array.isArray(rules)) return void 0;
1443
+ const settings = record(rules.map(record).find((rule) => rule?.providerId === providerId)?.config), auth = record(settings?.access), api = record(settings?.api);
1444
+ 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(api?.headers) ?? {}).length > 0 || Array.isArray(settings.personalModelIds) && !settings.personalModelIds.includes(modelId)) return void 0;
1445
+ return message(providerId);
1333
1446
  }
1334
1447
  //#endregion
1335
1448
  //#region src/runtime-capabilities.ts
@@ -1375,30 +1488,6 @@ const versionArguments = /* @__PURE__ */ new Set([
1375
1488
  "-v"
1376
1489
  ]);
1377
1490
  const runtimeVariadicOptions = /* @__PURE__ */ new Set(["--disallowedTools", "--disallowed-tools"]);
1378
- const fallbackRuntimeOptionTypes = {
1379
- attach: "string",
1380
- "browser-executable": "string",
1381
- "browser-use": "string",
1382
- continue: "boolean",
1383
- cwd: "string",
1384
- force: "boolean",
1385
- "force-mcs": "boolean",
1386
- help: "boolean",
1387
- json: "boolean",
1388
- locale: "string",
1389
- mode: "string",
1390
- "no-browser": "boolean",
1391
- "no-color": "boolean",
1392
- "output-format": "string",
1393
- prompt: "string",
1394
- resume: "string",
1395
- stdio: "boolean",
1396
- surface: "string",
1397
- target: "string",
1398
- "target-replace": "boolean",
1399
- verbose: "boolean",
1400
- version: "boolean"
1401
- };
1402
1491
  function resolveModelRetryMaxRetries(env) {
1403
1492
  return env.ZCODE_MODEL_RETRY_MAX_RETRIES?.trim() || defaultModelRetryMaxRetries;
1404
1493
  }
@@ -1422,10 +1511,10 @@ function readJsonVersion(path, key) {
1422
1511
  function readRuntimeCliOptionTypes(metadataPath = extractionMetadataPath) {
1423
1512
  try {
1424
1513
  const capabilities = capabilitiesFromExtractionMetadata(JSON.parse(readFileSync(metadataPath, "utf8")));
1425
- if (!capabilities) return fallbackRuntimeOptionTypes;
1514
+ if (!capabilities) throw new Error("Invalid capability manifest");
1426
1515
  return Object.fromEntries(Object.entries(capabilities.cli.globalOptions).map(([name, option]) => [name, option.type]));
1427
1516
  } catch {
1428
- return fallbackRuntimeOptionTypes;
1517
+ throw new Error("Runtime capability metadata is missing or invalid; sync the current runtime before launching.");
1429
1518
  }
1430
1519
  }
1431
1520
  function readDistributionVersion(manifestPath = packageManifestPath) {
@@ -1573,6 +1662,7 @@ function firstRunSetupEnv(setupPending, args) {
1573
1662
  function runtimeEnvironment(extra = {}) {
1574
1663
  const env = { ...process.env };
1575
1664
  delete env.ZCODE_CLI_OAUTH_CALLBACK_STDIN;
1665
+ delete env.ZCODE_CLI_MIGRATE_CONFIG;
1576
1666
  const distributionVersion = readDistributionVersion();
1577
1667
  const inherited = {
1578
1668
  ...env,
@@ -1580,6 +1670,7 @@ function runtimeEnvironment(extra = {}) {
1580
1670
  };
1581
1671
  const merged = {
1582
1672
  ...inherited,
1673
+ ZCODE_DATA_BASE_DIR: sharedDataBaseDir(inherited),
1583
1674
  ZCODE_BASE_URL: resolveZCodeBaseUrl(inherited),
1584
1675
  ZCODE_MODEL_RETRY_MAX_RETRIES: resolveModelRetryMaxRetries(inherited),
1585
1676
  ZCODE_APP_CLI_EXECUTABLE: process.execPath,
@@ -1593,6 +1684,13 @@ function signalExitCode(signal) {
1593
1684
  const number = constants.signals[signal];
1594
1685
  return typeof number === "number" ? 128 + number : 1;
1595
1686
  }
1687
+ function abortSignalName(signal) {
1688
+ const reason = signal.reason;
1689
+ return reason === "SIGINT" || reason === "SIGTERM" || reason === "SIGHUP" ? reason : void 0;
1690
+ }
1691
+ function abortSignalExitCode(signal) {
1692
+ return signalExitCode(abortSignalName(signal) ?? "SIGINT");
1693
+ }
1596
1694
  async function waitForChild(child, onError = (error) => console.error("Error: " + error.message)) {
1597
1695
  return await new Promise((resolveExit) => {
1598
1696
  let settled = false;
@@ -1681,7 +1779,7 @@ async function runRuntime(node, args, extraEnv = {}) {
1681
1779
  }
1682
1780
  }
1683
1781
  async function completeOfficialZaiLogin(node, payload, runtimeArgs, abortSignal) {
1684
- if (abortSignal.aborted) return 130;
1782
+ if (abortSignal.aborted) return abortSignalExitCode(abortSignal);
1685
1783
  const child = spawn(node, [runtimePath, ...runtimeArgs], {
1686
1784
  cwd: process.cwd(),
1687
1785
  env: runtimeEnvironment({ ZCODE_CLI_OAUTH_CALLBACK_STDIN: "1" }),
@@ -1691,7 +1789,7 @@ async function completeOfficialZaiLogin(node, payload, runtimeArgs, abortSignal)
1691
1789
  "inherit"
1692
1790
  ]
1693
1791
  });
1694
- const onAbort = () => child.kill("SIGINT");
1792
+ const onAbort = () => child.kill(abortSignalName(abortSignal) ?? "SIGINT");
1695
1793
  abortSignal.addEventListener("abort", onAbort, { once: true });
1696
1794
  try {
1697
1795
  child.stdin?.end(JSON.stringify(payload));
@@ -1717,7 +1815,10 @@ async function main(args) {
1717
1815
  }
1718
1816
  let setupPending = false;
1719
1817
  try {
1720
- if ((await ensureUserConfig()).created) {
1818
+ const bootstrap = await ensureCliSettings();
1819
+ await readCliSettings();
1820
+ sharedDataBaseDir();
1821
+ if (bootstrap.created && !bootstrap.migrated) {
1721
1822
  await markSetupPending();
1722
1823
  setupPending = true;
1723
1824
  } else setupPending = await readSetupPending();
@@ -1726,10 +1827,35 @@ async function main(args) {
1726
1827
  return 1;
1727
1828
  }
1728
1829
  const node = resolveNodeExecutable();
1830
+ if (providerMigrationNeeded()) try {
1831
+ await new Promise((resolve, reject) => {
1832
+ const child = spawn(node, [runtimePath, "--version"], {
1833
+ env: runtimeEnvironment({ ZCODE_CLI_MIGRATE_CONFIG: "1" }),
1834
+ stdio: [
1835
+ "ignore",
1836
+ "ignore",
1837
+ "pipe"
1838
+ ]
1839
+ });
1840
+ let error = "";
1841
+ child.stderr?.on("data", (chunk) => {
1842
+ error = `${error}${chunk}`.slice(-4096);
1843
+ });
1844
+ child.once("error", reject);
1845
+ child.once("close", (code) => code === 0 ? resolve() : reject(new Error(error.trim() || "Provider migration failed.")));
1846
+ });
1847
+ } catch (error) {
1848
+ console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
1849
+ return 1;
1850
+ }
1729
1851
  const pluginAbortController = new AbortController();
1730
- const cancelPluginCommand = () => pluginAbortController.abort();
1731
- process.once("SIGINT", cancelPluginCommand);
1732
- process.once("SIGTERM", cancelPluginCommand);
1852
+ const cancelPluginCommand = (signal) => () => pluginAbortController.abort(signal);
1853
+ const onPluginSigint = cancelPluginCommand("SIGINT");
1854
+ const onPluginSigterm = cancelPluginCommand("SIGTERM");
1855
+ const onPluginSighup = cancelPluginCommand("SIGHUP");
1856
+ process.once("SIGINT", onPluginSigint);
1857
+ process.once("SIGTERM", onPluginSigterm);
1858
+ if (process.platform !== "win32") process.once("SIGHUP", onPluginSighup);
1733
1859
  let pluginCommand;
1734
1860
  try {
1735
1861
  pluginCommand = await runPluginCommand(args, {
@@ -1747,24 +1873,29 @@ async function main(args) {
1747
1873
  signal: pluginAbortController.signal
1748
1874
  });
1749
1875
  } finally {
1750
- process.off("SIGINT", cancelPluginCommand);
1751
- process.off("SIGTERM", cancelPluginCommand);
1876
+ process.off("SIGINT", onPluginSigint);
1877
+ process.off("SIGTERM", onPluginSigterm);
1878
+ if (process.platform !== "win32") process.off("SIGHUP", onPluginSighup);
1752
1879
  }
1753
1880
  if (pluginCommand !== void 0) return pluginCommand;
1754
1881
  const login = normalizeLoginArgs(args);
1755
1882
  const zaiOAuth = classifyZaiOAuthInvocation(args);
1756
1883
  if (login.checkConfiguredAccess) {
1757
1884
  const access = await readConfiguredModelAccess();
1758
- if (access) {
1759
- console.log(`Model access is already configured for ${access.model}; OAuth login is not required.\nConfig: ${access.configPath}\nRun \`zcode login --oauth\` to force Z.AI OAuth.`);
1885
+ if (access || await hasConfiguredProviderAccess()) {
1886
+ console.log(`Model access is already configured${access ? ` for ${access.model}` : ""}; OAuth login is not required.\nConfig: ${access?.configPath ?? providerConfigPath()}\nRun \`zcode login --oauth\` to force Z.AI OAuth.`);
1760
1887
  return 0;
1761
1888
  }
1762
1889
  }
1763
1890
  if (zaiOAuth) {
1764
1891
  const abortController = new AbortController();
1765
- const cancel = () => abortController.abort(/* @__PURE__ */ new Error("Login cancelled."));
1766
- process.once("SIGINT", cancel);
1767
- process.once("SIGTERM", cancel);
1892
+ const cancel = (signal) => () => abortController.abort(signal);
1893
+ const onSigint = cancel("SIGINT");
1894
+ const onSigterm = cancel("SIGTERM");
1895
+ const onSighup = cancel("SIGHUP");
1896
+ process.once("SIGINT", onSigint);
1897
+ process.once("SIGTERM", onSigterm);
1898
+ if (process.platform !== "win32") process.once("SIGHUP", onSighup);
1768
1899
  try {
1769
1900
  const code = await runZaiOAuthLogin({
1770
1901
  abortSignal: abortController.signal,
@@ -1776,14 +1907,15 @@ async function main(args) {
1776
1907
  return code;
1777
1908
  } catch (error) {
1778
1909
  console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
1779
- return abortController.signal.aborted ? 130 : 1;
1910
+ return abortController.signal.aborted ? abortSignalExitCode(abortController.signal) : 1;
1780
1911
  } finally {
1781
- process.off("SIGINT", cancel);
1782
- process.off("SIGTERM", cancel);
1912
+ process.off("SIGINT", onSigint);
1913
+ process.off("SIGTERM", onSigterm);
1914
+ if (process.platform !== "win32") process.off("SIGHUP", onSighup);
1783
1915
  }
1784
1916
  }
1785
1917
  try {
1786
- const diagnostic = await promptPreflight(login.args);
1918
+ const diagnostic = await readConfiguredModelAccess() ? void 0 : await promptPreflight(login.args);
1787
1919
  if (diagnostic) {
1788
1920
  console.error(diagnostic);
1789
1921
  return 1;