@zhushanwen/zcode-subagent-cli 0.4.1 → 0.4.2

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.
@@ -3,7 +3,7 @@ var ZCODE_ENGINE_ID = "zcode";
3
3
  var ZCODE_ADAPTER_VERSION = "2.0.0";
4
4
  var ZCODE_CLI_DEFAULT_PATH = "/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs";
5
5
  var ZCODE_V2_CONFIG_PATH_SUFFIX = [".zcode", "v2", "config.json"];
6
- var ZCODE_FALLBACK_DEFAULT_MODEL = "builtin:bigmodel-coding-plan/GLM-5.3";
6
+ var ZCODE_PERSONAL_PROVIDER_CONFIG_PATH_SUFFIX = [".zcode", "v2", "provider_config.json"];
7
7
  var ZCODE_KILL_GRACE_MS = 5e3;
8
8
  var ZCODE_ERROR_TAIL_CHARS = 2e3;
9
9
  var ZCODE_APPSERVER_REQUEST_TIMEOUT_MS = 15e3;
@@ -390,11 +390,11 @@ var ZcodePrepareError = class extends Error {
390
390
  function isRecord(v) {
391
391
  return typeof v === "object" && v !== null && !Array.isArray(v);
392
392
  }
393
- function isProviderEntry(v) {
394
- return isRecord(v);
393
+ function strArray(v) {
394
+ return Array.isArray(v) ? v.filter((m) => typeof m === "string" && m.trim() !== "") : [];
395
395
  }
396
396
  function readSourceConfig(absPath) {
397
- const empty = { providers: /* @__PURE__ */ new Map() };
397
+ const empty = { providers: /* @__PURE__ */ new Map(), order: [] };
398
398
  let raw;
399
399
  try {
400
400
  raw = fs2.readFileSync(absPath, "utf8");
@@ -408,15 +408,30 @@ function readSourceConfig(absPath) {
408
408
  return empty;
409
409
  }
410
410
  if (!isRecord(parsed)) return empty;
411
- const conf = { providers: /* @__PURE__ */ new Map() };
412
- const provider = parsed["provider"];
413
- if (isRecord(provider)) {
414
- for (const [id, entry] of Object.entries(provider)) {
415
- if (isProviderEntry(entry)) conf.providers.set(id, entry);
416
- }
417
- }
411
+ const rules = parsed["config"]?.["providerConfigRules"];
412
+ const providerRules = !isRecord(rules) ? void 0 : rules["providerRules"];
413
+ const orderSrc = parsed["config"]?.["providerOrder"];
414
+ const conf = { providers: /* @__PURE__ */ new Map(), order: strArray(orderSrc) };
415
+ if (!Array.isArray(providerRules)) return conf;
416
+ collectProviderRules(providerRules, conf);
418
417
  return conf;
419
418
  }
419
+ function collectProviderRules(providerRules, conf) {
420
+ for (const rule of providerRules) {
421
+ if (!isRecord(rule)) continue;
422
+ const id = rule["providerId"];
423
+ if (typeof id !== "string" || id.trim() === "") continue;
424
+ const cfg = isRecord(rule["config"]) ? rule["config"] : {};
425
+ const access = isRecord(cfg["access"]) ? cfg["access"] : {};
426
+ const apiKey = access["apiKey"];
427
+ const personal = strArray(cfg["personalModelIds"]);
428
+ conf.providers.set(id, {
429
+ providerName: typeof rule["providerName"] === "string" ? rule["providerName"] : void 0,
430
+ apiKey: typeof apiKey === "string" && apiKey !== "" ? apiKey : void 0,
431
+ models: personal.length > 0 ? personal : strArray(cfg["modelOrder"])
432
+ });
433
+ }
434
+ }
420
435
  function modelShort(ref) {
421
436
  return ref.slice(ref.lastIndexOf("/") + 1);
422
437
  }
@@ -427,63 +442,148 @@ function splitZcodeModelRef(modelRef) {
427
442
  return { providerId: providerOf(modelRef), modelId: modelShort(modelRef) };
428
443
  }
429
444
  function hasApiKey(entry) {
430
- const key = entry.options?.apiKey;
431
- return typeof key === "string" && key !== "";
445
+ return typeof entry.apiKey === "string" && entry.apiKey !== "";
446
+ }
447
+ function defaultPersonalProviderConfigPath() {
448
+ return path2.join(os2.homedir(), ...ZCODE_PERSONAL_PROVIDER_CONFIG_PATH_SUFFIX);
432
449
  }
433
450
  function defaultV2ConfigPath() {
434
451
  return path2.join(os2.homedir(), ...ZCODE_V2_CONFIG_PATH_SUFFIX);
435
452
  }
436
- var DEFAULT_PROVIDER_ID = "builtin:bigmodel-coding-plan";
437
- function defaultProviderForShortName(merged, withKey) {
438
- if (merged.has(DEFAULT_PROVIDER_ID)) return DEFAULT_PROVIDER_ID;
453
+ var SEMVER_SEGMENTS = 3;
454
+ function locateZcodeBuiltinCatalog(sources) {
455
+ if (sources?.builtinCatalogPath !== void 0) return sources.builtinCatalogPath;
456
+ const fromEnv = process.env["ZCODE_BUILTIN_PROVIDER_CONFIG_FILE"]?.trim();
457
+ if (fromEnv !== void 0 && fromEnv !== "") return fromEnv;
458
+ try {
459
+ const providerRoot = path2.join(os2.homedir(), ".zcode", "v2", "runtime", "provider");
460
+ const prefix = `${process.platform}-`;
461
+ const platDirs = fs2.readdirSync(providerRoot, { withFileTypes: true }).filter((d) => d.isDirectory() && d.name.startsWith(prefix)).map((d) => d.name);
462
+ const byVerDesc = (a, b) => {
463
+ const pa = a.split(".");
464
+ const pb = b.split(".");
465
+ for (let i = 0; i < SEMVER_SEGMENTS; i++) {
466
+ const na = Number.parseInt(pa[i] ?? "", 10) || 0;
467
+ const nb = Number.parseInt(pb[i] ?? "", 10) || 0;
468
+ if (na !== nb) return nb - na;
469
+ }
470
+ return 0;
471
+ };
472
+ for (const plat of platDirs) {
473
+ const rtRoot = path2.join(providerRoot, plat);
474
+ let versions = [];
475
+ try {
476
+ versions = fs2.readdirSync(rtRoot).filter((v) => /^\d+\.\d+/.test(v)).sort(byVerDesc);
477
+ } catch {
478
+ continue;
479
+ }
480
+ for (const ver of versions) {
481
+ const verDir = path2.join(rtRoot, ver);
482
+ let endpoints = [];
483
+ try {
484
+ endpoints = fs2.readdirSync(verDir).filter((e) => e.startsWith("endpoint-")).sort();
485
+ } catch {
486
+ continue;
487
+ }
488
+ for (const ep of endpoints) {
489
+ const candidate = path2.join(verDir, ep, "zcode-builtin.json");
490
+ if (fs2.existsSync(candidate)) return candidate;
491
+ }
492
+ }
493
+ }
494
+ } catch {
495
+ return void 0;
496
+ }
497
+ return void 0;
498
+ }
499
+ function resolveZcodeMinimalReasoningLevel(modelRef, sources) {
500
+ const catalogPath = locateZcodeBuiltinCatalog(sources);
501
+ if (catalogPath === void 0) return void 0;
502
+ let parsed;
503
+ try {
504
+ parsed = JSON.parse(fs2.readFileSync(catalogPath, "utf8"));
505
+ } catch {
506
+ return void 0;
507
+ }
508
+ const modelId = modelShort(modelRef);
509
+ const rules = parsed["config"];
510
+ const modelRules = isRecord(rules) && isRecord(rules["modelConfigRules"]) ? rules["modelConfigRules"]["modelRules"] : void 0;
511
+ if (!Array.isArray(modelRules)) return void 0;
512
+ return lastMatchingReasoningValues(modelRules, modelId)?.[0];
513
+ }
514
+ function lastMatchingReasoningValues(modelRules, modelId) {
515
+ let values;
516
+ for (const rule of modelRules) {
517
+ if (!isRecord(rule)) continue;
518
+ const match = rule["modelMatch"];
519
+ if (typeof match !== "string") continue;
520
+ let re;
521
+ try {
522
+ re = new RegExp(match);
523
+ } catch {
524
+ continue;
525
+ }
526
+ if (!re.test(modelId)) continue;
527
+ const spec = rule["config"]?.["optionSpecs"];
528
+ const level = isRecord(spec) ? spec["reasoningLevel"] : void 0;
529
+ const vals = isRecord(level) ? strArray(level["values"]) : [];
530
+ if (vals.length > 0) values = vals;
531
+ }
532
+ return values;
533
+ }
534
+ function defaultProviderForShortName(conf, withKey) {
535
+ const ordered = conf.order.find((id) => {
536
+ const entry = conf.providers.get(id);
537
+ return entry !== void 0 && hasApiKey(entry);
538
+ });
539
+ if (ordered !== void 0) return ordered;
439
540
  return withKey[0][0];
440
541
  }
441
542
  function resolveZcodeModelRef(requested, sources) {
442
- const v2 = readSourceConfig(sources?.v2ConfigPath ?? defaultV2ConfigPath());
443
- const merged = v2.providers;
444
- const withKey = [...merged.entries()].filter(([, e]) => hasApiKey(e));
543
+ const srcPath = sources?.personalProviderConfigPath ?? defaultPersonalProviderConfigPath();
544
+ const conf = readSourceConfig(srcPath);
545
+ const withKey = [...conf.providers.entries()].filter(([, e]) => hasApiKey(e));
445
546
  const wanted = requested?.trim() || void 0;
446
- const target = wanted ?? ZCODE_FALLBACK_DEFAULT_MODEL;
447
547
  if (withKey.length === 0) {
448
- const hint = wanted ? `model="${wanted}" \u4E0D\u80FD\u6821\u9A8C` : `\u9ED8\u8BA4\u6A21\u578B "${target}" \u4E0D\u80FD\u6821\u9A8C`;
548
+ const hint = wanted ? `model="${wanted}" \u4E0D\u80FD\u6821\u9A8C` : "\u7F3A\u7701\u6A21\u578B\u89E3\u6790\u4E0D\u80FD\u6821\u9A8C";
449
549
  throw new ZcodePrepareError(
450
550
  "engine_credential_missing",
451
- `zcode \u5F15\u64CE\u627E\u4E0D\u5230\u4EFB\u4F55\u5E26 apiKey \u7684 provider\uFF08${hint}\uFF09\u3002\u5DF2\u8BFB\u6E90\uFF1A${sources?.v2ConfigPath ?? defaultV2ConfigPath()}\u3002\u6062\u590D\u6307\u5F15\uFF1A\u5148\u5728 ZCode \u684C\u9762\u7AEF\u767B\u5F55\u5E76\u914D\u7F6E provider\uFF08v2 config \u5185\u5B58\u5728\u542B apiKey \u7684\u6761\u76EE\uFF09\u540E\u91CD\u8BD5\uFF1B\u51ED\u636E\u914D\u7F6E\u8BF4\u660E\u89C1 docs/research/agent-engine-zcode.md\u3002`
551
+ `zcode \u5F15\u64CE\u627E\u4E0D\u5230\u4EFB\u4F55\u5E26 apiKey \u7684\u4E2A\u4EBA provider\uFF08${hint}\uFF09\u3002\u5DF2\u8BFB\u6E90\uFF1A${srcPath}\u3002\u6062\u590D\u6307\u5F15\uFF1A\u5728 ZCode \u684C\u9762\u7AEF\u914D\u7F6E\u81F3\u5C11\u4E00\u4E2A\u4E2A\u4EBA provider\uFF08provider_config.json \u5185\u5B58\u5728 config.access.apiKey \u975E\u7A7A\u6761\u76EE\uFF09\u540E\u91CD\u8BD5\uFF1Bplan \u5957\u9910\u65CF\uFF08builtin:/account: \u524D\u7F00\uFF09\u7ECF\u8D26\u53F7 entitlement \u95E8\u63A7\uFF0C\u5916\u90E8 spawn \u7684\u5F15\u64CE\u6CE8\u518C\u8868\u4E0D\u88C5\u8F7D\uFF0C\u4E0D\u53EF\u4F5C\u4E3A\u5F15\u64CE\u6A21\u578B\u3002`
452
552
  );
453
553
  }
454
- const provider = target.includes("/") ? providerOf(target) : defaultProviderForShortName(merged, withKey);
455
- const short = modelShort(target);
456
- const entry = merged.get(provider);
554
+ if (wanted === void 0) return "";
555
+ const provider = wanted.includes("/") ? providerOf(wanted) : defaultProviderForShortName(conf, withKey);
556
+ const short = modelShort(wanted);
557
+ const entry = conf.providers.get(provider);
457
558
  if (!entry) {
458
559
  const known = withKey.map(([id]) => id).join(", ");
459
560
  throw new ZcodePrepareError(
460
561
  "model_not_available",
461
- `\u672A\u77E5 provider "${provider}"\uFF08\u5E26\u51ED\u636E\u7684 provider: ${known}\uFF09\u3002\u6062\u590D\u6307\u5F15\uFF1A\u6539\u7528\u4E0A\u8FF0 provider \u4E4B\u4E00\uFF08\u5168\u540D provider/model\uFF09\uFF0C\u6216\u5148\u5728 ZCode \u684C\u9762\u7AEF\u914D\u7F6E\u8BE5 provider \u540E\u91CD\u8BD5\u3002`
562
+ `\u672A\u77E5 provider "${provider}"\uFF08\u5E26\u51ED\u636E\u7684\u4E2A\u4EBA provider: ${known}\uFF09\u3002\u6062\u590D\u6307\u5F15\uFF1A\u6539\u7528\u4E0A\u8FF0 provider \u4E4B\u4E00\uFF08\u5168\u540D provider/model\uFF09\uFF0C\u6216\u5728 ZCode \u684C\u9762\u7AEF\u914D\u7F6E\u8BE5 provider \u540E\u91CD\u8BD5\uFF1B\u7701\u7565 model \u53C2\u6570\u5219\u8D70\u5F15\u64CE\u7F3A\u7701\u89E3\u6790\uFF08CLI \u81EA\u8EAB\u9009\u53D6\u53EF\u7528\u6A21\u578B\uFF09\u3002`
462
563
  );
463
564
  }
464
565
  if (!hasApiKey(entry)) {
465
566
  throw new ZcodePrepareError(
466
567
  "engine_credential_missing",
467
- `provider "${provider}" \u5B58\u5728\u4F46\u672A\u914D\u7F6E apiKey\u3002\u6062\u590D\u6307\u5F15\uFF1A\u5728 ZCode \u684C\u9762\u7AEF\u4E3A\u8BE5 provider \u767B\u5F55\u914D\u7F6E\u51ED\u636E\uFF0C\u6216\u6539\u7528\u5DF2\u914D\u51ED\u636E\u7684 provider\uFF08${withKey.map(([id]) => id).join(", ")}\uFF09\u540E\u91CD\u8BD5\u3002`
568
+ `provider "${provider}" \u5B58\u5728\u4F46\u672A\u914D\u7F6E apiKey\u3002\u6062\u590D\u6307\u5F15\uFF1A\u5728 ZCode \u684C\u9762\u7AEF\u4E3A\u8BE5 provider \u914D\u7F6E\u51ED\u636E\uFF0C\u6216\u6539\u7528\u5DF2\u914D\u51ED\u636E\u7684 provider\uFF08${withKey.map(([id]) => id).join(", ")}\uFF09\u540E\u91CD\u8BD5\u3002`
468
569
  );
469
570
  }
470
- const models = Object.keys(entry.models ?? {});
571
+ const models = entry.models ?? [];
471
572
  if (models.length > 0 && !models.includes(short)) {
472
573
  throw new ZcodePrepareError(
473
574
  "model_not_available",
474
- `\u672A\u77E5\u6A21\u578B "${short}"\uFF08provider ${provider} \u4E0B\u53EF\u7528: ${models.join(", ")}\uFF09\u3002\u6062\u590D\u6307\u5F15\uFF1A\u6539\u7528\u8BE5 provider \u4E0B\u7684\u6A21\u578B\uFF0C\u6216\u5148\u5728 ZCode \u684C\u9762\u7AEF\u542F\u7528\u76EE\u6807\u6A21\u578B\u540E\u91CD\u8BD5\u3002`
575
+ `\u672A\u77E5\u6A21\u578B "${short}"\uFF08provider ${provider} \u4E0B\u53EF\u7528: ${models.join(", ")}\uFF09\u3002\u6062\u590D\u6307\u5F15\uFF1A\u6539\u7528\u8BE5 provider \u4E0B\u7684\u6A21\u578B\uFF0C\u6216\u5728 ZCode \u684C\u9762\u7AEF\u542F\u7528\u76EE\u6807\u6A21\u578B\u540E\u91CD\u8BD5\u3002`
475
576
  );
476
577
  }
477
578
  return `${provider}/${short}`;
478
579
  }
479
580
  function listZcodeModels(sources) {
480
- const v2 = readSourceConfig(sources?.v2ConfigPath ?? defaultV2ConfigPath());
581
+ const conf = readSourceConfig(sources?.personalProviderConfigPath ?? defaultPersonalProviderConfigPath());
481
582
  const out = [];
482
- for (const [pid, entry] of v2.providers) {
583
+ for (const [pid, entry] of conf.providers) {
483
584
  if (!hasApiKey(entry)) continue;
484
- const providerName = typeof entry["name"] === "string" && entry["name"].trim() !== "" ? entry["name"].trim() : void 0;
485
- const models = Object.keys(entry.models ?? {});
486
- for (const model of models) {
585
+ const providerName = entry.providerName !== void 0 && entry.providerName.trim() !== "" ? entry.providerName.trim() : void 0;
586
+ for (const model of entry.models ?? []) {
487
587
  out.push({
488
588
  id: `${pid}/${model}`,
489
589
  ...providerName !== void 0 ? { name: `${providerName} \xB7 ${model}` } : {}
@@ -511,13 +611,13 @@ const os = require('node:os');
511
611
  const CLI_PATH = process.env.ZCODE_ENG_CLI_PATH;
512
612
  const V2_PATH = process.env.ZCODE_ENG_V2_CONFIG || path.join(os.homedir(), '.zcode', 'v2', 'config.json');
513
613
  const CONFIG_PATH = path.join(os.homedir(), '.zcode', 'cli', 'config.json');
514
- // \u4E0E constants.ts ZCODE_FALLBACK_DEFAULT_MODEL \u53CC\u6E90\uFF08\u5185\u5D4C\u5B57\u7B26\u4E32\u65E0\u6CD5 import\uFF09\u2014\u2014\u6539\u90A3\u8FB9\u987B\u540C\u6B65\u6B64\u5904
515
- const FALLBACK_MODEL_MAIN = 'builtin:bigmodel-coding-plan/GLM-5.3';
516
614
 
517
615
  // \u5408\u5E76\u5F62\u6001\uFF1A\u771F\u5B9E cli config \u539F\u6837\uFF08model/plugins/mcp/subagents \u7B49 worker \u7EE7\u627F\u9762\u4E0D\u53D8\uFF09
518
616
  // + v2 \u7684 provider \u5B57\u5178\u6CE8\u5165\uFF0C\u540C id \u65F6 v2 \u6761\u76EE\u6574\u6761\u4F18\u5148\u2014\u2014GUI \u76F4\u4F20 modelConfig \u65F6
519
617
  // v2 \u5373\u6743\u5A01\u6E90\uFF08\u8FDB\u7A0B\u5916\u7B49\u4EF7\u590D\u523B\uFF09\uFF1Bcli config \u4E0D\u5728 GUI \u7BA1\u7406\u9762\u3001\u53EF\u80FD\u6B8B\u7559\u5386\u53F2\u9A8C\u8BC1
520
618
  // \u914D\u7F6E\uFF082026-08-25 \u4E8B\u6545\uFF1A\u6B8B\u7559\u65E7 key \u538B\u8FC7\u65B0\u51ED\u636E\u81F4 turn 0 401\uFF09\uFF0C\u6545\u4E0D\u53D6 real \u4F18\u5148\u3002
619
+ // model.main \u7F3A\u5931\u65F6\u53EA\u4ECE v2 \u900F\u4F20\uFF08v2 \u4E5F\u6CA1\u6709\u5219\u4E0D\u4F2A\u9020\u2014\u2014CLI \u7F3A\u7701\u89E3\u6790\u81EA\u4F1A\u843D\u5230\u6CE8\u518C\u8868
620
+ // \u53EF\u7528\u6A21\u578B\uFF1Bplan \u5BB6\u65CF id \u5DF2\u4E0D\u53EF\u7528\uFF0C\u4E0D\u518D\u515C\u5E95\u4F2A\u9020\uFF09\u3002
521
621
  // \u8FD4\u56DE null = \u65E0\u53EF\u6CE8\u5165\u51ED\u636E\uFF08v2 \u65E0 provider \u6761\u76EE\uFF09\u2014\u2014\u4E0D patch\uFF0C\u8BA9\u539F\u751F\u62A5\u9519\u900F\u51FA\u3002
522
622
  // \u8BFB\u6E90\u7ECF readOrig \u95F4\u63A5\u53D6\uFF1Apatch \u524D\u9996\u8C03 = fs.readFileSync \u672C\u4F53\uFF1Bpatch \u540E = \u539F\u51FD\u6570
523
623
  // \uFF08\u9632 patch \u540E\u7684\u9012\u5F52\u81EA\u8C03\u7528\uFF09\u3002
@@ -545,9 +645,9 @@ function injectedConfigText() {
545
645
  if (Object.keys(injectable).length === 0) return null;
546
646
  const merged = { ...real };
547
647
  merged.provider = { ...(real.provider && typeof real.provider === 'object' ? real.provider : {}), ...injectable };
548
- if (!merged.model || typeof merged.model !== 'object' || !merged.model.main) {
549
- const main = (v2.model && v2.model.main) || FALLBACK_MODEL_MAIN;
550
- merged.model = { ...(merged.model || {}), main };
648
+ if ((!merged.model || typeof merged.model !== 'object' || !merged.model.main)
649
+ && v2.model && typeof v2.model === 'object' && v2.model.main) {
650
+ merged.model = { ...(merged.model || {}), main: v2.model.main };
551
651
  }
552
652
  return JSON.stringify(merged);
553
653
  }
@@ -645,6 +745,23 @@ if (!process.env.ZCODE_BUILTIN_PROVIDER_CONFIG_FILE) {
645
745
  }
646
746
  } catch { /* provider \u76EE\u5F55\u7F3A\u5931/\u4E0D\u53EF\u8BFB \u2192 \u4E0D\u8BBE\u952E */ }
647
747
  if (located) process.env.ZCODE_BUILTIN_PROVIDER_CONFIG_FILE = located;
748
+ // endpoint origin \u5BF9\u9F50\uFF082026-09-29 \u8FC1\u79FB\u540C\u6B65\uFF09\uFF1ACLI \u6309 ZCODE_BASE_URL \u6D3E\u751F active
749
+ // \u76EE\u5F55\u8DEF\u5F84\uFF08sha256(origin) \u524D\u7F00\uFF09\uFF1BGUI \u5B89\u88C5\u7684\u76EE\u5F55\u5728 refresh \u63A7\u5236\u6587\u4EF6\u7684 endpointKey
750
+ // \u4E0B\uFF08\u5982 https://zcode.z.ai\uFF09\uFF0C\u4E0E CLI \u7F3A\u7701 origin\uFF08bigmodel.cn\uFF09\u4E0D\u540C\u2014\u2014\u4E0D\u6CE8\u5165\u5219
751
+ // active \u8DEF\u5F84\u7B97\u5230\u4E0D\u5B58\u5728\u7684\u76EE\u5F55\uFF0C\u89E6\u53D1\u65E0\u8C13\u7684\u8054\u7F51\u91CD\u88C5\u5C1D\u8BD5\u3002\u4ECE\u5DF2\u5B9A\u4F4D\u76EE\u5F55\u7684\u90BB\u4F4D\u63A7\u5236
752
+ // \u6587\u4EF6\u8BFB\u51FA origin \u6CE8\u5165\uFF08\u65E0\u786C\u7F16\u7801\uFF09\uFF1B\u663E\u5F0F env \u4F18\u5148\uFF0C\u4E0D\u8986\u76D6\u3002
753
+ if (located && !process.env.ZCODE_BASE_URL && !process.env.ZCODE_ENDPOINT_ORIGIN) {
754
+ try {
755
+ const ctlPath = path.join(path.dirname(located), 'zcode-builtin-refresh.json');
756
+ const ctlText = fs.__origReadFileSync
757
+ ? fs.__origReadFileSync.call(fs, ctlPath, 'utf8')
758
+ : fs.readFileSync(ctlPath, 'utf8');
759
+ const ctl = JSON.parse(ctlText);
760
+ if (ctl && typeof ctl.endpointKey === 'string' && ctl.endpointKey.indexOf('http') === 0) {
761
+ process.env.ZCODE_BASE_URL = ctl.endpointKey;
762
+ }
763
+ } catch { /* \u63A7\u5236\u6587\u4EF6\u7F3A\u5931/\u635F\u574F \u2192 \u4E0D\u6CE8\u5165\uFF08CLI \u7528\u7F3A\u7701 origin \u6D3E\u751F\uFF09 */ }
764
+ }
648
765
  }
649
766
 
650
767
  // \u4E0A\u6E38 provider bootstrap \u4EE5 argv[1] \u4E3A\u5165\u53E3\u951A\uFF0C\u4ECE\u8BE5\u8DEF\u5F84\u90BB\u8FD1\u5B9A\u4F4D CLI \u5185\u5EFA
@@ -2163,7 +2280,8 @@ var ZcodeEngine = class {
2163
2280
  */
2164
2281
  async attemptAppServerTurn(task, ctx, modelRef, cwd, prompt, opts = {}) {
2165
2282
  const rt = this.ensureAppServerRuntime();
2166
- const createParams = buildAppServerCreateParams(task, modelRef, cwd);
2283
+ const reasoningLevel = modelRef !== void 0 && modelRef !== "" ? this.minimalReasoningFor(modelRef) : void 0;
2284
+ const createParams = buildAppServerCreateParams(task, modelRef, cwd, reasoningLevel);
2167
2285
  let currentSessionId;
2168
2286
  let signalSessionCreated;
2169
2287
  const sessionCreated = new Promise((resolve2) => {
@@ -2204,26 +2322,52 @@ var ZcodeEngine = class {
2204
2322
  if (ctx.signal?.aborted === true) return abortedAppServerAttempt(ctx);
2205
2323
  return parsedAppServerAttempt(task, r);
2206
2324
  } catch (err) {
2207
- if (ctx.signal?.aborted === true) return abortedAppServerAttempt(ctx);
2208
- if (err instanceof TurnTimeoutError) {
2209
- const stopPath = await this.appServerAbortChain(
2210
- rt,
2211
- turn,
2212
- () => currentSessionId,
2213
- sessionCreated,
2214
- { escalateOn: "stop-outcome" }
2215
- );
2216
- return timeoutAppServerAttempt(err, currentSessionId, stopPath, { retried: opts.retried });
2217
- }
2218
- if (!isAppServerRpcError(err) && !rt.conn.alive) {
2219
- return failedAppServerAttempt(err, currentSessionId, { retried: opts.retried, transient: "conn-closed" });
2220
- }
2221
- return failedAppServerAttempt(err, currentSessionId, { retried: opts.retried });
2325
+ return await this.classifyAppServerTurnFailure(err, ctx, {
2326
+ rt,
2327
+ turn,
2328
+ currentSessionId: () => currentSessionId,
2329
+ sessionCreated,
2330
+ retried: opts.retried
2331
+ });
2222
2332
  } finally {
2223
2333
  if (currentSessionId !== void 0) rt.activeSessions.delete(currentSessionId);
2224
2334
  if (ctx.signal !== void 0) ctx.signal.removeEventListener("abort", onAbort);
2225
2335
  }
2226
2336
  }
2337
+ /**
2338
+ * [attemptAppServerTurn 拆分] 失败分流(catch 半边):
2339
+ * - signal 已 aborted → 中止终态收口;
2340
+ * - [P0-1 U2] 超时入口(D3 v1.1):turn 已被 channel 判死 reject——升级判据不能
2341
+ * 再挂在 turn 落定上(race 恒真,killChain 结构性不可达的 v1 击穿点),改以
2342
+ * stop 应答三态裁决。await 链终局(非 fire-and-forget):outcome 止损文案与
2343
+ * 重试时序(D6,u-z4)都依赖链终局信号——止损完成前不合成终态。timeout 类
2344
+ * (idle/ceiling 都算)是 D6 明文的可重试形态——结构化标记
2345
+ * (TurnTimeoutError 类型化判据,不经字符串匹配,D4 同精神);
2346
+ * - [P0-1 U4] 连接崩溃收割形态(failAllTurns 的错误,D6 第二可重试形态)判据:
2347
+ * 非 RPC error(服务端无明确应答——有应答即精确错误归类,非瞬时崩溃面)且
2348
+ * conn 不存活。时序可靠性:catch 时刻紧随 onClose 收割,连接重建仅由
2349
+ * conn.request 惰性触发——本链路中 runTurn finally 的 closeSession 对死连接
2350
+ * 短路(channel 侧 !alive 守卫)、stop 只属 abort/超时入口(前者已被
2351
+ * signal.aborted 短路、后者走上一分支)——此刻无 request 可重建,判据可靠;
2352
+ * - 其余 → 精确错误终态。
2353
+ */
2354
+ async classifyAppServerTurnFailure(err, ctx, args) {
2355
+ if (ctx.signal?.aborted === true) return abortedAppServerAttempt(ctx);
2356
+ if (err instanceof TurnTimeoutError) {
2357
+ const stopPath = await this.appServerAbortChain(
2358
+ args.rt,
2359
+ args.turn,
2360
+ args.currentSessionId,
2361
+ args.sessionCreated,
2362
+ { escalateOn: "stop-outcome" }
2363
+ );
2364
+ return timeoutAppServerAttempt(err, args.currentSessionId(), stopPath, { retried: args.retried });
2365
+ }
2366
+ if (!isAppServerRpcError(err) && !args.rt.conn.alive) {
2367
+ return failedAppServerAttempt(err, args.currentSessionId(), { retried: args.retried, transient: "conn-closed" });
2368
+ }
2369
+ return failedAppServerAttempt(err, args.currentSessionId(), { retried: args.retried });
2370
+ }
2227
2371
  /**
2228
2372
  * killChain 后等待连接 finalize 实际完成(child 置空 + onClose 广播)再宣告链终局:
2229
2373
  * shutdown resolve 于 `exit` 事件,而 finalize 挂 `close`(stdio 排空)——两者之间的
@@ -2478,10 +2622,21 @@ var ZcodeEngine = class {
2478
2622
  }
2479
2623
  for (const ev of synthesizeCoarseEvents(payload.response, payload.usage)) emit(ev);
2480
2624
  }
2481
- /** [U7] 模型可发现性:v2 桌面登录态聚合(带凭据 provider × models),失败安全返回清单本身可能为空。 */
2625
+ /** [U7] 模型可发现性:provider_config 个人 provider 聚合(注册表实况对齐源),失败安全返回清单本身可能为空。 */
2482
2626
  listModels() {
2483
2627
  return listZcodeModels(this.deps.sources);
2484
2628
  }
2629
+ /** 显式模型的最小 reasoning 档(目录 modelRules 值域;per-modelRef 记忆化——
2630
+ * 目录文件在引擎进程生命周期内视为静态,重复 run 不重读)。 */
2631
+ reasoningMemo = /* @__PURE__ */ new Map();
2632
+ minimalReasoningFor(modelRef) {
2633
+ const memoKey = `${locateZcodeBuiltinCatalog(this.deps.sources) ?? "none"}|${modelRef}`;
2634
+ const hit = this.reasoningMemo.get(memoKey);
2635
+ if (hit !== void 0 || this.reasoningMemo.has(memoKey)) return hit;
2636
+ const level = resolveZcodeMinimalReasoningLevel(modelRef, this.deps.sources);
2637
+ this.reasoningMemo.set(memoKey, level);
2638
+ return level;
2639
+ }
2485
2640
  /**
2486
2641
  * [u-h2 D2-2] 派发同步期 model 校验:委托 resolveZcodeModelRef(与 run prepare 期
2487
2642
  * 显式路径同一函数——canonicalRef 归一化、短名缺省 provider、凭据与清单校验单一
@@ -2490,11 +2645,11 @@ var ZcodeEngine = class {
2490
2645
  *
2491
2646
  * [R4/D6-②] 缺席语义:本实现是进程内形态 + 协议诊断面(宿主 cli 形态消费的是
2492
2647
  * RemoteEngine 的 manifest 本地判定,不经本方法——SDK protocol methods.ts 明示
2493
- * validateModel 为诊断面)。缺席 modelRef 时返回 ZCODE_FALLBACK_DEFAULT_MODEL
2494
- * canonical 全名作为「引擎缺省模型」的呈现值(诊断面只读不 create,不参与
2495
- * create 缺席不携带的 G3 行为链)。帧应答形态维持 {canonicalRef: string}(SDK
2496
- * port-contract 契约必填——「帧字段缺席」的 optional 对齐需放宽 SDK 契约与
2497
- * server handler 签名,非本包单方面可完成)。
2648
+ * validateModel 为诊断面)。缺席 modelRef 时返回空串 canonical(= create 帧省略
2649
+ * model 键、CLI 自身缺省解析——2026-09-29 account 体系迁移后 plan 家族兜底 id
2650
+ * 已不可用;record 留痕侧按 R4/D6-② 空串归一为「用户未指定」条件留空)。帧应答
2651
+ * 形态维持 {canonicalRef: string}(SDK port-contract 契约必填——「帧字段缺席」
2652
+ * 的 optional 对齐需放宽 SDK 契约与 server handler 签名,非本包单方面可完成)。
2498
2653
  */
2499
2654
  validateModel(modelRef) {
2500
2655
  return { canonicalRef: resolveZcodeModelRef(modelRef, this.deps.sources) };
@@ -2770,10 +2925,13 @@ function appendSchemaRetryDirective(basePrompt, validationError) {
2770
2925
  Your previous answer failed schema validation: ${validationError}
2771
2926
  Answer again. Output ONLY the JSON value conforming to the schema above \u2014 no prose, no markdown fences, no extra text.`;
2772
2927
  }
2773
- function buildAppServerCreateParams(task, modelRef, cwd) {
2928
+ function buildAppServerCreateParams(task, modelRef, cwd, reasoningLevel) {
2774
2929
  const denyTools = (task.denyTools ?? []).filter((t) => typeof t === "string" && t.trim() !== "");
2775
2930
  const thoughtLevel = task.thinkingLevel?.trim();
2776
- const model = modelRef !== void 0 && modelRef !== "" ? splitZcodeModelRef(modelRef) : void 0;
2931
+ const model = modelRef !== void 0 && modelRef !== "" ? {
2932
+ ...splitZcodeModelRef(modelRef),
2933
+ ...reasoningLevel !== void 0 && reasoningLevel !== "" ? { options: { reasoningLevel } } : {}
2934
+ } : void 0;
2777
2935
  return {
2778
2936
  workspacePath: cwd,
2779
2937
  mode: "yolo",
@@ -2920,6 +3078,7 @@ function createDefaultZcodeEngine() {
2920
3078
  import {
2921
3079
  ENGINE_PROTOCOL_VERSION,
2922
3080
  EngineSdkError,
3081
+ getLogger as getLogger5,
2923
3082
  isResponseFrame,
2924
3083
  isReverseRequestFrame
2925
3084
  } from "@zhushanwen/subagent-engine-sdk";
@@ -2928,6 +3087,7 @@ import {
2928
3087
  import { parseCtxModel } from "@zhushanwen/subagent-engine-sdk";
2929
3088
 
2930
3089
  // src/server.ts
3090
+ var logger5 = getLogger5("subagents");
2931
3091
  var REVERSE_TIMEOUT_DEFAULT_MS = 6e4;
2932
3092
  var EngineProtocolServer = class {
2933
3093
  write;
@@ -3041,22 +3201,23 @@ var EngineProtocolServer = class {
3041
3201
  ...ctx.cwd !== void 0 ? { cwd: ctx.cwd } : {}
3042
3202
  };
3043
3203
  const ctxModel = parseCtxModel(ctx.ctxModel);
3044
- const stream = ctx.streamMode === "stream" ? { onDelta: (delta) => {
3045
- void this.reverseRequestInternal("host/streamDelta", { runId, delta });
3046
- } } : void 0;
3204
+ const stream = ctx.streamMode === "stream" ? {
3205
+ onDelta: (delta) => {
3206
+ void this.reverseRequestInternal("host/streamDelta", { runId, delta }).catch(this.warnReverseFailure("host/streamDelta", `run ${runId}`));
3207
+ }
3208
+ } : void 0;
3047
3209
  const runCtx = {
3048
3210
  taskId: runId,
3049
3211
  signal: controller.signal,
3050
3212
  onEvent: (event) => this.emitEvent(runId, event),
3051
3213
  ...ctxModel !== void 0 ? { ctxModel } : {},
3052
3214
  ...stream !== void 0 ? { stream } : {},
3053
- ...ctx.schemaEnv !== void 0 ? { schemaEnv: ctx.schemaEnv } : {},
3054
3215
  ...ctx.engineFallback !== void 0 ? { engineFallback: ctx.engineFallback } : {},
3055
3216
  // [U6 / §3.2.6 要点 3] resume 锚点透传(宿主 → 引擎的续聊通道:zcode 锚
3056
3217
  // sessionRef {sessionId, dbPath},引擎侧 resume 读 + 新 session 注入消费)。
3057
3218
  ...params.resume !== void 0 ? { resume: params.resume } : {},
3058
3219
  onHandleReady: (partial) => {
3059
- void this.reverseRequestInternal("host/handleReady", { runId, sessionRef: partial.sessionRef });
3220
+ void this.reverseRequestInternal("host/handleReady", { runId, sessionRef: partial.sessionRef }).catch(this.warnReverseFailure("host/handleReady", `run ${runId}`));
3060
3221
  }
3061
3222
  };
3062
3223
  try {
@@ -3096,6 +3257,19 @@ var EngineProtocolServer = class {
3096
3257
  * 应答超时兜底 reject——数据面通道(host/log 等)core 10s 应答,reject 由调用方
3097
3258
  * 吞掉留痕(数据面丢失不拖死主链路)。
3098
3259
  */
3260
+ /**
3261
+ * fire-and-forget 反向请求(`void this.reverseRequestInternal(...)` 形态)的
3262
+ * rejection 兜底:60s 超时(reverseRequestInternal 计时器)或宿主 error 帧
3263
+ * (settleReverse)都会 reject——无 handler 即 unhandled rejection(Node ≥15
3264
+ * 默认崩引擎进程)。失败只降级该次通道上报,warn 留痕不断流。
3265
+ */
3266
+ warnReverseFailure(method, context) {
3267
+ return (err) => {
3268
+ logger5.warn(`[protocol] ${method} reverse request failed (${context}); continuing without it`, {
3269
+ detail: toErrorMessage(err)
3270
+ });
3271
+ };
3272
+ }
3099
3273
  /** 反向请求发送(公开面:main.ts 的 host/log 桥接消费;内部 run 通道同路)。 */
3100
3274
  reverseRequest(method, params) {
3101
3275
  return this.reverseRequestInternal(method, params);
@@ -3111,7 +3285,14 @@ var EngineProtocolServer = class {
3111
3285
  if (typeof timer.unref === "function") timer.unref();
3112
3286
  this.reversePending.set(id, { resolve: resolve2, reject, timer });
3113
3287
  this.reverseClock?.started(id);
3114
- this.write({ id, method, params });
3288
+ try {
3289
+ this.write({ id, method, params });
3290
+ } catch (err) {
3291
+ this.reversePending.delete(id);
3292
+ clearTimeout(timer);
3293
+ this.reverseClock?.settled(id);
3294
+ reject(new Error(`reverse request ${method} (${id}) could not be written: ${toErrorMessage(err)}`));
3295
+ }
3115
3296
  });
3116
3297
  }
3117
3298
  /** 反向请求应答落位(ack 两阶段:{ack:true}/{unsupported:true}/{ok:true} 均先 ack 计时面)。 */