evolcore 0.0.39 → 0.0.41-test.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.
Files changed (153) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +31 -20
  3. package/bin/codex-managed-hook.mjs +11 -0
  4. package/bin/ec-safe-output.js +25 -3
  5. package/dist/agents/baseagent-availability.js +1 -0
  6. package/dist/agents/claude-runner.js +53 -152
  7. package/dist/agents/codex-runner.js +485 -241
  8. package/dist/agents/ecagent-runner.js +48 -18
  9. package/dist/agents/gemini-runner.js +27 -8
  10. package/dist/agents/runner-types.js +39 -9
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/aid/control-aid.js +23 -98
  14. package/dist/aun/aid/ownership-operation.js +1 -3
  15. package/dist/aun/group/identity.js +8 -0
  16. package/dist/aun/group/invite-service.js +6 -0
  17. package/dist/aun/msg/managed-operation.js +4 -4
  18. package/dist/aun/msg/p2p.js +28 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +99 -52
  22. package/dist/channels/daemon.js +24 -4
  23. package/dist/channels/dingtalk.js +8 -2
  24. package/dist/channels/feishu.js +6 -1
  25. package/dist/channels/wecom.js +7 -3
  26. package/dist/cli/agent-command.js +2 -0
  27. package/dist/cli/agent-create.js +121 -23
  28. package/dist/cli/agent.js +10 -3
  29. package/dist/cli/aid-bind-command.js +4 -1
  30. package/dist/cli/aun-commands.js +82 -22
  31. package/dist/cli/daemon-commands.js +260 -26
  32. package/dist/cli/index.js +25 -13
  33. package/dist/cli/memory-command.js +33 -14
  34. package/dist/cli/restart-monitor.js +52 -13
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/task-context.js +1 -0
  38. package/dist/cli/trigger-command.js +2 -2
  39. package/dist/config/access-policy.js +2 -0
  40. package/dist/config/config-field-policy.js +1 -0
  41. package/dist/config/config-operation-service.js +17 -6
  42. package/dist/config/gateway-config.js +1 -1
  43. package/dist/config/peer-role-resolver.js +10 -8
  44. package/dist/contracts/ecweb-service-protocol.js +44 -0
  45. package/dist/core/agent-application-service.js +11 -1
  46. package/dist/core/agent-ipc-registration.js +4 -0
  47. package/dist/core/agent-runtime.js +6 -0
  48. package/dist/core/auth/agent-delegation.js +87 -9
  49. package/dist/core/auth/auth-gateway.js +3 -1
  50. package/dist/core/auth/authorization-audit.js +25 -4
  51. package/dist/core/auth/debug-context.js +5 -1
  52. package/dist/core/auth/operation-catalog.js +24 -0
  53. package/dist/core/command/agent-control.js +91 -12
  54. package/dist/core/command/command-handler.js +64 -47
  55. package/dist/core/command/connect-menu.js +23 -2
  56. package/dist/core/command/menu-catalog.js +49 -12
  57. package/dist/core/command/menu-handler.js +110 -105
  58. package/dist/core/command/menu-protocol.js +29 -3
  59. package/dist/core/command/role-menu.js +7 -6
  60. package/dist/core/command/slash-gate.js +22 -5
  61. package/dist/core/command/slash-handler.js +121 -102
  62. package/dist/core/event-catalog.js +17 -0
  63. package/dist/core/interaction-router.js +2 -1
  64. package/dist/core/ipc-registration.js +44 -8
  65. package/dist/core/memory/batch-meta.js +2 -0
  66. package/dist/core/memory/consolidation-context.js +42 -51
  67. package/dist/core/memory/consolidation-ops-records.js +39 -7
  68. package/dist/core/memory/consolidation-trigger.js +72 -65
  69. package/dist/core/memory/consolidation.js +226 -20
  70. package/dist/core/memory/memory-writer.js +160 -34
  71. package/dist/core/memory/relation-idle-monitor.js +287 -0
  72. package/dist/core/memory/relation-sweep.js +206 -0
  73. package/dist/core/message/aun-ipc-sender.js +31 -5
  74. package/dist/core/message/aun-request-registry.js +97 -3
  75. package/dist/core/message/im-renderer.js +4 -0
  76. package/dist/core/message/message-admission.js +8 -4
  77. package/dist/core/message/message-bridge.js +96 -53
  78. package/dist/core/message/message-log.js +72 -0
  79. package/dist/core/message/message-queue.js +11 -5
  80. package/dist/core/message/outbound.js +70 -0
  81. package/dist/core/message/peer-mode.js +7 -2
  82. package/dist/core/message/response-engine.js +633 -191
  83. package/dist/core/model/model-catalog.js +7 -6
  84. package/dist/core/ownership/owner-resolver.js +384 -178
  85. package/dist/core/permission/ec-command-parser.js +129 -8
  86. package/dist/core/permission/tool-policy.js +35 -14
  87. package/dist/core/role/runtime-policy.js +64 -0
  88. package/dist/core/session/session-capsule.js +197 -0
  89. package/dist/core/session/session-manager.js +172 -18
  90. package/dist/core/session/session-mapper.js +2 -0
  91. package/dist/core/system-session/memory.js +3 -18
  92. package/dist/ecweb/basic-settings-service.js +709 -0
  93. package/dist/ecweb/providers-service.js +172 -0
  94. package/dist/index.js +95 -7
  95. package/dist/ipc.js +100 -19
  96. package/dist/stats/budget.js +1 -1
  97. package/dist/stats/db.js +48 -0
  98. package/dist/stats/index.js +3 -3
  99. package/dist/stats/price-resolver.js +304 -5
  100. package/dist/stats/query.js +328 -3
  101. package/dist/stats/writer.js +79 -6
  102. package/dist/trigger/application-service.js +12 -0
  103. package/dist/trigger/authorization.js +2 -2
  104. package/dist/trigger/feedback.js +18 -7
  105. package/dist/trigger/history.js +36 -0
  106. package/dist/trigger/manager.js +20 -3
  107. package/dist/trigger/parser.js +6 -3
  108. package/dist/trigger/patch.js +1 -1
  109. package/dist/trigger/scheduler.js +3 -0
  110. package/dist/trigger/system-definitions.js +43 -7
  111. package/dist/trigger/validation.js +13 -5
  112. package/dist/utils/ecweb-supervisor.js +31 -10
  113. package/dist/utils/error-utils.js +22 -4
  114. package/dist/utils/evolcore-version.js +3 -2
  115. package/dist/utils/host-info.js +52 -0
  116. package/dist/utils/npm-ops.js +2 -1
  117. package/dist/utils/package-version-info.js +1 -1
  118. package/dist/utils/upgrade-jobs.js +45 -5
  119. package/ecagent/dist/harness/agent-harness.js +4 -1
  120. package/kits/docs/INDEX.md +1 -1
  121. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  122. package/kits/docs/evolcore/INDEX.md +3 -2
  123. package/kits/docs/evolcore/agent-create.md +3 -2
  124. package/kits/docs/evolcore/agent.md +1 -1
  125. package/kits/docs/evolcore/aid.md +29 -12
  126. package/kits/docs/evolcore/config.md +9 -7
  127. package/kits/docs/evolcore/event.md +1 -0
  128. package/kits/docs/evolcore/fs.md +5 -0
  129. package/kits/docs/evolcore/memory-architecture.md +3 -4
  130. package/kits/docs/evolcore/memory-consolidation.md +28 -7
  131. package/kits/docs/evolcore/memory-tags.md +1 -1
  132. package/kits/docs/evolcore/memory.md +1 -1
  133. package/kits/docs/evolcore/menu-client.md +1 -1
  134. package/kits/docs/evolcore/menu-protocol.md +38 -0
  135. package/kits/docs/evolcore/msg.md +18 -2
  136. package/kits/docs/evolcore/session.md +14 -0
  137. package/kits/eck_manifest.json +3 -3
  138. package/kits/rules/04-relation.md +3 -2
  139. package/kits/schemas/agent-config.schema.13.json +20 -1
  140. package/kits/skills/aid-ability/SKILL.md +35 -6
  141. package/kits/templates/memory-consolidation/generalize.md +32 -4
  142. package/kits/templates/memory-consolidation/notes.md +2 -2
  143. package/kits/templates/memory-consolidation/promote.md +10 -2
  144. package/kits/templates/session-capsule/recovery.md +5 -0
  145. package/kits/templates/session-capsule/renew.md +5 -0
  146. package/kits/templates/system-fragments/baseagent.md +5 -0
  147. package/kits/templates/system-fragments/bootstrap.md +6 -6
  148. package/kits/templates/system-fragments/channel.md +1 -1
  149. package/kits/templates/system-fragments/memory.md +12 -3
  150. package/kits/templates/system-fragments/session.md +1 -1
  151. package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
  152. package/package.json +3 -3
  153. package/dist/stats/billing.js +0 -215
@@ -33,8 +33,8 @@ import { buildClaudeUnixSocketAllowlist } from '../core/permission/unix-socket-p
33
33
  import { auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
34
34
  import { getManagedTaskTempDir, isManagedSessionRuntimeDir } from '../cli/task-context.js';
35
35
  import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext } from './runner-types.js';
36
- import { resolveModelSpec } from '../stats/billing.js';
37
- import { contextTokensForUsage, usageForContext, isClaudeContextUsageModel, realContextWindowForModel, autoCompactWindowForModel, sdkAutoCompactWindowForModel } from './runner-types.js';
36
+ import { getGatewayPricing as getSharedGatewayPricing, resolveModelSpec } from '../stats/price-resolver.js';
37
+ import { contextTokensForUsage, usageForContext, realContextWindowForModel, autoCompactWindowForModel, sdkAutoCompactWindowForModel } from './runner-types.js';
38
38
  import { hasContextWindowSuffix, stripContextWindowSuffix } from '../core/model/context-window-suffix.js';
39
39
  const resolveModule = createRequire(import.meta.url);
40
40
  const CLAUDE_INTERRUPT_TIMEOUT_MS = 5_000;
@@ -438,80 +438,9 @@ async function assertClaudeSettingSourcesHaveLiteralSandboxPaths(cwd, settingSou
438
438
  }
439
439
  }
440
440
  }
441
- // ── 网关价格缓存(从 /v1/models 的 pricing/effective_pricing 提取)─────────────
442
- // 与别名刷新同范式:按 baseUrl 缓存,1h TTL,stale-while-revalidate(缺失/过期时
443
- // fire-and-forget 触发刷新,本轮先用旧值或回退,不阻塞查询)。
444
- const GATEWAY_PRICING_TTL_MS = 60 * 60 * 1000; // 1h
445
- const gatewayPricingCache = new Map(); // key: baseUrl
446
- const gatewayPricingInFlight = new Set(); // 去重并发刷新
447
- /** 把 /v1/models 单个 model 的价格对象转为 PriceQuad(与 gateway-control 的 apiPricingToQuad 等价)。
448
- * 单位假设:接口价与 model-prices.jsonl 同口径(USD per 1M token),不做换算。 */
449
- function apiPricingToQuad(p) {
450
- if (!p || typeof p !== 'object')
451
- return undefined;
452
- const n = (v) => (typeof v === 'number' && isFinite(v) ? v : undefined);
453
- const quad = {
454
- input: n(p.input),
455
- output: n(p.output),
456
- cache_read: n(p.cache_read),
457
- cache_write: n(p.cache_write),
458
- };
459
- // 全空则视为无价
460
- if (quad.input === undefined && quad.output === undefined
461
- && quad.cache_read === undefined && quad.cache_write === undefined)
462
- return undefined;
463
- return quad;
464
- }
465
- /** 拉取网关 /v1/models 的官方价(pricing) + 网关价(effective_pricing),写入 gatewayPricingCache。
466
- * 失败静默——保持回退到本地价表 / official。 */
467
- async function refreshGatewayPricing(baseUrl, apiKey, requestHeaders) {
468
- if (gatewayPricingInFlight.has(baseUrl))
469
- return;
470
- gatewayPricingInFlight.add(baseUrl);
471
- try {
472
- const url = `${baseUrl.replace(/\/+$/, '')}/v1/models`;
473
- const controller = new AbortController();
474
- const timer = setTimeout(() => controller.abort(), 5000);
475
- const resp = await fetch(url, {
476
- signal: controller.signal,
477
- headers: {
478
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
479
- ...requestHeaders,
480
- },
481
- });
482
- clearTimeout(timer);
483
- if (!resp.ok)
484
- return;
485
- const json = await resp.json();
486
- const arr = Array.isArray(json?.data) ? json.data
487
- : Array.isArray(json?.models) ? json.models : [];
488
- const official = new Map();
489
- const gateway = new Map();
490
- for (const m of arr) {
491
- const id = typeof m === 'string' ? m : (m?.id || m?.name || m?.model);
492
- if (!id || typeof m !== 'object')
493
- continue;
494
- const off = apiPricingToQuad(m.pricing);
495
- if (off)
496
- official.set(id, off);
497
- const gw = apiPricingToQuad(m.effective_pricing);
498
- if (gw)
499
- gateway.set(id, gw);
500
- }
501
- // 汇率:接口 usd_to_cny,缺失则留空(计费层默认用 7)
502
- const usdToCny = (typeof json?.usd_to_cny === 'number' && json.usd_to_cny > 0) ? json.usd_to_cny : undefined;
503
- if (official.size > 0 || gateway.size > 0) {
504
- gatewayPricingCache.set(baseUrl, { cache: { official, gateway, usdToCny }, fetchedAt: Date.now() });
505
- logger.info(`[AgentRunner] Refreshed gateway pricing from ${url}: official=${official.size} gateway=${gateway.size} usd_to_cny=${usdToCny ?? '(default 7)'}`);
506
- }
507
- }
508
- catch {
509
- // 网络/解析失败:保持回退,不打断查询
510
- }
511
- finally {
512
- gatewayPricingInFlight.delete(baseUrl);
513
- }
514
- }
441
+ // ── 网关价格缓存 ─────────────────────────────────────────────────────────────
442
+ // 价格获取、缓存与计费统一由 price-resolver.ts 管理,各基座共用一份缓存
443
+ // (按 baseUrl、1h TTL、stale-while-revalidate)。
515
444
  /**
516
445
  * 为支持 1M 上下文的模型追加 `[1m]` 后缀——仅在交给 SDK query() 时调用。
517
446
  *
@@ -798,13 +727,7 @@ export class AgentRunner {
798
727
  /** 返回当前网关 /v1/models 的价格缓存(1h TTL,stale-while-revalidate)。
799
728
  * 缺失/过期时 fire-and-forget 触发刷新,本轮先返回旧值或 undefined(回退本地价表)。 */
800
729
  getGatewayPricing() {
801
- if (!this.baseUrl)
802
- return undefined;
803
- const entry = gatewayPricingCache.get(this.baseUrl);
804
- if (!entry || Date.now() - entry.fetchedAt > GATEWAY_PRICING_TTL_MS) {
805
- refreshGatewayPricing(this.baseUrl, this.apiKey, this.customHeaders); // 不 await,stale-while-revalidate
806
- }
807
- return entry?.cache;
730
+ return getSharedGatewayPricing(this.baseUrl, this.apiKey, this.customHeaders);
808
731
  }
809
732
  async resolveCapabilityRunOptions(projectPath) {
810
733
  let agentConfig = this.agentConfig;
@@ -941,19 +864,8 @@ export class AgentRunner {
941
864
  const questions = input.questions;
942
865
  // 没有交互上下文(无渠道适配器),回退到纯文本
943
866
  const permCtx = this.permissionContexts.get(sessionId);
944
- if (usesUnattendedInteractions(permCtx)) {
945
- logger.info(`[AgentRunner] interaction.auto_resolved kind=ask_user session=${sessionId}`);
946
- const unattendedAnswer = '当前为无人值守 Trigger,请基于已有上下文选择最安全合理的方案并继续执行。';
947
- const answers = {};
948
- for (const question of questions ?? []) {
949
- answers[question.question] = question.multiSelect ? [unattendedAnswer] : unattendedAnswer;
950
- }
951
- return {
952
- behavior: 'allow',
953
- updatedInput: { ...input, answers },
954
- decisionClassification: 'user_temporary',
955
- };
956
- }
867
+ if (usesUnattendedInteractions(permCtx))
868
+ throw new Error('无人值守任务不能自动回答用户问题');
957
869
  if (!permCtx?.adapter || !permCtx?.channelId) {
958
870
  return this.handleAskUserQuestionFallback(sessionId, input, questions, options);
959
871
  }
@@ -990,11 +902,15 @@ export class AgentRunner {
990
902
  buttons: [
991
903
  { key: 'submit', label: '✅ 确认选择', style: 'primary' },
992
904
  ],
905
+ ...(typeof q.recommendedOption === 'string'
906
+ ? { recommendedOption: q.options.find(opt => opt.label === q.recommendedOption)?.label }
907
+ : {}),
993
908
  allowCustomInput: true,
994
909
  },
995
910
  channelId: permCtx.channelId,
996
911
  sessionId,
997
912
  initiatorId: permCtx.userId,
913
+ blocking: true,
998
914
  };
999
915
  }
1000
916
  else {
@@ -1018,11 +934,15 @@ export class AgentRunner {
1018
934
  label: opt.label,
1019
935
  style: 'default',
1020
936
  })),
937
+ ...(typeof q.recommendedOption === 'string'
938
+ ? { recommendedOption: q.options.find(opt => opt.label === q.recommendedOption)?.label }
939
+ : {}),
1021
940
  allowCustomInput: true,
1022
941
  },
1023
942
  channelId: permCtx.channelId,
1024
943
  sessionId,
1025
944
  initiatorId: permCtx.userId,
945
+ blocking: true,
1026
946
  };
1027
947
  }
1028
948
  let cardSent = false;
@@ -1048,14 +968,7 @@ export class AgentRunner {
1048
968
  logger.warn(`[AgentRunner] AskUserQuestion card send failed for q${i}:`, err);
1049
969
  }
1050
970
  if (!cardSent) {
1051
- await permCtx.flushPending?.();
1052
- const firstLabel = q.options[0]?.label || '';
1053
- answers[q.question] = q.multiSelect ? [firstLabel] : firstLabel;
1054
- if (sendPrompt) {
1055
- const optText = q.options.map((o, idx) => ` ${idx + 1}. ${o.label}${o.description ? ` — ${o.description}` : ''}`).join('\n');
1056
- await sendPrompt(`💬 ${q.header || q.question}\n${q.header ? q.question + '\n' : ''}${optText}\n → 自动选择:${firstLabel}`);
1057
- }
1058
- continue;
971
+ throw new Error(`AskUserQuestion 卡片投递失败:${q.question}`);
1059
972
  }
1060
973
  try {
1061
974
  await permCtx.turn?.onInteractionOpen?.({
@@ -1063,7 +976,6 @@ export class AgentRunner {
1063
976
  kind: 'ask_user',
1064
977
  toolUseId: options.toolUseID,
1065
978
  requestId: options.requestId,
1066
- expiresAt: Date.now() + 20 * 60 * 1000,
1067
979
  });
1068
980
  }
1069
981
  catch (error) {
@@ -1091,7 +1003,10 @@ export class AgentRunner {
1091
1003
  }
1092
1004
  else if (action === '_custom_input') {
1093
1005
  const customText = values?.custom_text;
1094
- finish({ kind: 'answered', value: typeof customText === 'string' && customText.trim() ? customText.trim() : null });
1006
+ const trimmed = typeof customText === 'string' ? customText.trim() : '';
1007
+ if (!trimmed)
1008
+ return false;
1009
+ finish({ kind: 'answered', value: trimmed });
1095
1010
  }
1096
1011
  else if (action === 'submit' && q.multiSelect && values) {
1097
1012
  const selected = [];
@@ -1099,15 +1014,18 @@ export class AgentRunner {
1099
1014
  if (values[`opt_${idx}`] === true)
1100
1015
  selected.push(opt.label);
1101
1016
  });
1102
- finish({ kind: 'answered', value: selected.length > 0 ? selected : null });
1017
+ if (selected.length === 0)
1018
+ return false;
1019
+ finish({ kind: 'answered', value: selected });
1103
1020
  }
1104
1021
  else {
1105
1022
  finish({ kind: 'answered', value: action });
1106
1023
  }
1024
+ return true;
1107
1025
  }, {
1108
1026
  initiatorId: permCtx.userId,
1109
1027
  fallbackCommand: 'ask',
1110
- timeoutMs: 20 * 60 * 1000,
1028
+ // User questions wait until an explicit answer or cancellation.
1111
1029
  onCancel: async (reason) => {
1112
1030
  finish({ kind: 'cancelled', reason });
1113
1031
  await cancellationClosed;
@@ -1176,6 +1094,7 @@ export class AgentRunner {
1176
1094
  channelId: permCtx.channelId || '',
1177
1095
  sessionId,
1178
1096
  initiatorId: permCtx.userId,
1097
+ blocking: true,
1179
1098
  kind: {
1180
1099
  kind: 'action',
1181
1100
  title: `💬 ${q.question}`,
@@ -1198,7 +1117,6 @@ export class AgentRunner {
1198
1117
  kind: 'ask_user',
1199
1118
  toolUseId: options.toolUseID,
1200
1119
  requestId: options.requestId,
1201
- expiresAt: Date.now() + 20 * 60 * 1000,
1202
1120
  });
1203
1121
  }
1204
1122
  catch (error) {
@@ -1221,6 +1139,8 @@ export class AgentRunner {
1221
1139
  };
1222
1140
  permCtx.interactionRouter.register(requestId, sessionId, (action) => {
1223
1141
  const answer = action.trim();
1142
+ if (!answer)
1143
+ return false;
1224
1144
  const selectionParts = answer.split(/[,,]/).map(part => part.trim());
1225
1145
  const selectedIndexes = selectionParts.map(part => Number(part));
1226
1146
  const hasValidNumericSelection = selectionParts.length > 0
@@ -1240,10 +1160,10 @@ export class AgentRunner {
1240
1160
  else {
1241
1161
  finish({ kind: 'answered', value: answer });
1242
1162
  }
1163
+ return true;
1243
1164
  }, {
1244
1165
  initiatorId: permCtx.userId,
1245
1166
  fallbackCommand: 'ask',
1246
- timeoutMs: 20 * 60 * 1000,
1247
1167
  onCancel: async (reason) => {
1248
1168
  finish({ kind: 'cancelled', reason });
1249
1169
  await cancellationClosed;
@@ -1283,12 +1203,7 @@ export class AgentRunner {
1283
1203
  }
1284
1204
  }
1285
1205
  else {
1286
- const firstLabel = q.options[0]?.label || '';
1287
- answers[q.question] = firstLabel;
1288
- if (sendPrompt) {
1289
- const optText = q.options.map((o, i) => ` ${i + 1}. ${o.label}${o.description ? ` — ${o.description}` : ''}`).join('\n');
1290
- await sendPrompt(`💬 ${q.question}\n${optText}\n\n → 自动选择:${firstLabel}`);
1291
- }
1206
+ throw new Error(`AskUserQuestion 没有可用的交互路由:${q.question}`);
1292
1207
  }
1293
1208
  }
1294
1209
  }
@@ -1300,17 +1215,14 @@ export class AgentRunner {
1300
1215
  */
1301
1216
  async handleExitPlanMode(sessionId, input, options) {
1302
1217
  const permCtx = this.permissionContexts.get(sessionId);
1303
- if (usesUnattendedInteractions(permCtx)) {
1304
- logger.info(`[AgentRunner] interaction.auto_resolved kind=plan_approval session=${sessionId}`);
1305
- return { behavior: 'allow', updatedInput: input, decisionClassification: 'user_temporary' };
1306
- }
1218
+ if (usesUnattendedInteractions(permCtx))
1219
+ throw new Error('无人值守任务不能自动批准计划');
1307
1220
  const sendPrompt = permCtx?.adapter && permCtx?.channelId
1308
1221
  ? async (text) => permCtx.adapter.send(buildEnvelope({ channel: permCtx.adapter.channelName, channelId: permCtx.channelId, replyContext: permCtx.replyContext }), { kind: 'result.text', text, isFinal: true })
1309
1222
  : this.sendPromptFn;
1310
1223
  // 无任何交互能力,直接 allow
1311
- if (!permCtx?.channelId || !sendPrompt) {
1312
- return { behavior: 'allow', updatedInput: input, decisionClassification: 'user_temporary' };
1313
- }
1224
+ if (!permCtx?.channelId || !sendPrompt)
1225
+ throw new Error('计划审批没有可用的交互路由');
1314
1226
  // 立即暂停 idle 监控,不等卡片发完再 register
1315
1227
  permCtx.interactionRouter?.markWaiting(sessionId);
1316
1228
  const waitForPlanDecision = async (requestId) => {
@@ -1321,7 +1233,6 @@ export class AgentRunner {
1321
1233
  kind: 'plan_approval',
1322
1234
  toolUseId: options.toolUseID,
1323
1235
  requestId: options.requestId,
1324
- expiresAt: Date.now() + 20 * 60 * 1000,
1325
1236
  });
1326
1237
  }
1327
1238
  catch (error) {
@@ -1369,7 +1280,6 @@ export class AgentRunner {
1369
1280
  }, {
1370
1281
  initiatorId: permCtx.userId,
1371
1282
  fallbackCommand: 'ask',
1372
- timeoutMs: 20 * 60 * 1000,
1373
1283
  onCancel: async (reason) => {
1374
1284
  finish({ kind: 'cancelled', reason });
1375
1285
  await cancellationClosed;
@@ -1446,6 +1356,7 @@ export class AgentRunner {
1446
1356
  channelId: permCtx.channelId,
1447
1357
  sessionId,
1448
1358
  initiatorId: permCtx.userId,
1359
+ blocking: true,
1449
1360
  fallback: {
1450
1361
  command: 'ask',
1451
1362
  buttonArgMap: { approve: '1', reject: '2' },
@@ -1482,6 +1393,7 @@ export class AgentRunner {
1482
1393
  channelId: permCtx.channelId || '',
1483
1394
  sessionId,
1484
1395
  initiatorId: permCtx.userId,
1396
+ blocking: true,
1485
1397
  kind: {
1486
1398
  kind: 'action',
1487
1399
  title: '📋 计划审批',
@@ -1501,11 +1413,8 @@ export class AgentRunner {
1501
1413
  permCtx.interactionRouter.unmarkWaiting(sessionId);
1502
1414
  return await waitForPlanDecision(fallbackRequestId);
1503
1415
  }
1504
- // 无交互能力,发提示后直接 allow
1505
1416
  permCtx?.interactionRouter?.unmarkWaiting(sessionId);
1506
- await permCtx.flushPending?.();
1507
- await sendPrompt('📋 计划审批\nAI 已完成规划,自动批准执行。');
1508
- return { behavior: 'allow', updatedInput: input, decisionClassification: 'user_temporary' };
1417
+ throw new Error('计划审批没有可用的交互路由,已拒绝自动批准');
1509
1418
  }
1510
1419
  /**
1511
1420
  * SDK 原始事件 → 标准 AgentEvent 转换
@@ -1926,10 +1835,8 @@ export class AgentRunner {
1926
1835
  const cleanResult = typeof event.result === 'string'
1927
1836
  ? event.result.replace(/<thinking>[\s\S]*?<\/thinking>\s*/g, '').trim()
1928
1837
  : event.result;
1929
- // 从 usage 求当前上下文占用。
1930
- // Claude:input_tokens 是净输入(不含 cache),三项求和 = 实际上下文长度。
1931
- // 非 Claude(DeepSeek/OpenAI 兼容):cache_read 是服务端 KV cache 不占上下文窗口,
1932
- // input_tokens 本身就是完整的上下文输入量。
1838
+ // 非 GPT 的上下文占用 = 输入 + 输出 + 缓存创建 + 缓存读取。
1839
+ // GPT 沿用原有的输入口径,避免重复计算已包含在输入中的缓存。
1933
1840
  const u = event.usage;
1934
1841
  // Claude Code represents transport/API failures as a fresh
1935
1842
  // `<synthetic>` assistant message. Its usage describes the failed
@@ -1944,8 +1851,7 @@ export class AgentRunner {
1944
1851
  };
1945
1852
  const terminalUsage = isSyntheticError ? syntheticUsage : u;
1946
1853
  const effectiveModel = callModel ?? this.model;
1947
- const isClaudeModel = isClaudeContextUsageModel(effectiveModel);
1948
- const totalTokens = contextTokensForUsage(u, !!isClaudeModel);
1854
+ const totalTokens = contextTokensForUsage(u, effectiveModel);
1949
1855
  const contextWindowTokens = resolvedContextWindow ?? realContextWindowForModel(sdkModel);
1950
1856
  const autoCompactTokens = autoCompactWindowForModel(sdkModel);
1951
1857
  const aggregateContextUsage = totalTokens > 0 ? {
@@ -1958,7 +1864,7 @@ export class AgentRunner {
1958
1864
  } : undefined;
1959
1865
  if (lastModelCall?.tokenUsage) {
1960
1866
  const lastUsageForContext = usageForContext(lastModelCall.tokenUsage);
1961
- const lastTotalTokens = contextTokensForUsage(lastUsageForContext, !!isClaudeModel);
1867
+ const lastTotalTokens = contextTokensForUsage(lastUsageForContext, effectiveModel);
1962
1868
  lastModelCall = {
1963
1869
  ...lastModelCall,
1964
1870
  contextUsage: lastTotalTokens > 0 ? {
@@ -1972,7 +1878,7 @@ export class AgentRunner {
1972
1878
  };
1973
1879
  }
1974
1880
  const contextUsageForCall = (usage) => {
1975
- const callTotalTokens = contextTokensForUsage(usageForContext(usage), !!isClaudeModel);
1881
+ const callTotalTokens = contextTokensForUsage(usageForContext(usage), effectiveModel);
1976
1882
  return callTotalTokens > 0 ? {
1977
1883
  totalTokens: callTotalTokens,
1978
1884
  maxTokens: contextWindowTokens,
@@ -2165,10 +2071,7 @@ export class AgentRunner {
2165
2071
  const runCatalog = await this.getModelCatalog();
2166
2072
  if (this.baseUrl) {
2167
2073
  // 顺带预热网关价格缓存(1h TTL),让本轮结束写库时已就绪
2168
- const pricing = gatewayPricingCache.get(this.baseUrl);
2169
- if (!pricing || (Date.now() - pricing.fetchedAt > GATEWAY_PRICING_TTL_MS)) {
2170
- refreshGatewayPricing(this.baseUrl, this.apiKey, this.customHeaders);
2171
- }
2074
+ void getSharedGatewayPricing(this.baseUrl, this.apiKey, this.customHeaders);
2172
2075
  }
2173
2076
  ensureDir(projectPath);
2174
2077
  ensureDir(path.join(projectPath, '.claude'));
@@ -2231,13 +2134,16 @@ export class AgentRunner {
2231
2134
  throw error;
2232
2135
  }
2233
2136
  logger.warn(`[AgentRunner] Invalid session file, starting new session`);
2137
+ if (modelOverride?.capsule) {
2138
+ const recovered = await modelOverride.capsule.recover(agentSessionId, prompt, systemPromptAppend);
2139
+ prompt = recovered.prompt;
2140
+ systemPromptAppend = recovered.systemPrompt;
2141
+ }
2142
+ else if (this.onSessionIdUpdate) {
2143
+ await this.onSessionIdUpdate(sessionId, '');
2144
+ }
2234
2145
  agentSessionId = undefined;
2235
2146
  this.activeSessions.delete(sessionId);
2236
- if (this.onSessionIdUpdate) {
2237
- void Promise.resolve(this.onSessionIdUpdate(sessionId, '')).catch(error => {
2238
- logger.debug(`[AgentRunner] ignored empty session binding callback failure: ${error instanceof Error ? error.message : String(error)}`);
2239
- });
2240
- }
2241
2147
  }
2242
2148
  }
2243
2149
  // PreCompact Hook - 在压缩开始时触发
@@ -3084,12 +2990,7 @@ export class AgentRunner {
3084
2990
  logger.info('[AgentRunner] Creating query with images:', images.length, 'first image size:', images[0]?.data?.length ?? 0);
3085
2991
  msgStream.push(prompt, images, inputId);
3086
2992
  try {
3087
- // Topic bindings are authoritative for every input shape. Starting
3088
- // an unresumed Claude query for a bound topic would discover a second
3089
- // backend and then fail activation with a binding conflict.
3090
- sdkStream = topicBinding || recoverySessionId
3091
- ? createQuery(msgStream, agentSessionId, resumeAt)
3092
- : createQuery(msgStream);
2993
+ sdkStream = createQuery(msgStream, agentSessionId, resumeAt);
3093
2994
  }
3094
2995
  catch (error) {
3095
2996
  this.cleanupSandboxSettingsFile(sessionId, sandboxSettingsFile);