evolcore 0.0.40 → 0.0.41-test.1

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 (226) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/baseagent-availability.js +1 -1
  5. package/dist/agents/baseagent.js +20 -43
  6. package/dist/agents/claude-runner.js +197 -197
  7. package/dist/agents/codex-runner.js +535 -259
  8. package/dist/agents/ecagent-runner.js +31 -12
  9. package/dist/agents/gemini-runner.js +27 -7
  10. package/dist/agents/runner-types.js +11 -3
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/group/fs-download.js +39 -0
  14. package/dist/aun/group/identity.js +36 -13
  15. package/dist/aun/group/operations.js +5 -0
  16. package/dist/aun/msg/managed-operation.js +72 -11
  17. package/dist/aun/msg/p2p.js +32 -7
  18. package/dist/aun/service-proxy.js +36 -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 +367 -24
  22. package/dist/channels/daemon.js +39 -5
  23. package/dist/cli/agent-command.js +2 -0
  24. package/dist/cli/agent-create.js +98 -19
  25. package/dist/cli/agent.js +10 -3
  26. package/dist/cli/aun-commands.js +85 -41
  27. package/dist/cli/daemon-commands.js +678 -688
  28. package/dist/cli/fs-command.js +64 -2
  29. package/dist/cli/index.js +48 -4
  30. package/dist/cli/managed-command-guard.js +4 -0
  31. package/dist/cli/model.js +40 -40
  32. package/dist/cli/proxy-command.js +92 -0
  33. package/dist/cli/restart-monitor.js +17 -0
  34. package/dist/cli/role.js +85 -0
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/trigger-command.js +2 -2
  38. package/dist/config/access-policy.js +8 -1
  39. package/dist/config/boot-log.js +38 -1
  40. package/dist/config/config-field-policy.js +5 -32
  41. package/dist/config/config-manager.js +46 -39
  42. package/dist/config/config-operation-service.js +8 -11
  43. package/dist/config/contact-book-store.js +47 -21
  44. package/dist/config/contact-book.js +18 -12
  45. package/dist/config/contact-operation-service.js +3 -4
  46. package/dist/config/contact-request-service.js +11 -0
  47. package/dist/config/daemon-services.js +11 -0
  48. package/dist/config/gateway-config.js +89 -595
  49. package/dist/config/peer-role-resolver.js +15 -11
  50. package/dist/config/providers-config.js +12 -7
  51. package/dist/config/providers-import.js +3 -21
  52. package/dist/config/resolved-config-op.js +3 -0
  53. package/dist/config/role-command-service.js +166 -0
  54. package/dist/config/role-request-service.js +193 -0
  55. package/dist/config/schema-migration.js +686 -25
  56. package/dist/config-store.js +79 -3
  57. package/dist/contracts/ecweb-instance.js +41 -0
  58. package/dist/contracts/ecweb-service-protocol.js +3 -1
  59. package/dist/core/agent-application-service.js +11 -1
  60. package/dist/core/agent-ipc-registration.js +4 -0
  61. package/dist/core/agent-runtime.js +1 -1
  62. package/dist/core/auth/agent-delegation.js +82 -6
  63. package/dist/core/auth/auth-gateway.js +1 -1
  64. package/dist/core/auth/authorization-audit.js +37 -9
  65. package/dist/core/auth/delegation-authorization.js +3 -1
  66. package/dist/core/auth/operation-authorizer.js +15 -0
  67. package/dist/core/auth/operation-catalog.js +39 -6
  68. package/dist/core/command/agent-control.js +94 -19
  69. package/dist/core/command/agent-storage-menu.js +5 -3
  70. package/dist/core/command/cli-intent-parser.js +2 -1
  71. package/dist/core/command/command-handler.js +105 -145
  72. package/dist/core/command/connect-menu.js +31 -2
  73. package/dist/core/command/data-root-resolver.js +5 -4
  74. package/dist/core/command/memory-slash.js +16 -8
  75. package/dist/core/command/menu-catalog.js +6 -6
  76. package/dist/core/command/menu-handler.js +87 -163
  77. package/dist/core/command/menu-protocol.js +9 -2
  78. package/dist/core/command/role-menu.js +148 -30
  79. package/dist/core/command/slash-gate.js +13 -10
  80. package/dist/core/command/slash-handler.js +157 -352
  81. package/dist/core/daemon-control.js +8 -14
  82. package/dist/core/event-catalog.js +15 -0
  83. package/dist/core/evolagent-registry.js +4 -4
  84. package/dist/core/evolagent.js +2 -2
  85. package/dist/core/inference/text-inference.js +31 -40
  86. package/dist/core/ipc-registration.js +24 -3
  87. package/dist/core/memory/consolidation-context.js +51 -5
  88. package/dist/core/memory/consolidation-ops-records.js +1 -1
  89. package/dist/core/memory/consolidation-trigger.js +190 -190
  90. package/dist/core/memory/consolidation.js +316 -29
  91. package/dist/core/memory/forget-log.js +96 -0
  92. package/dist/core/memory/index-manager.js +27 -5
  93. package/dist/core/memory/memory-admin.js +45 -5
  94. package/dist/core/memory/memory-writer.js +163 -18
  95. package/dist/core/memory/relation-idle-monitor.js +119 -58
  96. package/dist/core/memory/relation-sweep.js +44 -39
  97. package/dist/core/message/aun-ipc-sender.js +34 -7
  98. package/dist/core/message/aun-request-registry.js +97 -3
  99. package/dist/core/message/im-renderer.js +11 -4
  100. package/dist/core/message/message-admission.js +97 -8
  101. package/dist/core/message/message-bridge.js +71 -24
  102. package/dist/core/message/message-log.js +55 -0
  103. package/dist/core/message/message-queue.js +5 -5
  104. package/dist/core/message/response-engine.js +387 -144
  105. package/dist/core/model/catalog-service.js +4 -2
  106. package/dist/core/model/config-scope.js +24 -64
  107. package/dist/core/model/field-scope.js +1 -1
  108. package/dist/core/model/model-catalog.js +37 -47
  109. package/dist/core/model/model-diagnostics.js +4 -3
  110. package/dist/core/model/model-fallback.js +10 -7
  111. package/dist/core/model/model-permission.js +3 -2
  112. package/dist/core/ownership/owner-resolver.js +25 -23
  113. package/dist/core/permission/ec-command-parser.js +138 -5
  114. package/dist/core/permission/sandbox-runtime.js +18 -1
  115. package/dist/core/permission/tool-policy.js +42 -10
  116. package/dist/core/relation/peer-identity.js +64 -1
  117. package/dist/core/role/runtime-policy.js +72 -13
  118. package/dist/core/session/session-capsule.js +197 -0
  119. package/dist/core/session/session-idle-monitor.js +1 -1
  120. package/dist/core/session/session-manager.js +168 -14
  121. package/dist/core/session/session-mapper.js +2 -0
  122. package/dist/core/session/session-renew.js +3 -3
  123. package/dist/core/skill/index-generator.js +15 -5
  124. package/dist/core/system-session/memory.js +6 -1
  125. package/dist/core/thread/thread-service.js +19 -6
  126. package/dist/directory/owner-directory-admission.js +95 -0
  127. package/dist/directory/owner-directory-authorization.js +309 -0
  128. package/dist/directory/owner-directory-cache.js +635 -0
  129. package/dist/eck/kit-renderer.js +2 -2
  130. package/dist/ecweb/basic-settings-service.js +33 -40
  131. package/dist/ecweb/message-context-service.js +110 -0
  132. package/dist/index.js +79 -17
  133. package/dist/ipc.js +189 -17
  134. package/dist/paths.js +4 -0
  135. package/dist/proxy/command.js +122 -0
  136. package/dist/proxy/ipc-service.js +68 -0
  137. package/dist/proxy/manager.js +485 -0
  138. package/dist/proxy/service-supervisor.js +603 -0
  139. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  140. package/dist/stats/budget.js +1 -1
  141. package/dist/stats/db.js +15 -0
  142. package/dist/stats/index.js +2 -2
  143. package/dist/stats/price-resolver.js +304 -5
  144. package/dist/stats/query.js +82 -3
  145. package/dist/stats/writer.js +38 -5
  146. package/dist/trigger/feedback.js +18 -7
  147. package/dist/trigger/manager.js +20 -3
  148. package/dist/trigger/parser.js +6 -3
  149. package/dist/trigger/patch.js +1 -1
  150. package/dist/trigger/system-definitions.js +43 -7
  151. package/dist/trigger/validation.js +13 -5
  152. package/dist/utils/cross-platform.js +14 -0
  153. package/dist/utils/ecweb-supervisor.js +258 -83
  154. package/dist/utils/error-utils.js +16 -2
  155. package/dist/utils/logger.js +24 -5
  156. package/dist/utils/npm-ops.js +2 -1
  157. package/dist/utils/package-version-info.js +5 -3
  158. package/dist/utils/upgrade-jobs.js +45 -5
  159. package/kits/docs/INDEX.md +1 -1
  160. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  161. package/kits/docs/channels/aun.md +9 -0
  162. package/kits/docs/evolcore/INDEX.md +2 -1
  163. package/kits/docs/evolcore/agent-create.md +3 -2
  164. package/kits/docs/evolcore/agent.md +1 -1
  165. package/kits/docs/evolcore/config.md +18 -7
  166. package/kits/docs/evolcore/contact.md +3 -0
  167. package/kits/docs/evolcore/event.md +1 -0
  168. package/kits/docs/evolcore/fs.md +16 -0
  169. package/kits/docs/evolcore/memory-architecture.md +2 -2
  170. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  171. package/kits/docs/evolcore/memory.md +1 -1
  172. package/kits/docs/evolcore/menu-protocol.md +36 -0
  173. package/kits/docs/evolcore/model.md +23 -20
  174. package/kits/docs/evolcore/msg.md +21 -8
  175. package/kits/docs/evolcore/session.md +14 -0
  176. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  177. package/kits/schemas/_meta.json +37 -4
  178. package/kits/schemas/agent-config.schema.13.json +23 -3
  179. package/kits/schemas/agent-config.schema.16.json +891 -0
  180. package/kits/schemas/daemon.schema.9.json +366 -0
  181. package/kits/schemas/defaults.schema.5.json +406 -127
  182. package/kits/schemas/relation-config.schema.11.json +260 -0
  183. package/kits/schemas/role-config.schema.1.json +7 -7
  184. package/kits/skills/.switches.json +3 -7
  185. package/kits/skills/aid-ability/SKILL.md +35 -6
  186. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  187. package/kits/skills/ec-trigger/SKILL.md +13 -5
  188. package/kits/skills/personal-assistant/SKILL.md +176 -0
  189. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  190. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  191. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  192. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  193. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  194. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  195. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  196. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  197. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  198. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  199. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  200. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  201. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  202. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  203. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  204. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  205. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  206. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  207. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  208. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  209. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  210. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  211. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  212. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  213. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  214. package/kits/templates/memory-consolidation/forget.md +19 -6
  215. package/kits/templates/memory-consolidation/notes.md +1 -1
  216. package/kits/templates/memory-consolidation/profile.md +2 -2
  217. package/kits/templates/memory-consolidation/promote.md +20 -3
  218. package/kits/templates/roles/member.json +8 -1
  219. package/kits/templates/session-capsule/recovery.md +5 -0
  220. package/kits/templates/session-capsule/renew.md +5 -0
  221. package/kits/templates/system-fragments/baseagent.md +2 -2
  222. package/kits/templates/system-fragments/bootstrap.md +6 -6
  223. package/kits/templates/system-fragments/channel.md +1 -1
  224. package/kits/templates/system-fragments/memory.md +4 -4
  225. package/package.json +7 -3
  226. package/dist/stats/billing.js +0 -215
@@ -5,7 +5,7 @@ import fs from 'fs';
5
5
  import os from 'os';
6
6
  import crypto from 'crypto';
7
7
  import { MAIN_CLI_BIN } from '../../product.js';
8
- import { BaseagentRunnerUnavailableError, hasCompact, autoCompactWindowForModel, isClaudeContextUsageModel, numericToken, formatAsyncQuestionAnswer, parseAsyncUserQuestions, } from '../../agents/runner-types.js';
8
+ import { BaseagentRunnerUnavailableError, hasCompact, autoCompactWindowForModel, contextTokensForUsage, numericToken, formatAsyncQuestionAnswer, parseAsyncUserQuestions, } from '../../agents/runner-types.js';
9
9
  import { loadedBaseagentIds } from '../../agents/baseagent-availability.js';
10
10
  import { isDiagnosticSessionActive } from '../command/diag-service.js';
11
11
  import { evaluateInboundAdmissionPreflight, evaluateOrdinaryInboundAdmission } from './message-admission.js';
@@ -21,7 +21,7 @@ import { createDecisionInferenceProvider, createTextInferenceProvider } from '..
21
21
  import { StreamIdleMonitor } from './stream-idle-monitor.js';
22
22
  import { logger } from '../../utils/logger.js';
23
23
  import { isHostChinese } from '../../utils/locale.js';
24
- import { ExecutionTimeoutError, OrphanedTargetSessionError, isExecutionFailure, getErrorMessage, getErrorRawText, getToolResultErrorText, classifyError, normalizeCoreErrorReason, normalizeCoreErrorSubtype, ErrorType, ERROR_PREFIX, isInfraError, isAbortTerminalReason, prefixErrorType, isRetryableError, isContextTooLongText } from '../../utils/error-utils.js';
24
+ import { ExecutionTimeoutError, OrphanedTargetSessionError, isExecutionFailure, getErrorMessage, getErrorRawText, getToolResultErrorText, classifyError, normalizeCoreErrorReason, normalizeCoreErrorSubtype, ErrorType, ERROR_PREFIX, isInfraError, isAbortTerminalReason, prefixErrorType, isRetryableError, isContextTooLongText, isPolicyRejectedError } from '../../utils/error-utils.js';
25
25
  import { readEvolcoreRuntimeFlavor, tagErrorTextWithEvolcoreVersion } from '../../utils/evolcore-version.js';
26
26
  import { describeProactiveSendCommandFailure, isExactEvolcoreSendCommandForSession, isThreadRoutedEvolcoreSendCommand, parseCodexToolCommand, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from '../permission/ec-command-parser.js';
27
27
  import { resolveThreadRouteTarget } from '../thread/thread-route.js';
@@ -653,6 +653,39 @@ function findDiagnosticShellSeparator(value, startOffset, endOffset) {
653
653
  }
654
654
  return -1;
655
655
  }
656
+ function findDiagnosticPatchDocumentEnd(value, startOffset, endOffset) {
657
+ let lineStart = startOffset;
658
+ while (lineStart < endOffset && (value[lineStart] === ' ' || value[lineStart] === '\t'))
659
+ lineStart++;
660
+ const beginEnd = diagnosticLineEnd(value, lineStart);
661
+ if (value.slice(lineStart, beginEnd).replace(/\r$/u, '') !== '*** Begin Patch')
662
+ return undefined;
663
+ let cursor = beginEnd < endOffset ? beginEnd + 1 : endOffset;
664
+ while (cursor < endOffset) {
665
+ const lineEnd = diagnosticLineEnd(value, cursor);
666
+ if (value.slice(cursor, lineEnd).replace(/\r$/u, '') === '*** End Patch')
667
+ return lineEnd;
668
+ if (lineEnd >= endOffset)
669
+ break;
670
+ cursor = lineEnd + 1;
671
+ }
672
+ return undefined;
673
+ }
674
+ function findDiagnosticTrailingCommand(value, startOffset, endOffset) {
675
+ let cursor = startOffset;
676
+ while (cursor < endOffset) {
677
+ const lineEnd = diagnosticLineEnd(value, cursor);
678
+ const line = value.slice(cursor, lineEnd).trim();
679
+ if (line && !line.startsWith('#')) {
680
+ const leadingWhitespace = value.slice(cursor, lineEnd).length - value.slice(cursor, lineEnd).trimStart().length;
681
+ return cursor + leadingWhitespace;
682
+ }
683
+ if (lineEnd >= endOffset)
684
+ break;
685
+ cursor = lineEnd + 1;
686
+ }
687
+ return undefined;
688
+ }
656
689
  function diagnosticLocation(source, startOffset, endOffset = startOffset) {
657
690
  const start = Math.max(0, Math.min(startOffset, source.value.length));
658
691
  const end = Math.max(start, Math.min(endOffset, source.value.length));
@@ -751,9 +784,21 @@ function addApplyPatchCompositionFinding(findings, candidate) {
751
784
  return;
752
785
  const heredocOffset = findUnquotedDiagnosticText(candidate.command, '<<', argumentsOffset);
753
786
  const endOffset = heredocOffset >= 0 ? heredocOffset : candidate.command.length;
754
- const separator = findDiagnosticShellSeparator(candidate.command, argumentsOffset, endOffset);
787
+ let separator = findDiagnosticShellSeparator(candidate.command, argumentsOffset, endOffset);
755
788
  if (separator < 0)
756
789
  return;
790
+ if (candidate.command[separator] === '\n' || candidate.command[separator] === '\r') {
791
+ const newlineLength = candidate.command[separator] === '\r' && candidate.command[separator + 1] === '\n' ? 2 : 1;
792
+ const patchEnd = findDiagnosticPatchDocumentEnd(candidate.command, separator + newlineLength, candidate.command.length);
793
+ if (patchEnd !== undefined) {
794
+ const afterPatch = patchEnd + (candidate.command[patchEnd] === '\r' && candidate.command[patchEnd + 1] === '\n'
795
+ ? 2 : candidate.command[patchEnd] === '\n' ? 1 : 0);
796
+ const trailingCommand = findDiagnosticTrailingCommand(candidate.command, afterPatch, candidate.command.length);
797
+ if (trailingCommand === undefined)
798
+ return;
799
+ separator = trailingCommand;
800
+ }
801
+ }
757
802
  findings.push(diagnosticFinding('apply-patch-composed-command', 'apply_patch 与其它 Shell 命令组合提交', '一次工具调用只提交完整的 apply_patch;测试、检查或其它命令另行调用。', '高', candidate.source, candidate.commandOffset + separator, candidate.commandOffset + separator + 1));
758
803
  }
759
804
  function addNestedShellDiagnosticFinding(findings, candidate) {
@@ -1317,6 +1362,7 @@ export class ResponseEngine {
1317
1362
  channelTypeMap = new Map(); // channelType → channelName(首个实例)
1318
1363
  /** 仅登记正在处理的任务,runner 的 session 回调绝不能投递到其它会话。 */
1319
1364
  activeRenderers = new Map();
1365
+ recoveryNoticeCapsules = new Set();
1320
1366
  /** 已主动发送开始提示时,忽略 runner 对同一次 compact 的回调。 */
1321
1367
  announcedCompactStarts = new Set();
1322
1368
  agentMap;
@@ -1416,15 +1462,15 @@ export class ResponseEngine {
1416
1462
  const aid = selfAID || (channel ? this.agentRegistry?.resolveByChannel(channel)?.aid : undefined);
1417
1463
  if (!aid)
1418
1464
  return undefined;
1419
- const config = resolveEffective({ self: aid }, { cache: true, expand: true });
1465
+ const config = resolveEffective({ self: aid }, { cache: true });
1420
1466
  return createTextInferenceProvider(baseagent, config);
1421
1467
  }
1422
1468
  getDecisionInferenceProvider(selfAID) {
1423
1469
  const aid = selfAID;
1424
1470
  if (!aid)
1425
1471
  return undefined;
1426
- const config = resolveEffective({ self: aid }, { cache: true, expand: true });
1427
- return createDecisionInferenceProvider(config.decision_model, config.Services);
1472
+ const config = resolveEffective({ self: aid }, { cache: true });
1473
+ return createDecisionInferenceProvider(config.Services);
1428
1474
  }
1429
1475
  getAvailableBaseagentsForOwner(evolName) {
1430
1476
  return loadedBaseagentIds(this.agentMap.keys(), evolName);
@@ -1493,6 +1539,10 @@ export class ResponseEngine {
1493
1539
  this.eventBus = eventBus;
1494
1540
  this.commandHandler = commandHandler;
1495
1541
  this.turnCoordinator = new SessionTurnCoordinator(sessionManager);
1542
+ sessionManager.setCapsuleTranscriptReader?.(async (session) => {
1543
+ const runner = this.getAgent(session.channel, session.baseagent, session.selfAID);
1544
+ return await runner.getSessionMessages?.(session.agentSessionId, session.projectPath) ?? [];
1545
+ });
1496
1546
  if (agentRunnerOrMap instanceof Map) {
1497
1547
  this.agentMap = agentRunnerOrMap;
1498
1548
  this.legacySingleRunnerMode = false;
@@ -1546,6 +1596,21 @@ export class ResponseEngine {
1546
1596
  this.activeTaskSpans.delete(event.sessionId);
1547
1597
  }
1548
1598
  });
1599
+ this.eventBus.subscribe('session:backend-recovery', event => {
1600
+ if (event.type !== 'session:backend-recovery' || this.recoveryNoticeCapsules.has(event.capsuleId))
1601
+ return;
1602
+ const active = this.activeRenderers.get(event.sessionId);
1603
+ if (!active)
1604
+ return;
1605
+ this.recoveryNoticeCapsules.add(event.capsuleId);
1606
+ if (this.recoveryNoticeCapsules.size > 512) {
1607
+ this.recoveryNoticeCapsules.delete(this.recoveryNoticeCapsules.values().next().value);
1608
+ }
1609
+ void active.renderer.sendSystemNotice(`原 ${event.baseagent} 会话无法恢复,已创建新的底层会话并载入恢复摘要。未确认的执行结果将先行核实。`, 'session.backend-recovery').catch(error => {
1610
+ this.recoveryNoticeCapsules.delete(event.capsuleId);
1611
+ logger.warn(`[ResponseEngine] Backend recovery notice failed: ${String(error)}`);
1612
+ });
1613
+ });
1549
1614
  // 初始化响应模式协调器,注册内置模式(interactive/proactive)
1550
1615
  const registry = new ResponseModeRegistry();
1551
1616
  registerBuiltinModes(registry);
@@ -1890,27 +1955,44 @@ export class ResponseEngine {
1890
1955
  return { state: 'missing' };
1891
1956
  }
1892
1957
  /** Outer execution deadlines use the same terminal owner as runner idle timeouts. */
1893
- async timeoutSession(sessionId, error) {
1958
+ async timeoutSession(sessionId, error, target) {
1959
+ const session = await this.sessionManager.getSessionById(sessionId);
1960
+ const active = session ? this.turnCoordinator.current(session).active : undefined;
1961
+ if (target && (!active || active.taskId !== target.taskId || active.generation !== target.generation))
1962
+ return;
1894
1963
  const timeout = this.activeTimeoutHandlers.get(sessionId);
1895
- if (timeout)
1896
- await timeout(error);
1964
+ if (timeout && active)
1965
+ await timeout(error, target);
1897
1966
  else
1898
- await this.interruptSession(sessionId, error instanceof OrphanedTargetSessionError ? 'execution_error' : 'timeout', false, isRetryableError(error));
1967
+ await this.interruptSession(sessionId, error instanceof OrphanedTargetSessionError ? 'execution_error' : 'timeout', false, isRetryableError(error), target);
1899
1968
  }
1900
- async interruptSession(sessionId, reason, strict = false, recoverable) {
1901
- this.clearPauseSession(sessionId);
1902
- // A retry delay has no active runner stream to abort. Wake it before any
1903
- // session-store I/O so /stop and a newer message take effect immediately.
1904
- this.cancelRetryDelays(sessionId);
1969
+ async interruptSession(sessionId, reason, strict = false, recoverable, target) {
1905
1970
  const session = await this.sessionManager.getSessionById(sessionId);
1906
1971
  if (!session)
1907
1972
  return;
1908
1973
  this.turnCoordinator.hydrate(session);
1974
+ const activeBeforeInterrupt = this.turnCoordinator.current(session).active;
1975
+ const interruptTarget = target ?? (activeBeforeInterrupt ? {
1976
+ taskId: activeBeforeInterrupt.taskId,
1977
+ generation: activeBeforeInterrupt.generation,
1978
+ } : undefined);
1979
+ // A delayed callback must never invalidate or interrupt a replacement
1980
+ // generation that claimed this session while the session lookup yielded.
1981
+ if (target && (!activeBeforeInterrupt
1982
+ || activeBeforeInterrupt.taskId !== target.taskId
1983
+ || activeBeforeInterrupt.generation !== target.generation))
1984
+ return;
1985
+ this.clearPauseSession(sessionId);
1986
+ // A retry delay has no active runner stream to abort. Wake it only after
1987
+ // verifying that this callback still owns the task generation.
1988
+ this.cancelRetryDelays(sessionId);
1909
1989
  const effectiveReason = reason === 'daemon_restart'
1910
1990
  || this.interruptedSessions.get(sessionId) === 'daemon_restart'
1911
1991
  ? 'daemon_restart'
1912
1992
  : reason;
1913
- const interruptedTurn = this.turnCoordinator.invalidate(sessionId, effectiveReason);
1993
+ const interruptedTurn = this.turnCoordinator.invalidate(sessionId, effectiveReason, interruptTarget);
1994
+ if (interruptTarget && !interruptedTurn?.active)
1995
+ return;
1914
1996
  const interruptedTaskId = interruptedTurn?.active?.taskId;
1915
1997
  this.interruptedSessions.set(sessionId, effectiveReason);
1916
1998
  this.messageQueue?.markActiveTerminal?.(sessionId, effectiveReason);
@@ -1982,9 +2064,9 @@ export class ResponseEngine {
1982
2064
  logger.debug(`[ResponseEngine] interrupt terminal status failure: session=${sessionId} task=${interruptedTaskId} error=${error instanceof Error ? error.message : String(error)}`);
1983
2065
  });
1984
2066
  })();
1985
- const runnerInterrupt = (cancelledQueuedTurn
2067
+ const runnerInterrupt = (cancelledQueuedTurn || !interruptTarget
1986
2068
  ? Promise.resolve()
1987
- : agent.interrupt(sessionId)).catch(error => {
2069
+ : agent.interrupt(sessionId, interruptTarget)).catch(error => {
1988
2070
  logger.debug(`[ResponseEngine] interrupt barrier runner failure: session=${sessionId} error=${error instanceof Error ? error.message : String(error)}`);
1989
2071
  if (strict)
1990
2072
  throw error;
@@ -2313,11 +2395,17 @@ export class ResponseEngine {
2313
2395
  generation: turnLease.generation,
2314
2396
  }) ?? false;
2315
2397
  if (!cancelledQueuedTurn) {
2316
- await agent.interrupt(sessionId).catch(interruptError => {
2398
+ await agent.interrupt(sessionId, {
2399
+ taskId: turnLease.taskId,
2400
+ generation: turnLease.generation,
2401
+ }).catch(interruptError => {
2317
2402
  logger.warn(`[ResponseEngine] Failed to cancel stale runner start: session=${sessionId} task=${taskId} error=${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
2318
2403
  });
2319
2404
  }
2320
- agent.cleanupStream(streamKey);
2405
+ agent.cleanupStream(streamKey, {
2406
+ taskId: turnLease.taskId,
2407
+ generation: turnLease.generation,
2408
+ });
2321
2409
  return true;
2322
2410
  }
2323
2411
  async retryAfterContextRecovery(prompt, opts) {
@@ -2365,7 +2453,10 @@ export class ResponseEngine {
2365
2453
  if (await this.cancelStaleRunnerStart(agent, session.id, streamKey, turnLease, turnLease.taskId)) {
2366
2454
  throw new Error('RUNNER_START_SUPERSEDED');
2367
2455
  }
2368
- agent.registerStream(streamKey, retryStream);
2456
+ agent.registerStream(streamKey, retryStream, {
2457
+ taskId: turnLease.taskId,
2458
+ generation: turnLease.generation,
2459
+ });
2369
2460
  return await this.processEventStream(retryStream, session, agent, renderer, resetTimer, shouldSuppress, proactive, undefined, // 重试分支不调插件钩子
2370
2461
  undefined, turnLease, opts.permissionMode, opts.proactiveSelfAid);
2371
2462
  }
@@ -3057,7 +3148,12 @@ export class ResponseEngine {
3057
3148
  return true;
3058
3149
  },
3059
3150
  };
3060
- const rejectAfterInterruptBarrier = (error) => {
3151
+ const rejectAfterInterruptBarrier = (error, expectedTarget) => {
3152
+ if (expectedTarget) {
3153
+ const current = this.turnCoordinator.current(session).active;
3154
+ if (!current || current.taskId !== expectedTarget.taskId || current.generation !== expectedTarget.generation)
3155
+ return;
3156
+ }
3061
3157
  if (timeoutTriggered)
3062
3158
  return;
3063
3159
  timeoutTriggered = true;
@@ -3066,9 +3162,14 @@ export class ResponseEngine {
3066
3162
  this.timeoutErrors.set(session.id, error);
3067
3163
  this.turnCoordinator.hydrate(session);
3068
3164
  const reason = error instanceof OrphanedTargetSessionError ? 'execution_error' : 'timeout';
3069
- this.turnCoordinator.invalidate(session.id, reason);
3165
+ const activeBeforeTimeout = this.turnCoordinator.current(session).active;
3166
+ const interruptTarget = expectedTarget ?? (activeBeforeTimeout ? {
3167
+ taskId: activeBeforeTimeout.taskId,
3168
+ generation: activeBeforeTimeout.generation,
3169
+ } : undefined);
3170
+ this.turnCoordinator.invalidate(session.id, reason, interruptTarget);
3070
3171
  this.interruptedSessions.set(session.id, reason);
3071
- const barrier = this.interruptSession(session.id, reason, false, timeoutControl.recoverable)
3172
+ const barrier = this.interruptSession(session.id, reason, false, timeoutControl.recoverable, interruptTarget)
3072
3173
  .catch(interruptError => {
3073
3174
  logger.debug(`[ResponseEngine] Timeout interrupt barrier failed: ${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
3074
3175
  });
@@ -3079,8 +3180,10 @@ export class ResponseEngine {
3079
3180
  });
3080
3181
  };
3081
3182
  const triggerAttemptId = message.replyContext?.metadata?.triggerAttemptId;
3082
- const externalTimeout = async (error) => {
3083
- rejectAfterInterruptBarrier(error);
3183
+ const externalTimeout = async (error, requestedTarget) => {
3184
+ if (this.activeTimeoutHandlers.get(session.id) !== externalTimeout)
3185
+ return;
3186
+ rejectAfterInterruptBarrier(error, requestedTarget);
3084
3187
  await timeoutControl.barrier;
3085
3188
  };
3086
3189
  this.activeTimeoutHandlers.set(session.id, externalTimeout);
@@ -3406,6 +3509,7 @@ export class ResponseEngine {
3406
3509
  const chatType = message.chatType || 'private';
3407
3510
  const identityRole = session.identity?.role || 'none';
3408
3511
  let agent;
3512
+ let turnLease;
3409
3513
  try {
3410
3514
  agent = this.getAgent(channelKey, session.baseagent, runnerSelfAid);
3411
3515
  }
@@ -3454,7 +3558,6 @@ export class ResponseEngine {
3454
3558
  }
3455
3559
  }
3456
3560
  const taskPauseController = this.getPauseController(session.id);
3457
- let turnLease;
3458
3561
  const inputCausation = normalizeCausation(message.causation) ?? createRootCausation();
3459
3562
  const taskCausation = deriveCausation(inputCausation);
3460
3563
  recordCausationSpan(taskCausation, 'task.run', {
@@ -3731,32 +3834,41 @@ export class ResponseEngine {
3731
3834
  const rawErrorText = getErrorRawText(timeoutError);
3732
3835
  const isTotalExecutionTimeout = timeoutError.message === 'TOTAL_EXECUTION_TIMEOUT';
3733
3836
  const totalExecutionMs = timeoutError instanceof ExecutionTimeoutError ? timeoutError.timeoutMs : this.totalExecutionLimitMs();
3837
+ const idleSec = getLastIdleSec?.() || 0;
3838
+ const userMessage = timeoutError instanceof OrphanedTargetSessionError
3839
+ ? '⚠️ 任务执行状态丢失,已结束本次执行。'
3840
+ : isTotalExecutionTimeout
3841
+ ? (totalExecutionMs === undefined
3842
+ ? '⚠️ 任务超过总执行时限,已自动中断'
3843
+ : `⚠️ 任务超过总执行时限(${Math.round(totalExecutionMs / 1000)}秒),已自动中断`)
3844
+ : idleSec > 0
3845
+ ? `⚠️ 任务超时(${idleSec}秒无响应),已自动中断`
3846
+ : '⚠️ 任务超时,已自动中断';
3847
+ const timeoutSubtype = normalizeCoreErrorSubtype(timeoutError, undefined, 'timeout');
3848
+ const timeoutReason = isExecutionFailure(timeoutError)
3849
+ ? normalizeCoreErrorReason(timeoutError.reason)
3850
+ : 'timeout';
3734
3851
  const statusPayload = timeoutError instanceof OrphanedTargetSessionError ? {
3735
3852
  kind: 'status.error',
3736
3853
  metadata: {
3737
3854
  errorType: timeoutError.reason,
3738
3855
  message: '任务执行状态丢失,已结束本次执行。',
3856
+ recoverable,
3739
3857
  ...(rawErrorText ? { raw: rawErrorText } : {}),
3740
3858
  },
3741
3859
  } : {
3742
3860
  kind: 'status.timeout',
3743
3861
  metadata: isTotalExecutionTimeout
3744
3862
  ? { ...(totalExecutionMs === undefined ? {} : { totalExecutionMs }),
3745
- ...(timeoutError instanceof ExecutionTimeoutError ? { reason: timeoutError.reason } : {}),
3863
+ errorType: timeoutSubtype,
3864
+ reason: timeoutReason,
3865
+ message: userMessage,
3866
+ recoverable,
3746
3867
  ...(rawErrorText ? { raw: rawErrorText } : {}) }
3747
- : { idleSec: getLastIdleSec?.() || undefined, ...(rawErrorText ? { raw: rawErrorText } : {}) },
3868
+ : { idleSec: idleSec || undefined, errorType: timeoutSubtype, reason: timeoutReason, message: userMessage, recoverable,
3869
+ ...(rawErrorText ? { raw: rawErrorText } : {}) },
3748
3870
  };
3749
- const idleSec = getLastIdleSec?.() || 0;
3750
- const userMessage = timeoutError instanceof OrphanedTargetSessionError
3751
- ? '⚠️ 任务执行状态丢失,已结束本次执行。'
3752
- : isTotalExecutionTimeout
3753
- ? (totalExecutionMs === undefined
3754
- ? '⚠️ 任务超过总执行时限,已自动中断'
3755
- : `⚠️ 任务超过总执行时限(${Math.round(totalExecutionMs / 1000)}秒),已自动中断`)
3756
- : idleSec > 0
3757
- ? `⚠️ 任务超时(${idleSec}秒无响应),已自动中断`
3758
- : '⚠️ 任务超时,已自动中断';
3759
- agent.cleanupStream(streamKey);
3871
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
3760
3872
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
3761
3873
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
3762
3874
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -3764,21 +3876,16 @@ export class ResponseEngine {
3764
3876
  }
3765
3877
  this.agentDelegationRegistry?.revokeTask(session.id, taskId, 'interrupted');
3766
3878
  const daemonTrigger = this.isTrustedDaemonTrigger(message);
3767
- if (!daemonTrigger) {
3768
- await adapter.send(envelope, statusPayload).catch(() => { });
3769
- }
3770
- await adapter.send(envelope, {
3771
- kind: 'result.error',
3772
- text: userMessage,
3773
- recoverable,
3774
- ...(rawErrorText ? { raw: rawErrorText } : {}),
3775
- subtype: normalizeCoreErrorSubtype(timeoutError, undefined, isTotalExecutionTimeout ? 'timeout' : 'timeout'),
3776
- reason: isExecutionFailure(timeoutError)
3777
- ? normalizeCoreErrorReason(timeoutError.reason)
3778
- : 'timeout',
3779
- }).catch(() => { });
3780
- if (daemonTrigger) {
3781
- await adapter.send(envelope, statusPayload).catch(() => { });
3879
+ await adapter.send(envelope, statusPayload).catch(() => { });
3880
+ if (!daemonTrigger && !(statusPayload.kind === 'status.error' && timeoutError instanceof OrphanedTargetSessionError)) {
3881
+ await adapter.send(envelope, {
3882
+ kind: 'result.error',
3883
+ text: userMessage,
3884
+ recoverable,
3885
+ ...(rawErrorText ? { raw: rawErrorText } : {}),
3886
+ subtype: timeoutSubtype,
3887
+ ...(timeoutReason ? { reason: timeoutReason } : {}),
3888
+ }).catch(() => { });
3782
3889
  }
3783
3890
  this.touchAgentActivity(channelKey);
3784
3891
  this.publishTriggerExecutionFailure(message, isExecutionFailure(timeoutError) ? timeoutError.reason : timeoutError.message, {
@@ -3849,7 +3956,10 @@ export class ResponseEngine {
3849
3956
  proactiveCircuitBreakTimer = undefined;
3850
3957
  }
3851
3958
  const interruptPromise = (async () => {
3852
- await agent.interrupt(session.id).catch(error => {
3959
+ await agent.interrupt(session.id, turnLease ? {
3960
+ taskId: turnLease.taskId,
3961
+ generation: turnLease.generation,
3962
+ } : undefined).catch(error => {
3853
3963
  logger.debug(`[ResponseEngine] circuit break interrupt failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
3854
3964
  });
3855
3965
  })();
@@ -3957,6 +4067,29 @@ export class ResponseEngine {
3957
4067
  return;
3958
4068
  }
3959
4069
  }
4070
+ // ── 模型只在 Agent 级配置:Agent 级没有模型就没有模型可用,不回落 runner/defaults 默认值 ──
4071
+ {
4072
+ const modelBaseagent = normalizeBaseagent(agent.name).canonical;
4073
+ const agentModel = effectiveAgentConfig?.baseagents?.[modelBaseagent]?.model;
4074
+ const triggerModel = message.triggerMeta?.modelOverride;
4075
+ const hasModel = (typeof agentModel === 'string' && agentModel.trim().length > 0)
4076
+ || (typeof triggerModel === 'string' && triggerModel.trim().length > 0);
4077
+ if (modelBaseagent !== 'unknown' && !hasModel) {
4078
+ logger.warn(`[ResponseEngine] No Agent-level model configured: agent=${selfAid ?? session.selfAID ?? '<none>'} baseagent=${modelBaseagent} session=${session.id}`);
4079
+ this.touchAgentActivity(channelKey);
4080
+ adapter.send(envelope, {
4081
+ kind: 'system.error',
4082
+ text: isHostChinese()
4083
+ ? `⚠️ 当前 Agent 未配置模型(baseagents.${modelBaseagent}.model),无法回复。请 Agent 的 owner/admin 使用 /model 设置模型。`
4084
+ : `⚠️ This Agent has no model configured (baseagents.${modelBaseagent}.model) and cannot reply. An Agent owner/admin must set one with /model.`,
4085
+ subtype: 'model_not_configured',
4086
+ recoverable: false,
4087
+ }).catch(() => { });
4088
+ adapter.send(envelope, { kind: 'status.completed', metadata: { durationMs: 0 } }).catch(() => { });
4089
+ this.publishTriggerExecutionFailure(message, 'model_not_configured');
4090
+ return;
4091
+ }
4092
+ }
3960
4093
  const imageInfo = message.images && message.images.length > 0 ? ` [${message.images.length} image(s)]` : '';
3961
4094
  const modeInfo = isBackground ? ' [\u540e\u53f0]' : '';
3962
4095
  const e2eeInfo = message.replyContext?.metadata?.encrypted != null ? ` encrypt=${message.replyContext.metadata.encrypted}` : '';
@@ -4386,12 +4519,13 @@ export class ResponseEngine {
4386
4519
  }
4387
4520
  : {}),
4388
4521
  armApprovedDelegationCommand: this.agentDelegationRegistry
4389
- ? (sessionToken, commandHash, approvalId) => this.agentDelegationRegistry.armApprovedCommand({
4522
+ ? (sessionToken, commandHash, approvalId, specHash) => this.agentDelegationRegistry.armApprovedCommand({
4390
4523
  sessionToken,
4391
4524
  sessionId: session.id,
4392
4525
  taskId,
4393
4526
  commandHash,
4394
4527
  approvalId,
4528
+ specHash,
4395
4529
  })
4396
4530
  : undefined,
4397
4531
  revokeApprovedDelegationCommand: this.agentDelegationRegistry
@@ -4466,7 +4600,10 @@ export class ResponseEngine {
4466
4600
  });
4467
4601
  }
4468
4602
  finally {
4469
- await agent.interrupt(session.id).catch(error => {
4603
+ await agent.interrupt(session.id, turnLease ? {
4604
+ taskId: turnLease.taskId,
4605
+ generation: turnLease.generation,
4606
+ } : undefined).catch(error => {
4470
4607
  logger.debug(`[ResponseEngine] permission terminal interrupt failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
4471
4608
  });
4472
4609
  }
@@ -4663,8 +4800,8 @@ export class ResponseEngine {
4663
4800
  fullAccessMessagePromptContext = fullAccessAuthorization
4664
4801
  ? FULL_ACCESS_MESSAGE_PROMPT_CONTEXT
4665
4802
  : undefined;
4666
- // 按 关系级 > agent级 > 全局 解析本次调用的模型/强度,作为 per-call 入参传入 runQuery。
4667
- // 不缓存、不绑会话——改关系级/agent级后该范围所有会话的下条消息即时生效;
4803
+ // 模型/强度只取 Agent 级配置(再经角色约束),作为 per-call 入参传入 runQuery。
4804
+ // 不缓存、不绑会话——改 Agent 级后该 Agent 所有会话的下条消息即时生效;
4668
4805
  // 多对端并发各自独立解析、各自传参,无共享状态可被污染。
4669
4806
  let effectiveModel;
4670
4807
  let effectiveModelSource;
@@ -4874,8 +5011,10 @@ export class ResponseEngine {
4874
5011
  inputId: turnLease.inputId,
4875
5012
  },
4876
5013
  };
4877
- const refreshTopicBindingForLogicalRetry = async () => {
4878
- if ((isMainSession(session) && !message.taskRecovery) || typeof this.sessionManager.getSessionById !== 'function')
5014
+ let hasCapsuleBoundary = !!session.metadata?.capsuleId;
5015
+ const refreshBackendBindingForLogicalRetry = async () => {
5016
+ if ((isMainSession(session) && !message.taskRecovery && !hasCapsuleBoundary)
5017
+ || typeof this.sessionManager.getSessionById !== 'function')
4879
5018
  return;
4880
5019
  const latest = await this.sessionManager.getSessionById(session.id);
4881
5020
  if (!latest || sessionLocalTopicId(latest) !== sessionLocalTopicId(session)) {
@@ -4890,16 +5029,16 @@ export class ResponseEngine {
4890
5029
  session.metadata = latest.metadata;
4891
5030
  if (latestAgentSessionId === runAgentSessionId)
4892
5031
  return;
4893
- logger.info(`[ResponseEngine] Refreshing authoritative topic backend for logical retry: `
5032
+ logger.info(`[ResponseEngine] Refreshing backend binding for logical retry: `
4894
5033
  + `session=${session.id} task=${taskId} backend=${latestAgentSessionId ?? 'none'}`);
4895
5034
  runAgentSessionId = latestAgentSessionId;
4896
- modelOverride = {
4897
- ...(modelOverride || {}),
4898
- backend: { kind: 'topic', agentSessionId: runAgentSessionId ?? null },
4899
- };
5035
+ if (isTopicSession(session)) {
5036
+ modelOverride = { ...(modelOverride || {}),
5037
+ backend: { kind: 'topic', agentSessionId: runAgentSessionId ?? null } };
5038
+ }
4900
5039
  };
4901
5040
  // 预压缩必须使用与本轮 runQuery 相同的有效模型/强度覆盖。
4902
- // 模型解析完成后再执行,避免关系级模型存在时回落到 runner 默认模型。
5041
+ // 模型解析完成后再执行,避免回落到 runner 默认模型。
4903
5042
  await this.runPendingAutoCompactAtTaskStart(session, agent, absoluteProjectPath, renderer, modelOverride, () => this.assertCurrentExecutionAuthorization(permissionContext, agent));
4904
5043
  startTime = Date.now();
4905
5044
  const causationPath = inputCausation.trigger?.path ?? [];
@@ -4990,7 +5129,8 @@ export class ResponseEngine {
4990
5129
  isBootstrapping,
4991
5130
  hasPersona: !!persona,
4992
5131
  peerId: peerIdRaw || undefined,
4993
- peerKey,
5132
+ // 与任务上下文同源:系统会话取目标关系,否则 peer-profile / relation 索引会按 bg: 伪对端注入
5133
+ peerKey: systemSessionContext?.peerKey ?? peerKey,
4994
5134
  peerName: peerName || undefined,
4995
5135
  // 系统会话与角色体系无关:不给 peerRole,消息头就不渲染 `· role:` 段
4996
5136
  peerRole: systemSessionMarker ? undefined : peerRole,
@@ -5083,7 +5223,7 @@ export class ResponseEngine {
5083
5223
  const estTokens = (s) => s ? Math.ceil(s.length / 4) : 0;
5084
5224
  const cbModel = effectiveModel || agentModel || 'unknown';
5085
5225
  // 从统一模型参数表获取模型的真实 context_window
5086
- const { resolveModelSpec } = await import('../../stats/billing.js');
5226
+ const { resolveModelSpec } = await import('../../stats/price-resolver.js');
5087
5227
  const modelSpec = resolveModelSpec(resolveRoot(), cbModel);
5088
5228
  const cbMaxTokens = modelSpec.context_window;
5089
5229
  const systemPromptTokens = estTokens(options?.systemPromptAppend);
@@ -5454,7 +5594,34 @@ export class ResponseEngine {
5454
5594
  this.activeRunnerModels.delete(session.id);
5455
5595
  // 每次尝试前覆盖:备用模型切换后,请求模型以最后一次尝试为准
5456
5596
  this.recordBgSessionModels(message, { requestedModel: debugRunnerModel });
5457
- const stream = await agent.runQuery(session.id, effectivePrompt, absoluteProjectPath, runAgentSessionId, runnerImages, effectiveSystemPrompt, this.sessionManager, modelOverride, runtimeEnv);
5597
+ if (message.restartResume?.submitted && runAgentSessionId) {
5598
+ // A durable recovery request resumes already-submitted input.
5599
+ // Reconcile a crash after acceptance but before the capsule journal append.
5600
+ const latest = await this.sessionManager.getSessionById?.(session.id);
5601
+ const pending = latest && this.sessionManager.getPendingCapsule?.(latest);
5602
+ if (pending?.agentSessionId === runAgentSessionId) {
5603
+ this.sessionManager.consumeSessionCapsule?.(session.id, pending.capsuleId, {
5604
+ agentSessionId: runAgentSessionId, messageId: pending.messageId,
5605
+ lease: turnLease,
5606
+ });
5607
+ }
5608
+ }
5609
+ const capsuleInput = this.sessionManager.prepareCapsuleInput?.(session.id, effectivePrompt)
5610
+ ?? { prompt: effectivePrompt };
5611
+ let attemptCapsuleId = capsuleInput.capsuleId;
5612
+ const attemptOverride = { ...modelOverride, capsule: {
5613
+ recover: async (oldId, prompt, systemPrompt) => {
5614
+ if (turnLease && !this.turnCoordinator.isCurrent(turnLease))
5615
+ throw new Error('RUNNER_START_SUPERSEDED');
5616
+ const prepared = await this.sessionManager.prepareBackendRecovery(session.id, oldId, prompt, systemPrompt, turnLease);
5617
+ attemptCapsuleId = prepared.capsuleId;
5618
+ hasCapsuleBoundary = true;
5619
+ effectiveSystemPrompt = prepared.systemPrompt;
5620
+ return prepared;
5621
+ },
5622
+ } };
5623
+ const rawStream = await agent.runQuery(session.id, capsuleInput.prompt, absoluteProjectPath, runAgentSessionId, runnerImages, effectiveSystemPrompt, this.sessionManager, attemptOverride, runtimeEnv);
5624
+ const stream = this.consumeCapsuleWithInput(rawStream, session, message, turnLease, () => attemptCapsuleId);
5458
5625
  // The turn may be superseded while the runner is still creating its
5459
5626
  // backend query. Replay the interrupt after runQuery resolves, when
5460
5627
  // every runner is required to have an addressable cancellation handle.
@@ -5483,7 +5650,10 @@ export class ResponseEngine {
5483
5650
  releaseHintClaim(accepted);
5484
5651
  ownerHintClaim = undefined;
5485
5652
  }
5486
- agent.registerStream(streamKey, stream);
5653
+ agent.registerStream(streamKey, stream, turnLease ? {
5654
+ taskId: turnLease.taskId,
5655
+ generation: turnLease.generation,
5656
+ } : undefined);
5487
5657
  streamRegistered = true;
5488
5658
  if (shouldTimeoutRetryAttempt) {
5489
5659
  attemptTimeout = createRetryAttemptTimeout(apiRetryTimeoutMs);
@@ -5512,7 +5682,10 @@ export class ResponseEngine {
5512
5682
  }
5513
5683
  try {
5514
5684
  if (blocking)
5515
- await agent.interrupt(session.id);
5685
+ await agent.interrupt(session.id, turnLease ? {
5686
+ taskId: turnLease.taskId,
5687
+ generation: turnLease.generation,
5688
+ } : undefined);
5516
5689
  await renderer.flush(false);
5517
5690
  await this.asyncQuestions.present(session, request, message, adapter, envelope);
5518
5691
  }
@@ -5542,7 +5715,7 @@ export class ResponseEngine {
5542
5715
  // Activation can complete either before runQuery returns (Codex)
5543
5716
  // or while its event stream is consumed (Claude/Gemini/Ecagent).
5544
5717
  // Always reconcile from strict latest before any logical retry.
5545
- await refreshTopicBindingForLogicalRetry();
5718
+ await refreshBackendBindingForLogicalRetry();
5546
5719
  if (!streamResult.isError && !isExpectedTerminalInterrupt(streamResult.terminalReason)) {
5547
5720
  const protocolDecision = this.turnCoordinator.evaluateCommit(turnLease, this.buildTurnCommitEvidence(session, streamResult));
5548
5721
  const protocolReason = protocolDecision.ok ? undefined : protocolDecision.reason;
@@ -5553,7 +5726,7 @@ export class ResponseEngine {
5553
5726
  const protocolRetry = retryScheduler.afterProtocolFailure(safeProtocolReplay ? protocolReason : undefined, safeProtocolReplay);
5554
5727
  if (protocolRetry.kind === 'protocol_replay') {
5555
5728
  protocolReplayAttempts = protocolRetry.attempt;
5556
- agent.cleanupStream(streamKey);
5729
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5557
5730
  logger.warn(`[ResponseEngine] Replaying zero-work protocol failure: session=${session.id} `
5558
5731
  + `task=${taskId} reason=${protocolReason} attempt=${protocolRetry.attempt}/${protocolRetry.maxAttempts}`);
5559
5732
  await this.emitOperationalNotice(renderer, `模型未确认完成,正在立即重试 ${protocolRetry.attempt}/${protocolRetry.maxAttempts}`, 'warn', 'protocol-retry');
@@ -5578,17 +5751,20 @@ export class ResponseEngine {
5578
5751
  break; // 成功,跳出重试循环
5579
5752
  }
5580
5753
  catch (retryError) {
5581
- await refreshTopicBindingForLogicalRetry();
5754
+ await refreshBackendBindingForLogicalRetry();
5582
5755
  const retryAttemptTimedOut = retryError instanceof RetryAttemptTimeoutError;
5583
5756
  if (retryAttemptTimedOut) {
5584
5757
  logger.warn(`[ResponseEngine] Retry attempt ${runAttempt} timed out after ${retryError.timeoutMs}ms without agent events; interrupting current stream`);
5585
5758
  renderer.discardPending();
5586
- await agent.interrupt(session.id).catch(interruptError => {
5759
+ await agent.interrupt(session.id, turnLease ? {
5760
+ taskId: turnLease.taskId,
5761
+ generation: turnLease.generation,
5762
+ } : undefined).catch(interruptError => {
5587
5763
  logger.warn(`[ResponseEngine] Failed to interrupt timed-out retry attempt: ${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
5588
5764
  });
5589
5765
  }
5590
5766
  if (streamRegistered) {
5591
- agent.cleanupStream(streamKey);
5767
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5592
5768
  }
5593
5769
  if (permissionTerminalFailure) {
5594
5770
  const permissionError = new Error(permissionTerminalFailure.message);
@@ -5765,7 +5941,7 @@ export class ResponseEngine {
5765
5941
  const commitEvidence = this.buildTurnCommitEvidence(session, streamResult);
5766
5942
  const commitDecision = this.turnCoordinator.evaluateCommit(turnLease, commitEvidence);
5767
5943
  if (!commitDecision.ok && commitDecision.reason === 'stale_generation') {
5768
- agent.cleanupStream(streamKey);
5944
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5769
5945
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5770
5946
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5771
5947
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5781,7 +5957,7 @@ export class ResponseEngine {
5781
5957
  }
5782
5958
  if (!commitDecision.ok) {
5783
5959
  if (commitDecision.reason === 'stale_generation') {
5784
- agent.cleanupStream(streamKey);
5960
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5785
5961
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5786
5962
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5787
5963
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5947,7 +6123,7 @@ export class ResponseEngine {
5947
6123
  && message.triggerMeta.noopSentinel.length > 0
5948
6124
  && visibleFinalReplyText.trim() === message.triggerMeta.noopSentinel;
5949
6125
  if (!this.turnCoordinator.isCurrent(turnLease)) {
5950
- agent.cleanupStream(streamKey);
6126
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5951
6127
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5952
6128
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5953
6129
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5974,27 +6150,36 @@ export class ResponseEngine {
5974
6150
  // (2026-10-11 403「无法连接到积分服务器」案例)。
5975
6151
  // 以错误收场的轮次一律走 system.error:前端收到的单条消息即可判断来源,
5976
6152
  // 不需要等后续的 result.error。
5977
- const errorText = visibleFinalReplyText || streamResult.syntheticDiagnosticText || getStreamErrorMessage(streamResult, false);
6153
+ const errorText = streamResult.isError
6154
+ ? (streamResult.syntheticDiagnosticText || getStreamErrorMessage(streamResult, false))
6155
+ : visibleFinalReplyText;
5978
6156
  if (streamResult.isError) {
5979
6157
  // 用原始诊断文本(含错误码)判断可重试性,不用已过 stripContextLimitErrorLines 的展示文本
5980
6158
  const subtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || getStreamErrorText(streamResult)), streamResult.subtype, streamResult.terminalReason);
5981
6159
  const reason = normalizeCoreErrorReason(streamResult.terminalReason);
5982
- await adapter.send(envelope, {
5983
- kind: 'system.error',
5984
- text: errorText,
5985
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
5986
- subtype,
5987
- ...(reason ? { reason } : {}),
5988
- recoverable: streamRecoverable,
5989
- }).catch(() => { });
5990
- sentErrorAsSystemError = true;
6160
+ if (this.isTrustedDaemonTrigger(message)) {
6161
+ // DaemonChannel must receive the metadata-bearing terminal below
6162
+ // before it settles the attempt; sending system.error here would
6163
+ // discard tool counts and recovery details.
6164
+ }
6165
+ else {
6166
+ await adapter.send(envelope, {
6167
+ kind: 'system.error',
6168
+ text: errorText,
6169
+ ...(subtype === ErrorType.POLICY_REJECTED ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
6170
+ subtype,
6171
+ ...(reason ? { reason } : {}),
6172
+ recoverable: streamRecoverable,
6173
+ }).catch(() => { });
6174
+ sentErrorAsSystemError = true;
6175
+ }
5991
6176
  }
5992
6177
  else if (visibleFinalReplyText && (shouldSuppress() || !streamResult.hasProjectedCurrentReplyText)) {
5993
6178
  await renderer.addText(visibleFinalReplyText, undefined, undefined, streamResult.assistantUuid);
5994
6179
  }
5995
6180
  }
5996
6181
  // 先清理流和处理中状态(保证即使 flush 卡住,session 也不会永久处于"处理中")
5997
- agent.cleanupStream(streamKey);
6182
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5998
6183
  logger.info(`[ResponseEngine] agent.cleanupStream ok: session=${session.id} task=${taskId}`);
5999
6184
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
6000
6185
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
@@ -6028,7 +6213,7 @@ export class ResponseEngine {
6028
6213
  // outcome so AUN does not label that text as normal completion.
6029
6214
  try {
6030
6215
  if (streamResult.isError && !isExpectedTerminalInterrupt(streamResult.terminalReason)) {
6031
- await renderer.flush(true, 'failed');
6216
+ await renderer.flush(false);
6032
6217
  }
6033
6218
  else {
6034
6219
  await renderer.flush(!isExpectedTerminalInterrupt(streamResult.terminalReason));
@@ -6081,8 +6266,9 @@ export class ResponseEngine {
6081
6266
  ? getContextTooLongHint(agent)
6082
6267
  : getStreamErrorMessage(streamResult, false);
6083
6268
  const rawSubtype = streamResult.subtype || 'agent_error';
6084
- const errorType = prefixErrorType(ERROR_PREFIX.AGENT, rawSubtype);
6085
6269
  const coreSubtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || errorSummary), rawSubtype, streamResult.terminalReason);
6270
+ const effectiveSubtype = coreSubtype === ErrorType.POLICY_REJECTED ? coreSubtype : rawSubtype;
6271
+ const errorType = prefixErrorType(ERROR_PREFIX.AGENT, effectiveSubtype);
6086
6272
  const coreReason = permissionTerminalFailure
6087
6273
  ? normalizeCoreErrorReason(permissionTerminalFailure.reason)
6088
6274
  : normalizeCoreErrorReason(streamResult.terminalReason);
@@ -6094,10 +6280,11 @@ export class ResponseEngine {
6094
6280
  taskActivityStatus = isExpectedInterrupt ? 'interrupted' : 'error';
6095
6281
  if (!isExpectedInterrupt && !permissionTerminalFailure) {
6096
6282
  const terminalMetadata = {
6097
- errorType: rawSubtype,
6283
+ errorType: effectiveSubtype,
6284
+ ...(coreReason ? { reason: coreReason } : {}),
6098
6285
  recoverable: streamRecoverable,
6099
6286
  message: userErrorSummary,
6100
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
6287
+ ...(coreSubtype === ErrorType.POLICY_REJECTED ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
6101
6288
  durationMs: Date.now() - startTime,
6102
6289
  numTurns: streamResult.numTurns,
6103
6290
  toolCallCount: streamResult.toolUseCount ?? 0,
@@ -6111,16 +6298,6 @@ export class ResponseEngine {
6111
6298
  // system.error 已在 finalReplyText 分支把错误文本发给了前端,不再重复发 result.error
6112
6299
  if (this.isTrustedDaemonTrigger(message)) {
6113
6300
  await adapter.send(envelope, { kind: 'status.error', metadata: terminalMetadata }).catch(() => { });
6114
- if (!sentErrorAsSystemError) {
6115
- await adapter.send(envelope, {
6116
- kind: 'result.error',
6117
- text: userErrorSummary,
6118
- recoverable: streamRecoverable,
6119
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
6120
- subtype: coreSubtype,
6121
- ...(coreReason ? { reason: coreReason } : {}),
6122
- }).catch(() => { });
6123
- }
6124
6301
  }
6125
6302
  else {
6126
6303
  if (!sentErrorAsSystemError) {
@@ -6128,7 +6305,7 @@ export class ResponseEngine {
6128
6305
  kind: 'result.error',
6129
6306
  text: userErrorSummary,
6130
6307
  recoverable: streamRecoverable,
6131
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
6308
+ ...(coreSubtype === ErrorType.POLICY_REJECTED ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
6132
6309
  subtype: coreSubtype,
6133
6310
  ...(coreReason ? { reason: coreReason } : {}),
6134
6311
  }).catch(() => { });
@@ -6183,7 +6360,7 @@ export class ResponseEngine {
6183
6360
  });
6184
6361
  recordCausationSpan(taskCausation, 'task.run', { status: 'failed', refs: { taskId, sessionId: session.id, messageId }, reason: errorType });
6185
6362
  // 系统级 subtype 仍累计错误计数,供 /status 诊断使用
6186
- if (isInfraError(rawSubtype, streamResult.terminalReason)) {
6363
+ if (isInfraError(effectiveSubtype, streamResult.terminalReason)) {
6187
6364
  const chatType = message.chatType || 'private';
6188
6365
  const identityRole = session.identity?.role || 'none';
6189
6366
  const { policy } = channelInfo;
@@ -6270,7 +6447,7 @@ export class ResponseEngine {
6270
6447
  auto_compact_tokens: mc.contextUsage?.autoCompactTokens,
6271
6448
  degraded: mc.degraded ? 1 : 0,
6272
6449
  }));
6273
- insertModelCalls(resolveRoot(), mcRows);
6450
+ insertModelCalls(resolveRoot(), mcRows, gwPricing);
6274
6451
  }
6275
6452
  const totalIn = event.input_tokens + event.cache_read_tokens;
6276
6453
  statsCacheHitRate = totalIn > 0 ? Math.round((event.cache_read_tokens / totalIn) * 100) / 100 : 0;
@@ -6284,7 +6461,7 @@ export class ResponseEngine {
6284
6461
  let sessionStats;
6285
6462
  let modelSpec;
6286
6463
  try {
6287
- const { resolveModelSpec } = await import('../../stats/billing.js');
6464
+ const { resolveModelSpec } = await import('../../stats/price-resolver.js');
6288
6465
  const { querySessionSummary } = await import('../../stats/query.js');
6289
6466
  modelSpec = resolveModelSpec(resolveRoot(), statsModel);
6290
6467
  const sum = querySessionSummary(resolveRoot(), session.id);
@@ -6473,7 +6650,7 @@ export class ResponseEngine {
6473
6650
  }
6474
6651
  const leaseWasCurrent = !!turnLease && this.turnCoordinator.isCurrent(turnLease);
6475
6652
  // 清理流和处理中状态(异常时也要清除)
6476
- agent.cleanupStream(streamKey);
6653
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
6477
6654
  logger.info(`[ResponseEngine] agent.cleanupStream ok (on error): session=${session.id} task=${taskId}`);
6478
6655
  try {
6479
6656
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
@@ -6520,25 +6697,49 @@ export class ResponseEngine {
6520
6697
  }
6521
6698
  const totalExecutionMs = error instanceof ExecutionTimeoutError ? error.timeoutMs : this.totalExecutionLimitMs();
6522
6699
  const rawErrorText = getErrorRawText(error);
6700
+ const safeRawErrorText = isPolicyRejectedError(error) ? undefined : rawErrorText;
6523
6701
  const procStatus = errType === ErrorType.SDK_TIMEOUT || isTotalExecutionTimeout ? 'timeout'
6524
6702
  : errType === ErrorType.STREAM_ERROR ? 'interrupted'
6525
6703
  : 'error';
6526
6704
  const daemonTrigger = this.isTrustedDaemonTrigger(message);
6705
+ const timeoutIdleSec = getLastIdleSec?.() || 0;
6706
+ const timeoutMessage = isTotalExecutionTimeout
6707
+ ? (totalExecutionMs === undefined
6708
+ ? '⚠️ 任务超过总执行时限,已自动中断'
6709
+ : `⚠️ 任务超过总执行时限(${Math.round(totalExecutionMs / 1000)}秒),已自动中断`)
6710
+ : timeoutIdleSec > 0
6711
+ ? `⚠️ 任务超时(${timeoutIdleSec}秒无响应),已自动中断`
6712
+ : '⚠️ 任务超时,已自动中断';
6713
+ const timeoutSubtype = normalizeCoreErrorSubtype(error, undefined, 'timeout');
6714
+ const timeoutReason = isExecutionFailure(error) ? normalizeCoreErrorReason(error.reason) : 'timeout';
6527
6715
  const statusPayload = error instanceof OrphanedTargetSessionError
6528
6716
  ? { kind: 'status.error', metadata: {
6529
6717
  errorType: error.reason,
6718
+ reason: error.reason,
6530
6719
  message: '任务执行状态丢失,已结束本次执行。',
6531
- ...(rawErrorText ? { raw: rawErrorText } : {}),
6720
+ recoverable,
6721
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}),
6532
6722
  } }
6533
6723
  : procStatus === 'timeout'
6534
6724
  ? { kind: 'status.timeout', metadata: isTotalExecutionTimeout
6535
6725
  ? { ...(totalExecutionMs === undefined ? {} : { totalExecutionMs }),
6536
- ...(error instanceof ExecutionTimeoutError ? { reason: error.reason } : {}),
6537
- ...(rawErrorText ? { raw: rawErrorText } : {}) }
6538
- : { idleSec: getLastIdleSec?.() || undefined, ...(rawErrorText ? { raw: rawErrorText } : {}) } }
6726
+ errorType: timeoutSubtype,
6727
+ reason: timeoutReason,
6728
+ message: timeoutMessage,
6729
+ recoverable,
6730
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}) }
6731
+ : { idleSec: timeoutIdleSec || undefined, errorType: timeoutSubtype, reason: timeoutReason,
6732
+ message: timeoutMessage, recoverable,
6733
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}) } }
6539
6734
  : procStatus === 'interrupted'
6540
6735
  ? { kind: 'status.interrupted', metadata: { reason: 'stream_error' } }
6541
- : { kind: 'status.error', metadata: rawErrorText ? { raw: rawErrorText } : undefined };
6736
+ : { kind: 'status.error', metadata: {
6737
+ errorType: errType,
6738
+ reason: normalizeCoreErrorReason(error instanceof Error ? error.message : undefined),
6739
+ message: errorMsg,
6740
+ recoverable,
6741
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}),
6742
+ } };
6542
6743
  // 用户主动中断(新消息打断 或 /stop 命令)时静默,不发送中断/错误提示
6543
6744
  if (!isUserInterrupt && ownsTimeoutTerminal && !daemonTrigger) {
6544
6745
  await adapter.send(envelope, statusPayload).catch(() => { });
@@ -6657,9 +6858,11 @@ export class ResponseEngine {
6657
6858
  : modelFallbackExhaustedMessage
6658
6859
  ? ErrorType.MODEL_UNAVAILABLE
6659
6860
  : normalizeCoreErrorSubtype(error, undefined, isTotalExecutionTimeout || isTimeout ? 'timeout' : undefined);
6660
- const distinctRawErrorText = rawErrorText && !userMessage.includes(rawErrorText)
6661
- ? rawErrorText
6662
- : undefined;
6861
+ const distinctRawErrorText = errorSubtype === ErrorType.POLICY_REJECTED
6862
+ ? undefined
6863
+ : rawErrorText && !userMessage.includes(rawErrorText)
6864
+ ? rawErrorText
6865
+ : undefined;
6663
6866
  const errorPayload = {
6664
6867
  kind: 'result.error',
6665
6868
  text: userMessage,
@@ -6668,34 +6871,46 @@ export class ResponseEngine {
6668
6871
  ...(distinctRawErrorText ? { raw: distinctRawErrorText } : {}),
6669
6872
  ...(errorReason ? { reason: errorReason } : {}),
6670
6873
  };
6671
- if (!isUserInterrupt && daemonTrigger && procStatus === 'error') {
6874
+ if (!isUserInterrupt && daemonTrigger) {
6672
6875
  // DaemonChannel settles a trigger on the first terminal payload. Put
6673
6876
  // the complete failure metadata first so the audit retains tool
6674
6877
  // counts and context-recovery diagnostics even for thrown errors
6675
6878
  // (for example when compact itself fails).
6676
- await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
6677
- kind: 'status.error',
6678
- metadata: {
6679
- errorType: errType,
6680
- message: userMessage,
6681
- ...(rawErrorText ? { raw: rawErrorText } : {}),
6682
- recoverable,
6683
- durationMs: Date.now() - startTime,
6684
- numTurns: streamResult.numTurns,
6685
- toolCallCount: streamResult.toolUseCount ?? 0,
6686
- tokenUsage: streamResult.tokenUsage,
6687
- contextUsage: streamResult.contextUsage,
6688
- contextRecoveryAttempts: streamResult.contextRecoveryAttempts ?? 0,
6689
- },
6690
- }).catch(() => { });
6691
- await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), errorPayload);
6879
+ const terminalMetadata = {
6880
+ errorType: errorSubtype,
6881
+ reason: errorReason,
6882
+ message: userMessage,
6883
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}),
6884
+ recoverable,
6885
+ durationMs: Date.now() - startTime,
6886
+ numTurns: streamResult.numTurns,
6887
+ toolCallCount: streamResult.toolUseCount ?? 0,
6888
+ tokenUsage: streamResult.tokenUsage,
6889
+ contextUsage: streamResult.contextUsage,
6890
+ contextRecoveryAttempts: streamResult.contextRecoveryAttempts ?? 0,
6891
+ };
6892
+ if (procStatus === 'timeout') {
6893
+ await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
6894
+ kind: 'status.timeout',
6895
+ metadata: {
6896
+ ...(statusPayload.kind === 'status.timeout' ? statusPayload.metadata : {}),
6897
+ ...terminalMetadata,
6898
+ },
6899
+ }).catch(() => { });
6900
+ }
6901
+ else {
6902
+ await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
6903
+ kind: 'status.error',
6904
+ metadata: {
6905
+ ...(statusPayload.kind === 'status.error' ? statusPayload.metadata : {}),
6906
+ ...terminalMetadata,
6907
+ },
6908
+ }).catch(() => { });
6909
+ }
6692
6910
  }
6693
6911
  else {
6694
6912
  await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), errorPayload);
6695
6913
  }
6696
- if (!isUserInterrupt && daemonTrigger && procStatus !== 'error') {
6697
- await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), statusPayload).catch(() => { });
6698
- }
6699
6914
  // Proactive 可观测:catch 块的基础设施错误也透传为 thought,保证按 task_id 聚合完整
6700
6915
  if (isProactive && adapter.capabilities?.thought) {
6701
6916
  await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
@@ -6852,7 +7067,7 @@ export class ResponseEngine {
6852
7067
  return undefined;
6853
7068
  const shouldClose = !writerDb;
6854
7069
  try {
6855
- const row = db.prepare(`SELECT model, input_tokens, cache_creation_tokens, cache_read_tokens,
7070
+ const row = db.prepare(`SELECT model, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens,
6856
7071
  context_tokens
6857
7072
  FROM model_calls
6858
7073
  WHERE session_id = ?
@@ -6867,11 +7082,13 @@ export class ResponseEngine {
6867
7082
  if (recordedTotalTokens && recordedTotalTokens > 0) {
6868
7083
  totalTokens = recordedTotalTokens;
6869
7084
  }
6870
- else if (isClaudeContextUsageModel(model)) {
6871
- totalTokens = (row.input_tokens ?? 0) + (row.cache_creation_tokens ?? 0) + (row.cache_read_tokens ?? 0);
6872
- }
6873
7085
  else {
6874
- totalTokens = row.input_tokens ?? 0;
7086
+ totalTokens = contextTokensForUsage({
7087
+ input_tokens: row.input_tokens,
7088
+ output_tokens: row.output_tokens,
7089
+ cache_creation_input_tokens: row.cache_creation_tokens,
7090
+ cache_read_input_tokens: row.cache_read_tokens,
7091
+ }, model);
6875
7092
  }
6876
7093
  if (totalTokens <= 0)
6877
7094
  return undefined;
@@ -7029,6 +7246,32 @@ export class ResponseEngine {
7029
7246
  hasTokenUsage: hasRecordedTokenUsage(result),
7030
7247
  };
7031
7248
  }
7249
+ /** Only backend acceptance, never a log write or startup status, consumes context. */
7250
+ async *consumeCapsuleWithInput(stream, session, message, lease, capsuleIdForAttempt) {
7251
+ let accepted = false;
7252
+ let consumed = false;
7253
+ for await (const event of stream) {
7254
+ if (!lease || this.turnCoordinator.isCurrent(lease)) {
7255
+ if (event.type === 'input_accepted' && (!lease || event.inputId === lease.inputId))
7256
+ accepted = true;
7257
+ if ((event.type === 'text' && !event.synthetic && !!event.text.trim()) || event.type === 'tool_use')
7258
+ accepted = true;
7259
+ const capsuleId = capsuleIdForAttempt();
7260
+ if (accepted && !consumed && capsuleId && this.sessionManager.consumeSessionCapsule) {
7261
+ const current = await this.sessionManager.getSessionById(session.id);
7262
+ if (current?.agentSessionId && (!lease || this.turnCoordinator.isCurrent(lease))) {
7263
+ consumed = !!this.sessionManager.consumeSessionCapsule(session.id, capsuleId, {
7264
+ agentSessionId: current.agentSessionId,
7265
+ messageId: message.messageId,
7266
+ timestamp: message.timestamp,
7267
+ lease,
7268
+ });
7269
+ }
7270
+ }
7271
+ }
7272
+ yield event;
7273
+ }
7274
+ }
7032
7275
  /**
7033
7276
  * 处理标准事件流(AgentEvent)
7034
7277
  *