evolcore 0.0.43-test.3 → 0.0.43-test.5

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 (192) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/bin/ecmsg.js +492 -0
  3. package/bin/install-codex-managed-hooks.mjs +130 -8
  4. package/dist/ability/application-service.js +37 -0
  5. package/dist/ability/resources.js +28 -0
  6. package/dist/ability/runtime.js +6 -1
  7. package/dist/agents/claude-runner.js +7 -5
  8. package/dist/agents/codex/app-server-client.js +0 -12
  9. package/dist/agents/codex-runner.js +12 -54
  10. package/dist/agents/ecagent-runner.js +130 -35
  11. package/dist/aun/aid/agentmd.js +56 -12
  12. package/dist/aun/aid/control-aid.js +15 -0
  13. package/dist/aun/aid/identity.js +8 -0
  14. package/dist/aun/aid/ownership-operation.js +12 -3
  15. package/dist/aun/menu/client.js +8 -7
  16. package/dist/aun/menu/index.js +1 -1
  17. package/dist/aun/menu/transport.js +8 -5
  18. package/dist/aun/service-proxy.js +3 -0
  19. package/dist/channels/aun.js +56 -22
  20. package/dist/channels/daemon.js +12 -4
  21. package/dist/cli/agent-command.js +5 -0
  22. package/dist/cli/agent-create.js +32 -8
  23. package/dist/cli/agent.js +9 -3
  24. package/dist/cli/aid-bind-command.js +3 -0
  25. package/dist/cli/aun-commands.js +12 -5
  26. package/dist/cli/code-stats.js +451 -213
  27. package/dist/cli/ctl-command.js +1 -3
  28. package/dist/cli/daemon-commands.js +42 -21
  29. package/dist/cli/directory.js +7 -8
  30. package/dist/cli/ecmsg-gateway.js +204 -0
  31. package/dist/cli/getmeta-command.js +2 -1
  32. package/dist/cli/index.js +6 -0
  33. package/dist/cli/init.js +58 -18
  34. package/dist/cli/provider-command.js +82 -5
  35. package/dist/cli/restart-monitor.js +11 -19
  36. package/dist/cli/stats.js +8 -1
  37. package/dist/cli/task-context.js +3 -0
  38. package/dist/cli/trigger-command.js +20 -14
  39. package/dist/config/boot-log.js +23 -2
  40. package/dist/config/config-field-policy.js +2 -0
  41. package/dist/config/config-manager.js +13 -17
  42. package/dist/config/daemon-services.js +1 -0
  43. package/dist/config/peer-role-resolver.js +6 -6
  44. package/dist/config/provider-identity-migration.js +202 -0
  45. package/dist/config/provider-identity.js +37 -0
  46. package/dist/config/provider-ipc-service.js +40 -3
  47. package/dist/config/provider-local-sync.js +153 -0
  48. package/dist/config/providers-config.js +32 -4
  49. package/dist/config/providers-management.js +144 -68
  50. package/dist/config/providers.js +4 -1
  51. package/dist/config/role-schema.js +3 -3
  52. package/dist/config/schema-migration.js +188 -3
  53. package/dist/core/agent-application-service.js +11 -0
  54. package/dist/core/agent-ipc-registration.js +2 -0
  55. package/dist/core/agent-runtime.js +45 -11
  56. package/dist/core/auth/auth-gateway.js +8 -6
  57. package/dist/core/auth/delegation-diagnostics.js +6 -2
  58. package/dist/core/auth/operation-authorizer.js +5 -2
  59. package/dist/core/auth/operation-catalog.js +6 -4
  60. package/dist/core/baseagent-loader.js +11 -3
  61. package/dist/core/bootstrap-service.js +8 -0
  62. package/dist/core/channel-loader.js +61 -23
  63. package/dist/core/command/agent-control.js +4 -1
  64. package/dist/core/command/chatmode-config.js +46 -0
  65. package/dist/core/command/cli-intent-parser.js +2 -1
  66. package/dist/core/command/command-handler.js +16 -20
  67. package/dist/core/command/daemon-diagnostics.js +2 -1
  68. package/dist/core/command/menu-catalog.js +1 -1
  69. package/dist/core/command/menu-handler.js +16 -16
  70. package/dist/core/command/menu-protocol.js +4 -2
  71. package/dist/core/command/provider-menu.js +4 -2
  72. package/dist/core/command/role-menu.js +2 -2
  73. package/dist/core/command/slash-handler.js +56 -42
  74. package/dist/core/daemon-lifecycle.js +35 -17
  75. package/dist/core/event-catalog.js +19 -0
  76. package/dist/core/evolagent-registry.js +3 -0
  77. package/dist/core/handoff/runtime.js +9 -3
  78. package/dist/core/initialization/service.js +4 -3
  79. package/dist/core/ipc-registration.js +6 -0
  80. package/dist/core/message/aun-ipc-sender.js +81 -3
  81. package/dist/core/message/im-renderer.js +24 -19
  82. package/dist/core/message/message-admission.js +13 -2
  83. package/dist/core/message/response-engine.js +40 -41
  84. package/dist/core/message/send-options.js +40 -0
  85. package/dist/core/message/send-routing.js +310 -0
  86. package/dist/core/model/model-capabilities.js +37 -0
  87. package/dist/core/model/model-catalog.js +6 -2
  88. package/dist/core/ownership/owner-resolver.js +117 -14
  89. package/dist/core/permission/ec-command-parser.js +195 -27
  90. package/dist/core/permission/readonly-shell-query.js +66 -7
  91. package/dist/core/permission/tool-error-code.js +13 -1
  92. package/dist/core/permission/tool-policy.js +74 -20
  93. package/dist/core/plugin-lifecycle.js +6 -2
  94. package/dist/core/relation/pa-team.js +7 -2
  95. package/dist/core/relation/same-owner-proof.js +131 -0
  96. package/dist/core/session/session-idle-monitor.js +94 -16
  97. package/dist/core/session/session-manager.js +69 -16
  98. package/dist/core/thread/thread-route.js +5 -2
  99. package/dist/directory/owner-directory-cache.js +690 -99
  100. package/dist/directory/owner-directory-markdown.js +146 -36
  101. package/dist/directory/owner-directory-query-operation.js +7 -9
  102. package/dist/directory/owner-directory-scope.js +12 -0
  103. package/dist/directory/owner-directory-search.js +5 -1
  104. package/dist/directory/owner-directory-store.js +28 -0
  105. package/dist/ecweb/basic-settings-service.js +15 -1
  106. package/dist/ecweb/message-context-service.js +2 -2
  107. package/dist/ecweb/providers-service.js +3 -1
  108. package/dist/ecweb/runtime/lifecycle.js +38 -5
  109. package/dist/ecweb/runtime/supervisor.js +157 -49
  110. package/dist/index.js +202 -38
  111. package/dist/paths.js +2 -1
  112. package/dist/proxy/manager.js +2 -0
  113. package/dist/proxy/service-supervisor.js +379 -143
  114. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  115. package/dist/trigger/application-service.js +1 -0
  116. package/dist/trigger/audit.js +3 -2
  117. package/dist/trigger/authorization.js +2 -3
  118. package/dist/trigger/event-source.js +4 -0
  119. package/dist/trigger/feedback.js +26 -2
  120. package/dist/trigger/history.js +4 -3
  121. package/dist/trigger/ipc-service.js +24 -19
  122. package/dist/trigger/manager.js +3 -5
  123. package/dist/trigger/parser.js +4 -21
  124. package/dist/trigger/patch.js +3 -15
  125. package/dist/trigger/scheduler.js +48 -13
  126. package/dist/trigger/system-definitions.js +2 -2
  127. package/dist/trigger/validation.js +4 -13
  128. package/dist/utils/autostart.js +2 -2
  129. package/dist/utils/cross-platform.js +36 -8
  130. package/dist/utils/error-utils.js +8 -0
  131. package/dist/utils/macos-autostart.js +31 -0
  132. package/dist/utils/model-prices.jsonl +15 -8
  133. package/dist/utils/process-introspect.js +21 -1
  134. package/dist/utils/public-suffix.js +5811 -0
  135. package/dist/utils/startup-trace.js +7 -1
  136. package/dist/utils/windows-autostart.js +42 -7
  137. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  138. package/ecagent/dist/harness/compaction/compaction.js +4 -4
  139. package/ecagent/dist/harness/env/nodejs.js +46 -2
  140. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  141. package/kits/docs/channels/aun.md +1 -1
  142. package/kits/docs/channels/feishu.md +2 -2
  143. package/kits/docs/context-assembly.md +20 -4
  144. package/kits/docs/evolcore/INDEX.md +3 -2
  145. package/kits/docs/evolcore/agent.md +2 -2
  146. package/kits/docs/evolcore/aid.md +8 -2
  147. package/kits/docs/evolcore/ctl.md +13 -4
  148. package/kits/docs/evolcore/directory.md +48 -15
  149. package/kits/docs/evolcore/file-navigation.md +63 -49
  150. package/kits/docs/evolcore/group.md +6 -6
  151. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  152. package/kits/docs/evolcore/menu-protocol.md +33 -3
  153. package/kits/docs/evolcore/model.md +5 -3
  154. package/kits/docs/evolcore/msg.md +28 -27
  155. package/kits/docs/evolcore/provider.md +39 -5
  156. package/kits/docs/evolcore/response.md +3 -1
  157. package/kits/docs/evolcore/thread-chain.md +12 -14
  158. package/kits/docs/evolcore/tool-authorization.md +21 -1
  159. package/kits/docs/evolcore/trigger.md +12 -9
  160. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  161. package/kits/docs/prompt-loading-architecture.md +30 -20
  162. package/kits/eck_manifest.auxiliary.json +5 -5
  163. package/kits/eck_manifest.json +28 -49
  164. package/kits/eck_manifest.memory.json +18 -18
  165. package/kits/rules/01-overview.md +43 -45
  166. package/kits/rules/02-navigation.md +44 -53
  167. package/kits/rules/03-identity.md +21 -25
  168. package/kits/rules/04-relation.md +23 -33
  169. package/kits/rules/05-venue.md +24 -25
  170. package/kits/rules/06-channel.md +3 -3
  171. package/kits/schemas/_meta.json +20 -27
  172. package/kits/schemas/agent-config.schema.19.json +10 -6
  173. package/kits/schemas/providers.schema.2.json +74 -0
  174. package/kits/schemas/relation-config.schema.12.json +2 -2
  175. package/kits/schemas/role-config.schema.2.json +5 -5
  176. package/kits/schemas/role-registry.schema.1.json +1 -1
  177. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  178. package/kits/skills/ec-service-proxy/SKILL.md +3 -0
  179. package/kits/skills/ec-trigger/SKILL.md +4 -4
  180. package/kits/skills/ec-trigger/references/examples.md +1 -1
  181. package/kits/templates/system-fragments/channel.md +5 -5
  182. package/kits/templates/system-fragments/commands.md +3 -2
  183. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  184. package/kits/templates/system-fragments/identity.md +0 -1
  185. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  186. package/kits/templates/system-fragments/reply.md +47 -28
  187. package/kits/templates/system-fragments/session.md +2 -9
  188. package/kits/templates/system-fragments/thread.md +5 -5
  189. package/package.json +17 -13
  190. package/kits/schemas/agent-config.schema.20.json +0 -925
  191. package/kits/schemas/relation-config.schema.13.json +0 -289
  192. package/kits/schemas/role-config.schema.3.json +0 -1038
@@ -10,7 +10,7 @@ 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';
12
12
  import { authorizeAccess, authorizeOperation, buildAuthSubject } from '../auth/auth-gateway.js';
13
- import { preparePaTeamQualification, paTeamQualification, requiresPaTeamVerification } from '../relation/pa-team.js';
13
+ import { prepareSameOwnerProof, sameOwnerQualification, requiresSameOwnerProof } from '../relation/same-owner-proof.js';
14
14
  import { getRoleDefinition } from '../../config/roles.js';
15
15
  import { buildTaskRuntimeEnv, ensureRuntimeLockDir, ensureSessionRuntimeDir } from '../../cli/task-context.js';
16
16
  import { BUILTIN_SESSION_PATH_GRANTS, mergeRuntimeGrantsForSession, resolveGrantedReadRoots, } from '../permission/session-path-grants.js';
@@ -28,7 +28,7 @@ import { logger } from '../../utils/logger.js';
28
28
  import { isHostChinese } from '../../utils/locale.js';
29
29
  import { ExecutionTimeoutError, OrphanedTargetSessionError, UnattendedInputRequiredError, isExecutionFailure, getErrorMessage, getErrorRawText, getToolResultErrorText, classifyError, normalizeCoreErrorReason, normalizeCoreErrorSubtype, ErrorType, ERROR_PREFIX, isInfraError, isAbortTerminalReason, prefixErrorType, isRetryableError, isContextTooLongText, isPolicyRejectedError } from '../../utils/error-utils.js';
30
30
  import { readEvolcoreRuntimeFlavor, tagErrorTextWithEvolcoreVersion } from '../../utils/evolcore-version.js';
31
- import { describeProactiveSendCommandFailure, isExactEvolcoreSendCommandForSession, isThreadRoutedEvolcoreSendCommand, parseCodexToolCommand, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from '../permission/ec-command-parser.js';
31
+ import { describeProactiveSendCommandFailure, isExactEvolcoreSendCommandForSession, isReadOnlyEcCommand, isThreadRoutedEvolcoreSendCommand, parseCodexToolCommand, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from '../permission/ec-command-parser.js';
32
32
  import { resolveThreadRouteTarget } from '../thread/thread-route.js';
33
33
  import { isMainSession, isTopicSession, isTopicThreadId, sessionLocalTopicId, sessionTopicThreadId } from '../thread/topic-id.js';
34
34
  import { summarizeToolInputForDisplay, toolInputForDisplay } from '../../utils/tool-summary.js';
@@ -1087,21 +1087,16 @@ function wasRetryInputAlreadySubmitted(error) {
1087
1087
  return !!(error && typeof error === 'object' && error[RETRY_INPUT_ALREADY_SUBMITTED_MARK] === true);
1088
1088
  }
1089
1089
  function formatRetryInputAlreadySubmittedMessage(error) {
1090
- const raw = getErrorRawText(error);
1091
1090
  const record = error && typeof error === 'object' ? error : undefined;
1092
- const retryCount = typeof record?.codexRetryCount === 'number' && Number.isSafeInteger(record.codexRetryCount)
1093
- ? record.codexRetryCount : undefined;
1094
- const statusCode = raw?.match(/\b([45]\d{2})\b/)?.[1];
1095
- if (retryCount !== undefined && statusCode) {
1096
- return `⚠️ Codex 已重连 ${retryCount} 次模型服务后仍失败(${statusCode})。本次执行已停止。`;
1097
- }
1098
- if (retryCount !== undefined) {
1099
- return `⚠️ Codex 已重连 ${retryCount} 次模型服务后仍失败。本次执行已停止。`;
1091
+ if (record?.codexExecutionOutcome !== 'failed') {
1092
+ return '⚠️ 本轮执行已中断,暂无法确认执行结果。为避免重复执行,系统未重新提交输入。';
1100
1093
  }
1101
- // 无重试进度可报时,说明输入已提交但终态未确认:明确告知未自动重试,
1102
- // 避免用户误以为系统会在后台继续。
1103
- const reason = getErrorMessage(error, undefined, false) || 'Codex 暂时不可用';
1104
- return `⚠️ ${reason}\n当前输入已经提交,但本轮未能确认完成。系统未自动重试,请检查会话状态后再决定是否重试。`;
1094
+ const retryCount = typeof record.codexRetryCount === 'number'
1095
+ && Number.isSafeInteger(record.codexRetryCount)
1096
+ && record.codexRetryCount > 0
1097
+ ? record.codexRetryCount : undefined;
1098
+ const message = '⚠️ 模型服务请求失败,本次执行已停止。';
1099
+ return retryCount === undefined ? message : `${message}Codex 已重连 ${retryCount} 次。`;
1105
1100
  }
1106
1101
  function isNonErrorInterruptReason(reason) {
1107
1102
  return reason === 'new_message'
@@ -2439,7 +2434,7 @@ export class ResponseEngine {
2439
2434
  .catch(error => logger.warn(`[ResponseEngine] compact-start notice send failed: ${error instanceof Error ? error.message : String(error)}`));
2440
2435
  }
2441
2436
  async emitOperationalNotice(renderer, text, severity, subtype) {
2442
- if (await renderer.sendOperationalNoticeAsText(text))
2437
+ if (await renderer.sendOperationalNotice(text, subtype))
2443
2438
  return;
2444
2439
  renderer.addNotice(text, severity, subtype, true);
2445
2440
  }
@@ -2489,7 +2484,7 @@ export class ResponseEngine {
2489
2484
  }
2490
2485
  : modelOverride;
2491
2486
  // text event 在进入 renderer 前已经剔除了上下文超限错误行。保留缓冲中的
2492
- // 有效正文,由 sendOperationalNoticeAsText 先 flush,避免恢复过程丢失已有模型输出。
2487
+ // 有效正文,由 sendOperationalNotice 先 flush,避免恢复过程丢失已有模型输出。
2493
2488
  await this.emitOperationalNotice(renderer, '上下文过长,正在压缩会话...', 'warn', 'compact-trigger');
2494
2489
  await renderer.flush();
2495
2490
  this.announcedCompactStarts.add(session.id);
@@ -3027,15 +3022,15 @@ export class ResponseEngine {
3027
3022
  const selfAidForAccess = accessAdapterSelfAid || message.selfAID || session.selfAID || undefined;
3028
3023
  if (message.source === 'trigger' && message.triggerMeta?.originChannelType === 'aun'
3029
3024
  && message.triggerMeta.originChatType !== 'group') {
3030
- await preparePaTeamQualification(selfAidForAccess, message.triggerMeta.originPeerId);
3025
+ await prepareSameOwnerProof(selfAidForAccess, message.triggerMeta.originPeerId);
3031
3026
  }
3032
3027
  if (message.source === 'handoff' && message.handoffDelivery?.direction === 'origin'
3033
3028
  && message.handoffDelivery.originAuthorization?.channelType === 'aun'
3034
3029
  && message.handoffDelivery.originAuthorization.chatType === 'private') {
3035
- await preparePaTeamQualification(selfAidForAccess, message.handoffDelivery.originAuthorization.actorId);
3030
+ await prepareSameOwnerProof(selfAidForAccess, message.handoffDelivery.originAuthorization.actorId);
3036
3031
  }
3037
3032
  if ((message.channelType || accessChannelKey.split('#')[0]) === 'aun' && message.chatType !== 'group') {
3038
- await preparePaTeamQualification(selfAidForAccess, message.peerId);
3033
+ await prepareSameOwnerProof(selfAidForAccess, message.peerId);
3039
3034
  }
3040
3035
  await refreshOwnershipForAuthorization(selfAidForAccess, {
3041
3036
  maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS,
@@ -3664,12 +3659,12 @@ export class ResponseEngine {
3664
3659
  const peerIdRaw = message.peerId;
3665
3660
  if (message.source === 'trigger' && message.triggerMeta?.originChannelType === 'aun'
3666
3661
  && message.triggerMeta.originChatType !== 'group') {
3667
- await preparePaTeamQualification(selfAid, message.triggerMeta.originPeerId);
3662
+ await prepareSameOwnerProof(selfAid, message.triggerMeta.originPeerId);
3668
3663
  }
3669
3664
  if (message.handoffDelivery?.direction === 'origin'
3670
3665
  && message.handoffDelivery.originAuthorization?.channelType === 'aun'
3671
3666
  && message.handoffDelivery.originAuthorization.chatType === 'private') {
3672
- await preparePaTeamQualification(selfAid, message.handoffDelivery.originAuthorization.actorId);
3667
+ await prepareSameOwnerProof(selfAid, message.handoffDelivery.originAuthorization.actorId);
3673
3668
  }
3674
3669
  const triggerExecutionIdentity = this.resolveTriggerExecutionIdentity(message, selfAid);
3675
3670
  const authorizationIdentity = triggerExecutionIdentity
@@ -3694,7 +3689,7 @@ export class ResponseEngine {
3694
3689
  : undefined);
3695
3690
  const peerType = message.peerType ?? session.metadata?.peerType;
3696
3691
  if (configChannelType === 'aun' && configChatType === 'private') {
3697
- await preparePaTeamQualification(selfAid, configActorId);
3692
+ await prepareSameOwnerProof(selfAid, configActorId);
3698
3693
  }
3699
3694
  const peerRoleDetail = authorizationIdentity ? undefined : (() => {
3700
3695
  try {
@@ -3822,11 +3817,9 @@ export class ResponseEngine {
3822
3817
  : isShowActivitiesMode(effectiveAgentConfig?.show_activities)
3823
3818
  ? effectiveAgentConfig.show_activities
3824
3819
  : legacyMiddleOutputMode();
3825
- const middleOutputMode = isProactive
3826
- ? 'all'
3827
- : systemOrServicePeer
3828
- ? 'none'
3829
- : configuredMiddleOutputMode;
3820
+ const middleOutputMode = systemOrServicePeer && !isProactive
3821
+ ? 'none'
3822
+ : configuredMiddleOutputMode;
3830
3823
  outputState.middleOutputMode = middleOutputMode;
3831
3824
  // 诊断日志:记录 inbound message_id 和生成的 task_id 的对应关系
3832
3825
  logger.info(`[ResponseEngine] task.started: inboundMsgId=${message.messageId ?? 'none'} taskId=${taskId} sessionId=${session.id} chatmode=${chatmode} mode=${resolvedMode?.mode.id ?? 'override/fallback'}`);
@@ -3873,6 +3866,8 @@ export class ResponseEngine {
3873
3866
  : undefined,
3874
3867
  previousTurnState: this.turnCoordinator.current(session),
3875
3868
  isSendCommand: (toolName, toolInput) => isExactEvolcoreSendCommandForSession(toolName, toolInput, session.channelId, chatType, selfAid) || isThreadRoutedSendForSelf(toolName, toolInput, selfAid),
3869
+ // 只读命令(--help / 查询类)不参与意图表达门禁,避免"查语法"被判违规。
3870
+ isReadOnlyCommand: (toolName, toolInput) => isReadOnlyEcCommand(toolName, toolInput),
3876
3871
  describeSendCommandFailure: (toolName, toolInput) => describeProactiveSendCommandFailure(toolName, toolInput, {
3877
3872
  selfAid,
3878
3873
  channelId: session.channelId,
@@ -4294,11 +4289,11 @@ export class ResponseEngine {
4294
4289
  agentAid: session.selfAID,
4295
4290
  permissionMode: () => effectivePermissionMode,
4296
4291
  flushDelay: (options?.flushDelay ?? this.agentRegistry?.resolveByChannel(channelKey)?.config?.flush_delay ?? 3) * 1000,
4297
- suppressActivityItems: isProactive ? false : middleOutputMode !== 'all',
4298
- suppressIntermediateText: isProactive ? false : middleOutputMode === 'none',
4292
+ suppressActivityItems: middleOutputMode !== 'all',
4293
+ suppressIntermediateText: middleOutputMode === 'none',
4299
4294
  deferTextUntilBoundary: (message.channelType ?? session.channelType) === 'aun' && session.chatType === 'private',
4300
4295
  noopSentinel: message.source === 'trigger' ? message.triggerMeta?.noopSentinel : undefined,
4301
- operationalNoticesAsText: !isProactive && middleOutputMode !== 'none',
4296
+ operationalNoticesEnabled: !isProactive && middleOutputMode !== 'none',
4302
4297
  fileMarkerPattern: options?.fileMarkerPattern,
4303
4298
  recordActivity: async (item, activityId) => {
4304
4299
  if (!taskActivityStore || (turnLease && !this.turnCoordinator.canPublish(turnLease)))
@@ -4402,7 +4397,7 @@ export class ResponseEngine {
4402
4397
  }
4403
4398
  renderer.addLifecycle('started');
4404
4399
  if (isProactive) {
4405
- logger.info(`[ResponseEngine] proactive mode: outputs via thought.put task=${taskId}`);
4400
+ logger.info(`[ResponseEngine] proactive mode: thought visibility=${middleOutputMode} task=${taskId}`);
4406
4401
  }
4407
4402
  // 调用 AgentRunner(含上下文过长自动 compact 重试)
4408
4403
  // 捕获当前消息的上下文(闭包),避免后续消息处理时串台
@@ -4643,15 +4638,15 @@ export class ResponseEngine {
4643
4638
  chatmode: effectiveChatMode,
4644
4639
  // 系统会话没有角色
4645
4640
  role: systemSessionMarker ? undefined : peerRole,
4646
- paTeamAuthorization: !systemSessionMarker && configChannelType === 'aun' && configChatType === 'private'
4647
- && !!selfAid && !!configActorId && (paTeamQualification(selfAid, configActorId) === 'matched'
4648
- || requiresPaTeamVerification(selfAid, configActorId)),
4649
- paTeamDefaultRole: peerRoleDetail?.source === 'pa-team-default'
4641
+ internalContactAuthorization: !systemSessionMarker && configChannelType === 'aun' && configChatType === 'private'
4642
+ && !!selfAid && !!configActorId && (sameOwnerQualification(selfAid, configActorId) === 'matched'
4643
+ || requiresSameOwnerProof(selfAid, configActorId)),
4644
+ internalContactDefaultRole: peerRoleDetail?.source === 'internal-contact-default'
4650
4645
  || (authorizationIdentity?.role === peerRole && configChannelType === 'aun'
4651
4646
  && configChatType === 'private' && !!selfAid && !!configActorId
4652
4647
  && resolvePeerRoleDetail({ selfAid, channelKey: authorizationIdentity.originChannelKey, channelType: 'aun', chatType: 'private',
4653
- actorId: configActorId, conversationId: configActorId }).source === 'pa-team-default'),
4654
- paTeamPolicy: JSON.stringify(getRoleDefinition(peerRole, selfAid)),
4648
+ actorId: configActorId, conversationId: configActorId }).source === 'internal-contact-default'),
4649
+ internalContactPolicy: JSON.stringify(getRoleDefinition(peerRole, selfAid)),
4655
4650
  chatType: authChatType,
4656
4651
  selfAid,
4657
4652
  managedTempDir: sessionRuntimeDir,
@@ -5720,6 +5715,9 @@ export class ResponseEngine {
5720
5715
  } : {}),
5721
5716
  daemonRuntimeEpoch: this.agentDelegationRegistry?.getRuntimeEpoch(),
5722
5717
  threadId: sessionTopicThreadId(session),
5718
+ // 仅观测:入站消息的加密状态,供 ecmsg 的 --encrypt auto 沿用。
5719
+ ...(message.replyContext?.metadata?.encrypted != null
5720
+ ? { inboundEncrypted: !!(message.replyContext.metadata.encrypted) } : {}),
5723
5721
  sessionRuntimeDir,
5724
5722
  runtimeLockDir: ensureRuntimeLockDir(sessionRuntimeDir),
5725
5723
  handoffIds: v2HandoffIds.length > 0 && v2HandoffDirection === 'target' ? v2HandoffIds : undefined,
@@ -6257,9 +6255,10 @@ export class ResponseEngine {
6257
6255
  // 由响应模式插件统一处理(InteractiveMode.afterProcess / ProactiveMode.afterProcess)
6258
6256
  const finalReplyText = streamResult.lastReplyText || streamResult.fullText;
6259
6257
  const visibleFinalReplyText = stripContextLimitErrorLines(finalReplyText);
6260
- const isNoopReply = !streamResult.isError
6258
+ const triggerNoopSentinel = message.source === 'trigger' ? message.triggerMeta?.noopSentinel : undefined;
6259
+ const isNoopReply = !!triggerNoopSentinel && !streamResult.isError
6261
6260
  && !isExpectedTerminalInterrupt(streamResult.terminalReason)
6262
- && isNoopText(visibleFinalReplyText, message.triggerMeta?.noopSentinel || undefined);
6261
+ && isNoopText(visibleFinalReplyText, triggerNoopSentinel);
6263
6262
  if (resolvedMode?.mode.afterProcess && !isNoopReply) {
6264
6263
  const flusherText = renderer.getFinalText();
6265
6264
  const fullText = flusherText.length >= (streamResult.fullText?.length || 0) ? flusherText : streamResult.fullText;
@@ -7161,7 +7160,7 @@ export class ResponseEngine {
7161
7160
  await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), errorPayload);
7162
7161
  }
7163
7162
  // Proactive 可观测:catch 块的基础设施错误也透传为 thought,保证按 task_id 聚合完整
7164
- if (isProactive && adapter.capabilities?.thought) {
7163
+ if (isProactive && adapter.capabilities?.thought && middleOutputMode === 'all') {
7165
7164
  await adapter.send(withEnvelopeReplyContext(envelope, sendOpts), {
7166
7165
  kind: 'activity.batch',
7167
7166
  items: [{
@@ -0,0 +1,40 @@
1
+ /**
2
+ * 托管发送的选项表——**唯一事实源**。
3
+ *
4
+ * 为什么单独成一个模块:这些选项原本在 `aun-commands.ts` 的 `resolveManagedSendArgv`
5
+ * 里内联定义,`ecmsg` 网关又维护了一份自己的表。两份表一旦漂移,就会出现
6
+ * "某个参数在一边能过、在另一边被当成正文"的静默错误。
7
+ *
8
+ * 本模块无任何依赖,`ecmsg` 可以安全引用(它刻意避免加载 aun-commands 那套重模块)。
9
+ */
10
+ /** 取一个值的选项(`ec msg|group send` 的权威列表)。 */
11
+ export const MANAGED_SEND_VALUE_FLAGS = [
12
+ '--format', '--file', '--payload', '--payload-file', '--text-from-file',
13
+ '--link', '--title', '--description', '--as', '--content-type', '--text',
14
+ '--transcript', '--thread', '--check-every', '--trigger-prompt',
15
+ '--return', '--timeout', '--handoff-context', '--mention', '--self', '--device-id',
16
+ ];
17
+ /** 布尔选项。 */
18
+ export const MANAGED_SEND_BOOLEAN_FLAGS = [
19
+ '--encrypt', '--no-encrypt', '--mention-all',
20
+ ];
21
+ /**
22
+ * 网关自己消费、不向下游透传的选项。
23
+ *
24
+ * 注意 `--encrypt` / `--no-encrypt` 在网关侧语义不同:网关接受
25
+ * `--encrypt yes|no|auto`(三态),解析后向下游下发二态。
26
+ */
27
+ export const GATEWAY_ROUTE_VALUE_FLAGS = [
28
+ '--thread', '--to', '--from', '--check-every', '--encrypt', '--format',
29
+ ];
30
+ /** 只有网关认识、`ec msg send` 不认识的选项。 */
31
+ export const GATEWAY_ONLY_VALUE_FLAGS = ['--to', '--from'];
32
+ /** 网关的别名映射:`--self` 与 `--from` 等价(托管发送里本端恒为会话本端)。 */
33
+ export const GATEWAY_FLAG_ALIASES = {
34
+ '--self': '--from',
35
+ };
36
+ /** 下游允许的选项总数,用于漂移自检。 */
37
+ export const MANAGED_SEND_KNOWN_FLAGS = [
38
+ ...MANAGED_SEND_VALUE_FLAGS,
39
+ ...MANAGED_SEND_BOOLEAN_FLAGS,
40
+ ];
@@ -0,0 +1,310 @@
1
+ /**
2
+ * 统一发送路由 —— 目标三元组解析(纯函数)
3
+ *
4
+ * 设计依据:`docs/send-routing/unified-send-routing-plan.md`
5
+ *
6
+ * 本模块只做**判定**,不做任何 IO:
7
+ * - 话题索引查询由调用方通过 `resolveThread` 注入
8
+ * - `--to` 的渠道/类型解析由调用方通过 `resolveTarget` 注入
9
+ * - 群 AID 的精确归一由调用方通过 `normalizeGroupId` 注入
10
+ *
11
+ * 之所以抽成纯函数:CLI(ecmsg 网关)、daemon(发送通道)、门禁(意图表达判定)
12
+ * 三处必须用**同一份**判定逻辑。历史上"文档一套、代码一套"的分裂正是在这里产生的。
13
+ *
14
+ * 核心不变量:
15
+ * I2 本端恒等于当前会话本端;`from` 出现且不等 → 立即失败
16
+ * I3 目标由 (self, peer, threadId) 唯一确定
17
+ * I4 跨话题 ⇔ threadId 不同 或 peer 不同
18
+ * I5 跨话题必有复查周期(缺省补默认);同话题永不建复查
19
+ * I6 加密默认 auto;只有目标对端是 AUN 时才能加密
20
+ */
21
+ import { canonicalizeMainTopicId, formatMainTopicId, isMainTopicId, mainTopicPeer, normalizeTopicAid, } from '../thread/topic-id.js';
22
+ // ── 常量 ────────────────────────────────────────────────────────────────
23
+ /** 跨话题缺省复查周期(plan 假设 A1)。改这里即可调整全局节奏。 */
24
+ export const DEFAULT_CROSS_TOPIC_CHECK_EVERY = '20m';
25
+ export const DEFAULT_CROSS_TOPIC_CHECK_EVERY_MS = 20 * 60_000;
26
+ /**
27
+ * 话题 id 形态:`thread-<ms>-<4位序号>-<4位hex>`。
28
+ *
29
+ * 与 `thread-service.ts` 的 THREAD_ID_RE 保持一致(那个常量未导出,且该模块
30
+ * 依赖 fs,不能被纯函数引用)。两侧改动必须同步。
31
+ */
32
+ const THREAD_TOPIC_ID_RE = /^thread-[0-9]+-[0-9a-f]{4}-[0-9a-f]{4}$/;
33
+ /** 时长语法:`<正整数><d|h|m|s>`。与 trigger/parser.ts 的 parseDuration 同口径。 */
34
+ const DURATION_RE = /^([1-9]\d*)([dhms])$/;
35
+ // ── 基础工具 ────────────────────────────────────────────────────────────
36
+ /** 解析时长;格式非法返回 null。 */
37
+ export function parseDurationToMs(value) {
38
+ const match = DURATION_RE.exec(String(value ?? '').trim().toLowerCase());
39
+ if (!match)
40
+ return null;
41
+ const amount = Number(match[1]);
42
+ const unit = match[2];
43
+ const multiplier = unit === 'd' ? 86_400_000
44
+ : unit === 'h' ? 3_600_000
45
+ : unit === 'm' ? 60_000 : 1_000;
46
+ return amount * multiplier;
47
+ }
48
+ /** 是否为独立话题 id(`thread-…`)。 */
49
+ export function isThreadTopicId(value) {
50
+ return typeof value === 'string' && THREAD_TOPIC_ID_RE.test(value);
51
+ }
52
+ /**
53
+ * 对端等值判定的规范形态。
54
+ *
55
+ * - AUN 私聊:去 `@`、转小写(AID 大小写不敏感)
56
+ * - AUN 群:去 `@`、转小写,并可经 `normalizeGroupId` 处理 base 简写
57
+ * - 非 AUN:仅 trim,**保持大小写**(`ou_xxx` 一类原生 ID 大小写敏感)
58
+ */
59
+ export function canonicalPeerKey(peer, deps = {}) {
60
+ const isAun = peer.channelType === 'aun';
61
+ let id = isAun
62
+ ? normalizeTopicAid(peer.id).toLowerCase()
63
+ : String(peer.id ?? '').trim();
64
+ if (isAun && peer.peerKind === 'group' && deps.normalizeGroupId) {
65
+ id = deps.normalizeGroupId(id);
66
+ }
67
+ return `${peer.channelType}|${peer.peerKind}|${id}`;
68
+ }
69
+ /** 两个对端是否指向同一目标。必须带 peerKind 与 channelType,否则不算同一个。 */
70
+ export function sameRoutePeer(a, b, deps = {}) {
71
+ return canonicalPeerKey(a, deps) === canonicalPeerKey(b, deps);
72
+ }
73
+ /**
74
+ * 当前会话的规范话题标识。
75
+ *
76
+ * 独立话题直接用它自己的 id;主会话用 `main:<self>:<peer>`(字典序规范形态)。
77
+ * 非 AUN 的原生 ID 拼不出主话题 id,此时返回空串,语义是"该渠道的主会话"。
78
+ */
79
+ export function currentTopicThreadId(session) {
80
+ if (session.threadId)
81
+ return session.threadId;
82
+ try {
83
+ return formatMainTopicId(session.selfAid, session.peerId);
84
+ }
85
+ catch {
86
+ return '';
87
+ }
88
+ }
89
+ /**
90
+ * 解析 `--thread`,只接受两种形态:`thread-…` 与 `main:<a>:<b>`。
91
+ *
92
+ * 明确拒绝:裸 `main`、`<peer>/main`、`<peer>/<id>`、裸对端 AID、`current`。
93
+ * 裸对端 AID 虽然能被 `resolveThreadRef` 宽松展开成主话题,但那是历史写法;
94
+ * 网关要求参数形态与实际语义一一对应,避免"看起来像对端其实是话题"的歧义。
95
+ */
96
+ function resolveThreadOption(raw, self, deps) {
97
+ const value = String(raw ?? '').trim();
98
+ const hint = (example) => `当前是回复本会话,可直接省略;指定话题请写 ${example}`;
99
+ if (!value) {
100
+ return fail('INVALID_THREAD_REF', '--thread 不能为空', hint('thread-… 或 main:<aidA>:<aidB>'));
101
+ }
102
+ if (value === 'current') {
103
+ return fail('INVALID_THREAD_REF', '--thread 不接受 current', '回复当前会话请直接省略 --thread');
104
+ }
105
+ if (isMainTopicId(value)) {
106
+ const peerId = mainTopicPeer(value, self);
107
+ if (!peerId) {
108
+ return fail('IDENTITY_MISMATCH', `主话题 ${value} 不属于当前本端 ${self}——主话题 id 由本端与对端共同构成`);
109
+ }
110
+ const threadId = canonicalizeMainTopicId(value) ?? value;
111
+ return { peer: { channelType: 'aun', peerKind: 'private', id: peerId }, threadId };
112
+ }
113
+ if (isThreadTopicId(value)) {
114
+ const info = deps.resolveThread?.(value);
115
+ if (!info) {
116
+ return fail('TOPIC_NOT_FOUND', `话题 ${value} 不存在于本端索引`, '用 ec thread list <对端AID> 查看可用话题');
117
+ }
118
+ if (normalizeTopicAid(info.selfAid) !== normalizeTopicAid(self)) {
119
+ return fail('IDENTITY_MISMATCH', `话题 ${value} 的本端是 ${info.selfAid},不是当前会话本端 ${self}`);
120
+ }
121
+ return { peer: info.peer, threadId: value };
122
+ }
123
+ return fail('INVALID_THREAD_REF', `--thread 只接受 thread-… 或 main:<aidA>:<aidB>,收到 "${value}"`, '裸对端 AID 不是话题 id;要指定对端请用 --to');
124
+ }
125
+ function fail(code, message, hint) {
126
+ return { ok: false, code, message, ...(hint ? { hint } : {}) };
127
+ }
128
+ // ── 主流程 ──────────────────────────────────────────────────────────────
129
+ /**
130
+ * 解析一次发送的目标三元组与派生约束。
131
+ *
132
+ * 判定顺序(与 plan 4.3 一致,失败即返回,异常均在发送前产生):
133
+ * 1. from 身份校验
134
+ * 2. --thread 形态与归属校验
135
+ * 3. --thread 与 --to 冲突校验
136
+ * 4. 跨话题判定
137
+ * 5. 复查周期
138
+ * 6. 加密模式
139
+ */
140
+ export function resolveSendRoute(input, session, deps = {}) {
141
+ const self = normalizeTopicAid(session.selfAid);
142
+ if (!self) {
143
+ return fail('IDENTITY_MISMATCH', '当前会话本端未知,无法确定发送者');
144
+ }
145
+ // 1. from 只允许等于会话本端
146
+ if (input.from !== undefined) {
147
+ const from = normalizeTopicAid(input.from);
148
+ if (from !== self) {
149
+ return fail('IDENTITY_MISMATCH', `from 必须是当前会话本端 ${self},收到 ${input.from}`, '托管会话里 from 恒等于本端,通常不需要写;若要联系其他对象请用 --to');
150
+ }
151
+ }
152
+ const currentPeer = {
153
+ channelType: session.channelType,
154
+ peerKind: session.chatType,
155
+ id: session.peerId,
156
+ };
157
+ const currentThread = currentTopicThreadId(session);
158
+ // 2. 目标解析:--thread > --to > 当前会话
159
+ let peer;
160
+ let threadId;
161
+ let source;
162
+ if (input.thread !== undefined) {
163
+ const resolved = resolveThreadOption(input.thread, self, deps);
164
+ if ('ok' in resolved)
165
+ return resolved;
166
+ peer = resolved.peer;
167
+ threadId = resolved.threadId;
168
+ source = { peer: 'thread', thread: 'thread' };
169
+ }
170
+ else if (input.to !== undefined) {
171
+ const targetId = String(input.to ?? '').trim();
172
+ if (!targetId) {
173
+ return fail('INVALID_ARGUMENT', '--to 不能为空', '省略 --to 表示发给当前会话对端');
174
+ }
175
+ const resolvedPeer = deps.resolveTarget?.(targetId) ?? {
176
+ channelType: session.channelType,
177
+ peerKind: session.chatType,
178
+ id: targetId,
179
+ };
180
+ if (!resolvedPeer.id) {
181
+ return fail('TARGET_UNRESOLVED', `无法解析 --to ${targetId}`);
182
+ }
183
+ peer = resolvedPeer;
184
+ const samePeer = sameRoutePeer(peer, currentPeer, deps);
185
+ if (samePeer) {
186
+ threadId = currentThread;
187
+ source = { peer: 'to', thread: 'session' };
188
+ }
189
+ else {
190
+ const derived = deriveMainTopicId(self, peer);
191
+ if (derived === undefined) {
192
+ return fail('TOPIC_REQUIRED', `--to ${targetId} 与当前对端不同,且该渠道的原生 ID 无法构成主话题`, '跨渠道发送请显式指定 --thread <话题id>(先用 ec thread list 查看或创建)');
193
+ }
194
+ threadId = derived;
195
+ source = { peer: 'to', thread: 'derived' };
196
+ }
197
+ }
198
+ else {
199
+ peer = currentPeer;
200
+ threadId = currentThread;
201
+ source = { peer: 'session', thread: 'session' };
202
+ }
203
+ // 3. --thread 与 --to 同时给出:对端必须一致
204
+ if (input.thread !== undefined && input.to !== undefined) {
205
+ const targetId = String(input.to ?? '').trim();
206
+ const explicitPeer = deps.resolveTarget?.(targetId) ?? {
207
+ channelType: session.channelType,
208
+ peerKind: session.chatType,
209
+ id: targetId,
210
+ };
211
+ if (!sameRoutePeer(explicitPeer, peer, deps)) {
212
+ return fail('TOPIC_CONFLICT', `--thread 指向 ${peer.id},--to 指向 ${explicitPeer.id},两者冲突`, '一次发送只能有一个目标:保留 --thread 或 --to 其中之一');
213
+ }
214
+ }
215
+ // 4. 跨话题判定
216
+ const crossTopic = !sameRoutePeer(peer, currentPeer, deps) || threadId !== currentThread;
217
+ // 5. 复查周期
218
+ let checkEveryMs;
219
+ let checkEveryDefaulted = false;
220
+ let checkEveryIgnored = false;
221
+ if (crossTopic) {
222
+ if (input.checkEvery === undefined) {
223
+ checkEveryMs = DEFAULT_CROSS_TOPIC_CHECK_EVERY_MS;
224
+ checkEveryDefaulted = true;
225
+ }
226
+ else {
227
+ const parsed = parseDurationToMs(input.checkEvery);
228
+ if (parsed === null) {
229
+ return fail('INVALID_ARGUMENT', `--check-every 时长非法:${input.checkEvery}`, '合法格式:5m、30m、2h、1d');
230
+ }
231
+ checkEveryMs = parsed;
232
+ }
233
+ }
234
+ else if (input.checkEvery !== undefined) {
235
+ // 同话题永不建复查:忽略而不是失败,回执里说明
236
+ checkEveryIgnored = true;
237
+ }
238
+ // 6. 加密
239
+ let encrypt = 'auto';
240
+ if (input.noEncrypt === true && input.encrypt !== undefined && input.encrypt !== 'no') {
241
+ return fail('INVALID_ARGUMENT', '--no-encrypt 与 --encrypt 互斥');
242
+ }
243
+ if (input.noEncrypt === true)
244
+ encrypt = 'no';
245
+ else if (input.encrypt !== undefined) {
246
+ if (!['yes', 'no', 'auto'].includes(input.encrypt)) {
247
+ return fail('INVALID_ARGUMENT', `--encrypt 只接受 yes|no|auto,收到 ${input.encrypt}`);
248
+ }
249
+ encrypt = input.encrypt;
250
+ }
251
+ if (peer.channelType !== 'aun' && encrypt === 'yes') {
252
+ return fail('ENCRYPT_UNSUPPORTED', `目标对端 ${peer.id} 不在 AUN 网络上(channel=${peer.channelType}),无法端到端加密`, '去掉 --encrypt 或改用 --encrypt no');
253
+ }
254
+ const encryptResolved = encrypt === 'auto' && peer.channelType === 'aun'
255
+ ? (input.inboundTriggered === true ? input.inboundEncrypted === true : false)
256
+ : encrypt === 'yes';
257
+ return {
258
+ ok: true,
259
+ self,
260
+ peer,
261
+ threadId,
262
+ crossTopic,
263
+ ...(checkEveryMs !== undefined ? { checkEveryMs } : {}),
264
+ checkEveryDefaulted,
265
+ checkEveryIgnored,
266
+ encrypt,
267
+ encryptResolved,
268
+ source,
269
+ };
270
+ }
271
+ /**
272
+ * 由 (本端, 对端) 推导主话题 id。
273
+ *
274
+ * 只有能构成合法 AID 段时才返回;非 AUN 原生 ID(`ou_xxx`)返回 undefined,
275
+ * 由调用方要求显式 `--thread`。
276
+ */
277
+ function deriveMainTopicId(self, peer) {
278
+ try {
279
+ return formatMainTopicId(self, peer.id);
280
+ }
281
+ catch {
282
+ // 非 AUN 原生 ID(`ou_xxx` / `wxid_xxx`)不是合法 AID 段,拼不出主话题。
283
+ // 这类目标必须显式给 --thread。
284
+ return undefined;
285
+ }
286
+ }
287
+ // ── 回执渲染 ────────────────────────────────────────────────────────────
288
+ /** 来源标注:让调用方分辨哪些值是系统补的。 */
289
+ function sourceLabel(source, field) {
290
+ const value = field === 'peer' ? source.peer : source.thread;
291
+ return value === 'session' ? '会话'
292
+ : value === 'thread' ? '传入'
293
+ : value === 'to' ? '传入'
294
+ : value === 'derived' ? '推导' : value;
295
+ }
296
+ /**
297
+ * 回执里的路由前缀(plan 9.1)。
298
+ *
299
+ * 格式:`from=<self> to=<id>(<来源>) thread=<threadId>(<来源>) chatType=<kind>`
300
+ * 推断补全的值标来源,全部为归一化后的实际生效值,不是输入原文。
301
+ */
302
+ export function formatRouteReceipt(route) {
303
+ const threadLabel = route.threadId ? route.threadId : 'main';
304
+ return [
305
+ `from=${route.self}`,
306
+ `to=${route.peer.id}(${sourceLabel(route.source, 'peer')})`,
307
+ `thread=${threadLabel}(${sourceLabel(route.source, 'thread')})`,
308
+ `chatType=${route.peer.peerKind}`,
309
+ ].join(' ');
310
+ }
@@ -0,0 +1,37 @@
1
+ import { findModelSpec } from '../../stats/price-resolver.js';
2
+ import { resolveCatalogModel } from './catalog-service.js';
3
+ import { parseModelId } from './context-window-suffix.js';
4
+ export function resolveModelCapabilities(evolcoreHome, modelId, options) {
5
+ const model = options.catalog ? resolveCatalogModel(options.catalog, modelId) : modelId;
6
+ const entry = options.catalog?.models.find(candidate => candidate.id === model);
7
+ const spec = findModelSpec(evolcoreHome, model);
8
+ const positiveToken = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 1;
9
+ const windowCandidates = [
10
+ [parseModelId(model).contextWindow, 'explicit-suffix'],
11
+ [options.runtimeContextWindow, 'runtime-report'],
12
+ [entry?.contextWindow, 'provider-catalog'],
13
+ [spec?.context_window, 'local-parameters'],
14
+ [options.fallbackContextWindow, 'safe-fallback'],
15
+ ];
16
+ const outputCandidates = [
17
+ [entry?.maxOutputTokens, 'provider-catalog'],
18
+ [spec?.max_output_tokens, 'local-parameters'],
19
+ [options.fallbackMaxOutputTokens ?? 8192, 'safe-fallback'],
20
+ ];
21
+ const window = windowCandidates.find(([value]) => positiveToken(value));
22
+ const output = outputCandidates.find(([value]) => positiveToken(value));
23
+ if (!window || !output)
24
+ throw new Error('No valid model capabilities for ' + model);
25
+ const contextWindow = Math.floor(window[0]);
26
+ return {
27
+ model,
28
+ contextWindow,
29
+ maxOutputTokens: Math.max(1, Math.min(Math.floor(output[0]), contextWindow - 1)),
30
+ contextWindowSource: window[1],
31
+ maxOutputTokensSource: output[1],
32
+ };
33
+ }
34
+ export function resolveAutoCompactWindow(contextWindow, maxOutputTokens, reserveTokens) {
35
+ const safetyReserve = Math.min(10_000, Math.floor(contextWindow * 0.05));
36
+ return Math.min(650_000, Math.max(1, contextWindow - Math.max(reserveTokens, maxOutputTokens, safetyReserve)));
37
+ }
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import path from 'node:path';
6
6
  import { clearRuntimeBaseagentModelDefaults } from '../../agents/baseagent.js';
7
+ import { buildModelRequestHeaders } from '../../agents/request-identity.js';
7
8
  import { activeBaseagent } from './config-scope.js';
8
9
  import { resolveEffective } from '../../config/config-manager.js';
9
10
  import { readRuntimeEnvironmentVariable } from '../../config/runtime-env.js';
@@ -137,7 +138,8 @@ export function resolveCatalogContext(self, ba) {
137
138
  if (envBaseUrl) {
138
139
  const envApiKey = readRuntimeEnvironmentVariable('ANTHROPIC_AUTH_TOKEN', self).value
139
140
  ?? readRuntimeEnvironmentVariable('ANTHROPIC_API_KEY', self).value;
140
- return { ...context, baseUrl: envBaseUrl, apiKey: envApiKey, style: 'claude' };
141
+ return { ...context, baseUrl: envBaseUrl, apiKey: envApiKey, style: 'claude',
142
+ headers: buildModelRequestHeaders({ baseagent: 'claude', baseUrl: envBaseUrl, agentAid: self }) };
141
143
  }
142
144
  }
143
145
  // 模型选择只在 Agent 级且必须指向 provider;没有 provider 就没有目录可查。
@@ -152,7 +154,9 @@ export function resolveCatalogContext(self, ba) {
152
154
  style: provider.style,
153
155
  baseUrl: provider.baseUrl,
154
156
  apiKey: provider.apiKey,
155
- headers: provider.headers,
157
+ headers: baseagent === 'claude' || baseagent === 'codex' || baseagent === 'ecagent'
158
+ ? buildModelRequestHeaders({ baseagent, baseUrl: provider.baseUrl, agentAid: self, configuredHeaders: provider.headers })
159
+ : provider.headers,
156
160
  queryParams: provider.queryParams,
157
161
  modelOverrides: provider.modelOverrides,
158
162
  });