evolcore 0.0.43-test.4 → 0.0.43-test.6

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 (186) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ecmsg.js +437 -91
  3. package/dist/agents/baseagent-availability.js +19 -4
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +14 -3
  7. package/dist/agents/codex-runner.js +18 -23
  8. package/dist/aun/aid/agentmd.js +25 -0
  9. package/dist/aun/aid/control-aid.js +15 -0
  10. package/dist/aun/aid/identity.js +8 -0
  11. package/dist/aun/aid/ownership-operation.js +12 -3
  12. package/dist/aun/group/invite-service.js +3 -2
  13. package/dist/aun/service-proxy.js +18 -6
  14. package/dist/channels/aun.js +99 -23
  15. package/dist/channels/daemon.js +2 -2
  16. package/dist/cli/agent-create.js +19 -7
  17. package/dist/cli/aid-bind-command.js +3 -0
  18. package/dist/cli/aun-commands.js +19 -4
  19. package/dist/cli/code-stats.js +451 -213
  20. package/dist/cli/ctl-command.js +1 -3
  21. package/dist/cli/daemon-commands.js +42 -4
  22. package/dist/cli/directory.js +3 -1
  23. package/dist/cli/ecmsg-gateway.js +206 -0
  24. package/dist/cli/index.js +6 -0
  25. package/dist/cli/init.js +120 -13
  26. package/dist/cli/provider-command.js +82 -5
  27. package/dist/cli/restart-monitor.js +35 -24
  28. package/dist/cli/stats.js +8 -1
  29. package/dist/cli/task-context.js +41 -1
  30. package/dist/cli/watch-logs.js +6 -4
  31. package/dist/config/boot-log.js +16 -3
  32. package/dist/config/builtin-roles.js +2 -2
  33. package/dist/config/config-manager.js +5 -14
  34. package/dist/config/daemon-services.js +1 -0
  35. package/dist/config/peer-role-resolver.js +6 -6
  36. package/dist/config/provider-identity-migration.js +277 -0
  37. package/dist/config/provider-identity.js +37 -0
  38. package/dist/config/provider-ipc-service.js +40 -3
  39. package/dist/config/provider-local-sync.js +155 -0
  40. package/dist/config/providers-config.js +45 -4
  41. package/dist/config/providers-management.js +242 -76
  42. package/dist/config/providers.js +4 -1
  43. package/dist/config/role-service.js +8 -8
  44. package/dist/config/role-store.js +22 -22
  45. package/dist/config/schema-migration.js +143 -86
  46. package/dist/config/snapshot.js +70 -41
  47. package/dist/core/agent-runtime.js +48 -9
  48. package/dist/core/auth/auth-gateway.js +5 -3
  49. package/dist/core/auth/delegation-diagnostics.js +6 -2
  50. package/dist/core/auth/operation-authorizer.js +3 -1
  51. package/dist/core/auth/operation-catalog.js +6 -4
  52. package/dist/core/baseagent-loader.js +114 -11
  53. package/dist/core/channel-loader.js +36 -13
  54. package/dist/core/channel-runtime.js +112 -42
  55. package/dist/core/command/cli-intent-parser.js +2 -1
  56. package/dist/core/command/command-handler.js +16 -11
  57. package/dist/core/command/menu-handler.js +8 -3
  58. package/dist/core/command/menu-protocol.js +80 -7
  59. package/dist/core/command/provider-menu.js +4 -2
  60. package/dist/core/command/role-menu.js +29 -17
  61. package/dist/core/command/slash-handler.js +52 -16
  62. package/dist/core/daemon-control.js +42 -15
  63. package/dist/core/daemon-lifecycle.js +411 -67
  64. package/dist/core/handoff/dispatcher.js +9 -3
  65. package/dist/core/handoff/runtime.js +139 -45
  66. package/dist/core/handoff/store.js +190 -2
  67. package/dist/core/handoff/types.js +5 -0
  68. package/dist/core/initialization/service.js +7 -6
  69. package/dist/core/ipc-registration.js +5 -4
  70. package/dist/core/lifecycle-notice.js +10 -4
  71. package/dist/core/message/aun-ipc-sender.js +83 -5
  72. package/dist/core/message/message-admission.js +2 -0
  73. package/dist/core/message/message-bridge.js +53 -4
  74. package/dist/core/message/message-queue.js +46 -4
  75. package/dist/core/message/pending-hints.js +4 -10
  76. package/dist/core/message/response-engine.js +33 -25
  77. package/dist/core/message/send-options.js +40 -0
  78. package/dist/core/message/send-routing.js +320 -0
  79. package/dist/core/ownership/owner-resolver.js +112 -8
  80. package/dist/core/permission/ec-command-parser.js +159 -16
  81. package/dist/core/permission/readonly-shell-query.js +66 -7
  82. package/dist/core/permission/tool-error-code.js +13 -1
  83. package/dist/core/permission/tool-policy.js +74 -20
  84. package/dist/core/relation/same-owner-proof.js +131 -0
  85. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  86. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  87. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  88. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  89. package/dist/core/session/session-fs-store.js +164 -3
  90. package/dist/core/session/session-idle-monitor.js +103 -17
  91. package/dist/core/session/session-manager.js +105 -18
  92. package/dist/core/thread/thread-route.js +5 -2
  93. package/dist/directory/owner-directory-admission.js +26 -1
  94. package/dist/directory/owner-directory-cache.js +739 -109
  95. package/dist/directory/owner-directory-markdown.js +146 -36
  96. package/dist/directory/owner-directory-query-operation.js +6 -3
  97. package/dist/directory/owner-directory-scope.js +12 -0
  98. package/dist/directory/owner-directory-search.js +5 -1
  99. package/dist/directory/owner-directory-store.js +28 -0
  100. package/dist/ecweb/basic-settings-service.js +15 -1
  101. package/dist/ecweb/message-context-service.js +2 -2
  102. package/dist/ecweb/providers-service.js +3 -1
  103. package/dist/ecweb/runtime/lifecycle.js +26 -15
  104. package/dist/ecweb/runtime/supervisor.js +120 -51
  105. package/dist/index.js +551 -250
  106. package/dist/paths.js +2 -1
  107. package/dist/proxy/manager.js +40 -17
  108. package/dist/proxy/service-supervisor.js +67 -33
  109. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  110. package/dist/trigger/application-service.js +4 -1
  111. package/dist/trigger/audit.js +19 -4
  112. package/dist/trigger/authorization.js +14 -5
  113. package/dist/trigger/event-source.js +4 -0
  114. package/dist/trigger/feedback.js +26 -2
  115. package/dist/trigger/history.js +176 -7
  116. package/dist/trigger/manager.js +1 -3
  117. package/dist/trigger/scheduler.js +81 -8
  118. package/dist/trigger/system-definitions.js +2 -2
  119. package/dist/trigger/validation.js +4 -0
  120. package/dist/utils/autostart.js +2 -2
  121. package/dist/utils/cross-platform.js +188 -12
  122. package/dist/utils/host-info.js +11 -8
  123. package/dist/utils/npm-ops.js +48 -0
  124. package/dist/utils/process-introspect.js +64 -1
  125. package/dist/utils/public-suffix.js +5811 -0
  126. package/dist/utils/startup-trace.js +160 -19
  127. package/dist/utils/windows-autostart.js +41 -7
  128. package/ecagent/dist/harness/env/nodejs.js +46 -2
  129. package/kits/docs/aun/ABILITY_CALLING.md +6 -6
  130. package/kits/docs/channels/aun.md +1 -1
  131. package/kits/docs/channels/feishu.md +2 -2
  132. package/kits/docs/context-assembly.md +20 -4
  133. package/kits/docs/evolcore/INDEX.md +5 -3
  134. package/kits/docs/evolcore/agent.md +2 -2
  135. package/kits/docs/evolcore/aid.md +8 -2
  136. package/kits/docs/evolcore/ctl.md +15 -5
  137. package/kits/docs/evolcore/directory.md +48 -15
  138. package/kits/docs/evolcore/group.md +8 -8
  139. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  140. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  141. package/kits/docs/evolcore/menu-protocol.md +32 -3
  142. package/kits/docs/evolcore/msg.md +38 -30
  143. package/kits/docs/evolcore/provider.md +57 -5
  144. package/kits/docs/evolcore/response.md +2 -2
  145. package/kits/docs/evolcore/thread-chain.md +11 -13
  146. package/kits/docs/evolcore/tool-authorization.md +17 -0
  147. package/kits/docs/evolcore/trigger.md +2 -2
  148. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  149. package/kits/docs/prompt-loading-architecture.md +30 -20
  150. package/kits/eck_manifest.auxiliary.json +5 -5
  151. package/kits/eck_manifest.json +44 -32
  152. package/kits/eck_manifest.memory.json +18 -18
  153. package/kits/eck_message_manifest.json +3 -3
  154. package/kits/rules/01-overview.md +1 -1
  155. package/kits/rules/06-channel.md +7 -8
  156. package/kits/schemas/_meta.json +7 -1
  157. package/kits/schemas/daemon.schema.1.json +5 -0
  158. package/kits/schemas/daemon.schema.2.json +5 -0
  159. package/kits/schemas/daemon.schema.3.json +2 -1
  160. package/kits/schemas/daemon.schema.4.json +2 -1
  161. package/kits/schemas/daemon.schema.5.json +2 -1
  162. package/kits/schemas/daemon.schema.6.json +1 -1
  163. package/kits/schemas/daemon.schema.7.json +1 -1
  164. package/kits/schemas/daemon.schema.8.json +2 -1
  165. package/kits/schemas/daemon.schema.9.json +2 -1
  166. package/kits/schemas/providers.schema.2.json +74 -0
  167. package/kits/schemas/role-registry.schema.1.json +2 -2
  168. package/kits/schemas/single-session.schema.1.json +1 -1
  169. package/kits/schemas/single-session.schema.2.json +1 -1
  170. package/kits/schemas/single-session.schema.3.json +1 -1
  171. package/kits/skills/aid-ability/SKILL.md +7 -7
  172. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  173. package/kits/skills/ec-group/SKILL.md +8 -5
  174. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  175. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  176. package/kits/skills/ec-trigger/SKILL.md +9 -9
  177. package/kits/skills/ec-trigger/references/examples.md +1 -1
  178. package/kits/skills/thread-ops/SKILL.md +10 -10
  179. package/kits/templates/system-fragments/channel.md +5 -5
  180. package/kits/templates/system-fragments/commands.md +7 -6
  181. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  182. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  183. package/kits/templates/system-fragments/reply.md +48 -28
  184. package/kits/templates/system-fragments/session.md +3 -10
  185. package/kits/templates/system-fragments/thread.md +5 -5
  186. package/package.json +4 -4
@@ -16,6 +16,8 @@ import { sameGroupAid } from '../../aun/group/identity.js';
16
16
  import { resolveThreadRouteTarget } from '../thread/thread-route.js';
17
17
  import { isTopicThreadId, parseMainTopicId, safeFormatMainTopicId, sessionLocalTopicId } from '../thread/topic-id.js';
18
18
  import { ThreadService } from '../thread/thread-service.js';
19
+ import { buildEnvelope } from './message-utils.js';
20
+ import { sessionTopicThreadId } from '../thread/topic-id.js';
19
21
  import { getAunRequestRegistry, requestDiagnostics, requestTtlSeconds } from './aun-request-registry.js';
20
22
  import { parseJsonObjectArgument } from '../permission/ec-command-parser.js';
21
23
  import { parsePeerKey } from '../relation/peer-identity.js';
@@ -36,9 +38,18 @@ export function createAunHandoffSender(sessionManager, channelInstances, getOutb
36
38
  const targetSession = await sessionManager.getSessionById(handoff.target_session_id);
37
39
  if (!targetSession)
38
40
  return { ok: false, error: 'target session not found' };
39
- const instance = channelInstances.find(candidate => (candidate.channelType === 'aun' && (candidate.adapter.channelKey === targetSession.metadata?.channelKey
41
+ // 目标会话可能属于任意渠道。先按该会话自己的 channelKey/渠道实例匹配,
42
+ // 只有拿到 AUN 渠道实例时才走 AUN 专用发送路径;其它渠道走通用 adapter。
43
+ const instance = channelInstances.find(candidate => (candidate.adapter.channelKey === targetSession.metadata?.channelKey
40
44
  || candidate.adapter.channelName === targetSession.channel
41
- || tryParseChannelKey(candidate.adapter.channelKey)?.selfAID === targetSession.selfAID)));
45
+ || (candidate.channelType === 'aun'
46
+ && tryParseChannelKey(candidate.adapter.channelKey)?.selfAID === targetSession.selfAID)));
47
+ if (!instance) {
48
+ return { ok: false, error: `channel not found for session ${targetSession.id}` };
49
+ }
50
+ if (instance.channelType !== 'aun') {
51
+ return sendViaSessionAdapter(handoff, targetSession, instance, getOutboundDebug);
52
+ }
42
53
  const channel = instance?.channel;
43
54
  if (!channel) {
44
55
  return { ok: false, error: `AUN channel not found for ${targetSession.selfAID || '<unknown>'}` };
@@ -87,6 +98,57 @@ export function createAunHandoffSender(sessionManager, channelInstances, getOutb
87
98
  return { ok: result.ok, message_id: result.message_id, error: result.error };
88
99
  };
89
100
  }
101
+ /**
102
+ * 跨会话投递到**非 AUN 渠道**的目标会话。
103
+ *
104
+ * 与 AUN 路径的区别只在投递方式:非 AUN 渠道没有 `sendDaemonMsg`,统一走
105
+ * adapter 的通用 `send(envelope, payload)`。目标会话已由 `createOutbound`
106
+ * 建好(`channelKey` / `channelId` / `threadId` 都来自该会话),这里只负责
107
+ * 把正文投出去。
108
+ *
109
+ * 边界:只支持文本正文。文件/链接/payload 的跨渠道投递尚未验证,明确报错
110
+ * 而不是静默丢弃。
111
+ */
112
+ async function sendViaSessionAdapter(handoff, targetSession, instance, getOutboundDebug) {
113
+ const payload = handoff.request.payload;
114
+ const text = typeof payload?.text === 'string' ? payload.text : '';
115
+ if (!text.trim()) {
116
+ return { ok: false, error: 'cross-channel handoff currently supports text payloads only' };
117
+ }
118
+ const threadId = sessionTopicThreadId(targetSession);
119
+ // 投递目标以**目标会话自身**为准,不依赖 request.delivery(那是 AUN 路由字段)。
120
+ const delivery = targetSession.chatType === 'group'
121
+ ? { chatType: 'group', groupId: targetSession.metadata?.groupId ?? targetSession.channelId }
122
+ : { chatType: 'private' };
123
+ const envelope = buildEnvelope({
124
+ taskId: `handoff:${handoff.handoff_id}`,
125
+ channel: instance.adapter.channelKey,
126
+ channelId: targetSession.channelId,
127
+ agentName: targetSession.selfAID,
128
+ causation: handoff.causation,
129
+ replyContext: {
130
+ delivery,
131
+ ...(threadId ? { threadId } : {}),
132
+ ...(typeof handoff.request.encrypt === 'boolean'
133
+ ? { metadata: { encrypted: handoff.request.encrypt } }
134
+ : {}),
135
+ },
136
+ });
137
+ try {
138
+ const receipt = await instance.adapter.send(envelope, { kind: 'result.text', text, isFinal: true });
139
+ if (receipt && typeof receipt === 'object' && 'status' in receipt) {
140
+ const status = receipt.status;
141
+ if (status === 'failed') {
142
+ return { ok: false, error: String(receipt.error ?? 'send failed') };
143
+ }
144
+ return { ok: true, message_id: receipt.messageId };
145
+ }
146
+ return { ok: true };
147
+ }
148
+ catch (error) {
149
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
150
+ }
151
+ }
90
152
  async function applyManagedCrossThreadSendEffects(input) {
91
153
  const originSessionId = input.grant.sessionId;
92
154
  const originPeer = parsePeerKey(input.grant.peerKey).channelId;
@@ -134,7 +196,11 @@ async function applyManagedCrossThreadSendEffects(input) {
134
196
  prompt,
135
197
  everyMs: input.durationMs,
136
198
  checkEvery: input.checkEveryLabel,
137
- channelKey: formatChannelKey({ type: 'aun', selfAID: input.selfAid, name: 'main' }),
199
+ // 目标话题所属渠道:从话题索引取,取不到时按 AUN 主渠兜底(历史行为)。
200
+ // 硬写 AUN 会让飞书等渠道的目标话题把 Trigger 的 feedback.target 指向错渠道。
201
+ channelKey: targetEntry?.channelType
202
+ ? formatChannelKey({ type: targetEntry.channelType, selfAID: input.selfAid, name: 'main' })
203
+ : formatChannelKey({ type: 'aun', selfAID: input.selfAid, name: 'main' }),
138
204
  targetChannelId: input.targetChannelId,
139
205
  targetThreadId: input.targetThreadId,
140
206
  originThreadId,
@@ -282,11 +348,11 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
282
348
  const session = await sessionManager.getSessionById(params.originSessionId);
283
349
  if (session) {
284
350
  const { buildDebugTaskContext } = await import('../auth/debug-context.js');
285
- const { ensureSessionRuntimeDir } = await import('../../cli/task-context.js');
351
+ const { ensureSessionRuntimeDirAsync } = await import('../../cli/task-context.js');
286
352
  runtime = buildDebugTaskContext({
287
353
  session,
288
354
  getTrigger: (agentAid, triggerId) => new TriggerDefinitionManager(agentAid).get(triggerId),
289
- sessionRuntimeDir: ensureSessionRuntimeDir(session.id),
355
+ sessionRuntimeDir: await ensureSessionRuntimeDirAsync(session.id),
290
356
  });
291
357
  }
292
358
  }
@@ -545,6 +611,18 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
545
611
  encrypt,
546
612
  thread: params.thread,
547
613
  targetChatType: params.scope === 'group' ? 'group' : 'private',
614
+ // 目标会话可能属于别的渠道(如飞书话题):带上它自己的 channelKey,
615
+ // 否则会按 AUN 主渠建会话,投递到错误的渠道。
616
+ ...(threadRoute?.channelType
617
+ ? {
618
+ targetChannelType: threadRoute.channelType,
619
+ targetChannelKey: formatChannelKey({
620
+ type: threadRoute.channelType,
621
+ selfAID: params.aid,
622
+ name: 'main',
623
+ }),
624
+ }
625
+ : {}),
548
626
  explicitReturnPolicy: params.returnPolicy,
549
627
  handoffContext: params.handoffContext,
550
628
  // 跨话题发送的目标侧上下文由话题链(thread-inbox)负责注入;
@@ -4,6 +4,7 @@ import { isValidAid } from '../../aun/aid/validation.js';
4
4
  import { readOwnerDirectoryMembership } from '../../directory/owner-directory-admission.js';
5
5
  import { resolveAunPeerKind } from '../relation/peer-identity.js';
6
6
  import { evaluateAppContactAdmission } from './contact-admission.js';
7
+ import { ownerResolver, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
7
8
  /**
8
9
  * AUN 出站私聊固定使用 app-v1,与入站保持相同的绑定和联系人判定。
9
10
  * 群聊的准入单位是群,出站到群不做发言人判定。
@@ -21,6 +22,7 @@ export async function evaluateOutboundContactAdmission(input) {
21
22
  return { allow: true, status: 'group' };
22
23
  let decision;
23
24
  try {
25
+ await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
24
26
  decision = evaluateAppContactAdmission(selfAid, targetAid);
25
27
  }
26
28
  catch (error) {
@@ -7,6 +7,7 @@ import path from 'path';
7
7
  import { agentStorageMenuService, isAgentStorageMenuRequest } from '../command/agent-storage-menu.js';
8
8
  import { agentMdMenuService } from '../command/agentmd-menu.js';
9
9
  import { containsAgentMdMenuRequest } from '../command/agentmd-menu-request.js';
10
+ import { currentContactBinding, sameContactBinding } from './contact-admission.js';
10
11
  import { logger, logPreview } from '../../utils/logger.js';
11
12
  import { StreamDebouncer } from './stream-debouncer.js';
12
13
  import { appendMessageLog, appendMessageLogStrict, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
@@ -29,7 +30,7 @@ import { AutoMentionGate } from './auto-mention-gate.js';
29
30
  import { syncGroupRulesContext } from '../../eck/group-rules-sync.js';
30
31
  import { readSoulContent } from '../soul.js';
31
32
  import { authorizeAccess, buildAuthSubject } from '../auth/auth-gateway.js';
32
- import { MenuDiagnosticLimiter, MenuRequestDeduper, hasValidMenuId, menuFailure, menuPayloadFingerprint, menuSuccess, normalizeMenuError, parseMenuControl, validateMenuRequest, evaluateEvolMenuVersionGate, evolMenuResponseTransportMetadata, isAunMenuTokenRequired, menuCommandForName, normalizeMenuResponseTiming, withMenuProcessingTime, logMenuRequestCompleted, logMenuRequestReceived, } from '../command/menu-protocol.js';
33
+ import { MenuDiagnosticLimiter, deliverMenuResponse, isRetryableMenuTransportError, MenuRequestDeduper, hasValidMenuId, menuFailure, menuPayloadFingerprint, menuSuccess, normalizeMenuError, parseMenuControl, validateMenuRequest, evaluateEvolMenuVersionGate, evolMenuResponseTransportMetadata, isAunMenuTokenRequired, menuCommandForName, normalizeMenuResponseTiming, withMenuProcessingTime, beginMenuDeliveryTiming, logMenuRequestCompleted, logMenuRequestReceived, logMenuResponseRetry, } from '../command/menu-protocol.js';
33
34
  import { resolveExplicitMenuExecutionContext, validateMenuCatalogArgs, validateMenuValueBatchArgs } from '../command/menu-catalog.js';
34
35
  import { MenuTokenStore } from '../command/menu-token-store.js';
35
36
  import { SessionRenewService } from '../session/session-renew.js';
@@ -1785,7 +1786,11 @@ export class MessageBridge {
1785
1786
  }
1786
1787
  }
1787
1788
  catch (error) {
1788
- logger.error(`[MessageBridge] Error in onMessage handler for ${channelName}:`, error);
1789
+ if (isRetryableMenuTransportError(error)) {
1790
+ logger.warn(`[MessageBridge] Retryable response delivery unavailable for ${channelName}:`, error);
1791
+ }
1792
+ else
1793
+ logger.error(`[MessageBridge] Error in onMessage handler for ${channelName}:`, error);
1789
1794
  }
1790
1795
  finally {
1791
1796
  releaseAdmission?.();
@@ -2182,9 +2187,51 @@ export class MessageBridge {
2182
2187
  agentName,
2183
2188
  replyContext,
2184
2189
  });
2190
+ const selfAid = this.menuTokenOwnerAid(channel, msg);
2191
+ const binding = selfAid ? currentContactBinding(selfAid) : undefined;
2192
+ const currentSubject = () => buildAuthSubject({
2193
+ selfAid, actorId: msg.peerId, channel, channelType: msg.channelType || 'aun',
2194
+ channelId: msg.channelId, chatType: msg.chatType || 'private', conversationId: msg.channelId,
2195
+ peerType: msg.peerType,
2196
+ roleDetail: this.resolveInboundRole({ selfAid, channelKey: channel, channelType: msg.channelType || 'aun',
2197
+ chatType: msg.chatType || 'private', actorId: msg.peerId, conversationId: msg.channelId, peerType: msg.peerType }),
2198
+ fromControlChannel: msg.isControlChannel, processOwners: [...(this.processOwnersProvider?.() ?? [])],
2199
+ });
2200
+ // A changed role must not receive a cached response authorized by its old role.
2201
+ const initialSubject = msg.channelType === 'aun' && !response.error ? currentSubject() : undefined;
2202
+ const deliveryTiming = beginMenuDeliveryTiming(msg);
2203
+ let deliveryOutcome;
2185
2204
  try {
2186
- await adapter.send(envelope, { kind: 'custom', channelType: channel, payload: timedResponse });
2187
- logMenuRequestCompleted(request, timedResponse, flowContext, { delivery: 'sent' });
2205
+ await deliverMenuResponse(async () => {
2206
+ Object.assign(timedResponse, withMenuProcessingTime(timedResponse, msg));
2207
+ await adapter.send(envelope, { kind: 'custom', channelType: channel, payload: timedResponse });
2208
+ }, {
2209
+ canRetry: async () => {
2210
+ if (msg.channelType !== 'aun' || !selfAid || !binding
2211
+ || !sameContactBinding(binding, currentContactBinding(selfAid)))
2212
+ return false;
2213
+ if (this.processor.getChannelInfo?.(channel)?.adapter !== adapter)
2214
+ return false;
2215
+ if (response.error)
2216
+ return true;
2217
+ const subject = currentSubject();
2218
+ if (!authorizeAccess(subject).allow || subject.role !== initialSubject?.role
2219
+ || subject.processRole !== initialSubject.processRole)
2220
+ return false;
2221
+ if (isAunMenuTokenRequired() && request.type !== 'menu.token.request'
2222
+ && !this.menuTokenStore.use(selfAid, msg.peerId, request.menu_token, { deviceId: msg.peerDeviceId, slotId: msg.peerSlotId }))
2223
+ return false;
2224
+ if (isAgentStorageMenuRequest(request))
2225
+ agentStorageMenuService.preflight(request, { ...subject, menuEncrypted: msg.encrypted === true }, false);
2226
+ if (containsAgentMdMenuRequest(request))
2227
+ await agentMdMenuService.preflight({ ...subject, menuEncrypted: msg.encrypted === true, menuTransportChatType: msg.chatType || 'private' });
2228
+ return sameContactBinding(binding, currentContactBinding(selfAid))
2229
+ && this.processor.getChannelInfo?.(channel)?.adapter === adapter;
2230
+ },
2231
+ onRetry: (attempt, error, delay) => logMenuResponseRetry(request, flowContext, attempt, delay, error),
2232
+ onComplete: outcome => { deliveryOutcome = outcome; },
2233
+ });
2234
+ logMenuRequestCompleted(request, timedResponse, flowContext, { delivery: 'sent', ...deliveryOutcome, ...deliveryTiming() });
2188
2235
  const upgradeData = 'data' in response ? response.data : undefined;
2189
2236
  if (request.type === 'menu.action' && request.action === 'upgrade' && (request.name === 'system' || request.cmd === '/system') && upgradeData?.jobId) {
2190
2237
  const jobId = upgradeData.jobId;
@@ -2201,6 +2248,8 @@ export class MessageBridge {
2201
2248
  delivery: 'failed',
2202
2249
  reason: 'transport-error',
2203
2250
  transportError: error,
2251
+ ...deliveryOutcome,
2252
+ ...deliveryTiming(),
2204
2253
  });
2205
2254
  throw error;
2206
2255
  }
@@ -50,12 +50,16 @@ export class MessageQueue {
50
50
  queueKeyToSessionKey = new Map(); // queueKey → sessionKey(human-readable 格式)
51
51
  droppedTriggerSessionIds = new Set();
52
52
  shuttingDown = false;
53
+ blockedReason;
54
+ blockedQueues = new Map();
55
+ readinessRetry;
53
56
  shutdownPromise;
54
57
  /** 逻辑队列桥接:管理出队顺序(响应模式可注入自定义策略,默认 FIFO) */
55
58
  logicalQueue = new LogicalQueueBridge();
56
59
  enqueueSequence = 0;
57
60
  constructor(handler, options) {
58
61
  this.handler = handler;
62
+ this.blockedReason = options?.blockedReason;
59
63
  this.persistencePath = options?.persistencePath;
60
64
  this.dedupPath = options?.dedupPath
61
65
  ?? (this.persistencePath ? `${this.persistencePath}.dedup.json` : undefined);
@@ -694,6 +698,9 @@ export class MessageQueue {
694
698
  if (this.shutdownPromise)
695
699
  return this.shutdownPromise;
696
700
  this.shuttingDown = true;
701
+ if (this.readinessRetry)
702
+ clearTimeout(this.readinessRetry);
703
+ this.readinessRetry = undefined;
697
704
  const allActive = Array.from(this.activeBatches.entries());
698
705
  const active = allActive.filter(([queueKey]) => !this.activeTerminalReasons.has(queueKey));
699
706
  const barriers = [];
@@ -942,11 +949,32 @@ export class MessageQueue {
942
949
  return restored;
943
950
  }
944
951
  startRestored() {
952
+ if (this.shuttingDown)
953
+ return;
945
954
  for (const [queueKey, queue] of this.queues) {
946
955
  if (queue.length > 0 && !this.processing.has(queueKey))
947
956
  void this.processNext(queueKey);
948
957
  }
949
958
  }
959
+ retryBlockedQueues() {
960
+ if (this.readinessRetry || this.shuttingDown)
961
+ return;
962
+ this.readinessRetry = setTimeout(() => {
963
+ this.readinessRetry = undefined;
964
+ for (const key of this.blockedQueues.keys()) {
965
+ const head = this.queues.get(key)?.[0];
966
+ if (!head) {
967
+ this.blockedQueues.delete(key);
968
+ continue;
969
+ }
970
+ if (!this.processing.has(key) && !this.blockedReason?.(head.message))
971
+ void this.processNext(key);
972
+ }
973
+ if (this.blockedQueues.size)
974
+ this.retryBlockedQueues();
975
+ }, 1000);
976
+ this.readinessRetry.unref?.();
977
+ }
950
978
  consumeDroppedTriggerSessionIds() {
951
979
  const sessionIds = [...this.droppedTriggerSessionIds];
952
980
  this.droppedTriggerSessionIds.clear();
@@ -1221,6 +1249,7 @@ export class MessageQueue {
1221
1249
  }
1222
1250
  const queue = this.queues.get(queueKey);
1223
1251
  if (!queue || queue.length === 0) {
1252
+ this.blockedQueues.delete(queueKey);
1224
1253
  logger.info(`[Queue] processNext: queue empty, releasing key=${queueKey}`);
1225
1254
  this.processing.delete(queueKey);
1226
1255
  this.processingAgent.delete(queueKey);
@@ -1239,6 +1268,19 @@ export class MessageQueue {
1239
1268
  // 逻辑队列重排:让响应模式的出队策略决定队首(默认 FIFO,不改变顺序)
1240
1269
  if (queue[0]?.message.source !== 'owner-inject' && queue[0]?.message.attentionPolicy !== 'interrupt')
1241
1270
  this.logicalQueue.reorderPhysical(queueKey, queue);
1271
+ const blocked = this.blockedReason?.(queue[0].message);
1272
+ if (blocked) {
1273
+ if (this.blockedQueues.get(queueKey) !== blocked) {
1274
+ logger.info(`[Queue] waiting: key=${queueKey} dependency=${blocked}`);
1275
+ }
1276
+ this.blockedQueues.set(queueKey, blocked);
1277
+ this.processing.delete(queueKey);
1278
+ this.processingAgent.delete(queueKey);
1279
+ this.activeStates.delete(queueKey);
1280
+ this.retryBlockedQueues();
1281
+ return;
1282
+ }
1283
+ this.blockedQueues.delete(queueKey);
1242
1284
  // 贪心合并:群聊按完整时间线,旧路径/私聊按 peerId
1243
1285
  const items = this.dequeueGreedy(queue);
1244
1286
  // 同步逻辑队列:移除所有被合并处理的消息
@@ -1385,7 +1427,7 @@ export class MessageQueue {
1385
1427
  const first = queue.shift();
1386
1428
  const result = [first];
1387
1429
  if (this.isOriginHandoff(first.message)) {
1388
- while (queue.length > 0 && this.canMergeOriginHandoffs(first, queue[0])) {
1430
+ while (queue.length > 0 && !this.blockedReason?.(queue[0].message) && this.canMergeOriginHandoffs(first, queue[0])) {
1389
1431
  result.push(queue.shift());
1390
1432
  }
1391
1433
  if (result.length > 1) {
@@ -1401,7 +1443,7 @@ export class MessageQueue {
1401
1443
  if (mergeSubmittedResume) {
1402
1444
  const remaining = [];
1403
1445
  for (const item of queue) {
1404
- if (!this.isMergeBarrier(item.message) && this.canDequeueAfterSubmittedResume(first, item)) {
1446
+ if (!this.blockedReason?.(item.message) && !this.isMergeBarrier(item.message) && this.canDequeueAfterSubmittedResume(first, item)) {
1405
1447
  result.push(item);
1406
1448
  }
1407
1449
  else {
@@ -1421,7 +1463,7 @@ export class MessageQueue {
1421
1463
  else if (mergeGroupTimeline) {
1422
1464
  const remaining = [];
1423
1465
  for (const item of queue) {
1424
- if (!this.isMergeBarrier(item.message) && this.canDequeueGroupTimeline(first, item)) {
1466
+ if (!this.blockedReason?.(item.message) && !this.isMergeBarrier(item.message) && this.canDequeueGroupTimeline(first, item)) {
1425
1467
  result.push(item);
1426
1468
  }
1427
1469
  else {
@@ -1433,7 +1475,7 @@ export class MessageQueue {
1433
1475
  result.sort((a, b) => this.firstTimestamp(a) - this.firstTimestamp(b));
1434
1476
  }
1435
1477
  else {
1436
- while (queue.length > 0 && !this.isMergeBarrier(queue[0].message) && queue[0].message.peerId === mergeKey) {
1478
+ while (queue.length > 0 && !this.blockedReason?.(queue[0].message) && !this.isMergeBarrier(queue[0].message) && queue[0].message.peerId === mergeKey) {
1437
1479
  result.push(queue.shift());
1438
1480
  }
1439
1481
  }
@@ -4,7 +4,7 @@
4
4
  import fs from 'fs';
5
5
  import path from 'path';
6
6
  import crypto from 'crypto';
7
- import { chatDirPath, appendJsonl, readAllJsonlLines, scanChatDirs } from '../session/session-fs-store.js';
7
+ import { chatDirPath, appendJsonl, readAllJsonlLines, readAllJsonlLinesAsync, scanAgentChatDirsAsync } from '../session/session-fs-store.js';
8
8
  import { logger } from '../../utils/logger.js';
9
9
  const PENDING_HINTS_FILE = 'pending-hints.jsonl';
10
10
  export const OBSERVER_HINT_FAILURE_MESSAGES = {
@@ -121,18 +121,12 @@ function deleteFile(fp) {
121
121
  function claimKey(claim) {
122
122
  return targetKey(claim.sessionsDir, claim.channelType, claim.channelId, claim.selfAID, claim.chatType, claim.threadId, claim.channelKey);
123
123
  }
124
- export function pendingInterruptHints(sessionsDir, selfAID) {
124
+ export async function pendingInterruptHints(sessionsDir, selfAID, channelKey) {
125
125
  const pending = [];
126
- for (const chat of scanChatDirs(sessionsDir)) {
126
+ for (const chat of await scanAgentChatDirsAsync(sessionsDir, selfAID, channelKey)) {
127
127
  if (chat.selfAID !== selfAID || chat.channelType !== 'aun' || !chat.channelKey)
128
128
  continue;
129
- let events;
130
- try {
131
- events = readEvents(path.join(chat.dirPath, PENDING_HINTS_FILE));
132
- }
133
- catch {
134
- continue;
135
- }
129
+ const events = await readAllJsonlLinesAsync(path.join(chat.dirPath, PENDING_HINTS_FILE));
136
130
  const keys = new Set(events.filter(event => event.action === 'add')
137
131
  .map(event => `${eventChatType(event)}\u0000${normThread(event.threadId)}`));
138
132
  for (const key of keys) {
@@ -10,9 +10,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';
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
- import { buildTaskRuntimeEnv, ensureRuntimeLockDir, ensureSessionRuntimeDir } from '../../cli/task-context.js';
15
+ import { buildTaskRuntimeEnv, ensureRuntimeLockDir, ensureSessionRuntimeDirAsync } from '../../cli/task-context.js';
16
16
  import { BUILTIN_SESSION_PATH_GRANTS, mergeRuntimeGrantsForSession, resolveGrantedReadRoots, } from '../permission/session-path-grants.js';
17
17
  import { buildSystemSessionContext, getSystemSessionModule, isSystemSessionType, readSystemSessionMarker } from '../system-session/registry.js';
18
18
  import { IMRenderer } from './im-renderer.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'
@@ -2161,6 +2156,10 @@ export class ResponseEngine {
2161
2156
  setHandoffRuntime(runtime) {
2162
2157
  this.handoffRuntime = runtime;
2163
2158
  }
2159
+ runnerReadiness;
2160
+ setRunnerReadiness(wait) {
2161
+ this.runnerReadiness = wait;
2162
+ }
2164
2163
  getTaskRuntimeContext(sessionId) {
2165
2164
  return this.activeTaskRuntimeContexts.get(sessionId) ?? null;
2166
2165
  }
@@ -3027,15 +3026,15 @@ export class ResponseEngine {
3027
3026
  const selfAidForAccess = accessAdapterSelfAid || message.selfAID || session.selfAID || undefined;
3028
3027
  if (message.source === 'trigger' && message.triggerMeta?.originChannelType === 'aun'
3029
3028
  && message.triggerMeta.originChatType !== 'group') {
3030
- await preparePaTeamQualification(selfAidForAccess, message.triggerMeta.originPeerId);
3029
+ await prepareSameOwnerProof(selfAidForAccess, message.triggerMeta.originPeerId);
3031
3030
  }
3032
3031
  if (message.source === 'handoff' && message.handoffDelivery?.direction === 'origin'
3033
3032
  && message.handoffDelivery.originAuthorization?.channelType === 'aun'
3034
3033
  && message.handoffDelivery.originAuthorization.chatType === 'private') {
3035
- await preparePaTeamQualification(selfAidForAccess, message.handoffDelivery.originAuthorization.actorId);
3034
+ await prepareSameOwnerProof(selfAidForAccess, message.handoffDelivery.originAuthorization.actorId);
3036
3035
  }
3037
3036
  if ((message.channelType || accessChannelKey.split('#')[0]) === 'aun' && message.chatType !== 'group') {
3038
- await preparePaTeamQualification(selfAidForAccess, message.peerId);
3037
+ await prepareSameOwnerProof(selfAidForAccess, message.peerId);
3039
3038
  }
3040
3039
  await refreshOwnershipForAuthorization(selfAidForAccess, {
3041
3040
  maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS,
@@ -3166,6 +3165,8 @@ export class ResponseEngine {
3166
3165
  const runnerSelfAid = this.agentRegistry?.resolveByChannel(channelKey)?.aid
3167
3166
  || session.selfAID
3168
3167
  || message.selfAID;
3168
+ if (runnerSelfAid)
3169
+ await this.runnerReadiness?.(runnerSelfAid, session.baseagent);
3169
3170
  agent = this.getAgent(channelKey, session.baseagent, runnerSelfAid);
3170
3171
  }
3171
3172
  catch (error) {
@@ -3569,6 +3570,8 @@ export class ResponseEngine {
3569
3570
  let agent;
3570
3571
  let turnLease;
3571
3572
  try {
3573
+ if (runnerSelfAid)
3574
+ await this.runnerReadiness?.(runnerSelfAid, session.baseagent);
3572
3575
  agent = this.getAgent(channelKey, session.baseagent, runnerSelfAid);
3573
3576
  }
3574
3577
  catch (error) {
@@ -3664,12 +3667,12 @@ export class ResponseEngine {
3664
3667
  const peerIdRaw = message.peerId;
3665
3668
  if (message.source === 'trigger' && message.triggerMeta?.originChannelType === 'aun'
3666
3669
  && message.triggerMeta.originChatType !== 'group') {
3667
- await preparePaTeamQualification(selfAid, message.triggerMeta.originPeerId);
3670
+ await prepareSameOwnerProof(selfAid, message.triggerMeta.originPeerId);
3668
3671
  }
3669
3672
  if (message.handoffDelivery?.direction === 'origin'
3670
3673
  && message.handoffDelivery.originAuthorization?.channelType === 'aun'
3671
3674
  && message.handoffDelivery.originAuthorization.chatType === 'private') {
3672
- await preparePaTeamQualification(selfAid, message.handoffDelivery.originAuthorization.actorId);
3675
+ await prepareSameOwnerProof(selfAid, message.handoffDelivery.originAuthorization.actorId);
3673
3676
  }
3674
3677
  const triggerExecutionIdentity = this.resolveTriggerExecutionIdentity(message, selfAid);
3675
3678
  const authorizationIdentity = triggerExecutionIdentity
@@ -3694,7 +3697,7 @@ export class ResponseEngine {
3694
3697
  : undefined);
3695
3698
  const peerType = message.peerType ?? session.metadata?.peerType;
3696
3699
  if (configChannelType === 'aun' && configChatType === 'private') {
3697
- await preparePaTeamQualification(selfAid, configActorId);
3700
+ await prepareSameOwnerProof(selfAid, configActorId);
3698
3701
  }
3699
3702
  const peerRoleDetail = authorizationIdentity ? undefined : (() => {
3700
3703
  try {
@@ -3871,6 +3874,8 @@ export class ResponseEngine {
3871
3874
  : undefined,
3872
3875
  previousTurnState: this.turnCoordinator.current(session),
3873
3876
  isSendCommand: (toolName, toolInput) => isExactEvolcoreSendCommandForSession(toolName, toolInput, session.channelId, chatType, selfAid) || isThreadRoutedSendForSelf(toolName, toolInput, selfAid),
3877
+ // 只读命令(--help / 查询类)不参与意图表达门禁,避免"查语法"被判违规。
3878
+ isReadOnlyCommand: (toolName, toolInput) => isReadOnlyEcCommand(toolName, toolInput),
3874
3879
  describeSendCommandFailure: (toolName, toolInput) => describeProactiveSendCommandFailure(toolName, toolInput, {
3875
3880
  selfAid,
3876
3881
  channelId: session.channelId,
@@ -4531,7 +4536,7 @@ export class ResponseEngine {
4531
4536
  // Allocate the stable session-owned root before any runner preflight
4532
4537
  // context is installed. Every runner for this EvolCore session receives
4533
4538
  // the same directory, independent of daemon or runner lifetimes.
4534
- const sessionRuntimeDir = ensureSessionRuntimeDir(session.id);
4539
+ const sessionRuntimeDir = await ensureSessionRuntimeDirAsync(session.id);
4535
4540
  const recordExecutionAnomaly = triggerRunId
4536
4541
  ? (anomaly) => {
4537
4542
  recordTriggerExecutionAnomaly(triggerRunId, {
@@ -4642,8 +4647,8 @@ export class ResponseEngine {
4642
4647
  // 系统会话没有角色
4643
4648
  role: systemSessionMarker ? undefined : peerRole,
4644
4649
  internalContactAuthorization: !systemSessionMarker && configChannelType === 'aun' && configChatType === 'private'
4645
- && !!selfAid && !!configActorId && (paTeamQualification(selfAid, configActorId) === 'matched'
4646
- || requiresPaTeamVerification(selfAid, configActorId)),
4650
+ && !!selfAid && !!configActorId && (sameOwnerQualification(selfAid, configActorId) === 'matched'
4651
+ || requiresSameOwnerProof(selfAid, configActorId)),
4647
4652
  internalContactDefaultRole: peerRoleDetail?.source === 'internal-contact-default'
4648
4653
  || (authorizationIdentity?.role === peerRole && configChannelType === 'aun'
4649
4654
  && configChatType === 'private' && !!selfAid && !!configActorId
@@ -5718,6 +5723,9 @@ export class ResponseEngine {
5718
5723
  } : {}),
5719
5724
  daemonRuntimeEpoch: this.agentDelegationRegistry?.getRuntimeEpoch(),
5720
5725
  threadId: sessionTopicThreadId(session),
5726
+ // 仅观测:入站消息的加密状态,供 ecmsg 的 --encrypt auto 沿用。
5727
+ ...(message.replyContext?.metadata?.encrypted != null
5728
+ ? { inboundEncrypted: !!(message.replyContext.metadata.encrypted) } : {}),
5721
5729
  sessionRuntimeDir,
5722
5730
  runtimeLockDir: ensureRuntimeLockDir(sessionRuntimeDir),
5723
5731
  handoffIds: v2HandoffIds.length > 0 && v2HandoffDirection === 'target' ? v2HandoffIds : undefined,
@@ -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
+ ];