@zhushanwen/zcode-subagent-cli 0.4.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,16 +11,6 @@ var ZCODE_APPSERVER_STDERR_TAIL_CHARS = 400;
11
11
  var ZCODE_APPSERVER_STDERR_TAIL_BUFFER_CHARS = 2048;
12
12
  var ZCODE_APPSERVER_TURN_READ_TIMEOUT_MS = 5e3;
13
13
  var ZCODE_APPSERVER_TURN_CLOSE_TIMEOUT_MS = 1500;
14
- var ZCODE_TURN_IDLE_TIMEOUT_ENV = "TAIJI_ZCODE_TURN_IDLE_TIMEOUT_MS";
15
- var ZCODE_TURN_MAX_TIMEOUT_ENV = "TAIJI_ZCODE_TURN_MAX_TIMEOUT_MS";
16
- var ZCODE_TURN_IDLE_TIMEOUT_MS = 18e5;
17
- var ZCODE_TURN_MAX_TIMEOUT_MS = 36e5;
18
- function parseZcodeTurnTimeoutEnv(raw) {
19
- if (raw === void 0 || raw === "") return { state: "unset" };
20
- const parsed = Number(raw);
21
- if (!Number.isFinite(parsed)) return { state: "invalid" };
22
- return { state: "valid", ms: parsed };
23
- }
24
14
  var ZCODE_APPSERVER_STOP_TIMEOUT_MS = 3e3;
25
15
  var ZCODE_APPSERVER_ABORT_GRACE_MS = 3e3;
26
16
  var ZCODE_APPSERVER_STOP_TIMEOUT_ENV = "TAIJI_ZCODE_TEST_STOP_TIMEOUT_MS";
@@ -610,6 +600,7 @@ const os = require('node:os');
610
600
 
611
601
  const CLI_PATH = process.env.ZCODE_ENG_CLI_PATH;
612
602
  const V2_PATH = process.env.ZCODE_ENG_V2_CONFIG || path.join(os.homedir(), '.zcode', 'v2', 'config.json');
603
+ const PROVIDER_CONFIG_PATH = process.env.ZCODE_ENG_PROVIDER_CONFIG || path.join(os.homedir(), '.zcode', 'v2', 'provider_config.json');
613
604
  const CONFIG_PATH = path.join(os.homedir(), '.zcode', 'cli', 'config.json');
614
605
 
615
606
  // \u5408\u5E76\u5F62\u6001\uFF1A\u771F\u5B9E cli config \u539F\u6837\uFF08model/plugins/mcp/subagents \u7B49 worker \u7EE7\u627F\u9762\u4E0D\u53D8\uFF09
@@ -618,6 +609,10 @@ const CONFIG_PATH = path.join(os.homedir(), '.zcode', 'cli', 'config.json');
618
609
  // \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
610
  // 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
611
  // \u53EF\u7528\u6A21\u578B\uFF1Bplan \u5BB6\u65CF id \u5DF2\u4E0D\u53EF\u7528\uFF0C\u4E0D\u518D\u515C\u5E95\u4F2A\u9020\uFF09\u3002
612
+ // [D3 \u987A\u5E26\u53D1\u73B0 6] provider_config.json\uFF08\u5F15\u64CE\u4FA7\u6A21\u578B\u6821\u9A8C\u6E90\uFF09\u8865\u6CE8\u5165\uFF1A\u4EC5\u5B58\u5728\u4E8E
613
+ // providerRules \u7684\u4E2A\u4EBA provider\uFF08v2 \u5B57\u5178\u672A\u7269\u5316\uFF09\u4E0D\u5728\u6CE8\u5165\u96C6 \u2192 app-server \u6CE8\u518C\u8868
614
+ // \u7F3A\u6761\u76EE\uFF0C\u663E\u5F0F\u6A21\u578B\u9996\u6D3E\u5373\u62A5\u300CProvider Registry \u4E2D\u4E0D\u5B58\u5728 Model\u300D\u3002\u4E3A\u5E26 apiKey+baseUrl
615
+ // \u4E14 v2/real \u5747\u7F3A\u5931\u7684 rule \u5408\u6210 cli-config \u6761\u76EE\uFF08\u5F62\u72B6\u7167\u6284\u73B0\u7F51\u4E2A\u4EBA\u6761\u76EE\uFF09\u3002
621
616
  // \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
622
617
  // \u8BFB\u6E90\u7ECF readOrig \u95F4\u63A5\u53D6\uFF1Apatch \u524D\u9996\u8C03 = fs.readFileSync \u672C\u4F53\uFF1Bpatch \u540E = \u539F\u51FD\u6570
623
618
  // \uFF08\u9632 patch \u540E\u7684\u9012\u5F52\u81EA\u8C03\u7528\uFF09\u3002
@@ -635,6 +630,7 @@ function injectedConfigText() {
635
630
  }
636
631
  return null;
637
632
  }
633
+ const realProviders = real.provider && typeof real.provider === 'object' ? real.provider : {};
638
634
  const v2Providers = v2.provider && typeof v2.provider === 'object' ? v2.provider : {};
639
635
  const hasKey = (entry) => entry && typeof entry === 'object'
640
636
  && entry.options && typeof entry.options.apiKey === 'string' && entry.options.apiKey !== '';
@@ -642,9 +638,60 @@ function injectedConfigText() {
642
638
  for (const [id, entry] of Object.entries(v2Providers)) {
643
639
  if (hasKey(entry)) injectable[id] = entry;
644
640
  }
641
+ // provider_config.json \u8865\u6CE8\u5165\uFF08\u8BFB\u53D6\u5931\u8D25\u9759\u9ED8\u964D\u7EA7\u2014\u2014\u6821\u9A8C\u6E90\u7F3A\u5E2D\u65F6\u5F15\u64CE\u4FA7\u6821\u9A8C\u540C\u6837\u4E0D\u53EF
642
+ // \u7528\uFF0C\u6CE8\u5165\u9762\u7EF4\u6301 v2-only \u73B0\u72B6\uFF1BproviderRules \u7F3A\u5931\u4E0D\u6784\u6210\u51ED\u636E\u9519\u8BEF\uFF09\u3002
643
+ try {
644
+ const pc = JSON.parse(readOrig(PROVIDER_CONFIG_PATH, 'utf8'));
645
+ const pcCfg = pc && typeof pc.config === 'object' && pc.config ? pc.config : {};
646
+ const pcr = typeof pcCfg.providerConfigRules === 'object' && pcCfg.providerConfigRules ? pcCfg.providerConfigRules : {};
647
+ const rules = Array.isArray(pcr.providerRules) ? pcr.providerRules : [];
648
+ const mcr = typeof pcCfg.modelConfigRules === 'object' && pcCfg.modelConfigRules ? pcCfg.modelConfigRules : {};
649
+ const modelRules = Array.isArray(mcr.providerModelRules) ? mcr.providerModelRules : [];
650
+ const modelMeta = {};
651
+ for (const mr of modelRules) {
652
+ if (!mr || typeof mr !== 'object' || typeof mr.providerId !== 'string' || typeof mr.modelId !== 'string') continue;
653
+ (modelMeta[mr.providerId] = modelMeta[mr.providerId] || []).push(mr);
654
+ }
655
+ for (const rule of rules) {
656
+ if (!rule || typeof rule !== 'object') continue;
657
+ const id = typeof rule.providerId === 'string' ? rule.providerId : '';
658
+ const cfg = rule.config && typeof rule.config === 'object' ? rule.config : {};
659
+ const access = cfg.access && typeof cfg.access === 'object' ? cfg.access : {};
660
+ const api = cfg.api && typeof cfg.api === 'object' ? cfg.api : {};
661
+ // v2/real \u5DF2\u6709 \u2192 \u4E0D\u91CD\u590D\u5408\u6210\uFF08v2 \u6761\u76EE\u66F4\u5168\uFF0C\u6574\u6761\u4F18\u5148\u8BED\u4E49\u4E0D\u53D7\u5F71\u54CD\uFF09
662
+ if (!id || injectable[id] || realProviders[id]) continue;
663
+ // hasKey \u7EAA\u5F8B\u540C\u6B3E\uFF1A\u65E0 apiKey \u4E0D\u5408\u6210\uFF1B\u65E0 baseUrl\uFF08endpoint \u7531\u6A21\u677F\u63D0\u4F9B\u7684\u5F62\u6001\uFF09
664
+ // \u4E0D\u5408\u6210\u2014\u2014\u6B8B\u7F3A\u6761\u76EE\u6BD4\u4E0D\u6CE8\u5165\u66F4\u7CDF\uFF0C\u539F\u751F\u300C\u4E0D\u5B58\u5728 Model\u300D\u62A5\u9519\u7167\u65E7\u900F\u51FA
665
+ if (typeof access.apiKey !== 'string' || access.apiKey === '') continue;
666
+ if (typeof api.baseUrl !== 'string' || api.baseUrl === '') continue;
667
+ const order = Array.isArray(cfg.modelOrder) ? cfg.modelOrder
668
+ : (Array.isArray(cfg.personalModelIds) ? cfg.personalModelIds : []);
669
+ const models = {};
670
+ for (const mr of modelMeta[id] || []) {
671
+ const mrCfg = mr.config && typeof mr.config === 'object' ? mr.config : {};
672
+ if (mrCfg.enabled === false) continue; // \u7981\u7528\u6A21\u578B\u4E0D\u8FDB\u6CE8\u518C\u8868\uFF08GUI \u8BED\u4E49\u4E00\u81F4\uFF09
673
+ const props = mrCfg.properties && typeof mrCfg.properties === 'object' ? mrCfg.properties : {};
674
+ models[mr.modelId] = typeof props.contextWindow === 'number'
675
+ ? { limit: { context: props.contextWindow } }
676
+ : {};
677
+ }
678
+ for (const mid of order) {
679
+ if (typeof mid === 'string' && mid !== '' && !(mid in models)) models[mid] = {};
680
+ }
681
+ injectable[id] = {
682
+ name: typeof rule.providerName === 'string' ? rule.providerName : id,
683
+ // provider_config.json \u4E0D\u643A\u5E26\u534F\u8BAE\u5F62\u6001\u2014\u2014standard-personal \u7EC4\u4EE5 openai-compatible
684
+ // \u4E3A\u591A\u6570\u5148\u4F8B\uFF1B\u9519\u914D\u65F6\u8BF7\u6C42\u671F\u534F\u8BAE\u9519\u8BEF\u53EF\u89C1\uFF08\u4E0D\u963B\u585E\u6CE8\u518C\u8868\u88C5\u8F7D\uFF09\uFF0C\u771F\u673A\u6F02\u79FB\u4FE1\u53F7\u660E\u786E
685
+ kind: 'openai-compatible',
686
+ options: { apiKey: access.apiKey, baseURL: api.baseUrl },
687
+ source: 'custom',
688
+ models: models,
689
+ };
690
+ }
691
+ } catch { /* provider_config \u7F3A\u5931/\u635F\u574F \u2192 \u8865\u6CE8\u5165\u9762\u9759\u9ED8\u964D\u7EA7\uFF08v2 \u6CE8\u5165\u4E0D\u53D7\u5F71\u54CD\uFF09 */ }
645
692
  if (Object.keys(injectable).length === 0) return null;
646
693
  const merged = { ...real };
647
- merged.provider = { ...(real.provider && typeof real.provider === 'object' ? real.provider : {}), ...injectable };
694
+ merged.provider = { ...realProviders, ...injectable };
648
695
  if ((!merged.model || typeof merged.model !== 'object' || !merged.model.main)
649
696
  && v2.model && typeof v2.model === 'object' && v2.model.main) {
650
697
  merged.model = { ...(merged.model || {}), main: v2.model.main };
@@ -1378,66 +1425,6 @@ function extractResumeTotalTokens(resumeResult) {
1378
1425
  }
1379
1426
  return acc.has ? acc.total : void 0;
1380
1427
  }
1381
- var TurnTimeoutError = class extends Error {
1382
- kind;
1383
- elapsed;
1384
- lastEventAt;
1385
- thresholdMs;
1386
- constructor(kind, parts) {
1387
- super(
1388
- kind === "idle" ? `zcode turn idle \u5224\u6B7B\uFF1A\u8FDE\u7EED ${parts.thresholdMs}ms \u672A\u89C2\u5BDF\u5230\u672C turn \u4EFB\u4F55\u4E8B\u4EF6\uFF08session/event \u4E0E v4/telemetry/event \u5747\u9759\u9ED8\uFF09\uFF0C\u7EC8\u6001\u672A\u5230\u8FBE\u3002` + (parts.lastEventAt === void 0 ? "\u672C\u8F6E\u81EA send \u8D77\u672A\u89C2\u5BDF\u5230\u4EFB\u4F55\u4E8B\u4EF6\uFF08\u8FDB\u7A0B\u5047\u6B7B/\u534F\u8BAE\u9759\u9ED8\u5F62\u6001\uFF09\u3002" : `\u6700\u540E\u4E8B\u4EF6\u65F6\u523B ${new Date(parts.lastEventAt).toISOString()}\u3002`) + "\u6062\u590D\u6307\u5F15\uFF1A\u76F4\u63A5\u91CD\u8DD1\u672C\u4EFB\u52A1\uFF1B\u82E5\u6301\u7EED\u51FA\u73B0\uFF0C\u68C0\u67E5 ZCode \u684C\u9762\u7AEF\u6A21\u578B\u8FDE\u901A\u6027\u6216\u6539\u7528 engine: pi\u3002" : `zcode turn \u603B\u4E0A\u754C\u5224\u6B7B\uFF1A${parts.thresholdMs}ms \u5185\u672A\u89C2\u5BDF\u5230\u7EC8\u6001\uFF08turn.terminal \u4E0E\u6536\u5C3E\u5E27\u5747\u672A\u5230\u8FBE\uFF1Bidle \u5224\u5B9A\u672A\u89E6\u53D1\u2014\u2014\u4E8B\u4EF6\u6D41\u4ECD\u6D3B\u8DC3\uFF0Cchatty-wedge \u5F62\u6001\uFF09\u3002` + (parts.lastEventAt === void 0 ? "" : `\u6700\u540E\u4E8B\u4EF6\u65F6\u523B ${new Date(parts.lastEventAt).toISOString()}\u3002`) + `\u6062\u590D\u6307\u5F15\uFF1A\u76F4\u63A5\u91CD\u8DD1\u672C\u4EFB\u52A1\uFF1B\u82E5\u672C\u4EFB\u52A1\u5C5E\u5408\u6CD5\u8D85\u957F\u4EFB\u52A1\uFF08\u9884\u671F\u8D85\u8FC7 ${parts.thresholdMs}ms \u603B\u4E0A\u754C\uFF09\uFF0C\u91CD\u8DD1\u524D\u8BBE ${ZCODE_TURN_MAX_TIMEOUT_ENV} \u4E3A\u66F4\u5927\u6BEB\u79D2\u503C\uFF0C\u6216\u8BBE 0 \u5173\u95ED\u603B\u4E0A\u754C\uFF08\u5173\u95ED\u540E chatty \u5F62\u6001\u4E0D\u518D\u81EA\u52A8\u56DE\u6536\uFF0C\u9759\u9ED8 wedged \u4ECD\u7531 idle \u5C42\u515C\u5E95\u2014\u2014\u81EA\u884C\u6743\u8861\uFF09\u3002`
1389
- );
1390
- this.name = "TurnTimeoutError";
1391
- this.kind = kind;
1392
- this.elapsed = parts.elapsed;
1393
- this.lastEventAt = parts.lastEventAt;
1394
- this.thresholdMs = parts.thresholdMs;
1395
- }
1396
- };
1397
- function clearTurnTimers(turn) {
1398
- if (turn.idleTimer !== void 0) {
1399
- clearTimeout(turn.idleTimer);
1400
- turn.idleTimer = void 0;
1401
- }
1402
- if (turn.ceilingTimer !== void 0) {
1403
- clearTimeout(turn.ceilingTimer);
1404
- turn.ceilingTimer = void 0;
1405
- }
1406
- }
1407
- function armTurnTimer(onFire, ms) {
1408
- const timer = setTimeout(onFire, ms);
1409
- if (typeof timer.unref === "function") timer.unref();
1410
- return timer;
1411
- }
1412
- function resolveTurnTimerMs(parts) {
1413
- let value;
1414
- let source;
1415
- if (parts.explicit !== void 0) {
1416
- value = parts.explicit;
1417
- source = "\u663E\u5F0F\u4F20\u53C2";
1418
- } else {
1419
- const raw = process.env[parts.envName];
1420
- const parsed = parseZcodeTurnTimeoutEnv(raw);
1421
- if (parsed.state === "valid") {
1422
- value = parsed.ms;
1423
- source = `env ${parts.envName}=${raw}`;
1424
- } else {
1425
- if (parsed.state === "invalid") {
1426
- logger2.warn(
1427
- `[session-channel] ${parts.envName}="${raw}" \u975E\u6CD5\uFF08\u5E94\u4E3A\u6BEB\u79D2\u6570\u5B57\uFF09\u2014\u2014\u56DE\u843D\u9ED8\u8BA4 ${parts.fallbackMs}ms\uFF08${parts.label}\uFF09\u3002\u8BBE\u7F6E\u6B63\u6BEB\u79D2\u503C\u8986\u76D6\uFF0C\u6216 0 \u663E\u5F0F\u5173\u95ED`
1428
- );
1429
- }
1430
- value = parts.fallbackMs;
1431
- source = "\u9ED8\u8BA4\u503C";
1432
- }
1433
- }
1434
- if (value <= 0) {
1435
- logger2.warn(
1436
- `[session-channel] zcode turn ${parts.label}\u5DF2\u5173\u95ED\uFF08${source}\uFF09\u2014\u2014${parts.offConsequence}\u3002\u8BBE\u6B63\u6BEB\u79D2\u503C\uFF08env ${parts.envName} \u6216\u663E\u5F0F\u4F20\u53C2\uFF09\u6062\u590D\u56DE\u6536\u5C42`
1437
- );
1438
- }
1439
- return value;
1440
- }
1441
1428
  var SessionChannel = class {
1442
1429
  conn;
1443
1430
  /** sessionId → 在途 turn(终态落定后仍保留到 runTurn 收尾——收尾帧数据吸收窗口)。 */
@@ -1463,23 +1450,23 @@ var SessionChannel = class {
1463
1450
  ),
1464
1451
  // 连接崩溃收割:进程死亡(崩溃/我方杀链)立即 fail 全部在途 turn——
1465
1452
  // onClose 契约保证触发时连接层在途 request 已全部 reject,此处补齐
1466
- // 「无在途 request 的 turn」的收割(否则挂到 turn idle/总上界预算耗尽)
1453
+ // 「无在途 request 的 turn」的收割(否则在途 turn 失去全部终局来源)
1467
1454
  conn.onClose((reason) => this.failAllTurns(`app-server ${reason}`))
1468
1455
  ];
1469
1456
  }
1470
1457
  /**
1471
1458
  * [P0-1 U5/D7] dispose 前收割 + 退订:「退订 = 不会再有事件」在结构上蕴含「在途
1472
1459
  * turn 不应再等」——close 缺失/被吞没形态(onClose 收割主路径未触发)下,在途
1473
- * turn 于退订前经既有 failAllTurns 收敛为明确失败,不再挂满自身 idle/总上界预算
1474
- * (设计 §3.4 退化路径闭合;race 窗口在引擎 shutdownRuntimeAndDisposeChannel,
1475
- * 量级与 awaitConnFinalized 同源 ZCODE_APPSERVER_HARVEST_GRACE_MS)。幂等:与
1476
- * onClose 收割先到者赢(turn.fail 的 settled 守卫——已落定 turn 不改写),
1477
- * activeTurns 已空则 no-op。不影响连接自身生命周期(R4)。
1460
+ * turn 于退订前经既有 failAllTurns 收敛为明确失败(设计 §3.4 退化路径闭合;
1461
+ * race 窗口在引擎 shutdownRuntimeAndDisposeChannel,量级与 awaitConnFinalized
1462
+ * 同源 ZCODE_APPSERVER_HARVEST_GRACE_MS)。幂等:与 onClose 收割先到者赢
1463
+ * (turn.fail 的 settled 守卫——已落定 turn 不改写),activeTurns 已空则 no-op。
1464
+ * 不影响连接自身生命周期(R4)。
1478
1465
  */
1479
1466
  dispose() {
1480
1467
  this.disposed = true;
1481
1468
  this.failAllTurns(
1482
- "zcode session channel \u5DF2 dispose\uFF1A\u8FDE\u63A5 close \u4E8B\u4EF6\u672A\u5728\u6536\u5272\u7A97\u53E3\u5185\u5230\u8FBE\uFF0C\u5728\u9014 turn \u4E8E\u9000\u8BA2\u524D\u6536\u5272\u4E3A\u660E\u786E\u5931\u8D25\uFF08\u4E0D\u518D\u6302\u5230 turn \u81EA\u8EAB\u9884\u7B97\u8017\u5C3D\uFF09\u3002\u6062\u590D\u6307\u5F15\uFF1A\u76F4\u63A5\u91CD\u8DD1\u672C\u4EFB\u52A1\u3002"
1469
+ "zcode session channel \u5DF2 dispose\uFF1A\u8FDE\u63A5 close \u4E8B\u4EF6\u672A\u5728\u6536\u5272\u7A97\u53E3\u5185\u5230\u8FBE\uFF0C\u5728\u9014 turn \u4E8E\u9000\u8BA2\u524D\u6536\u5272\u4E3A\u660E\u786E\u5931\u8D25\u3002\u6062\u590D\u6307\u5F15\uFF1A\u76F4\u63A5\u91CD\u8DD1\u672C\u4EFB\u52A1\u3002"
1483
1470
  );
1484
1471
  for (const off of this.offHandlers.splice(0)) off();
1485
1472
  }
@@ -1609,7 +1596,6 @@ var SessionChannel = class {
1609
1596
  ...opened.turn.lastTerminalError !== void 0 ? { lastTerminalError: opened.turn.lastTerminalError } : {}
1610
1597
  };
1611
1598
  } finally {
1612
- opened.stopTimers();
1613
1599
  this.activeTurns.delete(sessionId);
1614
1600
  await this.closeSession(sessionId);
1615
1601
  }
@@ -1630,7 +1616,7 @@ var SessionChannel = class {
1630
1616
  onTextDelta: opts.onTextDelta,
1631
1617
  onThinkingDelta: opts.onThinkingDelta,
1632
1618
  // [PR3] tool 执行期活性回调(SessionTurnCallbacks.onActivity 注释——宿主侧
1633
- // 无进展守护的工具执行期刷新面)
1619
+ // 的工具执行期刷新面)
1634
1620
  onActivity: opts.onActivity
1635
1621
  },
1636
1622
  settled: false,
@@ -1640,83 +1626,25 @@ var SessionChannel = class {
1640
1626
  terminal: void 0,
1641
1627
  lastTerminalStatus: void 0,
1642
1628
  lastTerminalError: void 0,
1643
- idleMs: 0,
1644
- ceilingMs: 0,
1645
- startedAt: Date.now(),
1646
- lastEventAt: void 0,
1647
- idleTimer: void 0,
1648
- ceilingTimer: void 0,
1649
- // 装配占位:下方 timer 创建后重绑(settle/fail 需要清理两 timer)
1629
+ // 装配占位:下方重绑(settle/fail 闭包引用 turn 本体)
1650
1630
  settle: () => {
1651
1631
  },
1652
1632
  fail: () => {
1653
- },
1654
- fireTimeout: () => {
1655
1633
  }
1656
1634
  };
1657
- turn.idleMs = resolveTurnTimerMs({
1658
- explicit: opts.idleTimeoutMs,
1659
- envName: ZCODE_TURN_IDLE_TIMEOUT_ENV,
1660
- fallbackMs: ZCODE_TURN_IDLE_TIMEOUT_MS,
1661
- label: "idle \u4E3B\u5224\u5B9A",
1662
- offConsequence: "\u9759\u9ED8 wedged\uFF08\u65E0\u4E8B\u4EF6\uFF09\u5F62\u6001\u5C06\u65E0\u81EA\u52A8\u56DE\u6536\uFF0C\u4EFB\u52A1\u53EF\u80FD\u6302\u5230\u5BBF\u4E3B\u8FDB\u7A0B\u9000\u51FA"
1663
- });
1664
- turn.ceilingMs = resolveTurnTimerMs({
1665
- explicit: opts.turnTimeoutMs,
1666
- envName: ZCODE_TURN_MAX_TIMEOUT_ENV,
1667
- fallbackMs: ZCODE_TURN_MAX_TIMEOUT_MS,
1668
- label: "\u603B\u4E0A\u754C",
1669
- offConsequence: "chatty-wedge\uFF08\u6709\u4E8B\u4EF6\u65E0\u7EC8\u6001\uFF09\u5F62\u6001\u5C06\u65E0\u81EA\u52A8\u56DE\u6536\uFF0C\u4EC5\u5269 idle \u9759\u9ED8\u5224\u5B9A\u515C\u5E95"
1670
- });
1671
- const fireTimeout = (kind) => {
1672
- if (turn.settled) return;
1673
- turn.settled = true;
1674
- clearTurnTimers(turn);
1675
- this.activeTurns.delete(sessionId);
1676
- rejectDone(
1677
- new TurnTimeoutError(kind, {
1678
- thresholdMs: kind === "idle" ? turn.idleMs : turn.ceilingMs,
1679
- elapsed: Date.now() - turn.startedAt,
1680
- lastEventAt: turn.lastEventAt
1681
- })
1682
- );
1683
- };
1684
- turn.fireTimeout = fireTimeout;
1685
- if (turn.idleMs > 0) {
1686
- turn.idleTimer = armTurnTimer(() => turn.fireTimeout("idle"), turn.idleMs);
1687
- }
1688
- if (turn.ceilingMs > 0) {
1689
- turn.ceilingTimer = armTurnTimer(
1690
- () => turn.fireTimeout("ceiling"),
1691
- turn.ceilingMs
1692
- );
1693
- }
1694
1635
  turn.settle = (t) => {
1695
1636
  if (turn.settled) return;
1696
1637
  turn.settled = true;
1697
1638
  turn.terminal = t;
1698
- clearTurnTimers(turn);
1699
1639
  resolveDone(t);
1700
1640
  };
1701
1641
  turn.fail = (err) => {
1702
1642
  if (turn.settled) return;
1703
1643
  turn.settled = true;
1704
- clearTurnTimers(turn);
1705
1644
  rejectDone(err);
1706
1645
  };
1707
1646
  this.activeTurns.set(sessionId, turn);
1708
- return { turn, done, stopTimers: () => clearTurnTimers(turn) };
1709
- }
1710
- /**
1711
- * idle 主判定的事件刷新(P0-1 D1):本 turn 任何事件到达即重置 idle 倒数——
1712
- * 活跃事件流零误杀的结构保证。总上界不受影响(固定倒数)。已落定 turn 无
1713
- * timer 可刷新(只剩 lastEventAt 记账)。
1714
- */
1715
- refreshIdle(turn) {
1716
- turn.lastEventAt = Date.now();
1717
- if (turn.settled || turn.idleTimer === void 0) return;
1718
- clearTimeout(turn.idleTimer);
1719
- turn.idleTimer = armTurnTimer(() => turn.fireTimeout("idle"), turn.idleMs);
1647
+ return { turn, done };
1720
1648
  }
1721
1649
  lookupTurn(sessionId) {
1722
1650
  if (sessionId !== void 0) return this.activeTurns.get(sessionId);
@@ -1746,7 +1674,6 @@ var SessionChannel = class {
1746
1674
  if (turn === void 0) return;
1747
1675
  const payload = isRecord3(params) && isRecord3(params.payload) ? params.payload : void 0;
1748
1676
  if (payload === void 0) return;
1749
- this.refreshIdle(turn);
1750
1677
  if (this.applyFinalFrame(turn, payload)) return;
1751
1678
  if (!this.applyStreamDelta(turn, payload) && !turn.settled) {
1752
1679
  turn.callbacks.onActivity?.();
@@ -1863,7 +1790,6 @@ var SessionChannel = class {
1863
1790
  applyStreamChunkTelemetry(params) {
1864
1791
  const turn = this.lookupTurn(extractPushSessionId(params));
1865
1792
  if (turn === void 0 || turn.settled) return;
1866
- this.refreshIdle(turn);
1867
1793
  for (const key of ["chunk", "text", "content"]) {
1868
1794
  const v = params[key];
1869
1795
  if (typeof v === "string" && v !== "") {
@@ -2104,7 +2030,10 @@ var ZcodeEngine = class {
2104
2030
  // --mode build/edit/plan/yolo 原生权限档位
2105
2031
  permissionMode: "native",
2106
2032
  // [D3-④] 无 turn_end 语义,轮数上限不可兑现(预检 gate 据此同步拒绝)
2107
- maxTurns: false
2033
+ maxTurns: false,
2034
+ // [subagent-model-switch] zcode 引擎不在模型切换设计范围(协议面引擎中立预留,
2035
+ // 后续另立项接入)——setModel 通路未接通,unsupported 如实声明
2036
+ setModel: "unsupported"
2108
2037
  };
2109
2038
  }
2110
2039
  /** 探针(D7):二进制存在 + 版本解析(zcode 无公开契约,版本漂移的入口信号)。 */
@@ -2219,30 +2148,19 @@ var ZcodeEngine = class {
2219
2148
  * 只在最终轮终态后合成(不变量 2/5)。
2220
2149
  */
2221
2150
  async runAppServerAttemptsWithRetry(task, ctx, modelRef, cwd, basePrompt, schema, usageAcc) {
2222
- const attemptStartedAt = Date.now();
2223
2151
  let final = await this.attemptAppServerTurn(task, ctx, modelRef, cwd, basePrompt);
2224
2152
  accumulateUsage(usageAcc, final);
2225
2153
  if (final.kind === "run-failed" && final.transient !== void 0 && ctx.signal?.aborted !== true && !this.disposed) {
2226
- const budget = resolveTransientRetryBudget(explicitTurnBudgetMs(), Date.now() - attemptStartedAt);
2227
- if (budget.state === "depleted") {
2228
- logger4.warn(
2229
- `[zcode-engine] \u672B\u6B21 attempt \u77AC\u65F6\u5931\u8D25\uFF08${final.transient}\uFF09\u2014\u2014\u663E\u5F0F\u603B\u4E0A\u754C\u9884\u7B97\u5269\u4F59\u4E0D\u8DB3 ${ZCODE_TURN_RETRY_MIN_BUDGET_MS}ms\uFF0C\u4E0D\u91CD\u8BD5\u76F4\u63A5\u7EC8\u6001\u5316\uFF08\u9884\u7B97\u7EE7\u627F\uFF1A\u91CD\u8BD5\u4E0D\u91CD\u7F6E\u603B\u9884\u7B97\uFF09`
2230
- );
2231
- } else {
2232
- logger4.warn(
2233
- `[zcode-engine] \u672B\u6B21 attempt \u77AC\u65F6\u5931\u8D25\uFF08${final.transient}\uFF09\u2014\u2014\u6B62\u635F\u94FE\u5DF2\u7EC8\u5C40\uFF0C\u65B0\u4F1A\u8BDD\u81EA\u52A8\u91CD\u8BD5\u4E00\u6B21` + (budget.state === "inherit" ? `\uFF08\u9884\u7B97\u7EE7\u627F\uFF1A\u91CD\u8BD5\u8F6E\u603B\u4E0A\u754C=\u5269\u4F59 ${budget.remainingMs}ms\uFF0C\u4E0D\u91CD\u7F6E\u603B\u9884\u7B97\uFF09` : "\uFF08\u65E0\u663E\u5F0F\u603B\u4E0A\u754C\u9884\u7B97\uFF0C\u91CD\u8BD5\u8F6E\u8D70 env/\u9ED8\u8BA4\u4E0A\u754C\uFF09")
2234
- );
2235
- const retry = await this.attemptAppServerTurn(task, ctx, modelRef, cwd, basePrompt, {
2236
- // 预算继承传递点(D2 内部传参面):显式预算 → 剩余值;无显式预算 → 缺省
2237
- // (channel 侧走同一 env/默认,与首轮行为一致)
2238
- ...budget.state === "inherit" ? { turnTimeoutMs: budget.remainingMs } : {},
2239
- // 重试事实进文案:「已自动重试一次」句仅对真实发生的重试生效(未重试形态
2240
- // 不含——与行为一致,§5.2 F-1/F-4)
2241
- retried: true
2242
- });
2243
- accumulateUsage(usageAcc, retry);
2244
- final = retry;
2245
- }
2154
+ logger4.warn(
2155
+ `[zcode-engine] \u672B\u6B21 attempt \u77AC\u65F6\u5931\u8D25\uFF08${final.transient}\uFF09\u2014\u2014\u6B62\u635F\u94FE\u5DF2\u7EC8\u5C40\uFF0C\u65B0\u4F1A\u8BDD\u81EA\u52A8\u91CD\u8BD5\u4E00\u6B21`
2156
+ );
2157
+ const retry = await this.attemptAppServerTurn(task, ctx, modelRef, cwd, basePrompt, {
2158
+ // 重试事实进文案:「已自动重试一次」句仅对真实发生的重试生效(未重试形态
2159
+ // 不含——与行为一致,§5.2 F-1/F-4)
2160
+ retried: true
2161
+ });
2162
+ accumulateUsage(usageAcc, retry);
2163
+ final = retry;
2246
2164
  }
2247
2165
  if (final.kind === "parsed" && final.schemaResult !== void 0 && !final.schemaResult.ok && schema !== void 0) {
2248
2166
  const retryPrompt = appendSchemaRetryDirective(basePrompt, final.schemaResult.error);
@@ -2274,9 +2192,7 @@ var ZcodeEngine = class {
2274
2192
  * 单轮常驻执行:runTurn 组合面 + D3 abort 链 + 事件前移(text_delta 实时流出;
2275
2193
  * 终态数据经 read 兜底收口后才 resolve——不变量 1/2)。
2276
2194
  *
2277
- * @param opts turnTimeoutMs:显式总上界传参面(D2 内部传参点)——U4/D6 预算继承
2278
- * 向重试轮传剩余值;缺省不传(channel 走 env→默认,首轮行为)。
2279
- * retried:瞬时重试轮标记——失败文案补「已自动重试一次」句(F-1/F-4)。
2195
+ * @param opts retried:瞬时重试轮标记——失败文案补「已自动重试一次」句(F-1/F-4)。
2280
2196
  */
2281
2197
  async attemptAppServerTurn(task, ctx, modelRef, cwd, prompt, opts = {}) {
2282
2198
  const rt = this.ensureAppServerRuntime();
@@ -2306,12 +2222,10 @@ var ZcodeEngine = class {
2306
2222
  ctx.onHandleReady?.({
2307
2223
  sessionRef: { dbPath: zcodeSessionDbPath(this.deps.engineDataDir()), sessionId }
2308
2224
  });
2309
- },
2310
- // 显式总上界传参(D2/U4:缺省缺席——channel 侧 resolveTurnTimerMs 走 env→默认)
2311
- ...opts.turnTimeoutMs !== void 0 ? { turnTimeoutMs: opts.turnTimeoutMs } : {}
2225
+ }
2312
2226
  });
2313
2227
  const onAbort = () => {
2314
- void this.appServerAbortChain(rt, turn, () => currentSessionId, sessionCreated, { escalateOn: "turn-settled" });
2228
+ void this.appServerAbortChain(rt, turn, () => currentSessionId, sessionCreated);
2315
2229
  };
2316
2230
  if (ctx.signal !== void 0) {
2317
2231
  if (ctx.signal.aborted) onAbort();
@@ -2337,32 +2251,16 @@ var ZcodeEngine = class {
2337
2251
  /**
2338
2252
  * [attemptAppServerTurn 拆分] 失败分流(catch 半边):
2339
2253
  * - 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 第二可重试形态)判据:
2254
+ * - [P0-1 U4] 连接崩溃收割形态(failAllTurns 的错误,D6 可重试形态)判据:
2347
2255
  * 非 RPC error(服务端无明确应答——有应答即精确错误归类,非瞬时崩溃面)且
2348
2256
  * conn 不存活。时序可靠性:catch 时刻紧随 onClose 收割,连接重建仅由
2349
2257
  * conn.request 惰性触发——本链路中 runTurn finally 的 closeSession 对死连接
2350
- * 短路(channel 侧 !alive 守卫)、stop 只属 abort/超时入口(前者已被
2351
- * signal.aborted 短路、后者走上一分支)——此刻无 request 可重建,判据可靠;
2258
+ * 短路(channel 侧 !alive 守卫)、stop 只属 abort 链(已被 signal.aborted
2259
+ * 短路)——此刻无 request 可重建,判据可靠;
2352
2260
  * - 其余 → 精确错误终态。
2353
2261
  */
2354
2262
  async classifyAppServerTurnFailure(err, ctx, args) {
2355
2263
  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
2264
  if (!isAppServerRpcError(err) && !args.rt.conn.alive) {
2367
2265
  return failedAppServerAttempt(err, args.currentSessionId(), { retried: args.retried, transient: "conn-closed" });
2368
2266
  }
@@ -2373,8 +2271,8 @@ var ZcodeEngine = class {
2373
2271
  * shutdown resolve 于 `exit` 事件,而 finalize 挂 `close`(stdio 排空)——两者之间的
2374
2272
  * 事件窗口内 conn.child 仍非 null,紧接的下一任务 request 会复用垂死进程(写入成功
2375
2273
  * 但必败,走崩溃路径)而非触发重建。与 shutdownRuntimeAndDisposeChannel 的
2376
- * HARVEST_GRACE 同款 race 形态(close 永不到达不挂死)。超时入口的 await 链终局
2377
- * 语义(D6 重试时序依据)因此是「进程收割确认完成」而非「SIGTERM 已发出」。
2274
+ * HARVEST_GRACE 同款 race 形态(close 永不到达不挂死)。abort 链的 await 终局
2275
+ * 语义因此是「进程收割确认完成」而非「SIGTERM 已发出」。
2378
2276
  */
2379
2277
  async awaitConnFinalized(rt) {
2380
2278
  if (!rt.conn.alive) return;
@@ -2390,25 +2288,14 @@ var ZcodeEngine = class {
2390
2288
  });
2391
2289
  }
2392
2290
  /**
2393
- * D3 abort 链执行体(双入口分岔,P0-1 U2 参数化,D3 v1.1):
2394
- * - **用户取消入口**(`escalateOn: "turn-settled"`,现状语义零改动;fire-and-forget——
2395
- * 与 turn promise 并行推进):stop 帧(超时 ZCODE_APPSERVER_STOP_TIMEOUT_MS)→
2396
- * grace 窗口内 turn 落定即止(不杀共享进程)→ 超窗 killChain(conn.shutdown 全序:
2397
- * SIGTERM→grace→SIGKILL)。turn 的最终落定由 attempt 主路径 await 收口,本链不
2398
- * 直接产出终态。abort 与 create 竞态(signal 先到、session 未建立):等会话建立
2399
- * (带上限)再发 stop——否则 stop 永远发不出,直接连坐杀共享进程。
2400
- * - **超时入口**(`escalateOn: "stop-outcome"`,channel 判死后由 catch await 链终局):
2401
- * turn 已 reject,对它 race 恒真不可用(v1 击穿点)——升级判据改挂在 **stop 应答
2402
- * 三态**:①成功应答 → 服务端接受停 turn,止损确认,链终止;②协议性 error 应答
2403
- * (有 error 帧即控制面活的证据,多因 runTurn finally 的 closeSession 先行关会话,
2404
- * 健康形态竞态)→ 链终止**不升级**(止损由 close 回收 + 服务端自治承担;把
2405
- * 「stop 报错」一律升级会误杀健康共享进程并连坐并发任务);③超时/写入失败/进程
2406
- * 死等连接级失败(控制面死)→ killChain 升级。判据实现依据:error 应答帧 reject
2407
- * 携带 number code(isAppServerRpcError);连接级失败是无 code 的新 Error
2408
- * (connection.request 三态 reject 形态)。返回值即止损路径(超时入口的 outcome
2409
- * 文案素材——D3 强制可观测面)。
2291
+ * D3 abort 链执行体(用户取消入口,fire-and-forget——与 turn promise 并行推进):
2292
+ * stop 帧(超时 ZCODE_APPSERVER_STOP_TIMEOUT_MS)→ grace 窗口内 turn 落定即止
2293
+ * (不杀共享进程)→ 超窗 killChain(conn.shutdown 全序:SIGTERM→grace→SIGKILL)。
2294
+ * turn 的最终落定由 attempt 主路径 await 收口,本链不直接产出终态。abort 与 create
2295
+ * 竞态(signal 先到、session 未建立):等会话建立(带上限)再发 stop——否则 stop
2296
+ * 永远发不出,直接连坐杀共享进程。
2410
2297
  */
2411
- async appServerAbortChain(rt, turn, getSessionId, sessionCreated, entry) {
2298
+ async appServerAbortChain(rt, turn, getSessionId, sessionCreated) {
2412
2299
  const graceRaceThenKill = async () => {
2413
2300
  const settled = await Promise.race([
2414
2301
  turn.then(
@@ -2417,49 +2304,31 @@ var ZcodeEngine = class {
2417
2304
  ),
2418
2305
  delayResolved(abortGraceMs(), false)
2419
2306
  ]);
2420
- if (settled) return "settled-in-grace";
2307
+ if (settled) return;
2421
2308
  logger4.warn(
2422
2309
  `[zcode-engine] abort grace \u7A97\u53E3\u5185\u672A\u89C1\u7EC8\u6001\u2014\u2014killChain \u6536\u5272\u5171\u4EAB\u8FDB\u7A0B\uFF08\u63A5\u53D7\u8FDE\u5750\uFF0C\u5728\u9014\u4EFB\u52A1\u8D70\u5D29\u6E83\u8DEF\u5F84\uFF09`
2423
2310
  );
2424
2311
  await rt.conn.shutdown({ graceMs: ZCODE_KILL_GRACE_MS });
2425
2312
  await this.awaitConnFinalized(rt);
2426
- return "escalated-kill";
2427
2313
  };
2428
2314
  let sessionId = getSessionId();
2429
2315
  if (sessionId === void 0) {
2430
2316
  await Promise.race([sessionCreated, delayResolved(stopTimeoutMs(), void 0)]);
2431
2317
  sessionId = getSessionId();
2432
2318
  if (sessionId === void 0) {
2433
- if (entry.escalateOn === "stop-outcome") return "no-session";
2434
2319
  return graceRaceThenKill();
2435
2320
  }
2436
2321
  }
2437
2322
  if (!rt.conn.alive) {
2438
- if (entry.escalateOn === "stop-outcome") return "stop-unreachable-killed";
2439
2323
  return graceRaceThenKill();
2440
2324
  }
2441
2325
  try {
2442
2326
  await rt.conn.request("session/stop", { sessionId }, { timeoutMs: stopTimeoutMs() });
2443
2327
  } catch (err) {
2444
- if (entry.escalateOn === "stop-outcome") {
2445
- if (isAppServerRpcError(err)) {
2446
- logger4.debug(
2447
- `[zcode-engine] session/stop \u62A5\u534F\u8BAE\u6027 error\uFF08${errMessage3(err)}\uFF09\u2014\u2014\u4F1A\u8BDD\u5DF2\u56DE\u6536\uFF0C\u63A7\u5236\u9762\u5B58\u6D3B\uFF0C\u4E0D\u5347\u7EA7\u6740\u94FE`
2448
- );
2449
- return "stop-rejected";
2450
- }
2451
- logger4.warn(
2452
- `[zcode-engine] session/stop \u65E0\u5E94\u7B54\uFF08${errMessage3(err)}\uFF09\u2014\u2014\u5347\u7EA7 killChain \u6536\u5272\u5171\u4EAB\u8FDB\u7A0B\uFF08\u8D85\u65F6\u5165\u53E3\uFF0C\u63A5\u53D7\u8FDE\u5750\uFF09`
2453
- );
2454
- await rt.conn.shutdown({ graceMs: ZCODE_KILL_GRACE_MS });
2455
- await this.awaitConnFinalized(rt);
2456
- return "stop-unreachable-killed";
2457
- }
2458
2328
  logger4.debug(
2459
2329
  `[zcode-engine] session/stop \u5931\u8D25\uFF08${errMessage3(err)}\uFF09\u2014\u2014grace \u540E\u8D70 killChain \u515C\u5E95`
2460
2330
  );
2461
2331
  }
2462
- if (entry.escalateOn === "stop-outcome") return "stop-acked";
2463
2332
  return graceRaceThenKill();
2464
2333
  }
2465
2334
  // ── 常驻运行时管理(D1/D6)──────────────────────
@@ -2481,6 +2350,7 @@ var ZcodeEngine = class {
2481
2350
  const env = buildAppServerEnv(this.deps.processEnv ?? process.env);
2482
2351
  env.ZCODE_ENG_CLI_PATH = cliPath;
2483
2352
  env.ZCODE_ENG_V2_CONFIG = this.deps.sources?.v2ConfigPath ?? defaultV2ConfigPath();
2353
+ env.ZCODE_ENG_PROVIDER_CONFIG = this.deps.sources?.personalProviderConfigPath ?? defaultPersonalProviderConfigPath();
2484
2354
  const sessionDbPath = zcodeSessionDbPath(engineDataDir);
2485
2355
  env.ZCODE_SESSION_DB_PATH = sessionDbPath;
2486
2356
  delete env.ZCODE_SESSION_DB;
@@ -2513,15 +2383,15 @@ var ZcodeEngine = class {
2513
2383
  * [R5 修复 R4 既有竞态] shutdown → 等崩溃收割实际发生 → channel 退订。killChain 在
2514
2384
  * `exit` 事件 resolve,而连接 finalize(onClose → channel 的 failAllTurns)挂
2515
2385
  * `close` 事件——两者之间有一个事件循环窗口:shutdown resolve 后立即退订,在途
2516
- * turn 会错过收割、挂到 turnTimeoutMs(300s)。退订前等 onClose 触发(本方法先于
2386
+ * turn 会错过收割而失去终局来源。退订前等 onClose 触发(本方法先于
2517
2387
  * shutdown 订阅;channel 的订阅在构造期更早——其 failAllTurns 先于本 promise
2518
2388
  * resolve 执行);ZCODE_APPSERVER_HARVEST_GRACE_MS 兜底防 `close` 永不到达时挂死。
2519
2389
  * [P0-1 U5/D7] grace race 输掉(close 迟到/永不到达——stdio 被孙进程持有排空不
2520
2390
  * 尽等病态形态)时,channel.dispose() 内置的 dispose 收割(failAllTurns 先于退订,
2521
- * SessionChannel.dispose)兜底在途 turn——退化终点从「挂满 turn 自身 idle/总上界
2522
- * 预算」收敛为「grace 窗口内明确失败」(设计 §3.4 退化路径闭合);race 窗口与
2523
- * awaitConnFinalized 同源同量级(ZCODE_APPSERVER_HARVEST_GRACE_MS)。正常 close
2524
- * 先到时 onClose 收割先行,dispose 收割幂等 no-op(零回归)。
2391
+ * SessionChannel.dispose)兜底在途 turn——在途 turn 收敛为「grace 窗口内明确失败」
2392
+ * (设计 §3.4 退化路径闭合);race 窗口与 awaitConnFinalized 同源同量级
2393
+ * (ZCODE_APPSERVER_HARVEST_GRACE_MS)。正常 close 先到时 onClose 收割先行,
2394
+ * dispose 收割幂等 no-op(零回归)。
2525
2395
  */
2526
2396
  async shutdownRuntimeAndDisposeChannel(rt) {
2527
2397
  const harvested = new Promise((resolve2) => {
@@ -2826,16 +2696,6 @@ ${omissionNote}${kept.join("\n")}
2826
2696
  function buildResumeUnavailableNoticeSegment() {
2827
2697
  return "[\u4F1A\u8BDD\u5EF6\u7EED\u63D0\u793A] \u672C\u6D88\u606F\u662F\u540C\u4E00\u4EFB\u52A1\u7684\u5EF6\u7EED\u4F1A\u8BDD\uFF0C\u4F46\u4E0A\u4E00\u4F1A\u8BDD\u7684\u5386\u53F2\u8BB0\u5F55\u4E0D\u53EF\u6062\u590D\uFF08\u539F\u59CB\u4F1A\u8BDD\u5DF2\u5931\u6548\uFF09\u3002\n\u6CA1\u6709\u66F4\u65E9\u7684\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u53EF\u5F15\u7528\u2014\u2014\u8BF7\u57FA\u4E8E\u4E0B\u65B9\u6700\u65B0\u6D88\u606F\u72EC\u7ACB\u5224\u65AD\u5E76\u7EE7\u7EED\u63A8\u8FDB\u4EFB\u52A1\u3002\n\n";
2828
2698
  }
2829
- var ZCODE_TURN_RETRY_MIN_BUDGET_MS = 3e5;
2830
- function resolveTransientRetryBudget(totalBudgetMs, consumedMs) {
2831
- if (totalBudgetMs === void 0) return { state: "unbounded" };
2832
- const remainingMs = totalBudgetMs - consumedMs;
2833
- return remainingMs >= ZCODE_TURN_RETRY_MIN_BUDGET_MS ? { state: "inherit", remainingMs } : { state: "depleted" };
2834
- }
2835
- function explicitTurnBudgetMs() {
2836
- const parsed = parseZcodeTurnTimeoutEnv(process.env[ZCODE_TURN_MAX_TIMEOUT_ENV]);
2837
- return parsed.state === "valid" && parsed.ms > 0 ? parsed.ms : void 0;
2838
- }
2839
2699
  function isPlainObject(v) {
2840
2700
  return typeof v === "object" && v !== null && !Array.isArray(v);
2841
2701
  }
@@ -2981,8 +2841,7 @@ function failedAppServerAttempt(err, currentSessionId, opts = {}) {
2981
2841
  kind: "run-failed",
2982
2842
  output: syntheticAppServerOutput(null),
2983
2843
  message: buildAppServerRunFailedMessage(err, currentSessionId, opts.retried === true),
2984
- // [P0-1 U4/D6] 瞬时失败形态标记(重试判定判据——timeout 形态走
2985
- // timeoutAppServerAttempt,此处只承载 conn-closed)
2844
+ // [P0-1 U4/D6] 瞬时失败形态标记(重试判定判据,conn-closed 连接崩溃形态)
2986
2845
  ...opts.transient !== void 0 ? { transient: opts.transient } : {},
2987
2846
  // 错误规格表 -32004 行「按任务失败上报(含会话 id)」:create 成功后运行中失败
2988
2847
  // (-32004/-32010 等)时留痕会话 id——经 applyRunFailedOutcome 落 outcome.sessionId
@@ -2990,38 +2849,6 @@ function failedAppServerAttempt(err, currentSessionId, opts = {}) {
2990
2849
  ...currentSessionId !== void 0 ? { sessionId: currentSessionId } : {}
2991
2850
  };
2992
2851
  }
2993
- function timeoutAppServerAttempt(err, currentSessionId, stopPath, opts = {}) {
2994
- return {
2995
- kind: "run-failed",
2996
- output: syntheticAppServerOutput(null),
2997
- message: buildAppServerTimeoutMessage(err, currentSessionId, stopPath, opts.retried === true),
2998
- transient: "timeout",
2999
- ...currentSessionId !== void 0 ? { sessionId: currentSessionId } : {}
3000
- };
3001
- }
3002
- function stopPathText(stopPath) {
3003
- switch (stopPath) {
3004
- case "stop-acked":
3005
- return "session/stop \u5DF2\u9001\u8FBE\uFF08\u670D\u52A1\u7AEF\u63A5\u53D7\u505C turn\uFF09";
3006
- case "stop-rejected":
3007
- return "session/stop \u62A5\u534F\u8BAE\u6027 error\uFF08\u4F1A\u8BDD\u5DF2\u88AB\u56DE\u6536\uFF0C\u63A7\u5236\u9762\u5B58\u6D3B\u2014\u2014\u6B62\u635F\u7531\u4F1A\u8BDD\u56DE\u6536\u627F\u62C5\uFF0C\u4E0D\u5347\u7EA7\u6740\u94FE\uFF09";
3008
- case "stop-unreachable-killed":
3009
- return `session/stop \u65E0\u5E94\u7B54\u5DF2\u5347\u7EA7\u6740\u94FE\uFF08SIGTERM\u2192${ZCODE_KILL_GRACE_MS}ms\u2192SIGKILL \u6536\u5272\u5171\u4EAB\u8FDB\u7A0B\uFF09`;
3010
- case "no-session":
3011
- return "\u4F1A\u8BDD\u672A\u5EFA\u7ACB\uFF08\u4EFB\u52A1\u672A\u5F00\u59CB\u6267\u884C\uFF0C\u65E0\u5728\u9014\u6D88\u8017\uFF09";
3012
- default:
3013
- return "grace \u7A97\u53E3\u5185\u7EC8\u6001\u843D\u5B9A\u6216\u5DF2\u8D70\u6740\u94FE";
3014
- }
3015
- }
3016
- function buildAppServerTimeoutMessage(err, sessionId, stopPath, retried = false) {
3017
- const sid = sessionId !== void 0 ? `\uFF08\u4F1A\u8BDD ${sessionId}\uFF09` : "";
3018
- const lastEventText = err.lastEventAt !== void 0 ? `\uFF0C\u6700\u540E\u4E8B\u4EF6 ${new Date(err.lastEventAt).toISOString()}` : "\uFF0C\u6574\u8F6E\u672A\u89C2\u5BDF\u5230\u4EFB\u4F55\u4E8B\u4EF6\uFF08\u8FDB\u7A0B\u5047\u6B7B/\u534F\u8BAE\u9759\u9ED8\u5F62\u6001\uFF09";
3019
- const head = err.kind === "idle" ? `engine_timeout: zcode turn \u8FDE\u7EED\u9759\u9ED8 ${err.thresholdMs}ms\uFF08idle \u5224\u5B9A${lastEventText}\uFF0C\u603B\u8017\u65F6 ${err.elapsed}ms\uFF09${sid}\u3002` : `engine_timeout: zcode turn \u603B\u4E0A\u754C ${err.thresholdMs}ms \u5185\u672A\u89C2\u5BDF\u5230\u7EC8\u6001\uFF08chatty-wedge \u5224\u5B9A\u2014\u2014\u4E8B\u4EF6\u6D41\u4ECD\u6D3B\u8DC3\u800C\u7EC8\u6001\u672A\u5230\u8FBE\uFF0C\u603B\u8017\u65F6 ${err.elapsed}ms\uFF09${sid}\u3002`;
3020
- const selfHelp = err.kind === "ceiling" ? `\u82E5\u672C\u4EFB\u52A1\u5C5E\u5408\u6CD5\u8D85\u957F\u4EFB\u52A1\uFF08\u9884\u671F\u8D85\u8FC7 ${err.thresholdMs}ms\uFF09\uFF0C\u91CD\u8DD1\u524D\u8BBE ${ZCODE_TURN_MAX_TIMEOUT_ENV} \u4E3A\u66F4\u5927\u6BEB\u79D2\u503C\u6216 0 \u5173\u95ED\u603B\u4E0A\u754C\uFF08\u5173\u95ED\u540E chatty \u5F62\u6001\u4E0D\u518D\u81EA\u52A8\u56DE\u6536\uFF0C\u9759\u9ED8 wedged \u4ECD\u7531 idle \u5C42\u515C\u5E95\u2014\u2014\u81EA\u884C\u6743\u8861\uFF09\u3002` : "";
3021
- const rerunGuide = retried ? `\u{1F449} \u6062\u590D\u6307\u5F15\uFF1A\u76F4\u63A5\u91CD\u8DD1\u672C\u4EFB\u52A1\uFF08\u77AC\u65F6\u6545\u969C\u5DF2\u81EA\u52A8\u91CD\u8BD5\u4E00\u6B21\u4ECD\u8D85\u65F6\uFF1B\u91CD\u8BD5\u5728\u6B62\u635F\u94FE\u7EC8\u5C40\u540E\u542F\u52A8\uFF0C\u65E0\u65B0\u65E7\u4EFB\u52A1\u53CC\u8DD1\u7A97\uFF09\uFF1B` : `\u{1F449} \u6062\u590D\u6307\u5F15\uFF1A\u76F4\u63A5\u91CD\u8DD1\u672C\u4EFB\u52A1\uFF1B`;
3022
- return `${head}\u6B62\u635F\u8DEF\u5F84\uFF1A${stopPathText(stopPath)}\u3002
3023
- ${rerunGuide}${selfHelp}\u82E5\u6301\u7EED\u51FA\u73B0\uFF0C\u68C0\u67E5 ZCode \u684C\u9762\u7AEF\u6A21\u578B\u8FDE\u901A\u6027\u6216\u6539\u7528 engine: pi\u3002`;
3024
- }
3025
2852
  function isHostTimeoutAbort(ctx) {
3026
2853
  return ctx.signal?.aborted === true && ctx.signal.reason === HOST_TIMEOUT_ABORT_REASON;
3027
2854
  }