evolcore 0.0.39 → 0.0.41-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +31 -20
  3. package/bin/codex-managed-hook.mjs +11 -0
  4. package/bin/ec-safe-output.js +25 -3
  5. package/dist/agents/baseagent-availability.js +1 -0
  6. package/dist/agents/claude-runner.js +53 -152
  7. package/dist/agents/codex-runner.js +485 -241
  8. package/dist/agents/ecagent-runner.js +48 -18
  9. package/dist/agents/gemini-runner.js +27 -8
  10. package/dist/agents/runner-types.js +39 -9
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/aid/control-aid.js +23 -98
  14. package/dist/aun/aid/ownership-operation.js +1 -3
  15. package/dist/aun/group/identity.js +8 -0
  16. package/dist/aun/group/invite-service.js +6 -0
  17. package/dist/aun/msg/managed-operation.js +4 -4
  18. package/dist/aun/msg/p2p.js +28 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +99 -52
  22. package/dist/channels/daemon.js +24 -4
  23. package/dist/channels/dingtalk.js +8 -2
  24. package/dist/channels/feishu.js +6 -1
  25. package/dist/channels/wecom.js +7 -3
  26. package/dist/cli/agent-command.js +2 -0
  27. package/dist/cli/agent-create.js +121 -23
  28. package/dist/cli/agent.js +10 -3
  29. package/dist/cli/aid-bind-command.js +4 -1
  30. package/dist/cli/aun-commands.js +82 -22
  31. package/dist/cli/daemon-commands.js +260 -26
  32. package/dist/cli/index.js +25 -13
  33. package/dist/cli/memory-command.js +33 -14
  34. package/dist/cli/restart-monitor.js +52 -13
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/task-context.js +1 -0
  38. package/dist/cli/trigger-command.js +2 -2
  39. package/dist/config/access-policy.js +2 -0
  40. package/dist/config/config-field-policy.js +1 -0
  41. package/dist/config/config-operation-service.js +17 -6
  42. package/dist/config/gateway-config.js +1 -1
  43. package/dist/config/peer-role-resolver.js +10 -8
  44. package/dist/contracts/ecweb-service-protocol.js +44 -0
  45. package/dist/core/agent-application-service.js +11 -1
  46. package/dist/core/agent-ipc-registration.js +4 -0
  47. package/dist/core/agent-runtime.js +6 -0
  48. package/dist/core/auth/agent-delegation.js +87 -9
  49. package/dist/core/auth/auth-gateway.js +3 -1
  50. package/dist/core/auth/authorization-audit.js +25 -4
  51. package/dist/core/auth/debug-context.js +5 -1
  52. package/dist/core/auth/operation-catalog.js +24 -0
  53. package/dist/core/command/agent-control.js +91 -12
  54. package/dist/core/command/command-handler.js +64 -47
  55. package/dist/core/command/connect-menu.js +23 -2
  56. package/dist/core/command/menu-catalog.js +49 -12
  57. package/dist/core/command/menu-handler.js +110 -105
  58. package/dist/core/command/menu-protocol.js +29 -3
  59. package/dist/core/command/role-menu.js +7 -6
  60. package/dist/core/command/slash-gate.js +22 -5
  61. package/dist/core/command/slash-handler.js +121 -102
  62. package/dist/core/event-catalog.js +17 -0
  63. package/dist/core/interaction-router.js +2 -1
  64. package/dist/core/ipc-registration.js +44 -8
  65. package/dist/core/memory/batch-meta.js +2 -0
  66. package/dist/core/memory/consolidation-context.js +42 -51
  67. package/dist/core/memory/consolidation-ops-records.js +39 -7
  68. package/dist/core/memory/consolidation-trigger.js +72 -65
  69. package/dist/core/memory/consolidation.js +226 -20
  70. package/dist/core/memory/memory-writer.js +160 -34
  71. package/dist/core/memory/relation-idle-monitor.js +287 -0
  72. package/dist/core/memory/relation-sweep.js +206 -0
  73. package/dist/core/message/aun-ipc-sender.js +31 -5
  74. package/dist/core/message/aun-request-registry.js +97 -3
  75. package/dist/core/message/im-renderer.js +4 -0
  76. package/dist/core/message/message-admission.js +8 -4
  77. package/dist/core/message/message-bridge.js +96 -53
  78. package/dist/core/message/message-log.js +72 -0
  79. package/dist/core/message/message-queue.js +11 -5
  80. package/dist/core/message/outbound.js +70 -0
  81. package/dist/core/message/peer-mode.js +7 -2
  82. package/dist/core/message/response-engine.js +633 -191
  83. package/dist/core/model/model-catalog.js +7 -6
  84. package/dist/core/ownership/owner-resolver.js +384 -178
  85. package/dist/core/permission/ec-command-parser.js +129 -8
  86. package/dist/core/permission/tool-policy.js +35 -14
  87. package/dist/core/role/runtime-policy.js +64 -0
  88. package/dist/core/session/session-capsule.js +197 -0
  89. package/dist/core/session/session-manager.js +172 -18
  90. package/dist/core/session/session-mapper.js +2 -0
  91. package/dist/core/system-session/memory.js +3 -18
  92. package/dist/ecweb/basic-settings-service.js +709 -0
  93. package/dist/ecweb/providers-service.js +172 -0
  94. package/dist/index.js +95 -7
  95. package/dist/ipc.js +100 -19
  96. package/dist/stats/budget.js +1 -1
  97. package/dist/stats/db.js +48 -0
  98. package/dist/stats/index.js +3 -3
  99. package/dist/stats/price-resolver.js +304 -5
  100. package/dist/stats/query.js +328 -3
  101. package/dist/stats/writer.js +79 -6
  102. package/dist/trigger/application-service.js +12 -0
  103. package/dist/trigger/authorization.js +2 -2
  104. package/dist/trigger/feedback.js +18 -7
  105. package/dist/trigger/history.js +36 -0
  106. package/dist/trigger/manager.js +20 -3
  107. package/dist/trigger/parser.js +6 -3
  108. package/dist/trigger/patch.js +1 -1
  109. package/dist/trigger/scheduler.js +3 -0
  110. package/dist/trigger/system-definitions.js +43 -7
  111. package/dist/trigger/validation.js +13 -5
  112. package/dist/utils/ecweb-supervisor.js +31 -10
  113. package/dist/utils/error-utils.js +22 -4
  114. package/dist/utils/evolcore-version.js +3 -2
  115. package/dist/utils/host-info.js +52 -0
  116. package/dist/utils/npm-ops.js +2 -1
  117. package/dist/utils/package-version-info.js +1 -1
  118. package/dist/utils/upgrade-jobs.js +45 -5
  119. package/ecagent/dist/harness/agent-harness.js +4 -1
  120. package/kits/docs/INDEX.md +1 -1
  121. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  122. package/kits/docs/evolcore/INDEX.md +3 -2
  123. package/kits/docs/evolcore/agent-create.md +3 -2
  124. package/kits/docs/evolcore/agent.md +1 -1
  125. package/kits/docs/evolcore/aid.md +29 -12
  126. package/kits/docs/evolcore/config.md +9 -7
  127. package/kits/docs/evolcore/event.md +1 -0
  128. package/kits/docs/evolcore/fs.md +5 -0
  129. package/kits/docs/evolcore/memory-architecture.md +3 -4
  130. package/kits/docs/evolcore/memory-consolidation.md +28 -7
  131. package/kits/docs/evolcore/memory-tags.md +1 -1
  132. package/kits/docs/evolcore/memory.md +1 -1
  133. package/kits/docs/evolcore/menu-client.md +1 -1
  134. package/kits/docs/evolcore/menu-protocol.md +38 -0
  135. package/kits/docs/evolcore/msg.md +18 -2
  136. package/kits/docs/evolcore/session.md +14 -0
  137. package/kits/eck_manifest.json +3 -3
  138. package/kits/rules/04-relation.md +3 -2
  139. package/kits/schemas/agent-config.schema.13.json +20 -1
  140. package/kits/skills/aid-ability/SKILL.md +35 -6
  141. package/kits/templates/memory-consolidation/generalize.md +32 -4
  142. package/kits/templates/memory-consolidation/notes.md +2 -2
  143. package/kits/templates/memory-consolidation/promote.md +10 -2
  144. package/kits/templates/session-capsule/recovery.md +5 -0
  145. package/kits/templates/session-capsule/renew.md +5 -0
  146. package/kits/templates/system-fragments/baseagent.md +5 -0
  147. package/kits/templates/system-fragments/bootstrap.md +6 -6
  148. package/kits/templates/system-fragments/channel.md +1 -1
  149. package/kits/templates/system-fragments/memory.md +12 -3
  150. package/kits/templates/system-fragments/session.md +1 -1
  151. package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
  152. package/package.json +3 -3
  153. package/dist/stats/billing.js +0 -215
@@ -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';
@@ -47,7 +47,7 @@ export { buildEnvelope, sendInteractionPayload } from './message-utils.js';
47
47
  import { constrainResolvedModelForRole, isModelAllowedForRoleBaseagent } from '../model/model-permission.js';
48
48
  import { eligibleFallbackModels } from '../model/model-fallback.js';
49
49
  import { RetryScheduler } from './retry-scheduler.js';
50
- import { constrainRuntimePermissionMode, resolveRuntimeStringField } from '../role/runtime-policy.js';
50
+ import { assertSessionFullAccessAuthorization, constrainRuntimePermissionMode, resolveRuntimeStringField } from '../role/runtime-policy.js';
51
51
  import { resolveEffective, resolveEffectiveFieldWithSource } from '../../config/config-manager.js';
52
52
  import { resolveAgentLifecycle } from '../../config/lifecycle.js';
53
53
  import { authorizationConfigRevision, checkRoleAccess, getFirstStaticAgentOwner, listStaticAgentAdmins, listStaticAgentOwners, resolvePeerRoleDetail, roleToSessionIdentity, } from '../../config/peer-role-resolver.js';
@@ -84,6 +84,7 @@ export class AsyncQuestionService {
84
84
  deps;
85
85
  registered = new Map();
86
86
  deliveries = new Map();
87
+ blockingWaiters = new Map();
87
88
  constructor(deps) {
88
89
  this.deps = deps;
89
90
  }
@@ -115,10 +116,11 @@ export class AsyncQuestionService {
115
116
  const value = JSON.parse(fs.readFileSync(this.file(selfAid, id), 'utf8'));
116
117
  if (value.version !== 1 || value.selfAid !== selfAid || value.id !== id
117
118
  || !value.sessionId || !value.providerThreadId || !value.itemId
118
- || !value.origin?.peerId || !value.channelKey || !Number.isFinite(value.expiresAt))
119
+ || !value.origin?.peerId || !value.channelKey
120
+ || (value.expiresAt !== undefined && !Number.isFinite(value.expiresAt)))
119
121
  return undefined;
120
122
  parseAsyncUserQuestions([value.question]);
121
- return value;
123
+ return { ...value, blocking: value.blocking === true };
122
124
  }
123
125
  catch (error) {
124
126
  if (error.code !== 'ENOENT')
@@ -126,6 +128,25 @@ export class AsyncQuestionService {
126
128
  return undefined;
127
129
  }
128
130
  }
131
+ waitForBlocking(id) {
132
+ return new Promise((resolve, reject) => {
133
+ this.blockingWaiters.set(id, { resolve, reject });
134
+ });
135
+ }
136
+ resolveBlocking(id) {
137
+ const waiter = this.blockingWaiters.get(id);
138
+ if (!waiter)
139
+ return;
140
+ this.blockingWaiters.delete(id);
141
+ waiter.resolve();
142
+ }
143
+ rejectBlocking(id, reason) {
144
+ const waiter = this.blockingWaiters.get(id);
145
+ if (!waiter)
146
+ return;
147
+ this.blockingWaiters.delete(id);
148
+ waiter.reject(new Error(`用户交互已结束(${reason})`));
149
+ }
129
150
  async present(session, request, message, adapter, envelope) {
130
151
  if (!session.selfAID || !message.peerId)
131
152
  throw new Error('Async question requires an authenticated route');
@@ -158,13 +179,19 @@ export class AsyncQuestionService {
158
179
  threadId: sessionTopicThreadId(session), selfAID: session.selfAID,
159
180
  },
160
181
  envelope: { ...envelope, sessionId: session.id, replyContext, delivery: replyContext.delivery },
161
- channelKey: adapter.channelKey, createdAt: Date.now(), expiresAt: Date.now() + QUESTION_TTL_MS,
182
+ channelKey: adapter.channelKey,
183
+ createdAt: Date.now(),
184
+ ...(question.blocking === true ? {} : { expiresAt: Date.now() + QUESTION_TTL_MS }),
185
+ blocking: question.blocking !== false,
162
186
  status: 'pending',
163
187
  };
164
188
  if (!existing)
165
189
  this.save(record);
166
190
  records.push(record);
167
191
  }
192
+ const blockingWaits = records
193
+ .filter(record => record.blocking)
194
+ .map(record => ({ record, promise: this.waitForBlocking(record.id) }));
168
195
  // Persist the complete batch before dispatch; one failed card must not lose the other questions.
169
196
  const errors = [];
170
197
  for (const record of records) {
@@ -173,10 +200,14 @@ export class AsyncQuestionService {
173
200
  }
174
201
  catch (error) {
175
202
  errors.push(error);
203
+ this.rejectBlocking(record.id, '卡片投递失败');
176
204
  }
177
205
  }
178
- if (errors.length)
206
+ if (errors.length) {
207
+ await Promise.allSettled(blockingWaits.map(wait => wait.promise));
179
208
  throw new AggregateError(errors, 'Async question delivery failed; pending questions retained');
209
+ }
210
+ await Promise.all(blockingWaits.map(wait => wait.promise));
180
211
  }
181
212
  async restore(adapter, selfAid) {
182
213
  let names;
@@ -197,7 +228,7 @@ export class AsyncQuestionService {
197
228
  continue;
198
229
  if (this.registered.get(record.id) === adapter)
199
230
  continue;
200
- if (record.expiresAt <= Date.now()) {
231
+ if (record.expiresAt !== undefined && record.expiresAt <= Date.now()) {
201
232
  fs.unlinkSync(this.file(selfAid, record.id));
202
233
  continue;
203
234
  }
@@ -257,18 +288,24 @@ export class AsyncQuestionService {
257
288
  }
258
289
  }
259
290
  async deliverOnce(record, adapter) {
260
- if (record.expiresAt <= Date.now() || !(await this.validSession(record))) {
291
+ if ((record.expiresAt !== undefined && record.expiresAt <= Date.now()) || !(await this.validSession(record))) {
261
292
  record.status = 'cancelled';
262
293
  record.reason = 'expired_or_binding_changed';
263
294
  this.save(record);
295
+ this.rejectBlocking(record.id, record.reason);
264
296
  return;
265
297
  }
266
298
  const options = record.question.options ?? [];
267
299
  const interaction = {
268
300
  type: 'interaction', id: record.id, sessionId: record.sessionId, channelId: record.origin.channelId,
269
- initiatorId: record.origin.peerId, blocking: false, expiresAt: record.expiresAt,
301
+ initiatorId: record.origin.peerId,
302
+ ...(record.blocking ? { blocking: true } : { blocking: false }),
303
+ ...(record.expiresAt !== undefined ? { expiresAt: record.expiresAt } : {}),
270
304
  kind: {
271
305
  kind: 'action', title: '请补充信息', body: record.question.title, bodyFormat: 'plain',
306
+ ...(record.question.recommendedOption
307
+ ? { recommendedOption: `opt-${options.indexOf(record.question.recommendedOption)}` }
308
+ : {}),
272
309
  buttons: options.map((label, index) => ({ key: `opt-${index}`, label })),
273
310
  allowCustomInput: true,
274
311
  },
@@ -282,13 +319,24 @@ export class AsyncQuestionService {
282
319
  this.registered.set(record.id, adapter);
283
320
  this.deps.router.register(record.id, record.sessionId, async (action, values) => {
284
321
  const current = this.read(record.selfAid, record.id);
285
- if (!current || current.status !== 'pending' || current.expiresAt <= Date.now()) {
322
+ if (!current || current.status !== 'pending'
323
+ || (current.expiresAt !== undefined && current.expiresAt <= Date.now())) {
286
324
  await this.deps.router.cancel(record.id, 'expired_or_resolved');
287
325
  return false;
288
326
  }
289
327
  const answer = this.answerText(current.question, action, values);
290
- if (!answer)
328
+ if (!answer) {
329
+ if (action === 'cancel' || action === 'dismiss' || values?.behavior === 'dismiss') {
330
+ current.status = 'cancelled';
331
+ current.reason = 'user_cancelled';
332
+ this.save(current);
333
+ this.registered.delete(record.id);
334
+ this.rejectBlocking(record.id, current.reason);
335
+ await adapter.invalidateInteraction?.(record.id, current.reason);
336
+ return true;
337
+ }
291
338
  return false;
339
+ }
292
340
  const session = await this.validSession(current);
293
341
  if (!session) {
294
342
  await this.deps.router.cancel(record.id, 'binding_or_authorization_changed');
@@ -305,6 +353,13 @@ export class AsyncQuestionService {
305
353
  current.status = 'answered';
306
354
  this.save(current);
307
355
  this.registered.delete(record.id);
356
+ this.resolveBlocking(record.id);
357
+ try {
358
+ await adapter.invalidateInteraction?.(record.id, 'answered');
359
+ }
360
+ catch (error) {
361
+ logger.debug(`[AsyncQuestions] card invalidation after answer failed: request=${record.id} error=${String(error)}`);
362
+ }
308
363
  logger.info(`[AsyncQuestions] answer accepted: session=${record.sessionId} request=${record.id}`);
309
364
  return true;
310
365
  }
@@ -312,12 +367,16 @@ export class AsyncQuestionService {
312
367
  current.status = 'uncertain';
313
368
  current.reason = 'submission_failed';
314
369
  this.save(current);
370
+ this.rejectBlocking(record.id, '答案提交失败');
315
371
  logger.warn(`[AsyncQuestions] answer submission failed: request=${record.id} error=${String(error)}`);
316
372
  throw error;
317
373
  }
318
374
  }, {
319
375
  initiatorId: record.origin.peerId, initiatorChannelKey: adapter.channelKey,
320
- blocking: false, retainOnRejected: true, fallbackCommand: 'ask', timeoutMs: record.expiresAt - Date.now(),
376
+ blocking: record.blocking,
377
+ retainOnRejected: true,
378
+ fallbackCommand: 'ask',
379
+ ...(record.expiresAt !== undefined ? { timeoutMs: Math.max(1, record.expiresAt - Date.now()) } : {}),
321
380
  onCancel: async (reason) => {
322
381
  this.registered.delete(record.id);
323
382
  if (reason === 'daemon_restart')
@@ -328,6 +387,7 @@ export class AsyncQuestionService {
328
387
  current.reason = reason;
329
388
  this.save(current);
330
389
  }
390
+ this.rejectBlocking(record.id, reason);
331
391
  await adapter.invalidateInteraction?.(record.id, reason);
332
392
  },
333
393
  });
@@ -432,6 +492,7 @@ const TOOL_INPUT_DIAGNOSTIC_MAX_LENGTH = 96_000;
432
492
  const TOOL_INPUT_DIAGNOSTIC_MAX_FINDINGS = 3;
433
493
  const TOOL_INPUT_DIAGNOSTIC_MAX_SHELL_DEPTH = 4;
434
494
  const TOOL_INPUT_DIAGNOSTIC_TIMEOUT_MS = 1_000;
495
+ const PROACTIVE_CIRCUIT_BREAK_DRAIN_TIMEOUT_MS = 2_000;
435
496
  function isToolResultFailure(event) {
436
497
  return event.isError === true
437
498
  || event.executionState === 'failed'
@@ -871,12 +932,13 @@ class RetryAttemptTimeoutError extends Error {
871
932
  function createRetryAttemptTimeout(timeoutMs) {
872
933
  let timer;
873
934
  let settled = false;
935
+ let paused = false;
874
936
  let rejectTimeout;
875
937
  const promise = new Promise((_, reject) => {
876
938
  rejectTimeout = reject;
877
939
  });
878
940
  const arm = () => {
879
- if (settled)
941
+ if (settled || paused)
880
942
  return;
881
943
  if (timer)
882
944
  clearTimeout(timer);
@@ -891,8 +953,23 @@ function createRetryAttemptTimeout(timeoutMs) {
891
953
  return {
892
954
  promise,
893
955
  reset: arm,
956
+ pause: () => {
957
+ if (settled || paused)
958
+ return;
959
+ paused = true;
960
+ if (timer)
961
+ clearTimeout(timer);
962
+ timer = undefined;
963
+ },
964
+ resume: () => {
965
+ if (settled || !paused)
966
+ return;
967
+ paused = false;
968
+ arm();
969
+ },
894
970
  clear: () => {
895
971
  settled = true;
972
+ paused = false;
896
973
  if (timer)
897
974
  clearTimeout(timer);
898
975
  timer = undefined;
@@ -979,7 +1056,8 @@ function isNonErrorInterruptReason(reason) {
979
1056
  return reason === 'new_message'
980
1057
  || reason === 'stop'
981
1058
  || reason === 'recalled'
982
- || reason === 'daemon_restart';
1059
+ || reason === 'daemon_restart'
1060
+ || reason === 'proactive_circuit_break';
983
1061
  }
984
1062
  function isExpectedTerminalInterrupt(reason) {
985
1063
  return isAbortTerminalReason(reason);
@@ -1109,7 +1187,7 @@ function getStreamRawErrorText(result, fallback) {
1109
1187
  fullTextLooksLikeDiagnostic ? fullText : undefined,
1110
1188
  fallbackLooksLikeDiagnostic ? fallback : undefined,
1111
1189
  ];
1112
- return candidates.find((part) => typeof part === 'string' && part.trim().length > 0)?.trim();
1190
+ return candidates.find((part) => typeof part === 'string' && part.trim().length > 0);
1113
1191
  }
1114
1192
  function getStreamErrorMessage(result, includeEmoji = false) {
1115
1193
  const raw = getStreamErrorText(result);
@@ -1239,6 +1317,7 @@ export class ResponseEngine {
1239
1317
  channelTypeMap = new Map(); // channelType → channelName(首个实例)
1240
1318
  /** 仅登记正在处理的任务,runner 的 session 回调绝不能投递到其它会话。 */
1241
1319
  activeRenderers = new Map();
1320
+ recoveryNoticeCapsules = new Set();
1242
1321
  /** 已主动发送开始提示时,忽略 runner 对同一次 compact 的回调。 */
1243
1322
  announcedCompactStarts = new Set();
1244
1323
  agentMap;
@@ -1366,7 +1445,13 @@ export class ResponseEngine {
1366
1445
  agentName: error.evolagentName,
1367
1446
  chatmode: this.resolveEffectiveChatmodeForSession(session, channelKey, channelId),
1368
1447
  replyContext: sessionReplyContext,
1369
- }), { kind: 'system.error', text, subtype: 'baseagent_unavailable', recoverable: true });
1448
+ }), {
1449
+ kind: 'system.error',
1450
+ text,
1451
+ raw: error.message,
1452
+ subtype: 'baseagent_unavailable',
1453
+ recoverable: true,
1454
+ });
1370
1455
  }
1371
1456
  resolveEffectiveChatmodeForSession(session, channelKey, channelId) {
1372
1457
  const peerType = session.metadata?.peerType;
@@ -1409,6 +1494,10 @@ export class ResponseEngine {
1409
1494
  this.eventBus = eventBus;
1410
1495
  this.commandHandler = commandHandler;
1411
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
+ });
1412
1501
  if (agentRunnerOrMap instanceof Map) {
1413
1502
  this.agentMap = agentRunnerOrMap;
1414
1503
  this.legacySingleRunnerMode = false;
@@ -1462,6 +1551,21 @@ export class ResponseEngine {
1462
1551
  this.activeTaskSpans.delete(event.sessionId);
1463
1552
  }
1464
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
+ });
1465
1569
  // 初始化响应模式协调器,注册内置模式(interactive/proactive)
1466
1570
  const registry = new ResponseModeRegistry();
1467
1571
  registerBuiltinModes(registry);
@@ -1806,27 +1910,44 @@ export class ResponseEngine {
1806
1910
  return { state: 'missing' };
1807
1911
  }
1808
1912
  /** Outer execution deadlines use the same terminal owner as runner idle timeouts. */
1809
- 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;
1810
1918
  const timeout = this.activeTimeoutHandlers.get(sessionId);
1811
- if (timeout)
1812
- await timeout(error);
1919
+ if (timeout && active)
1920
+ await timeout(error, target);
1813
1921
  else
1814
- 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);
1815
1923
  }
1816
- async interruptSession(sessionId, reason, strict = false, recoverable) {
1817
- this.clearPauseSession(sessionId);
1818
- // A retry delay has no active runner stream to abort. Wake it before any
1819
- // session-store I/O so /stop and a newer message take effect immediately.
1820
- this.cancelRetryDelays(sessionId);
1924
+ async interruptSession(sessionId, reason, strict = false, recoverable, target) {
1821
1925
  const session = await this.sessionManager.getSessionById(sessionId);
1822
1926
  if (!session)
1823
1927
  return;
1824
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);
1825
1944
  const effectiveReason = reason === 'daemon_restart'
1826
1945
  || this.interruptedSessions.get(sessionId) === 'daemon_restart'
1827
1946
  ? 'daemon_restart'
1828
1947
  : reason;
1829
- const interruptedTurn = this.turnCoordinator.invalidate(sessionId, effectiveReason);
1948
+ const interruptedTurn = this.turnCoordinator.invalidate(sessionId, effectiveReason, interruptTarget);
1949
+ if (interruptTarget && !interruptedTurn?.active)
1950
+ return;
1830
1951
  const interruptedTaskId = interruptedTurn?.active?.taskId;
1831
1952
  this.interruptedSessions.set(sessionId, effectiveReason);
1832
1953
  this.messageQueue?.markActiveTerminal?.(sessionId, effectiveReason);
@@ -1898,9 +2019,9 @@ export class ResponseEngine {
1898
2019
  logger.debug(`[ResponseEngine] interrupt terminal status failure: session=${sessionId} task=${interruptedTaskId} error=${error instanceof Error ? error.message : String(error)}`);
1899
2020
  });
1900
2021
  })();
1901
- const runnerInterrupt = (cancelledQueuedTurn
2022
+ const runnerInterrupt = (cancelledQueuedTurn || !interruptTarget
1902
2023
  ? Promise.resolve()
1903
- : agent.interrupt(sessionId)).catch(error => {
2024
+ : agent.interrupt(sessionId, interruptTarget)).catch(error => {
1904
2025
  logger.debug(`[ResponseEngine] interrupt barrier runner failure: session=${sessionId} error=${error instanceof Error ? error.message : String(error)}`);
1905
2026
  if (strict)
1906
2027
  throw error;
@@ -2229,11 +2350,17 @@ export class ResponseEngine {
2229
2350
  generation: turnLease.generation,
2230
2351
  }) ?? false;
2231
2352
  if (!cancelledQueuedTurn) {
2232
- await agent.interrupt(sessionId).catch(interruptError => {
2353
+ await agent.interrupt(sessionId, {
2354
+ taskId: turnLease.taskId,
2355
+ generation: turnLease.generation,
2356
+ }).catch(interruptError => {
2233
2357
  logger.warn(`[ResponseEngine] Failed to cancel stale runner start: session=${sessionId} task=${taskId} error=${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
2234
2358
  });
2235
2359
  }
2236
- agent.cleanupStream(streamKey);
2360
+ agent.cleanupStream(streamKey, {
2361
+ taskId: turnLease.taskId,
2362
+ generation: turnLease.generation,
2363
+ });
2237
2364
  return true;
2238
2365
  }
2239
2366
  async retryAfterContextRecovery(prompt, opts) {
@@ -2281,7 +2408,10 @@ export class ResponseEngine {
2281
2408
  if (await this.cancelStaleRunnerStart(agent, session.id, streamKey, turnLease, turnLease.taskId)) {
2282
2409
  throw new Error('RUNNER_START_SUPERSEDED');
2283
2410
  }
2284
- agent.registerStream(streamKey, retryStream);
2411
+ agent.registerStream(streamKey, retryStream, {
2412
+ taskId: turnLease.taskId,
2413
+ generation: turnLease.generation,
2414
+ });
2285
2415
  return await this.processEventStream(retryStream, session, agent, renderer, resetTimer, shouldSuppress, proactive, undefined, // 重试分支不调插件钩子
2286
2416
  undefined, turnLease, opts.permissionMode, opts.proactiveSelfAid);
2287
2417
  }
@@ -2333,6 +2463,22 @@ export class ResponseEngine {
2333
2463
  && !!message.bgSessionMeta?.runId;
2334
2464
  }
2335
2465
  bgSessionTerminalMessages = new WeakSet();
2466
+ /**
2467
+ * 后台会话本次运行的模型:解析出请求模型时写 requestedModel,runner 回报结果后写
2468
+ * actualModel,三个 bg-session 终态事件发布时读出。按入站 message 归属,随消息回收,
2469
+ * 不落盘、不跨会话;只服务终态事件,其它路径不要读。
2470
+ */
2471
+ bgSessionModels = new WeakMap();
2472
+ recordBgSessionModels(message, models) {
2473
+ if (message.source !== 'bg-session')
2474
+ return;
2475
+ const current = this.bgSessionModels.get(message) ?? {};
2476
+ this.bgSessionModels.set(message, {
2477
+ ...current,
2478
+ ...(models.requestedModel ? { requestedModel: models.requestedModel } : {}),
2479
+ ...(models.actualModel ? { actualModel: models.actualModel } : {}),
2480
+ });
2481
+ }
2336
2482
  claimBgSessionTerminal(message) {
2337
2483
  const meta = message.bgSessionMeta;
2338
2484
  if (message.source !== 'bg-session' || !meta?.runId || this.bgSessionTerminalMessages.has(message)) {
@@ -2352,6 +2498,7 @@ export class ResponseEngine {
2352
2498
  runId,
2353
2499
  sessionId: meta.boundSessionId ?? '',
2354
2500
  messageId: opts.messageId ?? message.messageId ?? runId,
2501
+ ...this.bgSessionModels.get(message),
2355
2502
  error,
2356
2503
  targetChannel: message.channel,
2357
2504
  targetChannelId: message.channelId,
@@ -2369,6 +2516,7 @@ export class ResponseEngine {
2369
2516
  runId,
2370
2517
  sessionId: meta.boundSessionId ?? '',
2371
2518
  messageId: message.messageId ?? runId,
2519
+ ...this.bgSessionModels.get(message),
2372
2520
  reason,
2373
2521
  targetChannel: message.channel,
2374
2522
  targetChannelId: message.channelId,
@@ -2387,6 +2535,7 @@ export class ResponseEngine {
2387
2535
  sessionId: meta.boundSessionId ?? '',
2388
2536
  messageId,
2389
2537
  durationMs,
2538
+ ...this.bgSessionModels.get(message),
2390
2539
  targetChannel: message.channel,
2391
2540
  targetChannelId: message.channelId,
2392
2541
  causation: causation ?? message.causation,
@@ -2429,7 +2578,7 @@ export class ResponseEngine {
2429
2578
  * them immediately before every Runner invocation, including retries.
2430
2579
  */
2431
2580
  async assertCurrentFullAccessExecutionAuthorization(authorization, agent) {
2432
- await refreshOwnershipForAuthorization(authorization.agentAid);
2581
+ await refreshOwnershipForAuthorization(authorization.agentAid, { allowTransient: true });
2433
2582
  if (authorization.permissionMode !== 'fullaccess'
2434
2583
  || authorization.processRole !== 'fullaccess-run'
2435
2584
  || authorization.dataScope !== 'daemon'
@@ -2444,6 +2593,12 @@ export class ResponseEngine {
2444
2593
  if (authorization.source === 'agent-policy') {
2445
2594
  assertAgentPolicyAuthorization(authorization);
2446
2595
  }
2596
+ else if (authorization.source === 'session-policy') {
2597
+ const currentSession = this.sessionManager.getSessionById
2598
+ ? await this.sessionManager.getSessionById(authorization.sessionId ?? '')
2599
+ : undefined;
2600
+ assertSessionFullAccessAuthorization(authorization, currentSession);
2601
+ }
2447
2602
  else if (authorization.source !== 'fullaccess-command' && authorization.source !== 'trigger') {
2448
2603
  throw new Error('fullaccess execution authorization has an unsupported source');
2449
2604
  }
@@ -2686,7 +2841,7 @@ export class ResponseEngine {
2686
2841
  * 处理消息(主入口)
2687
2842
  */
2688
2843
  async processMessage(message) {
2689
- const fallbackFullAccessAudit = this.resolveFullAccessAuditCandidate(message);
2844
+ const fallbackFullAccessAudit = await this.resolveFullAccessAuditCandidate(message);
2690
2845
  let outerFailureReason;
2691
2846
  try {
2692
2847
  await this.processMessageWithMonitors(message);
@@ -2707,7 +2862,9 @@ export class ResponseEngine {
2707
2862
  event: fallbackFullAccessAudit.authorization.source === 'trigger'
2708
2863
  ? 'fullaccess.trigger.execution.ended'
2709
2864
  : fallbackFullAccessAudit.authorization.source === 'agent-policy'
2710
- ? 'fullaccess.agent-policy.execution.ended' : 'fullaccess.execution.ended',
2865
+ ? 'fullaccess.agent-policy.execution.ended'
2866
+ : fallbackFullAccessAudit.authorization.source === 'session-policy'
2867
+ ? 'fullaccess.session-policy.execution.ended' : 'fullaccess.execution.ended',
2711
2868
  source: fallbackFullAccessAudit.authorization.source,
2712
2869
  actorId: fallbackFullAccessAudit.authorization.authorizedBy,
2713
2870
  processRole: fallbackFullAccessAudit.processRole,
@@ -2774,7 +2931,10 @@ export class ResponseEngine {
2774
2931
  const accessAdapter = accessChannelInfo?.adapter;
2775
2932
  const accessAdapterSelfAid = typeof accessAdapter?._selfAid === 'function' ? accessAdapter._selfAid() : undefined;
2776
2933
  const selfAidForAccess = accessAdapterSelfAid || message.selfAID || session.selfAID || undefined;
2777
- await refreshOwnershipForAuthorization(selfAidForAccess, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS });
2934
+ await refreshOwnershipForAuthorization(selfAidForAccess, {
2935
+ maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS,
2936
+ allowTransient: true,
2937
+ });
2778
2938
  if (message.handoffDelivery?.direction === 'target'
2779
2939
  && this.handoffRuntime
2780
2940
  && selfAidForAccess) {
@@ -2823,9 +2983,10 @@ export class ResponseEngine {
2823
2983
  // ── 角色访问控制检查:读取该用户角色的 allowAccess 配置,false 则拦截并回复权限不足 ──
2824
2984
  const userRole = session.identity?.role || 'none';
2825
2985
  const isInternalHandoff = message.source === 'handoff';
2826
- const fullAccessAuditCandidate = this.resolveFullAccessAuditCandidate(message);
2986
+ const fullAccessAuditCandidate = await this.resolveFullAccessAuditCandidate(message);
2827
2987
  const isCurrentFullAccessCommand = (fullAccessAuditCandidate?.authorization.source === 'fullaccess-command'
2828
- || fullAccessAuditCandidate?.authorization.source === 'agent-policy')
2988
+ || fullAccessAuditCandidate?.authorization.source === 'agent-policy'
2989
+ || fullAccessAuditCandidate?.authorization.source === 'session-policy')
2829
2990
  && fullAccessAuditCandidate.processRole === 'fullaccess-run';
2830
2991
  const isCurrentFullAccessTrigger = fullAccessAuditCandidate?.authorization.source === 'trigger'
2831
2992
  && fullAccessAuditCandidate.processRole === 'fullaccess-run';
@@ -2942,7 +3103,12 @@ export class ResponseEngine {
2942
3103
  return true;
2943
3104
  },
2944
3105
  };
2945
- 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
+ }
2946
3112
  if (timeoutTriggered)
2947
3113
  return;
2948
3114
  timeoutTriggered = true;
@@ -2951,9 +3117,14 @@ export class ResponseEngine {
2951
3117
  this.timeoutErrors.set(session.id, error);
2952
3118
  this.turnCoordinator.hydrate(session);
2953
3119
  const reason = error instanceof OrphanedTargetSessionError ? 'execution_error' : 'timeout';
2954
- 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);
2955
3126
  this.interruptedSessions.set(session.id, reason);
2956
- const barrier = this.interruptSession(session.id, reason, false, timeoutControl.recoverable)
3127
+ const barrier = this.interruptSession(session.id, reason, false, timeoutControl.recoverable, interruptTarget)
2957
3128
  .catch(interruptError => {
2958
3129
  logger.debug(`[ResponseEngine] Timeout interrupt barrier failed: ${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
2959
3130
  });
@@ -2964,8 +3135,10 @@ export class ResponseEngine {
2964
3135
  });
2965
3136
  };
2966
3137
  const triggerAttemptId = message.replyContext?.metadata?.triggerAttemptId;
2967
- const externalTimeout = async (error) => {
2968
- rejectAfterInterruptBarrier(error);
3138
+ const externalTimeout = async (error, requestedTarget) => {
3139
+ if (this.activeTimeoutHandlers.get(session.id) !== externalTimeout)
3140
+ return;
3141
+ rejectAfterInterruptBarrier(error, requestedTarget);
2969
3142
  await timeoutControl.barrier;
2970
3143
  };
2971
3144
  this.activeTimeoutHandlers.set(session.id, externalTimeout);
@@ -2976,6 +3149,35 @@ export class ResponseEngine {
2976
3149
  activityRecorder?.call(channelInfo.adapter, triggerAttemptId);
2977
3150
  }
2978
3151
  };
3152
+ let totalExecutionDeadline;
3153
+ let totalExecutionPausedRemaining;
3154
+ const pauseTotalExecutionTimer = () => {
3155
+ if (totalExecutionTimer === undefined || totalExecutionDeadline === undefined)
3156
+ return;
3157
+ totalExecutionPausedRemaining = Math.max(0, totalExecutionDeadline - Date.now());
3158
+ clearTimeout(totalExecutionTimer);
3159
+ totalExecutionTimer = undefined;
3160
+ };
3161
+ const resumeTotalExecutionTimer = () => {
3162
+ if (totalExecutionTimer !== undefined || totalExecutionPausedRemaining === undefined)
3163
+ return;
3164
+ const remaining = totalExecutionPausedRemaining;
3165
+ totalExecutionPausedRemaining = undefined;
3166
+ totalExecutionDeadline = Date.now() + remaining;
3167
+ totalExecutionTimer = setTimeout(() => {
3168
+ logger.warn(`[ResponseEngine] Total execution timeout after ${totalExecutionMs}ms, stream: ${streamKey}`);
3169
+ rejectAfterInterruptBarrier(new Error('TOTAL_EXECUTION_TIMEOUT'));
3170
+ }, remaining);
3171
+ totalExecutionTimer.unref?.();
3172
+ };
3173
+ timeoutControl.pauseForInteraction = () => {
3174
+ monitor?.pause();
3175
+ pauseTotalExecutionTimer();
3176
+ };
3177
+ timeoutControl.resumeForInteraction = () => {
3178
+ monitor?.resume();
3179
+ resumeTotalExecutionTimer();
3180
+ };
2979
3181
  // Cache background status to avoid async call inside setInterval
2980
3182
  const isBackground = this.isBackgroundSession(session, message.channel, message.channelId);
2981
3183
  const timeoutPromise = new Promise((_, reject) => {
@@ -3028,6 +3230,7 @@ export class ResponseEngine {
3028
3230
  const totalExecutionPromise = totalExecutionMs === undefined
3029
3231
  ? undefined
3030
3232
  : new Promise((_, reject) => {
3233
+ totalExecutionDeadline = Date.now() + totalExecutionMs;
3031
3234
  totalExecutionTimer = setTimeout(() => {
3032
3235
  logger.warn(`[ResponseEngine] Total execution timeout after ${totalExecutionMs}ms, stream: ${streamKey}`);
3033
3236
  rejectAfterInterruptBarrier(new Error('TOTAL_EXECUTION_TIMEOUT'));
@@ -3095,12 +3298,14 @@ export class ResponseEngine {
3095
3298
  this.activeTimeoutHandlers.delete(session.id);
3096
3299
  }
3097
3300
  }
3098
- resolveFullAccessAuditCandidate(message) {
3301
+ async resolveFullAccessAuditCandidate(message) {
3099
3302
  const commandAuthorization = message.executionPermissionOverride;
3100
3303
  if (commandAuthorization?.permissionMode === 'fullaccess'
3101
3304
  && commandAuthorization.processRole === 'fullaccess-run'
3102
3305
  && commandAuthorization.dataScope === 'daemon'
3103
- && (commandAuthorization.source === 'fullaccess-command' || commandAuthorization.source === 'agent-policy')
3306
+ && (commandAuthorization.source === 'fullaccess-command'
3307
+ || commandAuthorization.source === 'agent-policy'
3308
+ || commandAuthorization.source === 'session-policy')
3104
3309
  && typeof commandAuthorization.authorizedBy === 'string'
3105
3310
  && commandAuthorization.authorizedBy.length > 0) {
3106
3311
  let currentOwner = false;
@@ -3108,6 +3313,12 @@ export class ResponseEngine {
3108
3313
  currentOwner = new Set(getDaemonOwners()).has(commandAuthorization.authorizedBy);
3109
3314
  if (commandAuthorization.source === 'agent-policy')
3110
3315
  assertAgentPolicyAuthorization(commandAuthorization);
3316
+ if (commandAuthorization.source === 'session-policy') {
3317
+ const session = this.sessionManager.getSessionById
3318
+ ? await this.sessionManager.getSessionById(commandAuthorization.sessionId ?? '')
3319
+ : undefined;
3320
+ assertSessionFullAccessAuthorization(commandAuthorization, session);
3321
+ }
3111
3322
  }
3112
3323
  catch {
3113
3324
  currentOwner = false;
@@ -3253,6 +3464,7 @@ export class ResponseEngine {
3253
3464
  const chatType = message.chatType || 'private';
3254
3465
  const identityRole = session.identity?.role || 'none';
3255
3466
  let agent;
3467
+ let turnLease;
3256
3468
  try {
3257
3469
  agent = this.getAgent(channelKey, session.baseagent, runnerSelfAid);
3258
3470
  }
@@ -3301,7 +3513,6 @@ export class ResponseEngine {
3301
3513
  }
3302
3514
  }
3303
3515
  const taskPauseController = this.getPauseController(session.id);
3304
- let turnLease;
3305
3516
  const inputCausation = normalizeCausation(message.causation) ?? createRootCausation();
3306
3517
  const taskCausation = deriveCausation(inputCausation);
3307
3518
  recordCausationSpan(taskCausation, 'task.run', {
@@ -3575,18 +3786,9 @@ export class ResponseEngine {
3575
3786
  if (!timeoutControl.claimTerminal())
3576
3787
  return;
3577
3788
  const recoverable = timeoutControl.recoverable === true;
3789
+ const rawErrorText = getErrorRawText(timeoutError);
3578
3790
  const isTotalExecutionTimeout = timeoutError.message === 'TOTAL_EXECUTION_TIMEOUT';
3579
3791
  const totalExecutionMs = timeoutError instanceof ExecutionTimeoutError ? timeoutError.timeoutMs : this.totalExecutionLimitMs();
3580
- const statusPayload = timeoutError instanceof OrphanedTargetSessionError ? {
3581
- kind: 'status.error',
3582
- metadata: { errorType: timeoutError.reason, message: '任务执行状态丢失,已结束本次执行。' },
3583
- } : {
3584
- kind: 'status.timeout',
3585
- metadata: isTotalExecutionTimeout
3586
- ? { ...(totalExecutionMs === undefined ? {} : { totalExecutionMs }),
3587
- ...(timeoutError instanceof ExecutionTimeoutError ? { reason: timeoutError.reason } : {}) }
3588
- : { idleSec: getLastIdleSec?.() || undefined },
3589
- };
3590
3792
  const idleSec = getLastIdleSec?.() || 0;
3591
3793
  const userMessage = timeoutError instanceof OrphanedTargetSessionError
3592
3794
  ? '⚠️ 任务执行状态丢失,已结束本次执行。'
@@ -3597,7 +3799,31 @@ export class ResponseEngine {
3597
3799
  : idleSec > 0
3598
3800
  ? `⚠️ 任务超时(${idleSec}秒无响应),已自动中断`
3599
3801
  : '⚠️ 任务超时,已自动中断';
3600
- agent.cleanupStream(streamKey);
3802
+ const timeoutSubtype = normalizeCoreErrorSubtype(timeoutError, undefined, 'timeout');
3803
+ const timeoutReason = isExecutionFailure(timeoutError)
3804
+ ? normalizeCoreErrorReason(timeoutError.reason)
3805
+ : 'timeout';
3806
+ const statusPayload = timeoutError instanceof OrphanedTargetSessionError ? {
3807
+ kind: 'status.error',
3808
+ metadata: {
3809
+ errorType: timeoutError.reason,
3810
+ message: '任务执行状态丢失,已结束本次执行。',
3811
+ recoverable,
3812
+ ...(rawErrorText ? { raw: rawErrorText } : {}),
3813
+ },
3814
+ } : {
3815
+ kind: 'status.timeout',
3816
+ metadata: isTotalExecutionTimeout
3817
+ ? { ...(totalExecutionMs === undefined ? {} : { totalExecutionMs }),
3818
+ errorType: timeoutSubtype,
3819
+ reason: timeoutReason,
3820
+ message: userMessage,
3821
+ recoverable,
3822
+ ...(rawErrorText ? { raw: rawErrorText } : {}) }
3823
+ : { idleSec: idleSec || undefined, errorType: timeoutSubtype, reason: timeoutReason, message: userMessage, recoverable,
3824
+ ...(rawErrorText ? { raw: rawErrorText } : {}) },
3825
+ };
3826
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
3601
3827
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
3602
3828
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
3603
3829
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -3605,21 +3831,16 @@ export class ResponseEngine {
3605
3831
  }
3606
3832
  this.agentDelegationRegistry?.revokeTask(session.id, taskId, 'interrupted');
3607
3833
  const daemonTrigger = this.isTrustedDaemonTrigger(message);
3608
- if (!daemonTrigger) {
3609
- await adapter.send(envelope, statusPayload).catch(() => { });
3610
- }
3611
- await adapter.send(envelope, {
3612
- kind: 'result.error',
3613
- text: userMessage,
3614
- recoverable,
3615
- ...(getErrorRawText(timeoutError) ? { raw: getErrorRawText(timeoutError) } : {}),
3616
- subtype: normalizeCoreErrorSubtype(timeoutError, undefined, isTotalExecutionTimeout ? 'timeout' : 'timeout'),
3617
- reason: isExecutionFailure(timeoutError)
3618
- ? normalizeCoreErrorReason(timeoutError.reason)
3619
- : 'timeout',
3620
- }).catch(() => { });
3621
- if (daemonTrigger) {
3622
- 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(() => { });
3623
3844
  }
3624
3845
  this.touchAgentActivity(channelKey);
3625
3846
  this.publishTriggerExecutionFailure(message, isExecutionFailure(timeoutError) ? timeoutError.reason : timeoutError.message, {
@@ -3674,6 +3895,49 @@ export class ResponseEngine {
3674
3895
  let fullAccessExecutionFailed = false;
3675
3896
  let fullAccessExecutionFailureReason;
3676
3897
  let activePermissionContext;
3898
+ let proactiveCircuitBreakRequested = false;
3899
+ let proactiveCircuitBreakInterruptPromise;
3900
+ let proactiveCircuitBreakTimer;
3901
+ const interruptProactiveCircuitBreak = () => {
3902
+ if (proactiveCircuitBreakInterruptPromise)
3903
+ return proactiveCircuitBreakInterruptPromise;
3904
+ if (!proactiveCircuitBreakRequested
3905
+ || this.interruptedSessions.get(session.id) !== 'proactive_circuit_break'
3906
+ || (turnLease && !this.turnCoordinator.isCurrent(turnLease)))
3907
+ return Promise.resolve();
3908
+ this.interruptedSessions.set(session.id, 'proactive_circuit_break');
3909
+ if (proactiveCircuitBreakTimer) {
3910
+ clearTimeout(proactiveCircuitBreakTimer);
3911
+ proactiveCircuitBreakTimer = undefined;
3912
+ }
3913
+ const interruptPromise = (async () => {
3914
+ await agent.interrupt(session.id, turnLease ? {
3915
+ taskId: turnLease.taskId,
3916
+ generation: turnLease.generation,
3917
+ } : undefined).catch(error => {
3918
+ logger.debug(`[ResponseEngine] circuit break interrupt failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
3919
+ });
3920
+ })();
3921
+ proactiveCircuitBreakInterruptPromise = interruptPromise;
3922
+ return interruptPromise;
3923
+ };
3924
+ const requestProactiveCircuitBreak = () => {
3925
+ if (proactiveCircuitBreakRequested)
3926
+ return;
3927
+ proactiveCircuitBreakRequested = true;
3928
+ this.interruptedSessions.set(session.id, 'proactive_circuit_break');
3929
+ void adapter.send(withEnvelopeReplyContext(envelope, taskReplyContext()), {
3930
+ kind: 'result.text',
3931
+ text: '⚠️ 任务执行长时间不反馈,已被自动中断。请重新发言继续。',
3932
+ isFinal: true,
3933
+ }).catch(error => {
3934
+ logger.warn(`[ResponseEngine] circuit break channel send failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
3935
+ });
3936
+ proactiveCircuitBreakTimer = setTimeout(() => {
3937
+ void interruptProactiveCircuitBreak();
3938
+ }, PROACTIVE_CIRCUIT_BREAK_DRAIN_TIMEOUT_MS);
3939
+ proactiveCircuitBreakTimer.unref?.();
3940
+ };
3677
3941
  try {
3678
3942
  const isBackground = this.isBackgroundSession(session, message.channel, message.channelId);
3679
3943
  // 记录收到消息
@@ -4127,6 +4391,15 @@ export class ResponseEngine {
4127
4391
  ? systemSessionModule.runnerLaunch(normalizeBaseagent(agent.name).canonical, systemSessionContext).sandbox
4128
4392
  : undefined;
4129
4393
  const pureSessionPolicyHook = systemSessionMarker ? undefined : modePolicyHook;
4394
+ const purePreToolUsePolicyHook = pureSessionPolicyHook
4395
+ ? (toolName, toolInput) => proactiveCircuitBreakRequested
4396
+ ? {
4397
+ block: true,
4398
+ policyCode: 'proactive_circuit_break',
4399
+ reason: '任务已触发主动模式熔断,工具调用已停止',
4400
+ }
4401
+ : pureSessionPolicyHook(toolName, toolInput)
4402
+ : undefined;
4130
4403
  // 路径授权(仅用户会话):身份就是角色名;运行时授予(ec ctl path grant)按 sessionId 再并一层。
4131
4404
  const pathGrantIdentity = systemSessionMarker ? undefined : (peerRole || undefined);
4132
4405
  const grantedReadRoots = (() => {
@@ -4168,7 +4441,8 @@ export class ResponseEngine {
4168
4441
  permissionMode: effectivePermissionMode,
4169
4442
  recordExecutionAnomaly,
4170
4443
  pauseController: taskPauseController,
4171
- preToolUsePolicyHook: pureSessionPolicyHook,
4444
+ preToolUsePolicyHook: purePreToolUsePolicyHook,
4445
+ onProactiveCircuitBreak: requestProactiveCircuitBreak,
4172
4446
  systemSessionCheck,
4173
4447
  ...(systemSessionModule && systemSessionContext
4174
4448
  ? {
@@ -4177,12 +4451,13 @@ export class ResponseEngine {
4177
4451
  }
4178
4452
  : {}),
4179
4453
  armApprovedDelegationCommand: this.agentDelegationRegistry
4180
- ? (sessionToken, commandHash, approvalId) => this.agentDelegationRegistry.armApprovedCommand({
4454
+ ? (sessionToken, commandHash, approvalId, specHash) => this.agentDelegationRegistry.armApprovedCommand({
4181
4455
  sessionToken,
4182
4456
  sessionId: session.id,
4183
4457
  taskId,
4184
4458
  commandHash,
4185
4459
  approvalId,
4460
+ specHash,
4186
4461
  })
4187
4462
  : undefined,
4188
4463
  revokeApprovedDelegationCommand: this.agentDelegationRegistry
@@ -4257,7 +4532,10 @@ export class ResponseEngine {
4257
4532
  });
4258
4533
  }
4259
4534
  finally {
4260
- 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 => {
4261
4539
  logger.debug(`[ResponseEngine] permission terminal interrupt failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
4262
4540
  });
4263
4541
  }
@@ -4278,6 +4556,13 @@ export class ResponseEngine {
4278
4556
  if (!pluginHook)
4279
4557
  return undefined;
4280
4558
  return (toolName, toolInput, meta) => {
4559
+ if (proactiveCircuitBreakRequested) {
4560
+ return {
4561
+ block: true,
4562
+ policyCode: 'proactive_circuit_break',
4563
+ reason: '任务已触发主动模式熔断,工具调用已停止',
4564
+ };
4565
+ }
4281
4566
  const stBefore = modeState.get('proactive');
4282
4567
  const wasFirstPending = stBefore && !stBefore.firstToolDone;
4283
4568
  const result = pluginHook(toolName, toolInput, meta);
@@ -4287,19 +4572,9 @@ export class ResponseEngine {
4287
4572
  if (result?.block) {
4288
4573
  // 拦截事件(首工具非表态 / 工具进展汇报未完成)
4289
4574
  snapshot.set(session.id, taskId, { policyHook: { triggered: true, blocked: true, toolName } });
4290
- // 问题1/2修复:熔断码表示连续违规已超阈值,停止注入提醒,直接中断任务。
4291
- // F5修复:向渠道发一条人类可读的错误说明,避免静默中断。
4575
+ // 熔断后拒绝新的工具调用,当前调用收尾后再中断流。
4292
4576
  if (result.policyCode === 'proactive_circuit_break') {
4293
- void adapter.send(withEnvelopeReplyContext(envelope, capturedReplyContext), {
4294
- kind: 'result.text',
4295
- text: '⚠️ 任务执行遇到循环障碍,已自动中断。请重新描述你的需求。',
4296
- isFinal: true,
4297
- }).catch(err => {
4298
- logger.warn(`[ResponseEngine] circuit break channel send failed: session=${session.id} error=${err instanceof Error ? err.message : String(err)}`);
4299
- });
4300
- void agent.interrupt(session.id).catch(error => {
4301
- logger.debug(`[ResponseEngine] circuit break interrupt failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
4302
- });
4577
+ requestProactiveCircuitBreak();
4303
4578
  return result;
4304
4579
  }
4305
4580
  const errorMsg = `⚠️ proactive 模式违规:${result.reason ?? '请先发送必要说明'}。请重新执行正确的命令。`;
@@ -4390,7 +4665,7 @@ export class ResponseEngine {
4390
4665
  if (commandFullAccess.permissionMode !== 'fullaccess'
4391
4666
  || commandFullAccess.processRole !== 'fullaccess-run'
4392
4667
  || commandFullAccess.dataScope !== 'daemon'
4393
- || (commandFullAccess.source !== 'fullaccess-command' && commandFullAccess.source !== 'agent-policy')
4668
+ || (commandFullAccess.source !== 'fullaccess-command' && commandFullAccess.source !== 'agent-policy' && commandFullAccess.source !== 'session-policy')
4394
4669
  || !commandFullAccess.authorizedBy) {
4395
4670
  throw new Error('fullaccess command authorization is missing or malformed');
4396
4671
  }
@@ -4403,6 +4678,10 @@ export class ResponseEngine {
4403
4678
  || authenticatedActor.operatorId !== commandFullAccess.policyActor?.operatorId)) {
4404
4679
  throw new Error('Agent fullaccess policy authorization is missing its Agent identity');
4405
4680
  }
4681
+ if (commandFullAccess.source === 'session-policy'
4682
+ && (commandFullAccess.sessionId !== session.id || configChatType !== 'private')) {
4683
+ throw new Error('Session fullaccess policy authorization is missing its EC session identity');
4684
+ }
4406
4685
  fullAccessAuthorization = commandFullAccess;
4407
4686
  }
4408
4687
  else {
@@ -4413,7 +4692,7 @@ export class ResponseEngine {
4413
4692
  || !message.triggerMeta.authorizedBy) {
4414
4693
  throw new Error('fullaccess Trigger override lacks trusted scheduler identity or approval provenance');
4415
4694
  }
4416
- await refreshOwnershipForAuthorization(selfAid);
4695
+ await refreshOwnershipForAuthorization(selfAid, { allowTransient: true });
4417
4696
  const currentOwners = new Set(getDaemonOwners());
4418
4697
  if (!currentOwners.has(message.triggerMeta.authorizedBy)) {
4419
4698
  throw new Error('fullaccess Trigger approval is no longer owned');
@@ -4554,6 +4833,8 @@ export class ResponseEngine {
4554
4833
  }
4555
4834
  agentModel = (typeof agent.getModel === 'function') ? agent.getModel() : undefined;
4556
4835
  primaryModel = modelOverride?.model || agentModel;
4836
+ // runner 还没跑起来就终止时,终态事件至少带上解析出的模型
4837
+ this.recordBgSessionModels(message, { requestedModel: primaryModel });
4557
4838
  if (!hasExplicitTriggerModel && primaryModel) {
4558
4839
  const fallbackResolution = await eligibleFallbackModels({
4559
4840
  selfAid: selfAid || undefined,
@@ -4662,8 +4943,10 @@ export class ResponseEngine {
4662
4943
  inputId: turnLease.inputId,
4663
4944
  },
4664
4945
  };
4665
- const refreshTopicBindingForLogicalRetry = async () => {
4666
- 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')
4667
4950
  return;
4668
4951
  const latest = await this.sessionManager.getSessionById(session.id);
4669
4952
  if (!latest || sessionLocalTopicId(latest) !== sessionLocalTopicId(session)) {
@@ -4678,13 +4961,13 @@ export class ResponseEngine {
4678
4961
  session.metadata = latest.metadata;
4679
4962
  if (latestAgentSessionId === runAgentSessionId)
4680
4963
  return;
4681
- logger.info(`[ResponseEngine] Refreshing authoritative topic backend for logical retry: `
4964
+ logger.info(`[ResponseEngine] Refreshing backend binding for logical retry: `
4682
4965
  + `session=${session.id} task=${taskId} backend=${latestAgentSessionId ?? 'none'}`);
4683
4966
  runAgentSessionId = latestAgentSessionId;
4684
- modelOverride = {
4685
- ...(modelOverride || {}),
4686
- backend: { kind: 'topic', agentSessionId: runAgentSessionId ?? null },
4687
- };
4967
+ if (isTopicSession(session)) {
4968
+ modelOverride = { ...(modelOverride || {}),
4969
+ backend: { kind: 'topic', agentSessionId: runAgentSessionId ?? null } };
4970
+ }
4688
4971
  };
4689
4972
  // 预压缩必须使用与本轮 runQuery 相同的有效模型/强度覆盖。
4690
4973
  // 模型解析完成后再执行,避免关系级模型存在时回落到 runner 默认模型。
@@ -4871,7 +5154,7 @@ export class ResponseEngine {
4871
5154
  const estTokens = (s) => s ? Math.ceil(s.length / 4) : 0;
4872
5155
  const cbModel = effectiveModel || agentModel || 'unknown';
4873
5156
  // 从统一模型参数表获取模型的真实 context_window
4874
- const { resolveModelSpec } = await import('../../stats/billing.js');
5157
+ const { resolveModelSpec } = await import('../../stats/price-resolver.js');
4875
5158
  const modelSpec = resolveModelSpec(resolveRoot(), cbModel);
4876
5159
  const cbMaxTokens = modelSpec.context_window;
4877
5160
  const systemPromptTokens = estTokens(options?.systemPromptAppend);
@@ -5095,7 +5378,11 @@ export class ResponseEngine {
5095
5378
  chatType: configChatType,
5096
5379
  selfAid,
5097
5380
  peerId: configActorId || undefined,
5098
- peerKey,
5381
+ // 系统会话(如记忆整理)的消息 peerId 是后台伪对端 `bg:<kind>`,推出来的 peerKey 不是
5382
+ // 它要操作的关系;目标关系由发起方写在 session.metadata.peerKey,与 system-session
5383
+ // 模块的读写边界同源。ec memory 写盘读的是这里,必须用它。
5384
+ // 局部 peerKey(delegation grant / stats / 响应模式)保持伪对端不变,二者此处有意不一致。
5385
+ peerKey: systemSessionContext?.peerKey ?? peerKey,
5099
5386
  peerName: peerName || undefined,
5100
5387
  peerType: message.peerType || session.metadata?.peerType || undefined,
5101
5388
  // 系统会话没有角色
@@ -5183,7 +5470,9 @@ export class ResponseEngine {
5183
5470
  event: fullAccessAuthorization.source === 'trigger'
5184
5471
  ? 'fullaccess.trigger.execution.started'
5185
5472
  : fullAccessAuthorization.source === 'agent-policy'
5186
- ? 'fullaccess.agent-policy.execution.started' : 'fullaccess.execution.started',
5473
+ ? 'fullaccess.agent-policy.execution.started'
5474
+ : fullAccessAuthorization.source === 'session-policy'
5475
+ ? 'fullaccess.session-policy.execution.started' : 'fullaccess.execution.started',
5187
5476
  source: fullAccessAuthorization.source,
5188
5477
  actorId: fullAccessAuthorization.authorizedBy,
5189
5478
  processRole: fullAccessAuditProcessRole,
@@ -5234,7 +5523,36 @@ export class ResponseEngine {
5234
5523
  this.activeRunnerModels.set(session.id, debugRunnerModel);
5235
5524
  else
5236
5525
  this.activeRunnerModels.delete(session.id);
5237
- const stream = await agent.runQuery(session.id, effectivePrompt, absoluteProjectPath, runAgentSessionId, runnerImages, effectiveSystemPrompt, this.sessionManager, modelOverride, runtimeEnv);
5526
+ // 每次尝试前覆盖:备用模型切换后,请求模型以最后一次尝试为准
5527
+ this.recordBgSessionModels(message, { requestedModel: debugRunnerModel });
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);
5238
5556
  // The turn may be superseded while the runner is still creating its
5239
5557
  // backend query. Replay the interrupt after runQuery resolves, when
5240
5558
  // every runner is required to have an addressable cancellation handle.
@@ -5263,7 +5581,10 @@ export class ResponseEngine {
5263
5581
  releaseHintClaim(accepted);
5264
5582
  ownerHintClaim = undefined;
5265
5583
  }
5266
- agent.registerStream(streamKey, stream);
5584
+ agent.registerStream(streamKey, stream, turnLease ? {
5585
+ taskId: turnLease.taskId,
5586
+ generation: turnLease.generation,
5587
+ } : undefined);
5267
5588
  streamRegistered = true;
5268
5589
  if (shouldTimeoutRetryAttempt) {
5269
5590
  attemptTimeout = createRetryAttemptTimeout(apiRetryTimeoutMs);
@@ -5279,28 +5600,54 @@ export class ResponseEngine {
5279
5600
  } : undefined, taskCausation, turnLease, effectivePermissionMode, selfAid, async (request) => {
5280
5601
  if (!this.asyncQuestions)
5281
5602
  throw new Error('Async question service is unavailable');
5603
+ const blocking = request.questions.some(question => question.blocking === true);
5282
5604
  if (permissionContext.approvalInteractionPolicy === 'deny') {
5283
5605
  logger.info(`[AsyncQuestions] no interactive recipient for unattended task: session=${session.id}`);
5606
+ if (blocking)
5607
+ throw new Error('阻塞式用户问题无法在无人值守任务中继续');
5284
5608
  return;
5285
5609
  }
5286
- await renderer.flush(false);
5610
+ if (blocking) {
5611
+ attemptTimeout?.pause();
5612
+ timeoutControl?.pauseForInteraction?.();
5613
+ }
5287
5614
  try {
5615
+ if (blocking)
5616
+ await agent.interrupt(session.id, turnLease ? {
5617
+ taskId: turnLease.taskId,
5618
+ generation: turnLease.generation,
5619
+ } : undefined);
5620
+ await renderer.flush(false);
5288
5621
  await this.asyncQuestions.present(session, request, message, adapter, envelope);
5289
5622
  }
5290
5623
  catch (error) {
5291
- // Card dispatch is non-blocking business input. Keep consuming the running turn;
5292
- // pending records can be delivered after reconnect/restart.
5624
+ if (blocking)
5625
+ throw error;
5626
+ // Non-blocking business input can be restored after reconnect/restart.
5293
5627
  logger.warn(`[AsyncQuestions] presentation failed: session=${session.id} error=${String(error)}`);
5294
5628
  }
5629
+ finally {
5630
+ if (blocking) {
5631
+ attemptTimeout?.resume();
5632
+ timeoutControl?.resumeForInteraction?.();
5633
+ }
5634
+ }
5635
+ }, async () => {
5636
+ if (proactiveCircuitBreakRequested)
5637
+ await interruptProactiveCircuitBreak();
5295
5638
  });
5296
5639
  streamResult = attemptTimeout
5297
5640
  ? await Promise.race([processAttempt, attemptTimeout.promise])
5298
5641
  : await processAttempt;
5642
+ // runner 回报的实际模型;之后无论成功、失败还是被打断,终态事件都能带出
5643
+ this.recordBgSessionModels(message, {
5644
+ actualModel: streamResult.lastModelCall?.model || streamResult.model,
5645
+ });
5299
5646
  // Activation can complete either before runQuery returns (Codex)
5300
5647
  // or while its event stream is consumed (Claude/Gemini/Ecagent).
5301
5648
  // Always reconcile from strict latest before any logical retry.
5302
- await refreshTopicBindingForLogicalRetry();
5303
- if (!streamResult.isError) {
5649
+ await refreshBackendBindingForLogicalRetry();
5650
+ if (!streamResult.isError && !isExpectedTerminalInterrupt(streamResult.terminalReason)) {
5304
5651
  const protocolDecision = this.turnCoordinator.evaluateCommit(turnLease, this.buildTurnCommitEvidence(session, streamResult));
5305
5652
  const protocolReason = protocolDecision.ok ? undefined : protocolDecision.reason;
5306
5653
  // Codex app-server turn/start appends its input before runQuery
@@ -5310,7 +5657,7 @@ export class ResponseEngine {
5310
5657
  const protocolRetry = retryScheduler.afterProtocolFailure(safeProtocolReplay ? protocolReason : undefined, safeProtocolReplay);
5311
5658
  if (protocolRetry.kind === 'protocol_replay') {
5312
5659
  protocolReplayAttempts = protocolRetry.attempt;
5313
- agent.cleanupStream(streamKey);
5660
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5314
5661
  logger.warn(`[ResponseEngine] Replaying zero-work protocol failure: session=${session.id} `
5315
5662
  + `task=${taskId} reason=${protocolReason} attempt=${protocolRetry.attempt}/${protocolRetry.maxAttempts}`);
5316
5663
  await this.emitOperationalNotice(renderer, `模型未确认完成,正在立即重试 ${protocolRetry.attempt}/${protocolRetry.maxAttempts}`, 'warn', 'protocol-retry');
@@ -5335,17 +5682,20 @@ export class ResponseEngine {
5335
5682
  break; // 成功,跳出重试循环
5336
5683
  }
5337
5684
  catch (retryError) {
5338
- await refreshTopicBindingForLogicalRetry();
5685
+ await refreshBackendBindingForLogicalRetry();
5339
5686
  const retryAttemptTimedOut = retryError instanceof RetryAttemptTimeoutError;
5340
5687
  if (retryAttemptTimedOut) {
5341
5688
  logger.warn(`[ResponseEngine] Retry attempt ${runAttempt} timed out after ${retryError.timeoutMs}ms without agent events; interrupting current stream`);
5342
5689
  renderer.discardPending();
5343
- 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 => {
5344
5694
  logger.warn(`[ResponseEngine] Failed to interrupt timed-out retry attempt: ${interruptError instanceof Error ? interruptError.message : String(interruptError)}`);
5345
5695
  });
5346
5696
  }
5347
5697
  if (streamRegistered) {
5348
- agent.cleanupStream(streamKey);
5698
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5349
5699
  }
5350
5700
  if (permissionTerminalFailure) {
5351
5701
  const permissionError = new Error(permissionTerminalFailure.message);
@@ -5518,11 +5868,11 @@ export class ResponseEngine {
5518
5868
  // 上下文过长但无法 auto-compact(无 session ID 或 agent 不支持),显示友好提示
5519
5869
  await this.emitOperationalNotice(renderer, getContextTooLongHint(agent), 'warn', 'context-too-long');
5520
5870
  }
5521
- if (!streamResult.isError) {
5871
+ if (!streamResult.isError && !isExpectedTerminalInterrupt(streamResult.terminalReason)) {
5522
5872
  const commitEvidence = this.buildTurnCommitEvidence(session, streamResult);
5523
5873
  const commitDecision = this.turnCoordinator.evaluateCommit(turnLease, commitEvidence);
5524
5874
  if (!commitDecision.ok && commitDecision.reason === 'stale_generation') {
5525
- agent.cleanupStream(streamKey);
5875
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5526
5876
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5527
5877
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5528
5878
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5538,7 +5888,7 @@ export class ResponseEngine {
5538
5888
  }
5539
5889
  if (!commitDecision.ok) {
5540
5890
  if (commitDecision.reason === 'stale_generation') {
5541
- agent.cleanupStream(streamKey);
5891
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5542
5892
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5543
5893
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5544
5894
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5704,7 +6054,7 @@ export class ResponseEngine {
5704
6054
  && message.triggerMeta.noopSentinel.length > 0
5705
6055
  && visibleFinalReplyText.trim() === message.triggerMeta.noopSentinel;
5706
6056
  if (!this.turnCoordinator.isCurrent(turnLease)) {
5707
- agent.cleanupStream(streamKey);
6057
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5708
6058
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5709
6059
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5710
6060
  this.activeTaskRuntimeContexts.delete(session.id);
@@ -5715,6 +6065,7 @@ export class ResponseEngine {
5715
6065
  await this.publishTriggerExecutionInterrupted(message, adapter, envelope, 'stale_turn', taskCausation);
5716
6066
  return;
5717
6067
  }
6068
+ const terminalInterrupt = isExpectedTerminalInterrupt(streamResult.terminalReason);
5718
6069
  const streamRecoverable = !permissionTerminalFailure
5719
6070
  && !isExpectedTerminalInterrupt(streamResult.terminalReason)
5720
6071
  && isRetryableError(new Error(getStreamErrorText(streamResult)));
@@ -5730,34 +6081,43 @@ export class ResponseEngine {
5730
6081
  // (2026-10-11 403「无法连接到积分服务器」案例)。
5731
6082
  // 以错误收场的轮次一律走 system.error:前端收到的单条消息即可判断来源,
5732
6083
  // 不需要等后续的 result.error。
5733
- const errorText = visibleFinalReplyText || streamResult.syntheticDiagnosticText || getStreamErrorMessage(streamResult, false);
6084
+ const errorText = streamResult.isError
6085
+ ? (streamResult.syntheticDiagnosticText || getStreamErrorMessage(streamResult, false))
6086
+ : visibleFinalReplyText;
5734
6087
  if (streamResult.isError) {
5735
6088
  // 用原始诊断文本(含错误码)判断可重试性,不用已过 stripContextLimitErrorLines 的展示文本
5736
6089
  const subtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || getStreamErrorText(streamResult)), streamResult.subtype, streamResult.terminalReason);
5737
6090
  const reason = normalizeCoreErrorReason(streamResult.terminalReason);
5738
- await adapter.send(envelope, {
5739
- kind: 'system.error',
5740
- text: errorText,
5741
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
5742
- subtype,
5743
- ...(reason ? { reason } : {}),
5744
- recoverable: streamRecoverable,
5745
- }).catch(() => { });
5746
- 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
+ }
5747
6107
  }
5748
6108
  else if (visibleFinalReplyText && (shouldSuppress() || !streamResult.hasProjectedCurrentReplyText)) {
5749
6109
  await renderer.addText(visibleFinalReplyText, undefined, undefined, streamResult.assistantUuid);
5750
6110
  }
5751
6111
  }
5752
6112
  // 先清理流和处理中状态(保证即使 flush 卡住,session 也不会永久处于"处理中")
5753
- agent.cleanupStream(streamKey);
6113
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
5754
6114
  logger.info(`[ResponseEngine] agent.cleanupStream ok: session=${session.id} task=${taskId}`);
5755
6115
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
5756
6116
  if (this.activeTaskRuntimeContexts.get(session.id)?.taskId === taskId) {
5757
6117
  this.activeTaskRuntimeContexts.delete(session.id);
5758
6118
  this.activeRunnerModels.delete(session.id); // F1修复
5759
6119
  }
5760
- this.agentDelegationRegistry?.revokeTask(session.id, taskId, streamResult.isError ? 'failed' : 'completed');
6120
+ this.agentDelegationRegistry?.revokeTask(session.id, taskId, terminalInterrupt ? 'interrupted' : streamResult.isError ? 'failed' : 'completed');
5761
6121
  logger.info(`[ResponseEngine] session ${session.id} processing cleared task=${taskId}`);
5762
6122
  import('../../utils/msg-diag.js').then(m => m.diagLog('task_done', { aid: session.selfAID ?? '', msgId: message.messageId ?? '', taskId, text: message.content ?? '' })).catch(() => { });
5763
6123
  // 降级模型回复末尾追加标记(代码层硬注入,不依赖模型输出)
@@ -5784,7 +6144,7 @@ export class ResponseEngine {
5784
6144
  // outcome so AUN does not label that text as normal completion.
5785
6145
  try {
5786
6146
  if (streamResult.isError && !isExpectedTerminalInterrupt(streamResult.terminalReason)) {
5787
- await renderer.flush(true, 'failed');
6147
+ await renderer.flush(false);
5788
6148
  }
5789
6149
  else {
5790
6150
  await renderer.flush(!isExpectedTerminalInterrupt(streamResult.terminalReason));
@@ -5800,7 +6160,6 @@ export class ResponseEngine {
5800
6160
  throw tagged;
5801
6161
  }
5802
6162
  }
5803
- const terminalInterrupt = isExpectedTerminalInterrupt(streamResult.terminalReason);
5804
6163
  if (!streamResult.isError && !terminalInterrupt) {
5805
6164
  const commitDecision = await this.turnCoordinator.commit(session, turnLease, this.buildTurnCommitEvidence(session, streamResult));
5806
6165
  if (!commitDecision.ok) {
@@ -5828,16 +6187,19 @@ export class ResponseEngine {
5828
6187
  const interruptReason = this.interruptedSessions.get(session.id);
5829
6188
  if (streamResult.isError || terminalInterrupt) {
5830
6189
  // Agent 流正常结束但任务结果失败(权限被拒、max turns、工具链失败等)
5831
- const errorSummary = streamResult.errors?.join('; ')
5832
- || (terminalInterrupt ? '用户交互未确认,任务已暂停' : '任务执行失败');
6190
+ const errorSummary = streamResult.subtype === 'proactive_circuit_break'
6191
+ ? '主动模式门禁触发熔断,任务已中断'
6192
+ : streamResult.errors?.join('; ')
6193
+ || (terminalInterrupt ? '用户交互未确认,任务已暂停' : '任务执行失败');
5833
6194
  const userErrorSummary = streamResult.subtype === 'protocol_incomplete'
5834
6195
  ? errorSummary
5835
6196
  : streamHitContextLimit(streamResult)
5836
6197
  ? getContextTooLongHint(agent)
5837
6198
  : getStreamErrorMessage(streamResult, false);
5838
6199
  const rawSubtype = streamResult.subtype || 'agent_error';
5839
- const errorType = prefixErrorType(ERROR_PREFIX.AGENT, rawSubtype);
5840
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);
5841
6203
  const coreReason = permissionTerminalFailure
5842
6204
  ? normalizeCoreErrorReason(permissionTerminalFailure.reason)
5843
6205
  : normalizeCoreErrorReason(streamResult.terminalReason);
@@ -5849,9 +6211,11 @@ export class ResponseEngine {
5849
6211
  taskActivityStatus = isExpectedInterrupt ? 'interrupted' : 'error';
5850
6212
  if (!isExpectedInterrupt && !permissionTerminalFailure) {
5851
6213
  const terminalMetadata = {
5852
- errorType: rawSubtype,
6214
+ errorType: effectiveSubtype,
6215
+ ...(coreReason ? { reason: coreReason } : {}),
5853
6216
  recoverable: streamRecoverable,
5854
6217
  message: userErrorSummary,
6218
+ ...(coreSubtype === ErrorType.POLICY_REJECTED ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
5855
6219
  durationMs: Date.now() - startTime,
5856
6220
  numTurns: streamResult.numTurns,
5857
6221
  toolCallCount: streamResult.toolUseCount ?? 0,
@@ -5865,16 +6229,6 @@ export class ResponseEngine {
5865
6229
  // system.error 已在 finalReplyText 分支把错误文本发给了前端,不再重复发 result.error
5866
6230
  if (this.isTrustedDaemonTrigger(message)) {
5867
6231
  await adapter.send(envelope, { kind: 'status.error', metadata: terminalMetadata }).catch(() => { });
5868
- if (!sentErrorAsSystemError) {
5869
- await adapter.send(envelope, {
5870
- kind: 'result.error',
5871
- text: userErrorSummary,
5872
- recoverable: streamRecoverable,
5873
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
5874
- subtype: coreSubtype,
5875
- ...(coreReason ? { reason: coreReason } : {}),
5876
- }).catch(() => { });
5877
- }
5878
6232
  }
5879
6233
  else {
5880
6234
  if (!sentErrorAsSystemError) {
@@ -5882,7 +6236,7 @@ export class ResponseEngine {
5882
6236
  kind: 'result.error',
5883
6237
  text: userErrorSummary,
5884
6238
  recoverable: streamRecoverable,
5885
- ...(streamRawErrorText ? { raw: streamRawErrorText } : {}),
6239
+ ...(coreSubtype === ErrorType.POLICY_REJECTED ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
5886
6240
  subtype: coreSubtype,
5887
6241
  ...(coreReason ? { reason: coreReason } : {}),
5888
6242
  }).catch(() => { });
@@ -5937,7 +6291,7 @@ export class ResponseEngine {
5937
6291
  });
5938
6292
  recordCausationSpan(taskCausation, 'task.run', { status: 'failed', refs: { taskId, sessionId: session.id, messageId }, reason: errorType });
5939
6293
  // 系统级 subtype 仍累计错误计数,供 /status 诊断使用
5940
- if (isInfraError(rawSubtype, streamResult.terminalReason)) {
6294
+ if (isInfraError(effectiveSubtype, streamResult.terminalReason)) {
5941
6295
  const chatType = message.chatType || 'private';
5942
6296
  const identityRole = session.identity?.role || 'none';
5943
6297
  const { policy } = channelInfo;
@@ -6024,7 +6378,7 @@ export class ResponseEngine {
6024
6378
  auto_compact_tokens: mc.contextUsage?.autoCompactTokens,
6025
6379
  degraded: mc.degraded ? 1 : 0,
6026
6380
  }));
6027
- insertModelCalls(resolveRoot(), mcRows);
6381
+ insertModelCalls(resolveRoot(), mcRows, gwPricing);
6028
6382
  }
6029
6383
  const totalIn = event.input_tokens + event.cache_read_tokens;
6030
6384
  statsCacheHitRate = totalIn > 0 ? Math.round((event.cache_read_tokens / totalIn) * 100) / 100 : 0;
@@ -6038,7 +6392,7 @@ export class ResponseEngine {
6038
6392
  let sessionStats;
6039
6393
  let modelSpec;
6040
6394
  try {
6041
- const { resolveModelSpec } = await import('../../stats/billing.js');
6395
+ const { resolveModelSpec } = await import('../../stats/price-resolver.js');
6042
6396
  const { querySessionSummary } = await import('../../stats/query.js');
6043
6397
  modelSpec = resolveModelSpec(resolveRoot(), statsModel);
6044
6398
  const sum = querySessionSummary(resolveRoot(), session.id);
@@ -6162,6 +6516,7 @@ export class ResponseEngine {
6162
6516
  finalText: streamResult.lastReplyText || undefined,
6163
6517
  durationMs: Date.now() - startTime,
6164
6518
  agentName: agentNameForStats,
6519
+ agentAid: runnerSelfAid,
6165
6520
  numTurns: streamResult.numTurns,
6166
6521
  encrypted: message.encrypted ?? message.replyContext?.metadata?.encrypted,
6167
6522
  timestamp: Date.now(),
@@ -6180,7 +6535,7 @@ export class ResponseEngine {
6180
6535
  // 所有 message.send 成功后统一写入 messages.jsonl,此处不再重复写入。
6181
6536
  }
6182
6537
  const isFinallyBackground = this.isBackgroundSession(session, message.channel, message.channelId);
6183
- if (isFinallyBackground && !streamResult.isError) {
6538
+ if (isFinallyBackground && !streamResult.isError && !terminalInterrupt) {
6184
6539
  if (!this.turnCoordinator.canPublish(turnLease))
6185
6540
  return;
6186
6541
  this.messageCache.addEvent(session.id, {
@@ -6226,7 +6581,7 @@ export class ResponseEngine {
6226
6581
  }
6227
6582
  const leaseWasCurrent = !!turnLease && this.turnCoordinator.isCurrent(turnLease);
6228
6583
  // 清理流和处理中状态(异常时也要清除)
6229
- agent.cleanupStream(streamKey);
6584
+ agent.cleanupStream(streamKey, turnLease ? { taskId: turnLease.taskId, generation: turnLease.generation } : undefined);
6230
6585
  logger.info(`[ResponseEngine] agent.cleanupStream ok (on error): session=${session.id} task=${taskId}`);
6231
6586
  try {
6232
6587
  this.sessionManager.clearProcessingIfTask(session.id, taskId);
@@ -6272,20 +6627,50 @@ export class ResponseEngine {
6272
6627
  : failureReason, recoverable);
6273
6628
  }
6274
6629
  const totalExecutionMs = error instanceof ExecutionTimeoutError ? error.timeoutMs : this.totalExecutionLimitMs();
6630
+ const rawErrorText = getErrorRawText(error);
6631
+ const safeRawErrorText = isPolicyRejectedError(error) ? undefined : rawErrorText;
6275
6632
  const procStatus = errType === ErrorType.SDK_TIMEOUT || isTotalExecutionTimeout ? 'timeout'
6276
6633
  : errType === ErrorType.STREAM_ERROR ? 'interrupted'
6277
6634
  : 'error';
6278
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';
6279
6646
  const statusPayload = error instanceof OrphanedTargetSessionError
6280
- ? { kind: 'status.error', metadata: { errorType: error.reason, message: '任务执行状态丢失,已结束本次执行。' } }
6647
+ ? { kind: 'status.error', metadata: {
6648
+ errorType: error.reason,
6649
+ reason: error.reason,
6650
+ message: '任务执行状态丢失,已结束本次执行。',
6651
+ recoverable,
6652
+ ...(safeRawErrorText ? { raw: safeRawErrorText } : {}),
6653
+ } }
6281
6654
  : procStatus === 'timeout'
6282
6655
  ? { kind: 'status.timeout', metadata: isTotalExecutionTimeout
6283
6656
  ? { ...(totalExecutionMs === undefined ? {} : { totalExecutionMs }),
6284
- ...(error instanceof ExecutionTimeoutError ? { reason: error.reason } : {}) }
6285
- : { idleSec: getLastIdleSec?.() || undefined } }
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 } : {}) } }
6286
6665
  : procStatus === 'interrupted'
6287
6666
  ? { kind: 'status.interrupted', metadata: { reason: 'stream_error' } }
6288
- : { kind: 'status.error' };
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
+ } };
6289
6674
  // 用户主动中断(新消息打断 或 /stop 命令)时静默,不发送中断/错误提示
6290
6675
  if (!isUserInterrupt && ownsTimeoutTerminal && !daemonTrigger) {
6291
6676
  await adapter.send(envelope, statusPayload).catch(() => { });
@@ -6404,42 +6789,59 @@ export class ResponseEngine {
6404
6789
  : modelFallbackExhaustedMessage
6405
6790
  ? ErrorType.MODEL_UNAVAILABLE
6406
6791
  : normalizeCoreErrorSubtype(error, undefined, isTotalExecutionTimeout || isTimeout ? 'timeout' : undefined);
6407
- const rawErrorText = getErrorRawText(error);
6792
+ const distinctRawErrorText = errorSubtype === ErrorType.POLICY_REJECTED
6793
+ ? undefined
6794
+ : rawErrorText && !userMessage.includes(rawErrorText)
6795
+ ? rawErrorText
6796
+ : undefined;
6408
6797
  const errorPayload = {
6409
6798
  kind: 'result.error',
6410
6799
  text: userMessage,
6411
6800
  recoverable,
6412
6801
  subtype: errorSubtype,
6413
- ...(rawErrorText ? { raw: rawErrorText } : {}),
6802
+ ...(distinctRawErrorText ? { raw: distinctRawErrorText } : {}),
6414
6803
  ...(errorReason ? { reason: errorReason } : {}),
6415
6804
  };
6416
- if (!isUserInterrupt && daemonTrigger && procStatus === 'error') {
6805
+ if (!isUserInterrupt && daemonTrigger) {
6417
6806
  // DaemonChannel settles a trigger on the first terminal payload. Put
6418
6807
  // the complete failure metadata first so the audit retains tool
6419
6808
  // counts and context-recovery diagnostics even for thrown errors
6420
6809
  // (for example when compact itself fails).
6421
- await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
6422
- kind: 'status.error',
6423
- metadata: {
6424
- errorType: errType,
6425
- message: userMessage,
6426
- recoverable,
6427
- durationMs: Date.now() - startTime,
6428
- numTurns: streamResult.numTurns,
6429
- toolCallCount: streamResult.toolUseCount ?? 0,
6430
- tokenUsage: streamResult.tokenUsage,
6431
- contextUsage: streamResult.contextUsage,
6432
- contextRecoveryAttempts: streamResult.contextRecoveryAttempts ?? 0,
6433
- },
6434
- }).catch(() => { });
6435
- 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
+ }
6436
6841
  }
6437
6842
  else {
6438
6843
  await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), errorPayload);
6439
6844
  }
6440
- if (!isUserInterrupt && daemonTrigger && procStatus !== 'error') {
6441
- await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), statusPayload).catch(() => { });
6442
- }
6443
6845
  // Proactive 可观测:catch 块的基础设施错误也透传为 thought,保证按 task_id 聚合完整
6444
6846
  if (isProactive && adapter.capabilities?.thought) {
6445
6847
  await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
@@ -6457,6 +6859,8 @@ export class ResponseEngine {
6457
6859
  }
6458
6860
  }
6459
6861
  finally {
6862
+ if (proactiveCircuitBreakTimer)
6863
+ clearTimeout(proactiveCircuitBreakTimer);
6460
6864
  if (taskActivityStore) {
6461
6865
  try {
6462
6866
  taskActivityStore.updateStatus(taskId, taskActivityStatus);
@@ -6497,7 +6901,9 @@ export class ResponseEngine {
6497
6901
  event: fullAccessAuthorization.source === 'trigger'
6498
6902
  ? 'fullaccess.trigger.execution.ended'
6499
6903
  : fullAccessAuthorization.source === 'agent-policy'
6500
- ? 'fullaccess.agent-policy.execution.ended' : 'fullaccess.execution.ended',
6904
+ ? 'fullaccess.agent-policy.execution.ended'
6905
+ : fullAccessAuthorization.source === 'session-policy'
6906
+ ? 'fullaccess.session-policy.execution.ended' : 'fullaccess.execution.ended',
6501
6907
  source: fullAccessAuthorization.source,
6502
6908
  actorId: fullAccessAuthorization.authorizedBy,
6503
6909
  processRole: fullAccessAuditProcessRole,
@@ -6592,7 +6998,7 @@ export class ResponseEngine {
6592
6998
  return undefined;
6593
6999
  const shouldClose = !writerDb;
6594
7000
  try {
6595
- 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,
6596
7002
  context_tokens
6597
7003
  FROM model_calls
6598
7004
  WHERE session_id = ?
@@ -6607,11 +7013,13 @@ export class ResponseEngine {
6607
7013
  if (recordedTotalTokens && recordedTotalTokens > 0) {
6608
7014
  totalTokens = recordedTotalTokens;
6609
7015
  }
6610
- else if (isClaudeContextUsageModel(model)) {
6611
- totalTokens = (row.input_tokens ?? 0) + (row.cache_creation_tokens ?? 0) + (row.cache_read_tokens ?? 0);
6612
- }
6613
7016
  else {
6614
- 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);
6615
7023
  }
6616
7024
  if (totalTokens <= 0)
6617
7025
  return undefined;
@@ -6769,6 +7177,32 @@ export class ResponseEngine {
6769
7177
  hasTokenUsage: hasRecordedTokenUsage(result),
6770
7178
  };
6771
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
+ }
6772
7206
  /**
6773
7207
  * 处理标准事件流(AgentEvent)
6774
7208
  *
@@ -6777,7 +7211,7 @@ export class ResponseEngine {
6777
7211
  */
6778
7212
  async processEventStream(stream, session, agent, renderer, resetTimer, shouldSuppress, proactive,
6779
7213
  /** [迁移点4/5] 响应模式插件 + 状态,用于调 onToolUse/onComplete 钩子 */
6780
- modeHooks, causation, turnLease, permissionMode, proactiveSelfAid, onAsyncQuestion) {
7214
+ modeHooks, causation, turnLease, permissionMode, proactiveSelfAid, onAsyncQuestion, onToolCallsSettled) {
6781
7215
  // Per-session agent name for stats bucketing
6782
7216
  const statsChannelKey = session.channel === 'daemon' ? session.channel : (session.metadata?.channelKey || session.channel);
6783
7217
  const agentNameForStats = this.agentRegistry?.resolveByChannel(statsChannelKey)?.name ?? '<unknown>';
@@ -6799,17 +7233,23 @@ export class ResponseEngine {
6799
7233
  const openToolUseIds = new Set();
6800
7234
  const anonymousToolUseIds = new Map();
6801
7235
  const anonymousOpenIdByCorrelation = new Map();
6802
- const finalizeResult = () => ({
6803
- ...completeResult,
6804
- hasReceivedText,
6805
- hasProjectedCurrentReplyText,
6806
- inputAccepted,
6807
- assistantUuid,
6808
- protocolIncompleteReason,
6809
- textCount,
6810
- toolUseCount,
6811
- openToolUseIds: [...openToolUseIds],
6812
- });
7236
+ const finalizeResult = () => {
7237
+ const circuitBreakInterrupted = this.interruptedSessions.get(session.id) === 'proactive_circuit_break';
7238
+ return {
7239
+ ...completeResult,
7240
+ ...(circuitBreakInterrupted
7241
+ ? { isError: false, subtype: 'proactive_circuit_break', terminalReason: 'aborted_tools', errors: undefined }
7242
+ : {}),
7243
+ hasReceivedText,
7244
+ hasProjectedCurrentReplyText,
7245
+ inputAccepted,
7246
+ assistantUuid,
7247
+ protocolIncompleteReason: circuitBreakInterrupted ? undefined : protocolIncompleteReason,
7248
+ textCount,
7249
+ toolUseCount,
7250
+ openToolUseIds: [...openToolUseIds],
7251
+ };
7252
+ };
6813
7253
  // 追踪最后一轮 assistant 回复文本(tool_use 之后的纯文本)
6814
7254
  let lastReplyText = '';
6815
7255
  // 上游合成错误帧的原文(runner 标记 synthetic 的 text)。与正文通道分开存放:
@@ -7451,6 +7891,8 @@ export class ResponseEngine {
7451
7891
  else if (!toolResultFailed && !shouldSuppress()) {
7452
7892
  renderer.addToolResult(event.name || '\u5de5\u5177', true, event.result, undefined, event.callId, event.durationMs, cachedDesc, event, event.assistantUuid);
7453
7893
  }
7894
+ if (openToolUseIds.size === 0)
7895
+ await onToolCallsSettled?.();
7454
7896
  }
7455
7897
  // 非终态运行时告警走 status notify,不进入 activity/thought 历史。
7456
7898
  if (event.type === 'notice' && event.severity === 'warn') {