evolcore 0.0.47 → 0.0.49

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 (266) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +143 -40
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +34 -17
  8. package/dist/agents/codex-runner.js +36 -17
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/msg/p2p.js +2 -1
  14. package/dist/aun/service-proxy.js +4 -2
  15. package/dist/build-identity.json +1 -0
  16. package/dist/channels/aun.js +722 -295
  17. package/dist/channels/daemon.js +9 -25
  18. package/dist/cli/aun-commands.js +86 -51
  19. package/dist/cli/code-stats.js +19 -8
  20. package/dist/cli/command-log.js +1 -1
  21. package/dist/cli/daemon-commands.js +44 -43
  22. package/dist/cli/directory.js +13 -2
  23. package/dist/cli/ecmsg-gateway.js +5 -2
  24. package/dist/cli/index.js +9 -9
  25. package/dist/cli/init-channel.js +4 -6
  26. package/dist/cli/init.js +72 -50
  27. package/dist/cli/invoke-command.js +1 -1
  28. package/dist/cli/managed-command-guard.js +2 -0
  29. package/dist/cli/model.js +20 -5
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/quota.js +89 -0
  32. package/dist/cli/role.js +62 -17
  33. package/dist/cli/services-command.js +1 -0
  34. package/dist/cli/stats.js +3 -3
  35. package/dist/cli/team-workspace-command.js +56 -2
  36. package/dist/cli/thread-command.js +16 -51
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-field-policy.js +71 -1
  40. package/dist/config/config-manager.js +13 -7
  41. package/dist/config/daemon-services.js +30 -3
  42. package/dist/config/gateway-config.js +2 -2
  43. package/dist/config/invoke-ipc-service.js +6 -4
  44. package/dist/config/peer-bind-code.js +3 -4
  45. package/dist/config/peer-book-store.js +62 -229
  46. package/dist/config/peer-book.js +26 -27
  47. package/dist/config/peer-role-resolver.js +16 -1
  48. package/dist/config/provider-identity-migration.js +4 -1
  49. package/dist/config/provider-ipc-service.js +56 -11
  50. package/dist/config/provider-menu-request.js +24 -5
  51. package/dist/config/provider-templates.js +127 -0
  52. package/dist/config/providers-config.js +67 -12
  53. package/dist/config/providers-management.js +477 -51
  54. package/dist/config/resolved-config-op.js +3 -2
  55. package/dist/config/role-command-service.js +248 -1
  56. package/dist/config/schema-migration.js +105 -4
  57. package/dist/core/agent-application-service.js +6 -1
  58. package/dist/core/agent-runtime.js +4 -0
  59. package/dist/core/auth/agent-delegation.js +2 -1
  60. package/dist/core/auth/auth-gateway.js +2 -1
  61. package/dist/core/auth/delegation-authorization.js +36 -26
  62. package/dist/core/auth/operation-authorizer.js +25 -0
  63. package/dist/core/auth/operation-catalog.js +37 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/cli-intent-parser.js +13 -0
  68. package/dist/core/command/command-handler.js +126 -87
  69. package/dist/core/command/menu-catalog.js +1 -0
  70. package/dist/core/command/menu-handler.js +67 -150
  71. package/dist/core/command/menu-protocol.js +31 -1
  72. package/dist/core/command/provider-menu.js +13 -3
  73. package/dist/core/command/remote-shell.js +565 -0
  74. package/dist/core/command/role-menu.js +47 -23
  75. package/dist/core/command/slash-handler.js +26 -43
  76. package/dist/core/command/team-workspace-items.js +81 -12
  77. package/dist/core/command/team-workspace-team.js +9 -71
  78. package/dist/core/command/topic-slash.js +9 -30
  79. package/dist/core/daemon-bootstrap.js +8 -1
  80. package/dist/core/daemon-control.js +64 -8
  81. package/dist/core/daemon-lifecycle.js +16 -2
  82. package/dist/core/evolagent-registry.js +20 -3
  83. package/dist/core/file-integrity/store.js +2 -0
  84. package/dist/core/handoff/runtime.js +37 -1
  85. package/dist/core/inference/text-inference.js +3 -1
  86. package/dist/core/initialization/service.js +11 -6
  87. package/dist/core/interaction-router.js +3 -0
  88. package/dist/core/invoke/executors/text.js +72 -19
  89. package/dist/core/ipc-registration.js +3 -1
  90. package/dist/core/message/aun-ipc-sender.js +279 -107
  91. package/dist/core/message/contact-admission.js +91 -6
  92. package/dist/core/message/contact-pending-inbound.js +113 -0
  93. package/dist/core/message/contact-thread-approval.js +212 -0
  94. package/dist/core/message/im-renderer.js +41 -2
  95. package/dist/core/message/message-admission.js +5 -39
  96. package/dist/core/message/message-bridge.js +140 -370
  97. package/dist/core/message/message-log.js +29 -0
  98. package/dist/core/message/message-queue.js +119 -15
  99. package/dist/core/message/message-utils.js +8 -0
  100. package/dist/core/message/response-engine.js +580 -134
  101. package/dist/core/message/send-routing.js +5 -1
  102. package/dist/core/model/catalog-service.js +31 -11
  103. package/dist/core/model/config-scope.js +6 -14
  104. package/dist/core/model/model-capabilities.js +22 -4
  105. package/dist/core/model/model-catalog.js +1 -0
  106. package/dist/core/model/model-diagnostics.js +19 -0
  107. package/dist/core/model/model-fallback.js +13 -2
  108. package/dist/core/ownership/owner-resolver.js +328 -50
  109. package/dist/core/pack-auth.js +3 -0
  110. package/dist/core/pack-install.js +1 -1
  111. package/dist/core/permission/ec-command-parser.js +106 -19
  112. package/dist/core/permission/protected-paths.js +6 -6
  113. package/dist/core/permission/services-path-acl.js +451 -0
  114. package/dist/core/permission/tool-policy.js +5 -1
  115. package/dist/core/relation/peer-identity.js +36 -1
  116. package/dist/core/relation/same-owner-proof.js +81 -112
  117. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  118. package/dist/core/session/session-file-health.js +13 -7
  119. package/dist/core/session/session-fs-store.js +91 -35
  120. package/dist/core/session/session-manager.js +68 -24
  121. package/dist/core/session/session-mapper.js +14 -34
  122. package/dist/core/session/session-transcript.js +5 -1
  123. package/dist/core/task/task-activity-store.js +84 -0
  124. package/dist/core/task/task-recovery-service.js +13 -0
  125. package/dist/core/thread/command-parser.js +7 -12
  126. package/dist/core/thread/thread-context-storage.js +3 -2
  127. package/dist/core/thread/thread-operation.js +2 -13
  128. package/dist/core/thread/thread-service.js +15 -46
  129. package/dist/core/thread/topic-id.js +15 -0
  130. package/dist/directory/owner-directory-admission.js +12 -9
  131. package/dist/directory/owner-directory-cache.js +64 -28
  132. package/dist/directory/owner-directory-markdown.js +14 -2
  133. package/dist/directory/owner-directory-policy.js +5 -30
  134. package/dist/directory/owner-directory-query-operation.js +29 -3
  135. package/dist/directory/owner-directory-remarks.js +11 -3
  136. package/dist/directory/owner-directory-request-operation.js +5 -2
  137. package/dist/eck/kit-renderer.js +1 -1
  138. package/dist/eck/message-renderer.js +112 -29
  139. package/dist/ecweb/basic-settings-service.js +3 -1
  140. package/dist/ecweb/message-context-service.js +1 -1
  141. package/dist/ecweb/pairing.js +4 -3
  142. package/dist/ecweb/providers-service.js +26 -1
  143. package/dist/ecweb/runtime/lifecycle.js +18 -8
  144. package/dist/ecweb/runtime/proxy-access.js +74 -0
  145. package/dist/ecweb/runtime/supervisor.js +36 -6
  146. package/dist/event-center/center-config.js +9 -5
  147. package/dist/event-center/dispatcher.js +10 -1
  148. package/dist/event-center/ipc-operation.js +19 -0
  149. package/dist/event-center/registry.js +29 -3
  150. package/dist/event-center/runtime.js +106 -11
  151. package/dist/event-center/script-runner.js +5 -5
  152. package/dist/index.js +96 -59
  153. package/dist/ipc.js +38 -3
  154. package/dist/outputs/authorization.js +16 -0
  155. package/dist/outputs/cards.js +336 -0
  156. package/dist/outputs/events.js +63 -0
  157. package/dist/outputs/protocol.js +103 -0
  158. package/dist/outputs/service.js +266 -0
  159. package/dist/paths.js +3 -0
  160. package/dist/proxy/manager.js +43 -13
  161. package/dist/services/index.js +114 -5
  162. package/dist/services/ipc-operation.js +88 -15
  163. package/dist/services/pack-manager.js +13 -1
  164. package/dist/services/router.js +21 -6
  165. package/dist/services/script-runner.js +5 -4
  166. package/dist/services/service-payload.js +13 -7
  167. package/dist/services/validation.js +1 -1
  168. package/dist/stats/budget.js +2 -2
  169. package/dist/stats/db.js +19 -0
  170. package/dist/stats/index.js +1 -1
  171. package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
  172. package/dist/stats/normalizer.js +2 -0
  173. package/dist/stats/query.js +35 -27
  174. package/dist/stats/quota-query.js +95 -0
  175. package/dist/stats/role-budget.js +5 -2
  176. package/dist/stats/writer.js +10 -6
  177. package/dist/trigger/audit.js +7 -0
  178. package/dist/trigger/authorization.js +105 -11
  179. package/dist/trigger/feedback.js +10 -0
  180. package/dist/trigger/history.js +37 -11
  181. package/dist/trigger/ipc-service.js +12 -1
  182. package/dist/trigger/manager.js +1 -0
  183. package/dist/trigger/scheduler.js +7 -5
  184. package/dist/trigger/script-executor.js +2 -1
  185. package/dist/trigger/script-sandbox.js +21 -3
  186. package/dist/trigger/validation.js +22 -0
  187. package/dist/utils/atomic-write.js +22 -8
  188. package/dist/utils/cross-platform.js +73 -26
  189. package/dist/utils/error-dict.json +94 -4
  190. package/dist/utils/error-utils.js +27 -4
  191. package/dist/utils/evolcore-version.js +36 -65
  192. package/dist/utils/host-info.js +100 -1
  193. package/dist/utils/msg-diag.js +1 -0
  194. package/dist/utils/npm-ops.js +43 -8
  195. package/dist/utils/process-introspect.js +12 -7
  196. package/dist/utils/process-tree.js +50 -2
  197. package/dist/utils/windows-shell-trust.js +2 -0
  198. package/dist/workbench/protocol.js +80 -0
  199. package/dist/workbench/service.js +359 -0
  200. package/ecagent/dist/types.d.ts +6 -2
  201. package/kits/docs/context-assembly.md +1 -1
  202. package/kits/docs/evolcore/INDEX.md +4 -2
  203. package/kits/docs/evolcore/aid.md +25 -0
  204. package/kits/docs/evolcore/config.md +16 -1
  205. package/kits/docs/evolcore/directory.md +30 -12
  206. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  207. package/kits/docs/evolcore/model.md +10 -0
  208. package/kits/docs/evolcore/msg.md +9 -0
  209. package/kits/docs/evolcore/peer.md +19 -65
  210. package/kits/docs/evolcore/provider.md +124 -4
  211. package/kits/docs/evolcore/quota.md +54 -0
  212. package/kits/docs/evolcore/role.md +83 -0
  213. package/kits/docs/evolcore/services.md +6 -6
  214. package/kits/docs/evolcore/stats.md +2 -0
  215. package/kits/docs/evolcore/team-workspace.md +1 -1
  216. package/kits/docs/evolcore/thread-chain.md +14 -15
  217. package/kits/docs/evolcore/tool-authorization.md +5 -0
  218. package/kits/docs/evolcore/trigger.md +12 -0
  219. package/kits/eck_message_manifest.json +12 -0
  220. package/kits/provider-templates.json +1213 -0
  221. package/kits/rules/04-relation.md +3 -3
  222. package/kits/schemas/_meta.json +14 -2
  223. package/kits/schemas/agent-config.schema.20.json +24 -0
  224. package/kits/schemas/contact-book.schema.4.json +52 -0
  225. package/kits/schemas/providers.schema.3.json +200 -0
  226. package/kits/skills/.switches.json +8 -0
  227. package/kits/skills/ability/references/calling.md +1 -1
  228. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  229. package/kits/skills/ec-group/SKILL.md +2 -2
  230. package/kits/skills/ec-identity/SKILL.md +19 -72
  231. package/kits/skills/ec-provider/SKILL.md +270 -0
  232. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  233. package/kits/skills/ec-trigger/SKILL.md +1 -1
  234. package/kits/skills/thread-ops/SKILL.md +34 -21
  235. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  236. package/kits/templates/message-fragments/group-batch.md +1 -1
  237. package/kits/templates/message-fragments/inject-default.md +1 -1
  238. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  239. package/kits/templates/message-fragments/item-group.md +1 -1
  240. package/kits/templates/message-fragments/item-private.md +1 -1
  241. package/kits/templates/message-fragments/thread-context.md +1 -1
  242. package/kits/templates/message-fragments/trigger-session.md +1 -1
  243. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  244. package/kits/templates/roles/admin.json +2 -19
  245. package/kits/templates/roles/member.json +0 -3
  246. package/kits/templates/roles/visitor.json +1 -0
  247. package/kits/templates/system-fragments/baseagent.md +6 -0
  248. package/kits/templates/system-fragments/commands.md +4 -3
  249. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  250. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  251. package/kits/templates/system-fragments/relation.md +1 -1
  252. package/kits/templates/system-fragments/thread.md +7 -5
  253. package/kits/templates/system-fragments/venue.md +11 -0
  254. package/package.json +6 -4
  255. package/scripts/agent-template/inspect.mjs +50 -11
  256. package/scripts/agent-template/shared/common.mjs +11 -6
  257. package/scripts/agent-template/shared/team-schema.json +6 -4
  258. package/scripts/agent-template/shared/template-contract.mjs +62 -11
  259. package/scripts/agent-template/shared/template-package.mjs +189 -21
  260. package/scripts/agent-template/shared/template-runtime.mjs +54 -6
  261. package/scripts/agent-template/shared/template.mjs +2 -2
  262. package/scripts/agent-template/team-pack.mjs +52 -14
  263. package/dist/cli/peer.js +0 -127
  264. package/dist/config/peer-operation-service.js +0 -132
  265. package/dist/config/peer-request-service.js +0 -532
  266. package/dist/core/command/connect-menu.js +0 -624
@@ -7,17 +7,16 @@ import { AUN_HANDOFF_MARKER_FIELD } from '../../channels/aun.js';
7
7
  import { classifyAunPayloadForLog } from './message-log.js';
8
8
  import { isValidAunDeliveryForChannel } from './outbound.js';
9
9
  import { isHClassPath } from '../permission/protected-paths.js';
10
- import { evaluateOutboundContactAdmission } from './message-admission.js';
11
- import { contactIntroductionText, evaluateAppContactAdmission, parseFriendInvite } from './contact-admission.js';
12
10
  import { normalizeAunMentionEntries, withAunAttention } from '../../aun/msg/mention-schema.js';
13
11
  import { resolveManagedSendArgv } from '../../cli/aun-commands.js';
14
12
  import { readTriggerLocalFile, resolveAttachmentLocalPath } from '../../trigger/local-files.js';
15
13
  import { TriggerDefinitionManager } from '../../trigger/manager.js';
16
14
  import { normalizeGroupAid, sameGroupAid } from '../../aun/group/identity.js';
17
15
  import { resolveThreadRouteTarget } from '../thread/thread-route.js';
18
- import { isTopicThreadId, parseMainTopicId, safeFormatMainTopicId, sessionLocalTopicId } from '../thread/topic-id.js';
16
+ import { isMainSessionThreadId, isTopicThreadId, parseMainTopicId, safeFormatMainTopicId, sessionLocalTopicId, } from '../thread/topic-id.js';
19
17
  import { ThreadService } from '../thread/thread-service.js';
20
- import { buildEnvelope } from './message-utils.js';
18
+ import { diagLog } from '../../utils/msg-diag.js';
19
+ import { buildEnvelope, DEFAULT_NOOP_SENTINEL } from './message-utils.js';
21
20
  import { sessionTopicThreadId } from '../thread/topic-id.js';
22
21
  import { getAunRequestRegistry, requestDiagnostics, requestTtlSeconds } from './aun-request-registry.js';
23
22
  import { canonicalizeEvolcoreCommandArgv, parseJsonObjectArgument } from '../permission/ec-command-parser.js';
@@ -28,7 +27,45 @@ import { buildDownstreamArgv, expandGroupBase, parseGatewayArgs } from '../../cl
28
27
  import { resolveSendRoute } from './send-routing.js';
29
28
  import { agentDir } from '../../paths.js';
30
29
  import { chatDirPath, readAllJsonlLines } from '../session/session-fs-store.js';
30
+ import { prepareContactThreadDelegation, finishContactThreadDelegation, findContactThreadReturn } from './contact-thread-approval.js';
31
+ import { currentContactBinding } from './contact-admission.js';
31
32
  const TASK_ID_MESSAGE_PAYLOAD_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file']);
33
+ const TOPIC_SOURCE_MESSAGE_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file', 'action_card']);
34
+ /** Stamp the actual runtime source before handoff/outbox persistence, including retries. */
35
+ export function withAunTopicSource(payload, input) {
36
+ // A caller's payload can be copied from another message. Its old provenance
37
+ // must not survive a new managed send or mark an ordinary reply cross-topic.
38
+ const result = { ...payload };
39
+ delete result.topic_source;
40
+ const runtime = input.runtime;
41
+ if (!TOPIC_SOURCE_MESSAGE_TYPES.has(String(payload.type)) || runtime?.channel !== 'aun'
42
+ || runtime.selfAid !== input.selfAid
43
+ || (runtime.chatType !== 'private' && runtime.chatType !== 'group'))
44
+ return result;
45
+ // channelId is the conversation peer; peerId in a group is the speaker.
46
+ const peer = runtime.channelId?.trim() ?? '';
47
+ if (!safeFormatMainTopicId(input.selfAid, peer))
48
+ return result;
49
+ const threadId = isTopicThreadId(runtime.threadId) ? runtime.threadId : '';
50
+ if (!isMainSessionThreadId(runtime.threadId) && !/^thread-[a-zA-Z0-9-]+$/.test(threadId))
51
+ return result;
52
+ const targetThreadId = isTopicThreadId(input.targetThreadId) ? input.targetThreadId : '';
53
+ if (peer.toLowerCase() === input.targetPeer.trim().toLowerCase()
54
+ && runtime.chatType === input.targetChatType && threadId === targetThreadId)
55
+ return result;
56
+ const source = {
57
+ version: 1, agent_aid: input.selfAid, peer_id: peer,
58
+ chat_type: runtime.chatType, thread_id: threadId,
59
+ };
60
+ // An absent/deleted index entry must never prevent the message being sent.
61
+ try {
62
+ const name = input.resolveName?.(source)?.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 256);
63
+ if (name && name !== '话题会话' && name !== '默认会话')
64
+ source.name = name;
65
+ }
66
+ catch { /* the coordinates still identify the source */ }
67
+ return { ...result, topic_source: source };
68
+ }
32
69
  function normalizeAid(value) {
33
70
  return String(value ?? '').trim().replace(/^@/, '').toLowerCase();
34
71
  }
@@ -171,7 +208,9 @@ async function sendViaSessionAdapter(handoff, targetSession, instance, getOutbou
171
208
  }
172
209
  async function applyManagedCrossThreadSendEffects(input) {
173
210
  const originSessionId = input.grant.sessionId;
174
- const originPeer = parsePeerKey(input.grant.peerKey).channelId;
211
+ const conversationId = input.runtime?.channelId;
212
+ const originPeer = conversationId && !/^(trigger|bg):/.test(conversationId)
213
+ ? conversationId : parsePeerKey(input.grant.peerKey).channelId;
175
214
  // 来源话题 id:话题用原 id;主话题用"本端+对端"拼出的规范 id(展示与持久化用)。
176
215
  const originThreadId = isTopicThreadId(input.runtime?.threadId)
177
216
  ? input.runtime.threadId
@@ -188,6 +227,14 @@ async function applyManagedCrossThreadSendEffects(input) {
188
227
  : ThreadService.findMainSessionEntry(input.selfAid, input.targetChannelId);
189
228
  const originThreadName = originEntry?.name || (originThreadId || originPeer);
190
229
  const originPeerName = originEntry?.peerName || originPeer;
230
+ // 来源话题对端的主体类型:运行时上下文是唯一来源;伪对端不写。
231
+ const originPeerType = (() => {
232
+ const type = String(input.runtime?.peerType ?? '').trim();
233
+ const peerId = String(input.runtime?.peerId ?? '');
234
+ if (!type || peerId.startsWith('trigger:') || peerId.startsWith('bg:'))
235
+ return undefined;
236
+ return type;
237
+ })();
191
238
  const targetThreadName = targetEntry?.name || input.targetThreadId;
192
239
  const targetPeerName = targetEntry?.peerName || input.targetChannelId;
193
240
  const { buildCrossThreadReviewPrompt } = await import('../../cli/aun-commands.js');
@@ -205,44 +252,49 @@ async function applyManagedCrossThreadSendEffects(input) {
205
252
  });
206
253
  let createdTriggerId;
207
254
  let triggerError;
208
- try {
209
- if (!input.createCrossThreadReviewTrigger)
210
- throw new Error('cross-thread Trigger authorization is unavailable');
211
- const { buildThreadCheckTrigger } = await import('../../cli/aun-commands.js');
212
- const definition = buildThreadCheckTrigger({
213
- agentAid: input.selfAid,
214
- id: triggerId,
215
- name: triggerName,
216
- prompt,
217
- everyMs: input.durationMs,
218
- checkEvery: input.checkEveryLabel,
219
- // 目标话题所属渠道:从话题索引取,取不到时按 AUN 主渠兜底(历史行为)。
220
- // 硬写 AUN 会让飞书等渠道的目标话题把 Trigger 的 feedback.target 指向错渠道。
221
- channelKey: targetEntry?.channelType
222
- ? formatChannelKey({ type: targetEntry.channelType, selfAID: input.selfAid, name: 'main' })
223
- : formatChannelKey({ type: 'aun', selfAID: input.selfAid, name: 'main' }),
224
- targetChannelId: input.targetChannelId,
225
- targetThreadId: input.targetThreadId,
226
- originThreadId,
227
- originPeer,
228
- feedbackChatType: input.feedbackChatType,
229
- originalText: input.contentSummary,
230
- firstSentAt: input.timestamp,
231
- originThreadName,
232
- targetThreadName,
233
- });
234
- const created = await input.createCrossThreadReviewTrigger({
235
- agentAid: input.selfAid,
236
- grant: input.grant,
237
- definition,
238
- });
239
- createdTriggerId = created.id;
240
- }
241
- catch (error) {
242
- // 失败原因随发送回执返回给调用方:只打 daemon 日志时,CLI 照样显示"已投递",
243
- // 复查静默缺失无人察觉(2026-10-20 firstSentAt 类型错误即如此)。
244
- triggerError = error instanceof Error ? error.message : String(error);
245
- console.warn(`⚠ Trigger 创建失败: ${triggerError}(inbox 仍会写入)`);
255
+ // `--check-every none`:跳过 Trigger,只保留 inbox(「我发过」是事实,定时唤醒是可选项)。
256
+ if (input.durationMs !== undefined) {
257
+ try {
258
+ if (!input.createCrossThreadReviewTrigger)
259
+ throw new Error('cross-thread Trigger authorization is unavailable');
260
+ const { buildThreadCheckTrigger } = await import('../../cli/aun-commands.js');
261
+ const definition = buildThreadCheckTrigger({
262
+ agentAid: input.selfAid,
263
+ id: triggerId,
264
+ name: triggerName,
265
+ prompt,
266
+ everyMs: input.durationMs,
267
+ checkEvery: input.checkEveryLabel,
268
+ // 目标话题所属渠道:从话题索引取,取不到时按 AUN 主渠兜底(历史行为)。
269
+ // 硬写 AUN 会让飞书等渠道的目标话题把 Trigger 的 feedback.target 指向错渠道。
270
+ channelKey: targetEntry?.channelType
271
+ ? formatChannelKey({ type: targetEntry.channelType, selfAID: input.selfAid, name: 'main' })
272
+ : formatChannelKey({ type: 'aun', selfAID: input.selfAid, name: 'main' }),
273
+ targetChannelId: input.targetChannelId,
274
+ targetThreadId: input.targetThreadId,
275
+ originThreadId,
276
+ originPeer,
277
+ feedbackChatType: input.feedbackChatType,
278
+ originalText: input.contentSummary,
279
+ firstSentAt: input.timestamp,
280
+ originThreadName,
281
+ originPeerName,
282
+ originPeerType,
283
+ targetThreadName,
284
+ });
285
+ const created = await input.createCrossThreadReviewTrigger({
286
+ agentAid: input.selfAid,
287
+ grant: input.grant,
288
+ definition,
289
+ });
290
+ createdTriggerId = created.id;
291
+ }
292
+ catch (error) {
293
+ // 失败原因随发送回执返回给调用方:只打 daemon 日志时,CLI 照样显示"已投递",
294
+ // 复查静默缺失无人察觉(2026-10-20 firstSentAt 类型错误即如此)。
295
+ triggerError = error instanceof Error ? error.message : String(error);
296
+ console.warn(`⚠ Trigger 创建失败: ${triggerError}(inbox 仍会写入)`);
297
+ }
246
298
  }
247
299
  try {
248
300
  ThreadService.appendInbox(input.selfAid, {
@@ -251,6 +303,9 @@ async function applyManagedCrossThreadSendEffects(input) {
251
303
  timestamp: input.timestamp,
252
304
  originThreadId,
253
305
  originPeer,
306
+ // 显示名随条目落盘:渲染时不必再查话题索引,也保住了改名前的历史值。
307
+ ...(originPeerName && originPeerName !== originPeer ? { originPeerName } : {}),
308
+ ...(originPeerType ? { originPeerType } : {}),
254
309
  originSessionId,
255
310
  targetSessionId: input.targetSessionId,
256
311
  ...(createdTriggerId ? { triggerId: createdTriggerId } : {}),
@@ -379,6 +434,7 @@ async function deliverSelfAddressed(input) {
379
434
  messageId: sent.message_id,
380
435
  timestamp: sent.timestamp ?? Date.now(),
381
436
  source: 'self-address',
437
+ selfAddressedMeta: { noopSentinel: DEFAULT_NOOP_SENTINEL },
382
438
  encrypted: input.encrypted,
383
439
  replyContext: {
384
440
  threadId: sessionTopicThreadId(session) ?? undefined,
@@ -465,7 +521,7 @@ function targetTopicLabel(topicId) {
465
521
  return 'main';
466
522
  }
467
523
  /** Resolve gateway options only from an authenticated task and local topic evidence. */
468
- async function resolveGatewaySend(argv, grant, runtime) {
524
+ async function resolveGatewaySend(argv, grant, runtime, session) {
469
525
  if (argv[1] !== 'send' || grant.channelType !== 'aun' || !runtime) {
470
526
  throw new Error('An active AUN task is required for gateway sends');
471
527
  }
@@ -473,12 +529,40 @@ async function resolveGatewaySend(argv, grant, runtime) {
473
529
  if (!parsed.ok)
474
530
  throw new Error(parsed.error);
475
531
  const { route: options, text, passthrough } = parsed;
476
- const currentPeer = parsePeerKey(grant.peerKey).channelId;
532
+ if (runtime.selfAid !== grant.selfAid || (runtime.sessionId && runtime.sessionId !== grant.sessionId)
533
+ || session && (session.id !== grant.sessionId || session.selfAID !== grant.selfAid)) {
534
+ throw Object.assign(new Error('Current conversation does not match the delegated task'), { code: 'SCOPE_MISMATCH' });
535
+ }
536
+ // The grant identifies the authorizing actor. A target-session Trigger may
537
+ // run in another conversation, whose recipient and topic remain authoritative.
538
+ // Dedicated daemon Trigger sessions have no channel peer; preserve their
539
+ // origin-based send behavior. A target_session task has a real conversation.
540
+ const daemonSession = session?.channelType === 'daemon';
541
+ const currentPeer = daemonSession ? parsePeerKey(grant.peerKey).channelId : session?.channelId ?? runtime.channelId;
542
+ const currentChannelType = daemonSession ? grant.channelType : session?.channelType ?? runtime.channel;
543
+ const currentChatType = daemonSession ? grant.chatType : session?.chatType ?? runtime.chatType;
544
+ const currentThreadId = daemonSession ? undefined : session ? sessionTopicThreadId(session) : runtime.threadId;
545
+ if (!currentPeer || currentChannelType !== 'aun'
546
+ || (currentChatType !== 'private' && currentChatType !== 'group')) {
547
+ throw Object.assign(new Error('Current AUN conversation route is unavailable'), { code: 'AUN_OUTBOUND_ROUTE_REQUIRED' });
548
+ }
549
+ // An unqualified report to Owner continues its unique originating delegation.
550
+ // Explicit --thread always wins; unrelated conversations keep normal routing.
551
+ let returningToOrigin = false;
552
+ if (options.thread === undefined && options.to
553
+ && normalizeAid(options.to) === currentContactBinding(grant.selfAid)?.owner_aid) {
554
+ const origin = findContactThreadReturn({ selfAid: grant.selfAid, grant, runtime });
555
+ if (origin) {
556
+ options.thread = origin.originThreadId;
557
+ options.checkEvery ??= 'none';
558
+ returningToOrigin = true;
559
+ }
560
+ }
477
561
  const resolveKind = async (target) => {
478
562
  if (normalizeAid(target) === normalizeAid(currentPeer))
479
- return grant.chatType;
563
+ return currentChatType;
480
564
  if (normalizeAid(target) === normalizeAid(grant.selfAid))
481
- return grant.chatType;
565
+ return currentChatType;
482
566
  const local = readAunPeerKind(grant.selfAid, target)?.kind;
483
567
  if (local === 'private' || local === 'group')
484
568
  return local;
@@ -522,11 +606,13 @@ async function resolveGatewaySend(argv, grant, runtime) {
522
606
  encrypt: options.encrypt,
523
607
  inboundTriggered: runtime.inboundEncrypted !== undefined,
524
608
  inboundEncrypted: runtime.inboundEncrypted === true, }, {
525
- selfAid: grant.selfAid, channelType: grant.channelType, chatType: grant.chatType,
526
- peerId: currentPeer, threadId: isTopicThreadId(runtime.threadId) ? runtime.threadId : undefined,
609
+ selfAid: grant.selfAid, channelType: currentChannelType, chatType: currentChatType,
610
+ peerId: currentPeer, threadId: isTopicThreadId(currentThreadId) ? currentThreadId : undefined,
527
611
  }, deps);
528
612
  if (!route.ok)
529
613
  throw Object.assign(new Error(route.message), { code: route.code });
614
+ if (returningToOrigin)
615
+ route.source.thread = 'derived';
530
616
  return { route, argv: buildDownstreamArgv(route, text, passthrough) };
531
617
  }
532
618
  export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegationRegistry, responseEngine, handoffRuntime, sessionManager, messageQueue, createCrossThreadReviewTrigger, }) {
@@ -564,7 +650,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
564
650
  return request ? { ok: true, request: request }
565
651
  : { ok: false, code: 'REQUEST_NOT_FOUND', error: `request not found: ${params.requestId}` };
566
652
  });
567
- const sender = async (params, inspectedGrant) => {
653
+ const sender = async (params, inspectedGrant, gatewayRoute) => {
568
654
  let textFile;
569
655
  let payloadFile;
570
656
  try {
@@ -597,9 +683,13 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
597
683
  }
598
684
  const grant = authorization.grant;
599
685
  if (params.argv[0] === MESSAGE_CLI_BIN) {
600
- const resolved = await resolveGatewaySend(params.argv, grant, responseEngine.getTaskRuntimeContext(params.originSessionId));
686
+ const session = sessionManager ? await sessionManager.getSessionById(params.originSessionId) : undefined;
687
+ if (sessionManager && !session) {
688
+ return { ok: false, code: 'AUN_OUTBOUND_ROUTE_REQUIRED', error: 'Current conversation session is unavailable', sent: false };
689
+ }
690
+ const resolved = await resolveGatewaySend(params.argv, grant, responseEngine.getTaskRuntimeContext(params.originSessionId), session);
601
691
  // 只变更执行参数,审批仍绑定网关的原始命令;下游继续校验目标并消费一次审批。
602
- const result = await sender({ ...params, argv: resolved.argv }, grant);
692
+ const result = await sender({ ...params, argv: resolved.argv }, grant, resolved.route);
603
693
  return { ...result, send_route: resolved.route };
604
694
  }
605
695
  const command = resolveManagedSendArgv(params.argv, {
@@ -644,6 +734,12 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
644
734
  // 跨话题自派(self-address):收件人是本端自己,话题归属仍是 (自端, 对端)。
645
735
  // 此时 `params.to` 不是「话题对端」,不能拿它做话题一致性校验。
646
736
  const selfAddressed = isSelfAidTarget(params.aid, params.to);
737
+ // The downstream argv intentionally omits same-topic --thread/--check-every.
738
+ // Restore the verified topic independently of the authorization relation;
739
+ // keeping checkEveryMs unset prevents another review Trigger.
740
+ if (gatewayRoute && !gatewayRoute.crossTopic && isTopicThreadId(gatewayRoute.threadId)) {
741
+ params.thread = gatewayRoute.threadId;
742
+ }
647
743
  // 话题引用解析:`threadRef` 是调用方写的原值(可能是主话题 id),
648
744
  // `threadRoute` 非空即"这是跨话题发送"——与话题 id 是否为空无关。
649
745
  const threadRef = params.thread;
@@ -653,13 +749,17 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
653
749
  if (threadRef && !threadRoute) {
654
750
  return { ok: false, code: 'TOPIC_NOT_FOUND', error: `话题不存在或不属于目标对端: ${threadRef}` };
655
751
  }
656
- const threadRouted = !!threadRoute;
752
+ // Topic lookup also restores the current topic; cross-topic side effects
753
+ // must follow the verified route rather than the presence of a topic ID.
754
+ // First-contact gateway sends omit --thread until handoff creates the main
755
+ // session. They still cross topics and must retain their delegation/inbox.
756
+ const threadRouted = gatewayRoute?.crossTopic ?? !!threadRoute;
657
757
  // 规范目标 id:话题保留原 id;主话题用双方拼出的规范形态(用于 Trigger 标签与通知)。
658
758
  const targetTopicId = threadRoute
659
759
  ? (isTopicThreadId(threadRef)
660
760
  ? threadRef
661
761
  : (safeFormatMainTopicId(params.aid, threadRoute.peer) ?? threadRef))
662
- : undefined;
762
+ : gatewayRoute?.threadId;
663
763
  const isSystemEvent = params.trustedSystemEvent === true
664
764
  && params.payload?.type === 'event' && params.payload.event === 'topic.renamed';
665
765
  // 非托管跨话题自派:调用方没有委托凭证,用本机 controlToken 证明「本机控制面调用」。
@@ -669,6 +769,12 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
669
769
  && selfAddressed
670
770
  && params.scope === 'msg'
671
771
  && !params.originSessionId;
772
+ const grantPeerId = inspectedGrant ? parsePeerKey(inspectedGrant.peerKey).channelId : undefined;
773
+ const authorizationTargetRouted = threadRouted || !!gatewayRoute && !!inspectedGrant && !!grantPeerId && (gatewayRoute.peer.channelType !== inspectedGrant.channelType
774
+ || gatewayRoute.peer.peerKind !== inspectedGrant.chatType
775
+ || (gatewayRoute.peer.channelType === 'aun'
776
+ ? normalizeAid(gatewayRoute.peer.id) !== normalizeAid(grantPeerId)
777
+ : gatewayRoute.peer.id !== grantPeerId));
672
778
  const delegation = localSelfSend
673
779
  ? {
674
780
  ok: true,
@@ -692,7 +798,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
692
798
  to: params.to,
693
799
  scope: params.scope,
694
800
  action: params.file ? 'file' : 'send',
695
- threadRouted: !!threadRoute,
801
+ threadRouted: authorizationTargetRouted,
696
802
  isSystemEvent,
697
803
  });
698
804
  if (!delegation.ok) {
@@ -735,6 +841,20 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
735
841
  && !!runtime.channelId && (params.scope === 'group' ? sameGroupAid(runtime.channelId, params.to) : runtime.channelId === params.to);
736
842
  params.thread = params.rawPayload === true ? params.thread : typeof params.payload?.thread_id === 'string' && params.payload.thread_id.trim()
737
843
  ? params.payload.thread_id.trim() : params.thread ?? (currentRelation ? runtime?.threadId : undefined);
844
+ if (gatewayRoute) {
845
+ const topicId = isTopicThreadId(params.thread) ? params.thread
846
+ : safeFormatMainTopicId(params.aid, gatewayRoute.peer.id);
847
+ const payloadThread = params.payload?.thread_id;
848
+ const expectedThread = isTopicThreadId(gatewayRoute.threadId) ? gatewayRoute.threadId : undefined;
849
+ if (params.aid !== gatewayRoute.self || params.to !== gatewayRoute.recipientId
850
+ || params.scope !== (gatewayRoute.peer.peerKind === 'group' ? 'group' : 'msg')
851
+ || topicId !== gatewayRoute.threadId
852
+ || (payloadThread !== undefined && payloadThread !== expectedThread)) {
853
+ throw Object.assign(new Error('Message recipient or topic conflicts with the resolved send route'), {
854
+ code: 'AUN_OUTBOUND_ROUTE_MISMATCH',
855
+ });
856
+ }
857
+ }
738
858
  }
739
859
  catch (error) {
740
860
  return {
@@ -761,43 +881,6 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
761
881
  if (!ch) {
762
882
  return { ok: false, error: `AUN channel not found for ${params.aid}`, code: 'AUN_CHANNEL_NOT_FOUND' };
763
883
  }
764
- // 跨话题自派(`--to <本端AID>`):收件人就是自己,不属于跨主体通讯,跳过联系人准入。
765
- // 不放进 evaluateAppContactAdmission 内部:那是通用准入判定,其它调用方
766
- // (入站、handoff 等)也用它,在函数内开口子会扩散到所有路径。
767
- if (params.scope === 'msg' && !isSelfAidTarget(params.aid, params.to)) {
768
- const admission = await evaluateOutboundContactAdmission({ selfAid: params.aid, targetAid: params.to });
769
- if (!admission.allow) {
770
- const decision = evaluateAppContactAdmission(params.aid, params.to);
771
- const friendInvite = params.rawPayload === true && params.encrypt === true
772
- && parseFriendInvite(params.payload, params.aid, params.to);
773
- const inviteMayRequestContact = !!friendInvite
774
- && (decision?.reason === 'not_in_contacts' || admission.code === 'CONTACT_ALL_CONTACTS_DISABLED');
775
- if (!inviteMayRequestContact) {
776
- const canRequestOwner = !!decision && (decision.reason === 'not_in_contacts' || decision.reason === 'scope_extension')
777
- && !params.file && params.returnPolicy !== 'required' && contactIntroductionText(params.payload) !== undefined;
778
- if (!canRequestOwner || typeof ch.requestOutboundContact !== 'function') {
779
- return { ok: false, error: admission.error, code: admission.code, sent: false };
780
- }
781
- try {
782
- // Retries of the same task message share an event; never queue the original peer send.
783
- const sourceMessageId = 'outbound-' + crypto.createHash('sha256').update(JSON.stringify([
784
- params.originSessionId, params.originMessageId, params.to, contactIntroductionText(params.payload),
785
- ])).digest('hex');
786
- const request = await ch.requestOutboundContact({ to: params.to, payload: params.payload, sourceMessageId });
787
- if (!request.ok)
788
- return { ok: false, code: request.code, error: request.error, sent: false };
789
- const receipt = request.receipt;
790
- return { ok: false, code: 'CONTACT_APPROVAL_REQUIRED', sent: false, retryable: false,
791
- error: `目标 ${params.to} 未准入,${receipt.status === 'sent' ? '已向' : '已排队向'}本端 Owner ${receipt.owner_aid} 提交联系申请,等待审批;原消息未发送`,
792
- contact_request: receipt };
793
- }
794
- catch (error) {
795
- return { ok: false, code: 'CONTACT_OWNER_REQUEST_FAILED', sent: false,
796
- error: `向本端 Owner 提交联系申请失败:${error instanceof Error ? error.message : String(error)};原消息未发送` };
797
- }
798
- }
799
- }
800
- }
801
884
  // The IPC command already carries the caller-selected transport scope.
802
885
  // Never reclassify the target by parsing its AID string: a private AID may
803
886
  // look group-like and a group identifier may use a future format.
@@ -873,6 +956,21 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
873
956
  if (params.rawPayload !== true && isTopicThreadId(params.thread) && typeof payload.thread_id !== 'string') {
874
957
  payload = { ...payload, thread_id: params.thread };
875
958
  }
959
+ if (params.rawPayload !== true) {
960
+ payload = withAunTopicSource(payload, {
961
+ selfAid: params.aid,
962
+ runtime,
963
+ targetPeer: threadRoute?.peer ?? params.to,
964
+ targetChatType: params.scope === 'group' ? 'group' : 'private',
965
+ targetThreadId: params.thread,
966
+ resolveName: source => {
967
+ const entry = source.thread_id
968
+ ? ThreadService.findThreadById(params.aid, source.thread_id)
969
+ : ThreadService.findMainSessionEntry(params.aid, source.peer_id);
970
+ return entry?.peer === source.peer_id ? entry.name : undefined;
971
+ },
972
+ });
973
+ }
876
974
  // 跨话题自派:在线上载荷显式打标。客户端(尤其观察者转发/入站解析)不必只靠
877
975
  // `from == to` 推断,可直接认这个字段;同 AID 的其它设备也据此区分「自己派给自己」。
878
976
  if (selfAddressed && params.rawPayload !== true) {
@@ -911,7 +1009,35 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
911
1009
  payload = preparedRequest.payload;
912
1010
  getAunRequestRegistry().markSending(params.aid, preparedRequest.requestId);
913
1011
  }
914
- let targetSessionId;
1012
+ let contactDelegationId;
1013
+ const contactTarget = threadRoute ?? (gatewayRoute ? {
1014
+ peer: gatewayRoute.peer.id, peerKind: gatewayRoute.peer.peerKind, channelType: gatewayRoute.peer.channelType,
1015
+ } : undefined);
1016
+ if (!selfAddressed && !preparedRequest && params.scope === 'msg' && threadRouted && contactTarget && targetTopicId && delegation.grant) {
1017
+ try {
1018
+ contactDelegationId = prepareContactThreadDelegation({
1019
+ selfAid: params.aid, grant: delegation.grant, runtime, target: contactTarget,
1020
+ targetThreadId: targetTopicId, wireThreadId: payload.thread_id,
1021
+ });
1022
+ }
1023
+ catch (error) {
1024
+ logger.warn(`[AUN] Could not persist contact delegation: ${error instanceof Error ? error.message : String(error)}`);
1025
+ }
1026
+ }
1027
+ const finishContactDelegation = (messageId) => {
1028
+ if (!contactDelegationId)
1029
+ return;
1030
+ try {
1031
+ finishContactThreadDelegation(params.aid, contactDelegationId, messageId);
1032
+ }
1033
+ catch (error) {
1034
+ logger.warn(`[AUN] Could not settle contact delegation: ${error instanceof Error ? error.message : String(error)}`);
1035
+ }
1036
+ };
1037
+ // Topic effects need the destination even when handoff is bypassed. Keep
1038
+ // the legacy log override separate: only handoff resolves that session.
1039
+ const targetSessionId = threadRoute?.sessionId;
1040
+ let handoffSessionId;
915
1041
  // 跨话题自派一律跳过 handoff:目标会话是按话题索引解析出的 (自端, 对端) 会话,
916
1042
  // 而 handoff 用 `to`(=本端)作为 channelId 去 getOrCreateSession,会建出
917
1043
  // 「我↔我」的错误会话目录。话题内与跨话题同此处理(D14)。
@@ -925,6 +1051,13 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
925
1051
  payload,
926
1052
  encrypt,
927
1053
  thread: params.thread,
1054
+ ...(gatewayRoute ? { expectedTarget: {
1055
+ channelType: gatewayRoute.peer.channelType,
1056
+ channelId: gatewayRoute.peer.id,
1057
+ chatType: gatewayRoute.peer.peerKind,
1058
+ threadId: isTopicThreadId(gatewayRoute.threadId) ? gatewayRoute.threadId : undefined,
1059
+ ...(threadRoute ? { sessionId: threadRoute.sessionId } : {}),
1060
+ } } : {}),
928
1061
  targetChatType: params.scope === 'group' ? 'group' : 'private',
929
1062
  // 目标会话可能属于别的渠道(如飞书话题):带上它自己的 channelKey,
930
1063
  // 否则会按 AUN 主渠建会话,投递到错误的渠道。
@@ -942,7 +1075,8 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
942
1075
  handoffContext: params.handoffContext,
943
1076
  // 跨话题发送的目标侧上下文由话题链(thread-inbox)负责注入;
944
1077
  // handoff 只管投递,回复时不再拼"本地发言"段。
945
- threadRouted: threadRouted && params.checkEveryMs !== undefined,
1078
+ // `--check-every none` 也写 inbox(只是不建 Trigger),所以判据只看向量本身。
1079
+ threadRouted,
946
1080
  originAuthorization: {
947
1081
  actorId: delegation.grant.actorId,
948
1082
  channelKey: delegation.grant.channel,
@@ -953,8 +1087,9 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
953
1087
  },
954
1088
  causation: runtimeCausation,
955
1089
  });
956
- targetSessionId = created.targetSession.id;
1090
+ handoffSessionId = created.targetSession.id;
957
1091
  if (created.crossSession && created.handoff) {
1092
+ finishContactDelegation(created.handoff.target_message_id ?? created.handoff.handoff_id);
958
1093
  const response = {
959
1094
  ok: true,
960
1095
  status: created.handoff.state === 'target_sent' ? 'delivered' : 'queued',
@@ -962,14 +1097,29 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
962
1097
  handoff_id: created.handoff.handoff_id,
963
1098
  target_session_id: created.targetSession.id,
964
1099
  };
1100
+ // 跨话题走 handoff,不会进入下面的直发分支:诊断在这里单独补一对,
1101
+ // 用入队时刻记 aun_out,用 handoff 的目标 message_id(已投递时)记 send_ok。
1102
+ diagLog('aun_out', {
1103
+ aid: params.aid, from: params.aid, to: params.to,
1104
+ taskId: runtime?.taskId, sessionId: params.originSessionId,
1105
+ text: params.log?.content ?? classifyAunPayloadForLog(payload).content,
1106
+ });
1107
+ if (response.message_id) {
1108
+ diagLog('send_ok', {
1109
+ aid: params.aid, from: params.aid, to: params.to,
1110
+ taskId: runtime?.taskId, sessionId: params.originSessionId,
1111
+ msgId: response.message_id,
1112
+ text: params.log?.content ?? classifyAunPayloadForLog(payload).content,
1113
+ });
1114
+ }
965
1115
  // 排队未投递(无 message_id)时也要写 inbox + 建复查:handoff 已不再
966
1116
  // 承载目标侧上下文,跳过这里就会丢上下文。
967
- if (threadRouted && params.checkEveryMs !== undefined && threadRoute) {
1117
+ if (threadRouted && targetTopicId) {
968
1118
  const effects = await applyManagedCrossThreadSendEffects({
969
1119
  runtime,
970
1120
  selfAid: params.aid,
971
- targetThreadId: targetTopicId ?? params.thread ?? "",
972
- targetSessionId: threadRoute.sessionId,
1121
+ targetThreadId: targetTopicId,
1122
+ targetSessionId: created.targetSession.id,
973
1123
  targetChannelId: params.to,
974
1124
  feedbackChatType: params.scope === 'group' ? 'group' : 'private',
975
1125
  messageId: response.message_id ?? created.handoff.handoff_id,
@@ -993,6 +1143,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
993
1143
  }
994
1144
  }
995
1145
  catch (error) {
1146
+ finishContactDelegation();
996
1147
  const code = error?.code;
997
1148
  const handoffId = error?.handoffId
998
1149
  ?? error?.blockingHandoffId;
@@ -1005,10 +1156,22 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1005
1156
  }
1006
1157
  }
1007
1158
  const debug = await resolveOutboundDebug(sessionId => responseEngine.getOutboundDebug(sessionId), params.originSessionId);
1159
+ // 主动发送路径(ecmsg send / ec msg send / ec group send)不经过
1160
+ // deliverTextEntry,出站诊断需要在这里单独打点,否则 diag 里查不到 agent 手发的消息。
1161
+ const diagText = params.log?.content ?? classifyAunPayloadForLog(payload).content;
1162
+ const diagCommon = {
1163
+ aid: params.aid,
1164
+ from: params.aid,
1165
+ to: params.to,
1166
+ taskId: runtime?.taskId,
1167
+ sessionId: runtime?.sessionId ?? params.originSessionId,
1168
+ text: diagText,
1169
+ };
1008
1170
  if (params.scope === 'group') {
1009
1171
  if (typeof ch.sendDaemonGroupMsg !== 'function') {
1010
1172
  return { ok: false, error: 'AUN channel does not support daemon group sends', code: 'AUN_GROUP_UNSUPPORTED' };
1011
1173
  }
1174
+ diagLog('aun_out', diagCommon);
1012
1175
  const sent = await ch.sendDaemonGroupMsg({
1013
1176
  groupId: params.to,
1014
1177
  payload,
@@ -1016,14 +1179,14 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1016
1179
  encrypt,
1017
1180
  debug,
1018
1181
  model: typeof debug?.model === 'string' ? debug.model : undefined,
1019
- log: params.log ? { ...params.log, sessionId: targetSessionId ?? params.log.sessionId } : undefined,
1182
+ log: params.log ? { ...params.log, sessionId: handoffSessionId ?? params.log.sessionId } : undefined,
1020
1183
  });
1021
- if (params.thread && params.checkEveryMs !== undefined && sent.ok && sent.message_id && threadRoute) {
1184
+ if (threadRouted && targetTopicId && sent.ok && sent.message_id && targetSessionId) {
1022
1185
  const effects = await applyManagedCrossThreadSendEffects({
1023
1186
  runtime,
1024
1187
  selfAid: params.aid,
1025
- targetThreadId: params.thread,
1026
- targetSessionId: threadRoute.sessionId,
1188
+ targetThreadId: targetTopicId,
1189
+ targetSessionId,
1027
1190
  targetChannelId: params.to,
1028
1191
  feedbackChatType: 'group',
1029
1192
  messageId: sent.message_id,
@@ -1040,11 +1203,15 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1040
1203
  if (effects.triggerError)
1041
1204
  sent.trigger_error = effects.triggerError;
1042
1205
  }
1206
+ if (sent.ok && sent.message_id)
1207
+ diagLog('send_ok', { ...diagCommon, msgId: sent.message_id });
1043
1208
  return sent;
1044
1209
  }
1045
1210
  if (typeof ch.sendDaemonMsg !== 'function') {
1211
+ finishContactDelegation();
1046
1212
  return { ok: false, error: 'AUN channel does not support daemon private sends', code: 'AUN_MSG_UNSUPPORTED' };
1047
1213
  }
1214
+ diagLog('aun_out', diagCommon);
1048
1215
  const sent = await ch.sendDaemonMsg({
1049
1216
  to: params.to,
1050
1217
  deviceId: params.deviceId,
@@ -1055,8 +1222,13 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1055
1222
  causation: runtimeCausation,
1056
1223
  debug,
1057
1224
  model: typeof debug?.model === 'string' ? debug.model : undefined,
1058
- log: params.log ? { ...params.log, sessionId: targetSessionId ?? params.log.sessionId } : undefined,
1059
- });
1225
+ log: params.log ? { ...params.log, sessionId: handoffSessionId ?? params.log.sessionId } : undefined,
1226
+ }).catch((error) => { finishContactDelegation(); throw error; });
1227
+ finishContactDelegation(sent.ok ? sent.message_id : undefined);
1228
+ // send_ok 只看网关是否返回 message_id,与 aun_out 的差值即发送失败次数;
1229
+ // 放在各个 return 分支之前,request / self-addressed 路径也不会漏记。
1230
+ if (sent.ok && sent.message_id)
1231
+ diagLog('send_ok', { ...diagCommon, msgId: sent.message_id });
1060
1232
  if (preparedRequest) {
1061
1233
  if (!sent.ok || !sent.message_id) {
1062
1234
  const transportError = sent.error || 'transport send failed';
@@ -1103,12 +1275,12 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1103
1275
  sent.self_session_id = delivered.sessionId;
1104
1276
  return sent;
1105
1277
  }
1106
- if (params.thread && params.checkEveryMs !== undefined && sent.ok && sent.message_id && threadRoute) {
1278
+ if (threadRouted && targetTopicId && sent.ok && sent.message_id && targetSessionId) {
1107
1279
  const effects = await applyManagedCrossThreadSendEffects({
1108
1280
  runtime,
1109
1281
  selfAid: params.aid,
1110
- targetThreadId: params.thread,
1111
- targetSessionId: threadRoute.sessionId,
1282
+ targetThreadId: targetTopicId,
1283
+ targetSessionId,
1112
1284
  targetChannelId: params.to,
1113
1285
  feedbackChatType: 'private',
1114
1286
  messageId: sent.message_id,