evolcore 0.0.40 → 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 (100) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/claude-runner.js +21 -106
  5. package/dist/agents/codex-runner.js +451 -231
  6. package/dist/agents/ecagent-runner.js +30 -11
  7. package/dist/agents/gemini-runner.js +26 -6
  8. package/dist/agents/runner-types.js +11 -3
  9. package/dist/aun/ability-device-routing.js +26 -0
  10. package/dist/aun/aid/client.js +1 -1
  11. package/dist/aun/group/identity.js +8 -0
  12. package/dist/aun/msg/managed-operation.js +4 -4
  13. package/dist/aun/msg/p2p.js +27 -7
  14. package/dist/aun/storage/download.js +30 -0
  15. package/dist/aun/storage/index.js +14 -6
  16. package/dist/channels/aun.js +33 -4
  17. package/dist/channels/daemon.js +24 -4
  18. package/dist/cli/agent-command.js +2 -0
  19. package/dist/cli/agent-create.js +98 -19
  20. package/dist/cli/agent.js +10 -3
  21. package/dist/cli/aun-commands.js +82 -22
  22. package/dist/cli/daemon-commands.js +19 -10
  23. package/dist/cli/index.js +1 -1
  24. package/dist/cli/restart-monitor.js +17 -0
  25. package/dist/cli/session-command.js +128 -13
  26. package/dist/cli/stats.js +60 -4
  27. package/dist/cli/trigger-command.js +2 -2
  28. package/dist/config/access-policy.js +2 -0
  29. package/dist/config/config-operation-service.js +17 -6
  30. package/dist/config/gateway-config.js +1 -1
  31. package/dist/config/peer-role-resolver.js +10 -8
  32. package/dist/core/agent-application-service.js +11 -1
  33. package/dist/core/agent-ipc-registration.js +4 -0
  34. package/dist/core/auth/agent-delegation.js +80 -5
  35. package/dist/core/auth/authorization-audit.js +20 -3
  36. package/dist/core/auth/operation-catalog.js +8 -0
  37. package/dist/core/command/agent-control.js +91 -12
  38. package/dist/core/command/command-handler.js +57 -46
  39. package/dist/core/command/connect-menu.js +23 -2
  40. package/dist/core/command/menu-catalog.js +1 -0
  41. package/dist/core/command/menu-handler.js +38 -101
  42. package/dist/core/command/menu-protocol.js +9 -2
  43. package/dist/core/command/role-menu.js +7 -6
  44. package/dist/core/command/slash-gate.js +13 -10
  45. package/dist/core/command/slash-handler.js +34 -98
  46. package/dist/core/event-catalog.js +15 -0
  47. package/dist/core/ipc-registration.js +18 -1
  48. package/dist/core/memory/consolidation-trigger.js +1 -1
  49. package/dist/core/message/aun-ipc-sender.js +26 -5
  50. package/dist/core/message/aun-request-registry.js +97 -3
  51. package/dist/core/message/im-renderer.js +4 -0
  52. package/dist/core/message/message-admission.js +8 -4
  53. package/dist/core/message/message-bridge.js +40 -6
  54. package/dist/core/message/message-log.js +55 -0
  55. package/dist/core/message/message-queue.js +5 -5
  56. package/dist/core/message/response-engine.js +310 -136
  57. package/dist/core/model/model-catalog.js +7 -6
  58. package/dist/core/ownership/owner-resolver.js +2 -2
  59. package/dist/core/permission/ec-command-parser.js +110 -5
  60. package/dist/core/permission/tool-policy.js +28 -7
  61. package/dist/core/session/session-capsule.js +197 -0
  62. package/dist/core/session/session-manager.js +148 -14
  63. package/dist/core/session/session-mapper.js +2 -0
  64. package/dist/index.js +3 -3
  65. package/dist/ipc.js +22 -8
  66. package/dist/stats/budget.js +1 -1
  67. package/dist/stats/db.js +15 -0
  68. package/dist/stats/index.js +2 -2
  69. package/dist/stats/price-resolver.js +304 -5
  70. package/dist/stats/query.js +82 -3
  71. package/dist/stats/writer.js +38 -5
  72. package/dist/trigger/feedback.js +18 -7
  73. package/dist/trigger/manager.js +20 -3
  74. package/dist/trigger/parser.js +6 -3
  75. package/dist/trigger/patch.js +1 -1
  76. package/dist/trigger/system-definitions.js +43 -7
  77. package/dist/trigger/validation.js +13 -5
  78. package/dist/utils/error-utils.js +14 -0
  79. package/dist/utils/npm-ops.js +2 -1
  80. package/dist/utils/package-version-info.js +1 -1
  81. package/dist/utils/upgrade-jobs.js +45 -5
  82. package/kits/docs/INDEX.md +1 -1
  83. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  84. package/kits/docs/evolcore/INDEX.md +2 -1
  85. package/kits/docs/evolcore/agent-create.md +3 -2
  86. package/kits/docs/evolcore/agent.md +1 -1
  87. package/kits/docs/evolcore/config.md +1 -1
  88. package/kits/docs/evolcore/event.md +1 -0
  89. package/kits/docs/evolcore/fs.md +5 -0
  90. package/kits/docs/evolcore/menu-protocol.md +32 -0
  91. package/kits/docs/evolcore/msg.md +17 -1
  92. package/kits/docs/evolcore/session.md +14 -0
  93. package/kits/schemas/agent-config.schema.13.json +15 -0
  94. package/kits/skills/aid-ability/SKILL.md +35 -6
  95. package/kits/templates/session-capsule/recovery.md +5 -0
  96. package/kits/templates/session-capsule/renew.md +5 -0
  97. package/kits/templates/system-fragments/bootstrap.md +6 -6
  98. package/kits/templates/system-fragments/channel.md +1 -1
  99. package/package.json +3 -3
  100. 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';
@@ -1317,6 +1317,7 @@ export class ResponseEngine {
1317
1317
  channelTypeMap = new Map(); // channelType → channelName(首个实例)
1318
1318
  /** 仅登记正在处理的任务,runner 的 session 回调绝不能投递到其它会话。 */
1319
1319
  activeRenderers = new Map();
1320
+ recoveryNoticeCapsules = new Set();
1320
1321
  /** 已主动发送开始提示时,忽略 runner 对同一次 compact 的回调。 */
1321
1322
  announcedCompactStarts = new Set();
1322
1323
  agentMap;
@@ -1493,6 +1494,10 @@ export class ResponseEngine {
1493
1494
  this.eventBus = eventBus;
1494
1495
  this.commandHandler = commandHandler;
1495
1496
  this.turnCoordinator = new SessionTurnCoordinator(sessionManager);
1497
+ sessionManager.setCapsuleTranscriptReader?.(async (session) => {
1498
+ const runner = this.getAgent(session.channel, session.baseagent, session.selfAID);
1499
+ return await runner.getSessionMessages?.(session.agentSessionId, session.projectPath) ?? [];
1500
+ });
1496
1501
  if (agentRunnerOrMap instanceof Map) {
1497
1502
  this.agentMap = agentRunnerOrMap;
1498
1503
  this.legacySingleRunnerMode = false;
@@ -1546,6 +1551,21 @@ export class ResponseEngine {
1546
1551
  this.activeTaskSpans.delete(event.sessionId);
1547
1552
  }
1548
1553
  });
1554
+ this.eventBus.subscribe('session:backend-recovery', event => {
1555
+ if (event.type !== 'session:backend-recovery' || this.recoveryNoticeCapsules.has(event.capsuleId))
1556
+ return;
1557
+ const active = this.activeRenderers.get(event.sessionId);
1558
+ if (!active)
1559
+ return;
1560
+ this.recoveryNoticeCapsules.add(event.capsuleId);
1561
+ if (this.recoveryNoticeCapsules.size > 512) {
1562
+ this.recoveryNoticeCapsules.delete(this.recoveryNoticeCapsules.values().next().value);
1563
+ }
1564
+ void active.renderer.sendSystemNotice(`原 ${event.baseagent} 会话无法恢复,已创建新的底层会话并载入恢复摘要。未确认的执行结果将先行核实。`, 'session.backend-recovery').catch(error => {
1565
+ this.recoveryNoticeCapsules.delete(event.capsuleId);
1566
+ logger.warn(`[ResponseEngine] Backend recovery notice failed: ${String(error)}`);
1567
+ });
1568
+ });
1549
1569
  // 初始化响应模式协调器,注册内置模式(interactive/proactive)
1550
1570
  const registry = new ResponseModeRegistry();
1551
1571
  registerBuiltinModes(registry);
@@ -1890,27 +1910,44 @@ export class ResponseEngine {
1890
1910
  return { state: 'missing' };
1891
1911
  }
1892
1912
  /** Outer execution deadlines use the same terminal owner as runner idle timeouts. */
1893
- async timeoutSession(sessionId, error) {
1913
+ async timeoutSession(sessionId, error, target) {
1914
+ const session = await this.sessionManager.getSessionById(sessionId);
1915
+ const active = session ? this.turnCoordinator.current(session).active : undefined;
1916
+ if (target && (!active || active.taskId !== target.taskId || active.generation !== target.generation))
1917
+ return;
1894
1918
  const timeout = this.activeTimeoutHandlers.get(sessionId);
1895
- if (timeout)
1896
- await timeout(error);
1919
+ if (timeout && active)
1920
+ await timeout(error, target);
1897
1921
  else
1898
- await this.interruptSession(sessionId, error instanceof OrphanedTargetSessionError ? 'execution_error' : 'timeout', false, isRetryableError(error));
1922
+ await this.interruptSession(sessionId, error instanceof OrphanedTargetSessionError ? 'execution_error' : 'timeout', false, isRetryableError(error), target);
1899
1923
  }
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);
1924
+ async interruptSession(sessionId, reason, strict = false, recoverable, target) {
1905
1925
  const session = await this.sessionManager.getSessionById(sessionId);
1906
1926
  if (!session)
1907
1927
  return;
1908
1928
  this.turnCoordinator.hydrate(session);
1929
+ const activeBeforeInterrupt = this.turnCoordinator.current(session).active;
1930
+ const interruptTarget = target ?? (activeBeforeInterrupt ? {
1931
+ taskId: activeBeforeInterrupt.taskId,
1932
+ generation: activeBeforeInterrupt.generation,
1933
+ } : undefined);
1934
+ // A delayed callback must never invalidate or interrupt a replacement
1935
+ // generation that claimed this session while the session lookup yielded.
1936
+ if (target && (!activeBeforeInterrupt
1937
+ || activeBeforeInterrupt.taskId !== target.taskId
1938
+ || activeBeforeInterrupt.generation !== target.generation))
1939
+ return;
1940
+ this.clearPauseSession(sessionId);
1941
+ // A retry delay has no active runner stream to abort. Wake it only after
1942
+ // verifying that this callback still owns the task generation.
1943
+ this.cancelRetryDelays(sessionId);
1909
1944
  const effectiveReason = reason === 'daemon_restart'
1910
1945
  || this.interruptedSessions.get(sessionId) === 'daemon_restart'
1911
1946
  ? 'daemon_restart'
1912
1947
  : reason;
1913
- const interruptedTurn = this.turnCoordinator.invalidate(sessionId, effectiveReason);
1948
+ const interruptedTurn = this.turnCoordinator.invalidate(sessionId, effectiveReason, interruptTarget);
1949
+ if (interruptTarget && !interruptedTurn?.active)
1950
+ return;
1914
1951
  const interruptedTaskId = interruptedTurn?.active?.taskId;
1915
1952
  this.interruptedSessions.set(sessionId, effectiveReason);
1916
1953
  this.messageQueue?.markActiveTerminal?.(sessionId, effectiveReason);
@@ -1982,9 +2019,9 @@ export class ResponseEngine {
1982
2019
  logger.debug(`[ResponseEngine] interrupt terminal status failure: session=${sessionId} task=${interruptedTaskId} error=${error instanceof Error ? error.message : String(error)}`);
1983
2020
  });
1984
2021
  })();
1985
- const runnerInterrupt = (cancelledQueuedTurn
2022
+ const runnerInterrupt = (cancelledQueuedTurn || !interruptTarget
1986
2023
  ? Promise.resolve()
1987
- : agent.interrupt(sessionId)).catch(error => {
2024
+ : agent.interrupt(sessionId, interruptTarget)).catch(error => {
1988
2025
  logger.debug(`[ResponseEngine] interrupt barrier runner failure: session=${sessionId} error=${error instanceof Error ? error.message : String(error)}`);
1989
2026
  if (strict)
1990
2027
  throw error;
@@ -2313,11 +2350,17 @@ export class ResponseEngine {
2313
2350
  generation: turnLease.generation,
2314
2351
  }) ?? false;
2315
2352
  if (!cancelledQueuedTurn) {
2316
- await agent.interrupt(sessionId).catch(interruptError => {
2353
+ await agent.interrupt(sessionId, {
2354
+ taskId: turnLease.taskId,
2355
+ generation: turnLease.generation,
2356
+ }).catch(interruptError => {
2317
2357
  logger.warn(`[ResponseEngine] Failed to cancel stale runner start: session=${sessionId} task=${taskId} error=${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
2318
2358
  });
2319
2359
  }
2320
- agent.cleanupStream(streamKey);
2360
+ agent.cleanupStream(streamKey, {
2361
+ taskId: turnLease.taskId,
2362
+ generation: turnLease.generation,
2363
+ });
2321
2364
  return true;
2322
2365
  }
2323
2366
  async retryAfterContextRecovery(prompt, opts) {
@@ -2365,7 +2408,10 @@ export class ResponseEngine {
2365
2408
  if (await this.cancelStaleRunnerStart(agent, session.id, streamKey, turnLease, turnLease.taskId)) {
2366
2409
  throw new Error('RUNNER_START_SUPERSEDED');
2367
2410
  }
2368
- agent.registerStream(streamKey, retryStream);
2411
+ agent.registerStream(streamKey, retryStream, {
2412
+ taskId: turnLease.taskId,
2413
+ generation: turnLease.generation,
2414
+ });
2369
2415
  return await this.processEventStream(retryStream, session, agent, renderer, resetTimer, shouldSuppress, proactive, undefined, // 重试分支不调插件钩子
2370
2416
  undefined, turnLease, opts.permissionMode, opts.proactiveSelfAid);
2371
2417
  }
@@ -3057,7 +3103,12 @@ export class ResponseEngine {
3057
3103
  return true;
3058
3104
  },
3059
3105
  };
3060
- const rejectAfterInterruptBarrier = (error) => {
3106
+ const rejectAfterInterruptBarrier = (error, expectedTarget) => {
3107
+ if (expectedTarget) {
3108
+ const current = this.turnCoordinator.current(session).active;
3109
+ if (!current || current.taskId !== expectedTarget.taskId || current.generation !== expectedTarget.generation)
3110
+ return;
3111
+ }
3061
3112
  if (timeoutTriggered)
3062
3113
  return;
3063
3114
  timeoutTriggered = true;
@@ -3066,9 +3117,14 @@ export class ResponseEngine {
3066
3117
  this.timeoutErrors.set(session.id, error);
3067
3118
  this.turnCoordinator.hydrate(session);
3068
3119
  const reason = error instanceof OrphanedTargetSessionError ? 'execution_error' : 'timeout';
3069
- this.turnCoordinator.invalidate(session.id, reason);
3120
+ const activeBeforeTimeout = this.turnCoordinator.current(session).active;
3121
+ const interruptTarget = expectedTarget ?? (activeBeforeTimeout ? {
3122
+ taskId: activeBeforeTimeout.taskId,
3123
+ generation: activeBeforeTimeout.generation,
3124
+ } : undefined);
3125
+ this.turnCoordinator.invalidate(session.id, reason, interruptTarget);
3070
3126
  this.interruptedSessions.set(session.id, reason);
3071
- const barrier = this.interruptSession(session.id, reason, false, timeoutControl.recoverable)
3127
+ const barrier = this.interruptSession(session.id, reason, false, timeoutControl.recoverable, interruptTarget)
3072
3128
  .catch(interruptError => {
3073
3129
  logger.debug(`[ResponseEngine] Timeout interrupt barrier failed: ${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
3074
3130
  });
@@ -3079,8 +3135,10 @@ export class ResponseEngine {
3079
3135
  });
3080
3136
  };
3081
3137
  const triggerAttemptId = message.replyContext?.metadata?.triggerAttemptId;
3082
- const externalTimeout = async (error) => {
3083
- rejectAfterInterruptBarrier(error);
3138
+ const externalTimeout = async (error, requestedTarget) => {
3139
+ if (this.activeTimeoutHandlers.get(session.id) !== externalTimeout)
3140
+ return;
3141
+ rejectAfterInterruptBarrier(error, requestedTarget);
3084
3142
  await timeoutControl.barrier;
3085
3143
  };
3086
3144
  this.activeTimeoutHandlers.set(session.id, externalTimeout);
@@ -3406,6 +3464,7 @@ export class ResponseEngine {
3406
3464
  const chatType = message.chatType || 'private';
3407
3465
  const identityRole = session.identity?.role || 'none';
3408
3466
  let agent;
3467
+ let turnLease;
3409
3468
  try {
3410
3469
  agent = this.getAgent(channelKey, session.baseagent, runnerSelfAid);
3411
3470
  }
@@ -3454,7 +3513,6 @@ export class ResponseEngine {
3454
3513
  }
3455
3514
  }
3456
3515
  const taskPauseController = this.getPauseController(session.id);
3457
- let turnLease;
3458
3516
  const inputCausation = normalizeCausation(message.causation) ?? createRootCausation();
3459
3517
  const taskCausation = deriveCausation(inputCausation);
3460
3518
  recordCausationSpan(taskCausation, 'task.run', {
@@ -3731,32 +3789,41 @@ export class ResponseEngine {
3731
3789
  const rawErrorText = getErrorRawText(timeoutError);
3732
3790
  const isTotalExecutionTimeout = timeoutError.message === 'TOTAL_EXECUTION_TIMEOUT';
3733
3791
  const totalExecutionMs = timeoutError instanceof ExecutionTimeoutError ? timeoutError.timeoutMs : this.totalExecutionLimitMs();
3792
+ const idleSec = getLastIdleSec?.() || 0;
3793
+ const userMessage = timeoutError instanceof OrphanedTargetSessionError
3794
+ ? '⚠️ 任务执行状态丢失,已结束本次执行。'
3795
+ : isTotalExecutionTimeout
3796
+ ? (totalExecutionMs === undefined
3797
+ ? '⚠️ 任务超过总执行时限,已自动中断'
3798
+ : `⚠️ 任务超过总执行时限(${Math.round(totalExecutionMs / 1000)}秒),已自动中断`)
3799
+ : idleSec > 0
3800
+ ? `⚠️ 任务超时(${idleSec}秒无响应),已自动中断`
3801
+ : '⚠️ 任务超时,已自动中断';
3802
+ const timeoutSubtype = normalizeCoreErrorSubtype(timeoutError, undefined, 'timeout');
3803
+ const timeoutReason = isExecutionFailure(timeoutError)
3804
+ ? normalizeCoreErrorReason(timeoutError.reason)
3805
+ : 'timeout';
3734
3806
  const statusPayload = timeoutError instanceof OrphanedTargetSessionError ? {
3735
3807
  kind: 'status.error',
3736
3808
  metadata: {
3737
3809
  errorType: timeoutError.reason,
3738
3810
  message: '任务执行状态丢失,已结束本次执行。',
3811
+ recoverable,
3739
3812
  ...(rawErrorText ? { raw: rawErrorText } : {}),
3740
3813
  },
3741
3814
  } : {
3742
3815
  kind: 'status.timeout',
3743
3816
  metadata: isTotalExecutionTimeout
3744
3817
  ? { ...(totalExecutionMs === undefined ? {} : { totalExecutionMs }),
3745
- ...(timeoutError instanceof ExecutionTimeoutError ? { reason: timeoutError.reason } : {}),
3818
+ errorType: timeoutSubtype,
3819
+ reason: timeoutReason,
3820
+ message: userMessage,
3821
+ recoverable,
3746
3822
  ...(rawErrorText ? { raw: rawErrorText } : {}) }
3747
- : { idleSec: getLastIdleSec?.() || undefined, ...(rawErrorText ? { raw: rawErrorText } : {}) },
3823
+ : { idleSec: idleSec || undefined, errorType: timeoutSubtype, reason: timeoutReason, message: userMessage, recoverable,
3824
+ ...(rawErrorText ? { raw: rawErrorText } : {}) },
3748
3825
  };
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);
3826
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
3760
3827
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
3761
3828
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
3762
3829
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -3764,21 +3831,16 @@ export class ResponseEngine {
3764
3831
  }
3765
3832
  this.agentDelegationRegistry?.revokeTask(session.id, taskId, 'interrupted');
3766
3833
  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(() => { });
3834
+ await adapter.send(envelope, statusPayload).catch(() => { });
3835
+ if (!daemonTrigger && !(statusPayload.kind === 'status.error' && timeoutError instanceof OrphanedTargetSessionError)) {
3836
+ await adapter.send(envelope, {
3837
+ kind: 'result.error',
3838
+ text: userMessage,
3839
+ recoverable,
3840
+ ...(rawErrorText ? { raw: rawErrorText } : {}),
3841
+ subtype: timeoutSubtype,
3842
+ ...(timeoutReason ? { reason: timeoutReason } : {}),
3843
+ }).catch(() => { });
3782
3844
  }
3783
3845
  this.touchAgentActivity(channelKey);
3784
3846
  this.publishTriggerExecutionFailure(message, isExecutionFailure(timeoutError) ? timeoutError.reason : timeoutError.message, {
@@ -3849,7 +3911,10 @@ export class ResponseEngine {
3849
3911
  proactiveCircuitBreakTimer = undefined;
3850
3912
  }
3851
3913
  const interruptPromise = (async () => {
3852
- await agent.interrupt(session.id).catch(error => {
3914
+ await agent.interrupt(session.id, turnLease ? {
3915
+ taskId: turnLease.taskId,
3916
+ generation: turnLease.generation,
3917
+ } : undefined).catch(error => {
3853
3918
  logger.debug(`[ResponseEngine] circuit break interrupt failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
3854
3919
  });
3855
3920
  })();
@@ -4386,12 +4451,13 @@ export class ResponseEngine {
4386
4451
  }
4387
4452
  : {}),
4388
4453
  armApprovedDelegationCommand: this.agentDelegationRegistry
4389
- ? (sessionToken, commandHash, approvalId) => this.agentDelegationRegistry.armApprovedCommand({
4454
+ ? (sessionToken, commandHash, approvalId, specHash) => this.agentDelegationRegistry.armApprovedCommand({
4390
4455
  sessionToken,
4391
4456
  sessionId: session.id,
4392
4457
  taskId,
4393
4458
  commandHash,
4394
4459
  approvalId,
4460
+ specHash,
4395
4461
  })
4396
4462
  : undefined,
4397
4463
  revokeApprovedDelegationCommand: this.agentDelegationRegistry
@@ -4466,7 +4532,10 @@ export class ResponseEngine {
4466
4532
  });
4467
4533
  }
4468
4534
  finally {
4469
- await agent.interrupt(session.id).catch(error => {
4535
+ await agent.interrupt(session.id, turnLease ? {
4536
+ taskId: turnLease.taskId,
4537
+ generation: turnLease.generation,
4538
+ } : undefined).catch(error => {
4470
4539
  logger.debug(`[ResponseEngine] permission terminal interrupt failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
4471
4540
  });
4472
4541
  }
@@ -4874,8 +4943,10 @@ export class ResponseEngine {
4874
4943
  inputId: turnLease.inputId,
4875
4944
  },
4876
4945
  };
4877
- const refreshTopicBindingForLogicalRetry = async () => {
4878
- if ((isMainSession(session) && !message.taskRecovery) || typeof this.sessionManager.getSessionById !== 'function')
4946
+ let hasCapsuleBoundary = !!session.metadata?.capsuleId;
4947
+ const refreshBackendBindingForLogicalRetry = async () => {
4948
+ if ((isMainSession(session) && !message.taskRecovery && !hasCapsuleBoundary)
4949
+ || typeof this.sessionManager.getSessionById !== 'function')
4879
4950
  return;
4880
4951
  const latest = await this.sessionManager.getSessionById(session.id);
4881
4952
  if (!latest || sessionLocalTopicId(latest) !== sessionLocalTopicId(session)) {
@@ -4890,13 +4961,13 @@ export class ResponseEngine {
4890
4961
  session.metadata = latest.metadata;
4891
4962
  if (latestAgentSessionId === runAgentSessionId)
4892
4963
  return;
4893
- logger.info(`[ResponseEngine] Refreshing authoritative topic backend for logical retry: `
4964
+ logger.info(`[ResponseEngine] Refreshing backend binding for logical retry: `
4894
4965
  + `session=${session.id} task=${taskId} backend=${latestAgentSessionId ?? 'none'}`);
4895
4966
  runAgentSessionId = latestAgentSessionId;
4896
- modelOverride = {
4897
- ...(modelOverride || {}),
4898
- backend: { kind: 'topic', agentSessionId: runAgentSessionId ?? null },
4899
- };
4967
+ if (isTopicSession(session)) {
4968
+ modelOverride = { ...(modelOverride || {}),
4969
+ backend: { kind: 'topic', agentSessionId: runAgentSessionId ?? null } };
4970
+ }
4900
4971
  };
4901
4972
  // 预压缩必须使用与本轮 runQuery 相同的有效模型/强度覆盖。
4902
4973
  // 模型解析完成后再执行,避免关系级模型存在时回落到 runner 默认模型。
@@ -5083,7 +5154,7 @@ export class ResponseEngine {
5083
5154
  const estTokens = (s) => s ? Math.ceil(s.length / 4) : 0;
5084
5155
  const cbModel = effectiveModel || agentModel || 'unknown';
5085
5156
  // 从统一模型参数表获取模型的真实 context_window
5086
- const { resolveModelSpec } = await import('../../stats/billing.js');
5157
+ const { resolveModelSpec } = await import('../../stats/price-resolver.js');
5087
5158
  const modelSpec = resolveModelSpec(resolveRoot(), cbModel);
5088
5159
  const cbMaxTokens = modelSpec.context_window;
5089
5160
  const systemPromptTokens = estTokens(options?.systemPromptAppend);
@@ -5454,7 +5525,34 @@ export class ResponseEngine {
5454
5525
  this.activeRunnerModels.delete(session.id);
5455
5526
  // 每次尝试前覆盖:备用模型切换后,请求模型以最后一次尝试为准
5456
5527
  this.recordBgSessionModels(message, { requestedModel: debugRunnerModel });
5457
- const stream = await agent.runQuery(session.id, effectivePrompt, absoluteProjectPath, runAgentSessionId, runnerImages, effectiveSystemPrompt, this.sessionManager, modelOverride, runtimeEnv);
5528
+ if (message.restartResume?.submitted && runAgentSessionId) {
5529
+ // A durable recovery request resumes already-submitted input.
5530
+ // Reconcile a crash after acceptance but before the capsule journal append.
5531
+ const latest = await this.sessionManager.getSessionById?.(session.id);
5532
+ const pending = latest && this.sessionManager.getPendingCapsule?.(latest);
5533
+ if (pending?.agentSessionId === runAgentSessionId) {
5534
+ this.sessionManager.consumeSessionCapsule?.(session.id, pending.capsuleId, {
5535
+ agentSessionId: runAgentSessionId, messageId: pending.messageId,
5536
+ lease: turnLease,
5537
+ });
5538
+ }
5539
+ }
5540
+ const capsuleInput = this.sessionManager.prepareCapsuleInput?.(session.id, effectivePrompt)
5541
+ ?? { prompt: effectivePrompt };
5542
+ let attemptCapsuleId = capsuleInput.capsuleId;
5543
+ const attemptOverride = { ...modelOverride, capsule: {
5544
+ recover: async (oldId, prompt, systemPrompt) => {
5545
+ if (turnLease && !this.turnCoordinator.isCurrent(turnLease))
5546
+ throw new Error('RUNNER_START_SUPERSEDED');
5547
+ const prepared = await this.sessionManager.prepareBackendRecovery(session.id, oldId, prompt, systemPrompt, turnLease);
5548
+ attemptCapsuleId = prepared.capsuleId;
5549
+ hasCapsuleBoundary = true;
5550
+ effectiveSystemPrompt = prepared.systemPrompt;
5551
+ return prepared;
5552
+ },
5553
+ } };
5554
+ const rawStream = await agent.runQuery(session.id, capsuleInput.prompt, absoluteProjectPath, runAgentSessionId, runnerImages, effectiveSystemPrompt, this.sessionManager, attemptOverride, runtimeEnv);
5555
+ const stream = this.consumeCapsuleWithInput(rawStream, session, message, turnLease, () => attemptCapsuleId);
5458
5556
  // The turn may be superseded while the runner is still creating its
5459
5557
  // backend query. Replay the interrupt after runQuery resolves, when
5460
5558
  // every runner is required to have an addressable cancellation handle.
@@ -5483,7 +5581,10 @@ export class ResponseEngine {
5483
5581
  releaseHintClaim(accepted);
5484
5582
  ownerHintClaim = undefined;
5485
5583
  }
5486
- agent.registerStream(streamKey, stream);
5584
+ agent.registerStream(streamKey, stream, turnLease ? {
5585
+ taskId: turnLease.taskId,
5586
+ generation: turnLease.generation,
5587
+ } : undefined);
5487
5588
  streamRegistered = true;
5488
5589
  if (shouldTimeoutRetryAttempt) {
5489
5590
  attemptTimeout = createRetryAttemptTimeout(apiRetryTimeoutMs);
@@ -5512,7 +5613,10 @@ export class ResponseEngine {
5512
5613
  }
5513
5614
  try {
5514
5615
  if (blocking)
5515
- await agent.interrupt(session.id);
5616
+ await agent.interrupt(session.id, turnLease ? {
5617
+ taskId: turnLease.taskId,
5618
+ generation: turnLease.generation,
5619
+ } : undefined);
5516
5620
  await renderer.flush(false);
5517
5621
  await this.asyncQuestions.present(session, request, message, adapter, envelope);
5518
5622
  }
@@ -5542,7 +5646,7 @@ export class ResponseEngine {
5542
5646
  // Activation can complete either before runQuery returns (Codex)
5543
5647
  // or while its event stream is consumed (Claude/Gemini/Ecagent).
5544
5648
  // Always reconcile from strict latest before any logical retry.
5545
- await refreshTopicBindingForLogicalRetry();
5649
+ await refreshBackendBindingForLogicalRetry();
5546
5650
  if (!streamResult.isError && !isExpectedTerminalInterrupt(streamResult.terminalReason)) {
5547
5651
  const protocolDecision = this.turnCoordinator.evaluateCommit(turnLease, this.buildTurnCommitEvidence(session, streamResult));
5548
5652
  const protocolReason = protocolDecision.ok ? undefined : protocolDecision.reason;
@@ -5553,7 +5657,7 @@ export class ResponseEngine {
5553
5657
  const protocolRetry = retryScheduler.afterProtocolFailure(safeProtocolReplay ? protocolReason : undefined, safeProtocolReplay);
5554
5658
  if (protocolRetry.kind === 'protocol_replay') {
5555
5659
  protocolReplayAttempts = protocolRetry.attempt;
5556
- agent.cleanupStream(streamKey);
5660
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5557
5661
  logger.warn(`[ResponseEngine] Replaying zero-work protocol failure: session=${session.id} `
5558
5662
  + `task=${taskId} reason=${protocolReason} attempt=${protocolRetry.attempt}/${protocolRetry.maxAttempts}`);
5559
5663
  await this.emitOperationalNotice(renderer, `模型未确认完成,正在立即重试 ${protocolRetry.attempt}/${protocolRetry.maxAttempts}`, 'warn', 'protocol-retry');
@@ -5578,17 +5682,20 @@ export class ResponseEngine {
5578
5682
  break; // 成功,跳出重试循环
5579
5683
  }
5580
5684
  catch (retryError) {
5581
- await refreshTopicBindingForLogicalRetry();
5685
+ await refreshBackendBindingForLogicalRetry();
5582
5686
  const retryAttemptTimedOut = retryError instanceof RetryAttemptTimeoutError;
5583
5687
  if (retryAttemptTimedOut) {
5584
5688
  logger.warn(`[ResponseEngine] Retry attempt ${runAttempt} timed out after ${retryError.timeoutMs}ms without agent events; interrupting current stream`);
5585
5689
  renderer.discardPending();
5586
- await agent.interrupt(session.id).catch(interruptError => {
5690
+ await agent.interrupt(session.id, turnLease ? {
5691
+ taskId: turnLease.taskId,
5692
+ generation: turnLease.generation,
5693
+ } : undefined).catch(interruptError => {
5587
5694
  logger.warn(`[ResponseEngine] Failed to interrupt timed-out retry attempt: ${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
5588
5695
  });
5589
5696
  }
5590
5697
  if (streamRegistered) {
5591
- agent.cleanupStream(streamKey);
5698
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5592
5699
  }
5593
5700
  if (permissionTerminalFailure) {
5594
5701
  const permissionError = new Error(permissionTerminalFailure.message);
@@ -5765,7 +5872,7 @@ export class ResponseEngine {
5765
5872
  const commitEvidence = this.buildTurnCommitEvidence(session, streamResult);
5766
5873
  const commitDecision = this.turnCoordinator.evaluateCommit(turnLease, commitEvidence);
5767
5874
  if (!commitDecision.ok && commitDecision.reason === 'stale_generation') {
5768
- agent.cleanupStream(streamKey);
5875
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5769
5876
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5770
5877
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5771
5878
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5781,7 +5888,7 @@ export class ResponseEngine {
5781
5888
  }
5782
5889
  if (!commitDecision.ok) {
5783
5890
  if (commitDecision.reason === 'stale_generation') {
5784
- agent.cleanupStream(streamKey);
5891
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5785
5892
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5786
5893
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5787
5894
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5947,7 +6054,7 @@ export class ResponseEngine {
5947
6054
  && message.triggerMeta.noopSentinel.length > 0
5948
6055
  && visibleFinalReplyText.trim() === message.triggerMeta.noopSentinel;
5949
6056
  if (!this.turnCoordinator.isCurrent(turnLease)) {
5950
- agent.cleanupStream(streamKey);
6057
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5951
6058
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5952
6059
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5953
6060
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5974,27 +6081,36 @@ export class ResponseEngine {
5974
6081
  // (2026-10-11 403「无法连接到积分服务器」案例)。
5975
6082
  // 以错误收场的轮次一律走 system.error:前端收到的单条消息即可判断来源,
5976
6083
  // 不需要等后续的 result.error。
5977
- const errorText = visibleFinalReplyText || streamResult.syntheticDiagnosticText || getStreamErrorMessage(streamResult, false);
6084
+ const errorText = streamResult.isError
6085
+ ? (streamResult.syntheticDiagnosticText || getStreamErrorMessage(streamResult, false))
6086
+ : visibleFinalReplyText;
5978
6087
  if (streamResult.isError) {
5979
6088
  // 用原始诊断文本(含错误码)判断可重试性,不用已过 stripContextLimitErrorLines 的展示文本
5980
6089
  const subtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || getStreamErrorText(streamResult)), streamResult.subtype, streamResult.terminalReason);
5981
6090
  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;
6091
+ if (this.isTrustedDaemonTrigger(message)) {
6092
+ // DaemonChannel must receive the metadata-bearing terminal below
6093
+ // before it settles the attempt; sending system.error here would
6094
+ // discard tool counts and recovery details.
6095
+ }
6096
+ else {
6097
+ await adapter.send(envelope, {
6098
+ kind: 'system.error',
6099
+ text: errorText,
6100
+ ...(subtype === ErrorType.POLICY_REJECTED ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
6101
+ subtype,
6102
+ ...(reason ? { reason } : {}),
6103
+ recoverable: streamRecoverable,
6104
+ }).catch(() => { });
6105
+ sentErrorAsSystemError = true;
6106
+ }
5991
6107
  }
5992
6108
  else if (visibleFinalReplyText && (shouldSuppress() || !streamResult.hasProjectedCurrentReplyText)) {
5993
6109
  await renderer.addText(visibleFinalReplyText, undefined, undefined, streamResult.assistantUuid);
5994
6110
  }
5995
6111
  }
5996
6112
  // 先清理流和处理中状态(保证即使 flush 卡住,session 也不会永久处于"处理中")
5997
- agent.cleanupStream(streamKey);
6113
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5998
6114
  logger.info(`[ResponseEngine] agent.cleanupStream ok: session=${session.id} task=${taskId}`);
5999
6115
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
6000
6116
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
@@ -6028,7 +6144,7 @@ export class ResponseEngine {
6028
6144
  // outcome so AUN does not label that text as normal completion.
6029
6145
  try {
6030
6146
  if (streamResult.isError && !isExpectedTerminalInterrupt(streamResult.terminalReason)) {
6031
- await renderer.flush(true, 'failed');
6147
+ await renderer.flush(false);
6032
6148
  }
6033
6149
  else {
6034
6150
  await renderer.flush(!isExpectedTerminalInterrupt(streamResult.terminalReason));
@@ -6081,8 +6197,9 @@ export class ResponseEngine {
6081
6197
  ? getContextTooLongHint(agent)
6082
6198
  : getStreamErrorMessage(streamResult, false);
6083
6199
  const rawSubtype = streamResult.subtype || 'agent_error';
6084
- const errorType = prefixErrorType(ERROR_PREFIX.AGENT, rawSubtype);
6085
6200
  const coreSubtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || errorSummary), rawSubtype, streamResult.terminalReason);
6201
+ const effectiveSubtype = coreSubtype === ErrorType.POLICY_REJECTED ? coreSubtype : rawSubtype;
6202
+ const errorType = prefixErrorType(ERROR_PREFIX.AGENT, effectiveSubtype);
6086
6203
  const coreReason = permissionTerminalFailure
6087
6204
  ? normalizeCoreErrorReason(permissionTerminalFailure.reason)
6088
6205
  : normalizeCoreErrorReason(streamResult.terminalReason);
@@ -6094,10 +6211,11 @@ export class ResponseEngine {
6094
6211
  taskActivityStatus = isExpectedInterrupt ? 'interrupted' : 'error';
6095
6212
  if (!isExpectedInterrupt && !permissionTerminalFailure) {
6096
6213
  const terminalMetadata = {
6097
- errorType: rawSubtype,
6214
+ errorType: effectiveSubtype,
6215
+ ...(coreReason ? { reason: coreReason } : {}),
6098
6216
  recoverable: streamRecoverable,
6099
6217
  message: userErrorSummary,
6100
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
6218
+ ...(coreSubtype === ErrorType.POLICY_REJECTED ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
6101
6219
  durationMs: Date.now() - startTime,
6102
6220
  numTurns: streamResult.numTurns,
6103
6221
  toolCallCount: streamResult.toolUseCount ?? 0,
@@ -6111,16 +6229,6 @@ export class ResponseEngine {
6111
6229
  // system.error 已在 finalReplyText 分支把错误文本发给了前端,不再重复发 result.error
6112
6230
  if (this.isTrustedDaemonTrigger(message)) {
6113
6231
  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
6232
  }
6125
6233
  else {
6126
6234
  if (!sentErrorAsSystemError) {
@@ -6128,7 +6236,7 @@ export class ResponseEngine {
6128
6236
  kind: 'result.error',
6129
6237
  text: userErrorSummary,
6130
6238
  recoverable: streamRecoverable,
6131
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
6239
+ ...(coreSubtype === ErrorType.POLICY_REJECTED ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
6132
6240
  subtype: coreSubtype,
6133
6241
  ...(coreReason ? { reason: coreReason } : {}),
6134
6242
  }).catch(() => { });
@@ -6183,7 +6291,7 @@ export class ResponseEngine {
6183
6291
  });
6184
6292
  recordCausationSpan(taskCausation, 'task.run', { status: 'failed', refs: { taskId, sessionId: session.id, messageId }, reason: errorType });
6185
6293
  // 系统级 subtype 仍累计错误计数,供 /status 诊断使用
6186
- if (isInfraError(rawSubtype, streamResult.terminalReason)) {
6294
+ if (isInfraError(effectiveSubtype, streamResult.terminalReason)) {
6187
6295
  const chatType = message.chatType || 'private';
6188
6296
  const identityRole = session.identity?.role || 'none';
6189
6297
  const { policy } = channelInfo;
@@ -6270,7 +6378,7 @@ export class ResponseEngine {
6270
6378
  auto_compact_tokens: mc.contextUsage?.autoCompactTokens,
6271
6379
  degraded: mc.degraded ? 1 : 0,
6272
6380
  }));
6273
- insertModelCalls(resolveRoot(), mcRows);
6381
+ insertModelCalls(resolveRoot(), mcRows, gwPricing);
6274
6382
  }
6275
6383
  const totalIn = event.input_tokens + event.cache_read_tokens;
6276
6384
  statsCacheHitRate = totalIn > 0 ? Math.round((event.cache_read_tokens / totalIn) * 100) / 100 : 0;
@@ -6284,7 +6392,7 @@ export class ResponseEngine {
6284
6392
  let sessionStats;
6285
6393
  let modelSpec;
6286
6394
  try {
6287
- const { resolveModelSpec } = await import('../../stats/billing.js');
6395
+ const { resolveModelSpec } = await import('../../stats/price-resolver.js');
6288
6396
  const { querySessionSummary } = await import('../../stats/query.js');
6289
6397
  modelSpec = resolveModelSpec(resolveRoot(), statsModel);
6290
6398
  const sum = querySessionSummary(resolveRoot(), session.id);
@@ -6473,7 +6581,7 @@ export class ResponseEngine {
6473
6581
  }
6474
6582
  const leaseWasCurrent = !!turnLease && this.turnCoordinator.isCurrent(turnLease);
6475
6583
  // 清理流和处理中状态(异常时也要清除)
6476
- agent.cleanupStream(streamKey);
6584
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
6477
6585
  logger.info(`[ResponseEngine] agent.cleanupStream ok (on error): session=${session.id} task=${taskId}`);
6478
6586
  try {
6479
6587
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
@@ -6520,25 +6628,49 @@ export class ResponseEngine {
6520
6628
  }
6521
6629
  const totalExecutionMs = error instanceof ExecutionTimeoutError ? error.timeoutMs : this.totalExecutionLimitMs();
6522
6630
  const rawErrorText = getErrorRawText(error);
6631
+ const safeRawErrorText = isPolicyRejectedError(error) ? undefined : rawErrorText;
6523
6632
  const procStatus = errType === ErrorType.SDK_TIMEOUT || isTotalExecutionTimeout ? 'timeout'
6524
6633
  : errType === ErrorType.STREAM_ERROR ? 'interrupted'
6525
6634
  : 'error';
6526
6635
  const daemonTrigger = this.isTrustedDaemonTrigger(message);
6636
+ const timeoutIdleSec = getLastIdleSec?.() || 0;
6637
+ const timeoutMessage = isTotalExecutionTimeout
6638
+ ? (totalExecutionMs === undefined
6639
+ ? '⚠️ 任务超过总执行时限,已自动中断'
6640
+ : `⚠️ 任务超过总执行时限(${Math.round(totalExecutionMs / 1000)}秒),已自动中断`)
6641
+ : timeoutIdleSec > 0
6642
+ ? `⚠️ 任务超时(${timeoutIdleSec}秒无响应),已自动中断`
6643
+ : '⚠️ 任务超时,已自动中断';
6644
+ const timeoutSubtype = normalizeCoreErrorSubtype(error, undefined, 'timeout');
6645
+ const timeoutReason = isExecutionFailure(error) ? normalizeCoreErrorReason(error.reason) : 'timeout';
6527
6646
  const statusPayload = error instanceof OrphanedTargetSessionError
6528
6647
  ? { kind: 'status.error', metadata: {
6529
6648
  errorType: error.reason,
6649
+ reason: error.reason,
6530
6650
  message: '任务执行状态丢失,已结束本次执行。',
6531
- ...(rawErrorText ? { raw: rawErrorText } : {}),
6651
+ recoverable,
6652
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}),
6532
6653
  } }
6533
6654
  : procStatus === 'timeout'
6534
6655
  ? { kind: 'status.timeout', metadata: isTotalExecutionTimeout
6535
6656
  ? { ...(totalExecutionMs === undefined ? {} : { totalExecutionMs }),
6536
- ...(error instanceof ExecutionTimeoutError ? { reason: error.reason } : {}),
6537
- ...(rawErrorText ? { raw: rawErrorText } : {}) }
6538
- : { idleSec: getLastIdleSec?.() || undefined, ...(rawErrorText ? { raw: rawErrorText } : {}) } }
6657
+ errorType: timeoutSubtype,
6658
+ reason: timeoutReason,
6659
+ message: timeoutMessage,
6660
+ recoverable,
6661
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}) }
6662
+ : { idleSec: timeoutIdleSec || undefined, errorType: timeoutSubtype, reason: timeoutReason,
6663
+ message: timeoutMessage, recoverable,
6664
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}) } }
6539
6665
  : procStatus === 'interrupted'
6540
6666
  ? { kind: 'status.interrupted', metadata: { reason: 'stream_error' } }
6541
- : { kind: 'status.error', metadata: rawErrorText ? { raw: rawErrorText } : undefined };
6667
+ : { kind: 'status.error', metadata: {
6668
+ errorType: errType,
6669
+ reason: normalizeCoreErrorReason(error instanceof Error ? error.message : undefined),
6670
+ message: errorMsg,
6671
+ recoverable,
6672
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}),
6673
+ } };
6542
6674
  // 用户主动中断(新消息打断 或 /stop 命令)时静默,不发送中断/错误提示
6543
6675
  if (!isUserInterrupt && ownsTimeoutTerminal && !daemonTrigger) {
6544
6676
  await adapter.send(envelope, statusPayload).catch(() => { });
@@ -6657,9 +6789,11 @@ export class ResponseEngine {
6657
6789
  : modelFallbackExhaustedMessage
6658
6790
  ? ErrorType.MODEL_UNAVAILABLE
6659
6791
  : normalizeCoreErrorSubtype(error, undefined, isTotalExecutionTimeout || isTimeout ? 'timeout' : undefined);
6660
- const distinctRawErrorText = rawErrorText && !userMessage.includes(rawErrorText)
6661
- ? rawErrorText
6662
- : undefined;
6792
+ const distinctRawErrorText = errorSubtype === ErrorType.POLICY_REJECTED
6793
+ ? undefined
6794
+ : rawErrorText && !userMessage.includes(rawErrorText)
6795
+ ? rawErrorText
6796
+ : undefined;
6663
6797
  const errorPayload = {
6664
6798
  kind: 'result.error',
6665
6799
  text: userMessage,
@@ -6668,34 +6802,46 @@ export class ResponseEngine {
6668
6802
  ...(distinctRawErrorText ? { raw: distinctRawErrorText } : {}),
6669
6803
  ...(errorReason ? { reason: errorReason } : {}),
6670
6804
  };
6671
- if (!isUserInterrupt && daemonTrigger && procStatus === 'error') {
6805
+ if (!isUserInterrupt && daemonTrigger) {
6672
6806
  // DaemonChannel settles a trigger on the first terminal payload. Put
6673
6807
  // the complete failure metadata first so the audit retains tool
6674
6808
  // counts and context-recovery diagnostics even for thrown errors
6675
6809
  // (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);
6810
+ const terminalMetadata = {
6811
+ errorType: errorSubtype,
6812
+ reason: errorReason,
6813
+ message: userMessage,
6814
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}),
6815
+ recoverable,
6816
+ durationMs: Date.now() - startTime,
6817
+ numTurns: streamResult.numTurns,
6818
+ toolCallCount: streamResult.toolUseCount ?? 0,
6819
+ tokenUsage: streamResult.tokenUsage,
6820
+ contextUsage: streamResult.contextUsage,
6821
+ contextRecoveryAttempts: streamResult.contextRecoveryAttempts ?? 0,
6822
+ };
6823
+ if (procStatus === 'timeout') {
6824
+ await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
6825
+ kind: 'status.timeout',
6826
+ metadata: {
6827
+ ...(statusPayload.kind === 'status.timeout' ? statusPayload.metadata : {}),
6828
+ ...terminalMetadata,
6829
+ },
6830
+ }).catch(() => { });
6831
+ }
6832
+ else {
6833
+ await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
6834
+ kind: 'status.error',
6835
+ metadata: {
6836
+ ...(statusPayload.kind === 'status.error' ? statusPayload.metadata : {}),
6837
+ ...terminalMetadata,
6838
+ },
6839
+ }).catch(() => { });
6840
+ }
6692
6841
  }
6693
6842
  else {
6694
6843
  await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), errorPayload);
6695
6844
  }
6696
- if (!isUserInterrupt && daemonTrigger && procStatus !== 'error') {
6697
- await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), statusPayload).catch(() => { });
6698
- }
6699
6845
  // Proactive 可观测:catch 块的基础设施错误也透传为 thought,保证按 task_id 聚合完整
6700
6846
  if (isProactive && adapter.capabilities?.thought) {
6701
6847
  await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
@@ -6852,7 +6998,7 @@ export class ResponseEngine {
6852
6998
  return undefined;
6853
6999
  const shouldClose = !writerDb;
6854
7000
  try {
6855
- const row = db.prepare(`SELECT model, input_tokens, cache_creation_tokens, cache_read_tokens,
7001
+ const row = db.prepare(`SELECT model, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens,
6856
7002
  context_tokens
6857
7003
  FROM model_calls
6858
7004
  WHERE session_id = ?
@@ -6867,11 +7013,13 @@ export class ResponseEngine {
6867
7013
  if (recordedTotalTokens && recordedTotalTokens > 0) {
6868
7014
  totalTokens = recordedTotalTokens;
6869
7015
  }
6870
- else if (isClaudeContextUsageModel(model)) {
6871
- totalTokens = (row.input_tokens ?? 0) + (row.cache_creation_tokens ?? 0) + (row.cache_read_tokens ?? 0);
6872
- }
6873
7016
  else {
6874
- totalTokens = row.input_tokens ?? 0;
7017
+ totalTokens = contextTokensForUsage({
7018
+ input_tokens: row.input_tokens,
7019
+ output_tokens: row.output_tokens,
7020
+ cache_creation_input_tokens: row.cache_creation_tokens,
7021
+ cache_read_input_tokens: row.cache_read_tokens,
7022
+ }, model);
6875
7023
  }
6876
7024
  if (totalTokens <= 0)
6877
7025
  return undefined;
@@ -7029,6 +7177,32 @@ export class ResponseEngine {
7029
7177
  hasTokenUsage: hasRecordedTokenUsage(result),
7030
7178
  };
7031
7179
  }
7180
+ /** Only backend acceptance, never a log write or startup status, consumes context. */
7181
+ async *consumeCapsuleWithInput(stream, session, message, lease, capsuleIdForAttempt) {
7182
+ let accepted = false;
7183
+ let consumed = false;
7184
+ for await (const event of stream) {
7185
+ if (!lease || this.turnCoordinator.isCurrent(lease)) {
7186
+ if (event.type === 'input_accepted' && (!lease || event.inputId === lease.inputId))
7187
+ accepted = true;
7188
+ if ((event.type === 'text' && !event.synthetic && !!event.text.trim()) || event.type === 'tool_use')
7189
+ accepted = true;
7190
+ const capsuleId = capsuleIdForAttempt();
7191
+ if (accepted && !consumed && capsuleId && this.sessionManager.consumeSessionCapsule) {
7192
+ const current = await this.sessionManager.getSessionById(session.id);
7193
+ if (current?.agentSessionId && (!lease || this.turnCoordinator.isCurrent(lease))) {
7194
+ consumed = !!this.sessionManager.consumeSessionCapsule(session.id, capsuleId, {
7195
+ agentSessionId: current.agentSessionId,
7196
+ messageId: message.messageId,
7197
+ timestamp: message.timestamp,
7198
+ lease,
7199
+ });
7200
+ }
7201
+ }
7202
+ }
7203
+ yield event;
7204
+ }
7205
+ }
7032
7206
  /**
7033
7207
  * 处理标准事件流(AgentEvent)
7034
7208
  *