evolcore 0.0.48 → 0.0.50

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 (302) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/bin/ecmsg.js +9 -4
  3. package/dist/ability/caller/authorization.js +21 -0
  4. package/dist/ability/caller/command.js +164 -0
  5. package/dist/ability/caller/contract.js +102 -0
  6. package/dist/ability/caller/daemon.js +158 -0
  7. package/dist/ability/caller/service.js +380 -0
  8. package/dist/ability/command-contract.js +5 -0
  9. package/dist/ability/daemon.js +5 -1
  10. package/dist/ability/interop-v1.js +10 -3
  11. package/dist/ability/management.js +1 -0
  12. package/dist/agent-template/jobs.js +173 -1
  13. package/dist/agent-template/runtime.js +285 -8
  14. package/dist/agent-template/service.js +1159 -40
  15. package/dist/agent-template/types.js +2 -1
  16. package/dist/agents/baseagent-availability.js +27 -3
  17. package/dist/agents/baseagent-capability-adapter.js +102 -0
  18. package/dist/agents/baseagent-plugin-descriptor.js +274 -0
  19. package/dist/agents/baseagent-plugin-loader.js +145 -0
  20. package/dist/agents/baseagent.js +68 -2
  21. package/dist/agents/claude-gateway/agent-registration.js +389 -0
  22. package/dist/agents/claude-gateway/binding.js +96 -0
  23. package/dist/agents/claude-gateway/inbox.js +138 -0
  24. package/dist/agents/claude-gateway/index.js +125 -0
  25. package/dist/agents/claude-gateway/listing.js +330 -0
  26. package/dist/agents/claude-gateway/router.js +328 -0
  27. package/dist/agents/claude-gateway/sessions.js +128 -0
  28. package/dist/agents/claude-gateway/terminal.js +250 -0
  29. package/dist/agents/claude-gateway/transcript.js +272 -0
  30. package/dist/agents/claude-gateway/types.js +14 -0
  31. package/dist/agents/claude-runner.js +6 -10
  32. package/dist/agents/codex-runner.js +9 -2
  33. package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
  34. package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
  35. package/dist/agents/gemini/index.js +51 -0
  36. package/dist/aun/aid/control-aid.js +52 -32
  37. package/dist/aun/group/invite-service.js +6 -36
  38. package/dist/aun/group/operations.js +6 -0
  39. package/dist/aun/msg/mention-schema.js +1 -1
  40. package/dist/aun/msg/p2p.js +31 -2
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +1175 -457
  44. package/dist/cli/ability-command.js +42 -0
  45. package/dist/cli/agent-command.js +20 -1
  46. package/dist/cli/agent-create.js +78 -18
  47. package/dist/cli/agent-template.js +5 -3
  48. package/dist/cli/agent.js +91 -0
  49. package/dist/cli/aun-commands.js +92 -34
  50. package/dist/cli/bench.js +5 -2
  51. package/dist/cli/config.js +22 -6
  52. package/dist/cli/daemon-commands.js +245 -101
  53. package/dist/cli/directory.js +6 -1
  54. package/dist/cli/ecmsg-gateway.js +11 -9
  55. package/dist/cli/index.js +30 -5
  56. package/dist/cli/init.js +39 -63
  57. package/dist/cli/managed-command-guard.js +3 -0
  58. package/dist/cli/menu-client.js +32 -7
  59. package/dist/cli/model.js +20 -5
  60. package/dist/cli/pay-command.js +30 -0
  61. package/dist/cli/provider-command.js +6 -2
  62. package/dist/cli/quota.js +89 -0
  63. package/dist/cli/restart-monitor.js +2 -2
  64. package/dist/cli/role.js +1 -0
  65. package/dist/cli/services-command.js +12 -9
  66. package/dist/cli/team-workspace-command.js +56 -2
  67. package/dist/cli/thread-command.js +78 -12
  68. package/dist/config/access-policy.js +16 -3
  69. package/dist/config/config-field-policy.js +88 -9
  70. package/dist/config/config-manager.js +97 -47
  71. package/dist/config/config-operation-service.js +22 -1
  72. package/dist/config/gateway-config.js +9 -8
  73. package/dist/config/owner-config.js +0 -16
  74. package/dist/config/peer-role-resolver.js +1 -7
  75. package/dist/config/providers-config.js +107 -20
  76. package/dist/config/providers-management.js +45 -21
  77. package/dist/config/resolved-config-op.js +4 -44
  78. package/dist/config/schema-migration.js +78 -5
  79. package/dist/config/schema-registry.js +52 -7
  80. package/dist/config-store.js +1309 -17
  81. package/dist/core/agent-application-service.js +220 -1
  82. package/dist/core/agent-ipc-registration.js +19 -2
  83. package/dist/core/agent-reload-coordinator.js +5 -0
  84. package/dist/core/agent-runtime.js +198 -54
  85. package/dist/core/auth/agent-delegation.js +14 -0
  86. package/dist/core/auth/delegation-authorization.js +33 -26
  87. package/dist/core/auth/operation-authorizer.js +16 -1
  88. package/dist/core/auth/operation-catalog.js +59 -7
  89. package/dist/core/baseagent-loader.js +30 -3
  90. package/dist/core/capability/capability-manager.js +16 -7
  91. package/dist/core/channel-runtime.js +4 -2
  92. package/dist/core/command/agent-control.js +20 -2
  93. package/dist/core/command/agent-template-menu.js +4 -3
  94. package/dist/core/command/cli-intent-parser.js +28 -0
  95. package/dist/core/command/command-handler.js +45 -2
  96. package/dist/core/command/menu-catalog.js +20 -4
  97. package/dist/core/command/menu-file-path.js +70 -0
  98. package/dist/core/command/menu-handler.js +97 -73
  99. package/dist/core/command/menu-protocol.js +29 -0
  100. package/dist/core/command/menu-query-batch.js +2 -2
  101. package/dist/core/command/private-mention-menu.js +71 -0
  102. package/dist/core/command/remote-shell.js +565 -0
  103. package/dist/core/command/slash-handler.js +17 -26
  104. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  105. package/dist/core/command/topic-slash.js +7 -1
  106. package/dist/core/daemon-bootstrap.js +0 -4
  107. package/dist/core/daemon-control.js +58 -1
  108. package/dist/core/daemon-lifecycle.js +29 -7
  109. package/dist/core/evolagent-registry.js +18 -9
  110. package/dist/core/handoff/runtime.js +1 -1
  111. package/dist/core/host-snapshot.js +8 -3
  112. package/dist/core/initialization/service.js +3 -0
  113. package/dist/core/interaction-router.js +130 -0
  114. package/dist/core/ipc-registration.js +5 -0
  115. package/dist/core/memory/consolidation-context.js +2 -1
  116. package/dist/core/memory/consolidation.js +35 -64
  117. package/dist/core/message/aun-ipc-sender.js +213 -74
  118. package/dist/core/message/aun-request-registry.js +31 -0
  119. package/dist/core/message/contact-admission.js +91 -6
  120. package/dist/core/message/contact-pending-inbound.js +113 -0
  121. package/dist/core/message/contact-thread-approval.js +212 -0
  122. package/dist/core/message/im-renderer.js +40 -1
  123. package/dist/core/message/message-admission.js +5 -39
  124. package/dist/core/message/message-bridge.js +197 -45
  125. package/dist/core/message/message-log.js +32 -0
  126. package/dist/core/message/message-queue.js +102 -18
  127. package/dist/core/message/peer-mode.js +15 -4
  128. package/dist/core/message/response-engine.js +174 -26
  129. package/dist/core/message/send-options.js +37 -3
  130. package/dist/core/message/send-routing.js +11 -7
  131. package/dist/core/model/config-scope.js +6 -14
  132. package/dist/core/model/model-catalog.js +5 -5
  133. package/dist/core/model/model-diagnostics.js +19 -0
  134. package/dist/core/model/model-fallback.js +13 -2
  135. package/dist/core/ownership/owner-resolver.js +12 -86
  136. package/dist/core/pack-auth.js +7 -0
  137. package/dist/core/pack-install.js +1 -1
  138. package/dist/core/permission/ec-command-parser.js +288 -77
  139. package/dist/core/permission/protected-paths.js +64 -9
  140. package/dist/core/permission/services-path-acl.js +458 -0
  141. package/dist/core/permission/tool-policy.js +26 -10
  142. package/dist/core/relation/peer-identity.js +13 -0
  143. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  144. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  145. package/dist/core/session/session-manager.js +47 -10
  146. package/dist/core/session/session-mapper.js +16 -0
  147. package/dist/core/skill/index-generator.js +2 -3
  148. package/dist/core/skill/switch-resolver.js +3 -0
  149. package/dist/core/task/task-recovery-service.js +1 -0
  150. package/dist/core/thread/command-parser.js +4 -1
  151. package/dist/core/thread/ipc-operation.js +4 -2
  152. package/dist/core/thread/thread-operation.js +25 -10
  153. package/dist/core/thread/thread-service.js +294 -55
  154. package/dist/core/thread/topic-id.js +67 -2
  155. package/dist/core/thread/types.js +15 -1
  156. package/dist/directory/owner-directory-admission.js +11 -8
  157. package/dist/directory/owner-directory-cache.js +19 -0
  158. package/dist/directory/owner-directory-markdown.js +1 -1
  159. package/dist/directory/owner-directory-policy.js +5 -30
  160. package/dist/directory/owner-directory-request-operation.js +5 -2
  161. package/dist/eck/kit-renderer.js +3 -2
  162. package/dist/eck/message-renderer.js +28 -5
  163. package/dist/ecweb/basic-settings-service.js +5 -9
  164. package/dist/ecweb/providers-service.js +4 -2
  165. package/dist/ecweb/runtime/supervisor.js +36 -8
  166. package/dist/event-center/center-config.js +9 -5
  167. package/dist/event-center/dispatcher.js +10 -1
  168. package/dist/event-center/ipc-operation.js +19 -0
  169. package/dist/event-center/registry.js +20 -5
  170. package/dist/event-center/runtime.js +10 -7
  171. package/dist/index.js +120 -41
  172. package/dist/ipc.js +83 -3
  173. package/dist/outputs/authorization.js +16 -0
  174. package/dist/outputs/cards.js +336 -0
  175. package/dist/outputs/events.js +3 -2
  176. package/dist/outputs/protocol.js +1 -0
  177. package/dist/outputs/service.js +2 -15
  178. package/dist/paths.js +48 -1
  179. package/dist/pay/command.js +38 -0
  180. package/dist/pay/protocol.js +136 -0
  181. package/dist/pay/runtime.js +188 -0
  182. package/dist/pay/service.js +384 -0
  183. package/dist/pay/store.js +81 -0
  184. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  185. package/dist/services/dispatcher.js +23 -5
  186. package/dist/services/host/main.js +388 -0
  187. package/dist/services/host/protocol.js +118 -0
  188. package/dist/services/host/resident.js +310 -0
  189. package/dist/services/host-client.js +386 -0
  190. package/dist/services/host-deploy.js +180 -0
  191. package/dist/services/host-launch.js +117 -0
  192. package/dist/services/host-recycle.js +203 -0
  193. package/dist/services/host-runtime.js +802 -0
  194. package/dist/services/idempotency.js +44 -86
  195. package/dist/services/index-generator.js +4 -3
  196. package/dist/services/index.js +204 -22
  197. package/dist/services/ipc-operation.js +288 -44
  198. package/dist/services/pack-manager.js +1 -0
  199. package/dist/services/script-runner.js +515 -83
  200. package/dist/services/service-payload.js +13 -7
  201. package/dist/services/validation.js +109 -4
  202. package/dist/stats/budget.js +1 -1
  203. package/dist/stats/model-resolver.js +2 -2
  204. package/dist/stats/quota-query.js +95 -0
  205. package/dist/trigger/application-service.js +6 -4
  206. package/dist/trigger/local-files.js +19 -9
  207. package/dist/trigger/scheduler.js +22 -12
  208. package/dist/trigger/script-sandbox.js +51 -8
  209. package/dist/utils/aid-bind.js +3 -0
  210. package/dist/utils/atomic-write.js +22 -8
  211. package/dist/utils/evolcore-version.js +2 -2
  212. package/dist/utils/host-info.js +173 -1
  213. package/dist/utils/logger.js +2 -2
  214. package/dist/utils/media-cache.js +190 -43
  215. package/dist/utils/npm-ops.js +43 -8
  216. package/dist/utils/restart-safety.js +14 -1
  217. package/dist/utils/system-memory.js +113 -25
  218. package/dist/utils/systemd-lifecycle.js +154 -0
  219. package/dist/utils/windows-shell-trust.js +7 -3
  220. package/dist/workbench/service.js +1 -1
  221. package/kits/docs/INDEX.md +3 -2
  222. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
  223. package/kits/docs/channels/aun.md +1 -1
  224. package/kits/docs/evolcore/INDEX.md +9 -6
  225. package/kits/docs/evolcore/agent.md +36 -1
  226. package/kits/docs/evolcore/aid.md +45 -3
  227. package/kits/docs/evolcore/config.md +5 -2
  228. package/kits/docs/evolcore/directory.md +8 -9
  229. package/kits/docs/evolcore/group.md +2 -1
  230. package/kits/docs/evolcore/memory-tags.md +2 -0
  231. package/kits/docs/evolcore/menu-client.md +3 -3
  232. package/kits/docs/evolcore/menu-protocol.md +7 -0
  233. package/kits/docs/evolcore/model.md +3 -0
  234. package/kits/docs/evolcore/msg.md +77 -10
  235. package/kits/docs/evolcore/pay.md +34 -0
  236. package/kits/docs/evolcore/provider.md +22 -1
  237. package/kits/docs/evolcore/quota.md +54 -0
  238. package/kits/docs/evolcore/role.md +3 -0
  239. package/kits/docs/evolcore/services.md +46 -18
  240. package/kits/docs/evolcore/stats.md +2 -0
  241. package/kits/docs/evolcore/thread-chain.md +2 -0
  242. package/kits/docs/evolcore/tool-authorization.md +10 -0
  243. package/kits/docs/evolcore/trigger.md +2 -0
  244. package/kits/rules/01-overview.md +11 -32
  245. package/kits/rules/02-navigation.md +7 -0
  246. package/kits/rules/06-channel.md +3 -3
  247. package/kits/schemas/_meta.json +38 -5
  248. package/kits/schemas/agent-config.schema.20.json +24 -0
  249. package/kits/schemas/agent-config.schema.21.json +974 -0
  250. package/kits/schemas/agent-config.schema.22.json +977 -0
  251. package/kits/schemas/agent-config.schema.23.json +958 -0
  252. package/kits/schemas/daemon.schema.10.json +373 -0
  253. package/kits/schemas/daemon.schema.9.json +12 -0
  254. package/kits/schemas/defaults.schema.7.json +472 -0
  255. package/kits/schemas/providers.schema.3.json +18 -2
  256. package/kits/schemas/relation-config.schema.13.json +289 -0
  257. package/kits/skills/.switches.json +17 -1
  258. package/kits/skills/ability/SKILL.md +229 -34
  259. package/kits/skills/ability/STRUCTURE.md +333 -0
  260. package/kits/skills/ability/references/cli.md +208 -0
  261. package/kits/skills/ability/references/development.md +107 -37
  262. package/kits/skills/ability/references/management.md +106 -46
  263. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  264. package/kits/skills/agent-output-cards/SKILL.md +64 -0
  265. package/kits/skills/ec-group/SKILL.md +8 -6
  266. package/kits/skills/ec-group/TASK.md +186 -0
  267. package/kits/skills/ec-group/WORKLOG.md +180 -0
  268. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  269. package/kits/skills/ec-pay/SKILL.md +101 -0
  270. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  271. package/kits/skills/ec-provider/SKILL.md +58 -9
  272. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  273. package/kits/skills/ec-service-call/SKILL.md +135 -0
  274. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  275. package/kits/skills/ec-trigger/SKILL.md +1 -1
  276. package/kits/templates/memory-consolidation/notes.md +2 -2
  277. package/kits/templates/memory-consolidation/workflow.md +46 -0
  278. package/kits/templates/roles/visitor.json +1 -0
  279. package/kits/templates/system-fragments/channel.md +13 -4
  280. package/kits/templates/system-fragments/commands.md +5 -3
  281. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  282. package/kits/templates/system-fragments/reply.md +1 -0
  283. package/kits/templates/system-fragments/session.md +1 -1
  284. package/kits/templates/system-fragments/thread.md +27 -128
  285. package/kits/templates/system-fragments/venue.md +27 -0
  286. package/package.json +4 -5
  287. package/scripts/agent-template/inspect.mjs +79 -29
  288. package/scripts/agent-template/overlay.mjs +20 -2
  289. package/scripts/agent-template/shared/common.mjs +24 -6
  290. package/scripts/agent-template/shared/team-schema.json +23 -5
  291. package/scripts/agent-template/shared/template-contract.mjs +107 -17
  292. package/scripts/agent-template/shared/template-package.mjs +254 -29
  293. package/scripts/agent-template/shared/template-runtime.mjs +145 -2
  294. package/scripts/agent-template/shared/template.mjs +67 -9
  295. package/scripts/agent-template/team-pack.mjs +132 -41
  296. package/scripts/agent-template/team-preview.mjs +249 -5
  297. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  298. package/kits/docs/evolcore/ability.md +0 -185
  299. package/kits/skills/ability/references/calling.md +0 -56
  300. package/kits/skills/ability/references/contract-checklist.md +0 -37
  301. package/kits/skills/ability/references/recovery.md +0 -27
  302. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -1186,48 +1186,25 @@ export function createConsolidationFeedbackSender(getChannel) {
1186
1186
  const debug = origin.debug;
1187
1187
  if (debug)
1188
1188
  replyContext.debug = debug;
1189
- // 对比期:同一份反馈 notice、text 各发一条,观察两种模式在对端的差异,
1190
- // 跑通后删掉 text 那条。两条 taskId 后缀不同,避免共用 operationId 被出站去重吞掉一条;
1191
- // 各自 try,一条失败不连累另一条。
1192
- const stamp = Date.now();
1193
- const envelopeFor = (suffix) => buildEnvelope({
1194
- taskId: `memory-feedback-${stamp}-${suffix}`,
1189
+ // 反馈只走 system.notice 一条:整理是后台任务的结果汇报,不是对用户提问的
1190
+ // 答复。用 result.text + isFinal 会让它在对端被当成 Agent 最终回复(提示音、
1191
+ // 最终回复标记),语义和事实都不对;群聊里同类反馈(command.result)也是
1192
+ // 降级成 notice 的,对齐那个先例。
1193
+ const envelope = buildEnvelope({
1194
+ taskId: `memory-feedback-${Date.now()}`,
1195
1195
  channel: binding.adapter.channelKey,
1196
1196
  channelId,
1197
1197
  agentName: binding.agentName,
1198
1198
  replyContext: Object.keys(replyContext).length > 0 ? replyContext : undefined,
1199
1199
  });
1200
- const attempts = [
1201
- {
1202
- mode: 'notice',
1203
- send: () => binding.adapter.send(envelopeFor('notice'), {
1204
- kind: 'system.notice',
1205
- text,
1206
- subtype: 'memory.consolidation.result',
1207
- }),
1208
- },
1209
- {
1210
- mode: 'text',
1211
- send: () => binding.adapter.send(envelopeFor('text'), {
1212
- kind: 'result.text',
1213
- text,
1214
- isFinal: true,
1215
- format: 'markdown',
1216
- }),
1217
- },
1218
- ];
1219
- const failures = [];
1220
- for (const { mode, send } of attempts) {
1221
- try {
1222
- await send();
1223
- logger.info(`[Memory] 整理反馈已投递(mode=${mode},aid=${selfAid},channelId=${channelId})`);
1224
- }
1225
- catch (error) {
1226
- failures.push(`${mode}: ${error?.message}`);
1227
- }
1228
- }
1229
- if (failures.length > 0)
1230
- throw new Error(failures.join('; '));
1200
+ await binding.adapter.send(envelope, {
1201
+ kind: 'system.notice',
1202
+ // notice 在对端按普通文字渲染、不解析 Markdown:自定义反馈即使写成多行
1203
+ // (或带 ## / ** 标记),也压成一行发出,避免格式标记原样外露。
1204
+ text: collapseToLine(text),
1205
+ subtype: 'memory.consolidation.result',
1206
+ });
1207
+ logger.info(`[Memory] 整理反馈已投递(aid=${selfAid},channelId=${channelId})`);
1231
1208
  };
1232
1209
  }
1233
1210
  /** 从 bg-session 终态事件里取出模型字段,原样交给收尾流程。 */
@@ -1461,12 +1438,14 @@ export function registerConsolidationCheckExecutor({ ipcServer, agentRegistry, e
1461
1438
  // The relation directory is optional during initial bootstrap.
1462
1439
  }
1463
1440
  const useMetaIndex = shouldUseMetaIndex(agentCount, relationCount);
1464
- const knownOwnerAid = ownerResolver.knownOwner(selfAid);
1465
1441
  const candidates = checkConsolidationCandidates({
1466
1442
  selfAid, config: { ...agentConfig?.memory, enableOwner: false }, useMetaIndex,
1467
1443
  });
1444
+ // Ownership comes from the protocol only. This pre-check runs before the
1445
+ // refresh below, so an unbound Agent deliberately scans every owner
1446
+ // directory: a superset is a wasted refresh, never a skipped candidate.
1468
1447
  const ownerCandidates = hasOwnerConsolidationCandidates({
1469
- selfAid, ownerAid: knownOwnerAid, config: agentConfig?.memory,
1448
+ selfAid, ownerAid: getProtocolOwner(selfAid), config: agentConfig?.memory,
1470
1449
  });
1471
1450
  if (candidates.length === 0 && !ownerCandidates)
1472
1451
  return { launched: [] };
@@ -1575,7 +1554,12 @@ export function registerRelationConsolidationEvents({ eventBus, agentRegistry, r
1575
1554
  void triggerRelationConsolidation(taskCtx, 'session-new');
1576
1555
  });
1577
1556
  }
1578
- /** Render the default feedback message for a completed memory consolidation. */
1557
+ /**
1558
+ * Render the default feedback line for a completed memory consolidation.
1559
+ *
1560
+ * 只产**单行纯文本**:这条反馈以 system.notice 投递,对端按普通文字渲染,
1561
+ * 不解析 Markdown。多行或 `##`/`**` 标记会在气泡里原样露出来。
1562
+ */
1579
1563
  export function renderDefaultConsolidationFeedback(input) {
1580
1564
  const triggerLabel = {
1581
1565
  manual: '手动触发',
@@ -1586,33 +1570,20 @@ export function renderDefaultConsolidationFeedback(input) {
1586
1570
  };
1587
1571
  const mode = input.mode ?? 'notes';
1588
1572
  const cause = triggerLabel[input.triggeredBy] ?? input.triggeredBy;
1573
+ const context = `${mode} / ${cause}`;
1589
1574
  if (!input.success) {
1590
- return [
1591
- '## 记忆整理失败',
1592
- '',
1593
- `**模式**:${mode}`,
1594
- `**触发**:${cause}`,
1595
- ...(input.failureReason ? [`**原因**:${input.failureReason}`] : []),
1596
- '',
1597
- '本次整理未完成,已回退未归档的改动。详情见整理批次:',
1598
- `\`${input.batchDir}\``,
1599
- ].join('\n');
1575
+ const reason = input.failureReason ? `:${collapseToLine(input.failureReason)}` : '';
1576
+ // 失败要留可追查的落点:批次目录是唯一能翻到细节的地方
1577
+ return `记忆整理失败(${context})${reason}。已回退未归档改动,详情见 ${input.batchDir}`;
1600
1578
  }
1601
1579
  const { created, updated, archived, errors } = input.summary;
1602
- const lines = [
1603
- '## 记忆整理完成',
1604
- '',
1605
- `**模式**:${mode} `,
1606
- `**触发**:${cause}`,
1607
- '',
1608
- '### 处理结果',
1609
- `- 新建记忆:${created} 条`,
1610
- `- 更新记忆:${updated} 条`,
1611
- `- 归档记忆:${archived} 条`,
1612
- ];
1580
+ const counts = [`新建 ${created} 条`, `更新 ${updated} 条`, `归档 ${archived} 条`];
1613
1581
  if (errors > 0)
1614
- lines.push(`- 错误:${errors} 条`);
1615
- lines.push('', `整理批次:\`${input.batchDir}\``);
1616
- return lines.join('\n');
1582
+ counts.push(`错误 ${errors} 条`);
1583
+ return `记忆整理完成(${context}):${counts.join('、')}`;
1584
+ }
1585
+ /** 把可能带换行的外部文本压成一行,避免破坏 notice 的单行呈现。 */
1586
+ function collapseToLine(value) {
1587
+ return value.replace(/\s+/g, ' ').trim();
1617
1588
  }
1618
1589
  export { resolveRoot };
@@ -1,21 +1,19 @@
1
1
  import path from 'node:path';
2
2
  import { resolveAunSendDevice } from '../../aun/ability-device-routing.js';
3
3
  import crypto from 'crypto';
4
- import { authorizeDelegatedAunMsgSend, delegationFailureDetailCode, hasTrustedFullAccessDelegation, } from '../auth/agent-delegation.js';
4
+ import { authorizeDelegatedAunMsgSend, delegationFailureDetailCode, hasTrustedFullAccessDelegation, hashDelegatedCommandArgv, } from '../auth/agent-delegation.js';
5
5
  import { formatChannelKey, tryParseChannelKey } from '../channel-loader.js';
6
6
  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
18
  import { diagLog } from '../../utils/msg-diag.js';
21
19
  import { buildEnvelope, DEFAULT_NOOP_SENTINEL } from './message-utils.js';
@@ -24,12 +22,51 @@ import { getAunRequestRegistry, requestDiagnostics, requestTtlSeconds } from './
24
22
  import { canonicalizeEvolcoreCommandArgv, parseJsonObjectArgument } from '../permission/ec-command-parser.js';
25
23
  import { formatPeerKey, parsePeerKey, readAunPeerKind, resolveAunPeerKind } from '../relation/peer-identity.js';
26
24
  import { logger } from '../../utils/logger.js';
27
- import { MESSAGE_CLI_BIN } from '../../product.js';
25
+ import { MESSAGE_CLI_BIN, MAIN_CLI_BIN } from '../../product.js';
26
+ import { parseRemoteCommand } from '../../ability/caller/command.js';
28
27
  import { buildDownstreamArgv, expandGroupBase, parseGatewayArgs } from '../../cli/ecmsg-gateway.js';
29
28
  import { resolveSendRoute } from './send-routing.js';
30
29
  import { agentDir } from '../../paths.js';
31
30
  import { chatDirPath, readAllJsonlLines } from '../session/session-fs-store.js';
31
+ import { prepareContactThreadDelegation, finishContactThreadDelegation, findContactThreadReturn } from './contact-thread-approval.js';
32
+ import { currentContactBinding } from './contact-admission.js';
32
33
  const TASK_ID_MESSAGE_PAYLOAD_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file']);
34
+ const TOPIC_SOURCE_MESSAGE_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file', 'action_card', 'widget_card']);
35
+ /** Stamp the actual runtime source before handoff/outbox persistence, including retries. */
36
+ export function withAunTopicSource(payload, input) {
37
+ // A caller's payload can be copied from another message. Its old provenance
38
+ // must not survive a new managed send or mark an ordinary reply cross-topic.
39
+ const result = { ...payload };
40
+ delete result.topic_source;
41
+ const runtime = input.runtime;
42
+ if (!TOPIC_SOURCE_MESSAGE_TYPES.has(String(payload.type)) || runtime?.channel !== 'aun'
43
+ || runtime.selfAid !== input.selfAid
44
+ || (runtime.chatType !== 'private' && runtime.chatType !== 'group'))
45
+ return result;
46
+ // channelId is the conversation peer; peerId in a group is the speaker.
47
+ const peer = runtime.channelId?.trim() ?? '';
48
+ if (!safeFormatMainTopicId(input.selfAid, peer))
49
+ return result;
50
+ const threadId = isTopicThreadId(runtime.threadId) ? runtime.threadId : '';
51
+ if (!isMainSessionThreadId(runtime.threadId) && !/^thread-[a-zA-Z0-9-]+$/.test(threadId))
52
+ return result;
53
+ const targetThreadId = isTopicThreadId(input.targetThreadId) ? input.targetThreadId : '';
54
+ if (peer.toLowerCase() === input.targetPeer.trim().toLowerCase()
55
+ && runtime.chatType === input.targetChatType && threadId === targetThreadId)
56
+ return result;
57
+ const source = {
58
+ version: 1, agent_aid: input.selfAid, peer_id: peer,
59
+ chat_type: runtime.chatType, thread_id: threadId,
60
+ };
61
+ // An absent/deleted index entry must never prevent the message being sent.
62
+ try {
63
+ const name = input.resolveName?.(source)?.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 256);
64
+ if (name && name !== '话题会话' && name !== '默认会话')
65
+ source.name = name;
66
+ }
67
+ catch { /* the coordinates still identify the source */ }
68
+ return { ...result, topic_source: source };
69
+ }
33
70
  function normalizeAid(value) {
34
71
  return String(value ?? '').trim().replace(/^@/, '').toLowerCase();
35
72
  }
@@ -510,6 +547,18 @@ async function resolveGatewaySend(argv, grant, runtime, session) {
510
547
  || (currentChatType !== 'private' && currentChatType !== 'group')) {
511
548
  throw Object.assign(new Error('Current AUN conversation route is unavailable'), { code: 'AUN_OUTBOUND_ROUTE_REQUIRED' });
512
549
  }
550
+ // An unqualified report to Owner continues its unique originating delegation.
551
+ // Explicit --thread always wins; unrelated conversations keep normal routing.
552
+ let returningToOrigin = false;
553
+ if (options.thread === undefined && options.to
554
+ && normalizeAid(options.to) === currentContactBinding(grant.selfAid)?.owner_aid) {
555
+ const origin = findContactThreadReturn({ selfAid: grant.selfAid, grant, runtime });
556
+ if (origin) {
557
+ options.thread = origin.originThreadId;
558
+ options.checkEvery ??= 'none';
559
+ returningToOrigin = true;
560
+ }
561
+ }
513
562
  const resolveKind = async (target) => {
514
563
  if (normalizeAid(target) === normalizeAid(currentPeer))
515
564
  return currentChatType;
@@ -563,10 +612,12 @@ async function resolveGatewaySend(argv, grant, runtime, session) {
563
612
  }, deps);
564
613
  if (!route.ok)
565
614
  throw Object.assign(new Error(route.message), { code: route.code });
615
+ if (returningToOrigin)
616
+ route.source.thread = 'derived';
566
617
  return { route, argv: buildDownstreamArgv(route, text, passthrough) };
567
618
  }
568
619
  export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegationRegistry, responseEngine, handoffRuntime, sessionManager, messageQueue, createCrossThreadReviewTrigger, }) {
569
- ipcServer.setAunRequestGetExecutor(async (params) => {
620
+ const getRequest = async (params, abilityGrant) => {
570
621
  if (!params.sessionId || !params.delegationToken) {
571
622
  return { ok: false, code: 'DELEGATION_REQUIRED', error: 'Request queries require an active delegated session' };
572
623
  }
@@ -583,6 +634,14 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
583
634
  || request.origin.peerKey !== authorization.grant.peerKey || request.origin.threadId !== runtime.threadId) {
584
635
  return { ok: false, code: 'REQUEST_NOT_FOUND', error: 'Request is not available in this session' };
585
636
  }
637
+ if (abilityGrant) {
638
+ if (!agentDelegationRegistry.isCurrentTaskGrant(abilityGrant) || !request.responseCorrelation
639
+ || authorization.grant.taskId !== abilityGrant.taskId || authorization.grant.selfAid !== abilityGrant.selfAid
640
+ || authorization.grant.sessionId !== abilityGrant.sessionId) {
641
+ return { ok: false, code: 'REQUEST_NOT_FOUND', error: 'Ability request is not available in the current task' };
642
+ }
643
+ return { ok: true, request: request };
644
+ }
586
645
  const targetRoute = request.origin.targetThreadId
587
646
  ? resolveThreadRouteTarget(params.aid, request.origin.targetThreadId, 'msg', request.targetAid)
588
647
  : undefined;
@@ -599,8 +658,10 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
599
658
  return { ok: false, code: permitted.code, error: permitted.reason };
600
659
  return request ? { ok: true, request: request }
601
660
  : { ok: false, code: 'REQUEST_NOT_FOUND', error: `request not found: ${params.requestId}` };
602
- });
603
- const sender = async (params, inspectedGrant, gatewayRoute) => {
661
+ };
662
+ ipcServer.setAunRequestGetExecutor(params => getRequest(params));
663
+ ipcServer.setAbilityRequestGetExecutor?.((params, grant) => getRequest(params, grant));
664
+ const sender = async (params, inspectedGrant, gatewayRoute, protocolGrant) => {
604
665
  let textFile;
605
666
  let payloadFile;
606
667
  try {
@@ -681,6 +742,10 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
681
742
  }
682
743
  }
683
744
  const runtimeCausation = runtime?.causation;
745
+ if (protocolGrant && (!runtime || runtime.selfAid !== params.aid || runtime.peerKey !== protocolGrant.peerKey
746
+ || !agentDelegationRegistry.isCurrentTaskGrant(protocolGrant))) {
747
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'Ability transport requires the current task context', sent: false };
748
+ }
684
749
  // 跨话题自派(self-address):收件人是本端自己,话题归属仍是 (自端, 对端)。
685
750
  // 此时 `params.to` 不是「话题对端」,不能拿它做话题一致性校验。
686
751
  const selfAddressed = isSelfAidTarget(params.aid, params.to);
@@ -701,13 +766,15 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
701
766
  }
702
767
  // Topic lookup also restores the current topic; cross-topic side effects
703
768
  // must follow the verified route rather than the presence of a topic ID.
704
- const threadRouted = !!threadRoute && (gatewayRoute?.crossTopic ?? true);
769
+ // First-contact gateway sends omit --thread until handoff creates the main
770
+ // session. They still cross topics and must retain their delegation/inbox.
771
+ const threadRouted = gatewayRoute?.crossTopic ?? !!threadRoute;
705
772
  // 规范目标 id:话题保留原 id;主话题用双方拼出的规范形态(用于 Trigger 标签与通知)。
706
773
  const targetTopicId = threadRoute
707
774
  ? (isTopicThreadId(threadRef)
708
775
  ? threadRef
709
776
  : (safeFormatMainTopicId(params.aid, threadRoute.peer) ?? threadRef))
710
- : undefined;
777
+ : gatewayRoute?.threadId;
711
778
  const isSystemEvent = params.trustedSystemEvent === true
712
779
  && params.payload?.type === 'event' && params.payload.event === 'topic.renamed';
713
780
  // 非托管跨话题自派:调用方没有委托凭证,用本机 controlToken 证明「本机控制面调用」。
@@ -737,18 +804,19 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
737
804
  sessionId: '',
738
805
  },
739
806
  }
740
- : await authorizeDelegatedAunMsgSend(agentDelegationRegistry, {
741
- delegationToken: params.delegationToken,
742
- delegationCommandHash: params.delegationCommandHash,
743
- sessionId: params.originSessionId,
744
- messageId: params.originMessageId,
745
- aid: params.aid,
746
- to: params.to,
747
- scope: params.scope,
748
- action: params.file ? 'file' : 'send',
749
- threadRouted: authorizationTargetRouted,
750
- isSystemEvent,
751
- });
807
+ : protocolGrant ? { ok: true, grant: protocolGrant }
808
+ : await authorizeDelegatedAunMsgSend(agentDelegationRegistry, {
809
+ delegationToken: params.delegationToken,
810
+ delegationCommandHash: params.delegationCommandHash,
811
+ sessionId: params.originSessionId,
812
+ messageId: params.originMessageId,
813
+ aid: params.aid,
814
+ to: params.to,
815
+ scope: params.scope,
816
+ action: params.file ? 'file' : 'send',
817
+ threadRouted: authorizationTargetRouted,
818
+ isSystemEvent,
819
+ });
752
820
  if (!delegation.ok) {
753
821
  return {
754
822
  ok: false,
@@ -829,50 +897,19 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
829
897
  if (!ch) {
830
898
  return { ok: false, error: `AUN channel not found for ${params.aid}`, code: 'AUN_CHANNEL_NOT_FOUND' };
831
899
  }
832
- // 跨话题自派(`--to <本端AID>`):收件人就是自己,不属于跨主体通讯,跳过联系人准入。
833
- // 不放进 evaluateAppContactAdmission 内部:那是通用准入判定,其它调用方
834
- // (入站、handoff 等)也用它,在函数内开口子会扩散到所有路径。
835
- if (params.scope === 'msg' && !isSelfAidTarget(params.aid, params.to)) {
836
- const admission = await evaluateOutboundContactAdmission({ selfAid: params.aid, targetAid: params.to });
837
- if (!admission.allow) {
838
- const decision = evaluateAppContactAdmission(params.aid, params.to);
839
- const friendInvite = params.rawPayload === true && params.encrypt === true
840
- && parseFriendInvite(params.payload, params.aid, params.to);
841
- const inviteMayRequestContact = !!friendInvite
842
- && (decision?.reason === 'not_in_contacts' || admission.code === 'CONTACT_ALL_CONTACTS_DISABLED');
843
- if (!inviteMayRequestContact) {
844
- const canRequestOwner = !!decision && (decision.reason === 'not_in_contacts' || decision.reason === 'scope_extension')
845
- && !params.file && params.returnPolicy !== 'required' && contactIntroductionText(params.payload) !== undefined;
846
- if (!canRequestOwner || typeof ch.requestOutboundContact !== 'function') {
847
- return { ok: false, error: admission.error, code: admission.code, sent: false };
848
- }
849
- try {
850
- // Retries of the same task message share an event; never queue the original peer send.
851
- const sourceMessageId = 'outbound-' + crypto.createHash('sha256').update(JSON.stringify([
852
- params.originSessionId, params.originMessageId, params.to, contactIntroductionText(params.payload),
853
- ])).digest('hex');
854
- const request = await ch.requestOutboundContact({ to: params.to, payload: params.payload, sourceMessageId });
855
- if (!request.ok)
856
- return { ok: false, code: request.code, error: request.error, sent: false };
857
- const receipt = request.receipt;
858
- return { ok: false, code: 'CONTACT_APPROVAL_REQUIRED', sent: false, retryable: false,
859
- error: `目标 ${params.to} 未准入,${receipt.status === 'sent' ? '已向' : '已排队向'}本端 Owner ${receipt.owner_aid} 提交联系申请,等待审批;原消息未发送`,
860
- contact_request: receipt };
861
- }
862
- catch (error) {
863
- return { ok: false, code: 'CONTACT_OWNER_REQUEST_FAILED', sent: false,
864
- error: `向本端 Owner 提交联系申请失败:${error instanceof Error ? error.message : String(error)};原消息未发送` };
865
- }
866
- }
867
- }
868
- }
869
900
  // The IPC command already carries the caller-selected transport scope.
870
901
  // Never reclassify the target by parsing its AID string: a private AID may
871
902
  // look group-like and a group identifier may use a future format.
903
+ // `auto` 不能在本层塌成渠道默认值:它要求「被对端消息触发时沿用该消息的
904
+ // 加密状态,否则明文」。入站态只有处理这条消息的一侧知道,从这里取。
872
905
  const encrypt = typeof params.encrypt === 'boolean'
873
906
  ? params.encrypt
874
- : (typeof ch.getDefaultEncrypt === 'function' ? ch.getDefaultEncrypt() : false);
907
+ : params.encrypt === 'auto'
908
+ ? runtime?.inboundEncrypted === true
909
+ : (typeof ch.getDefaultEncrypt === 'function' ? ch.getDefaultEncrypt() : false);
875
910
  let payload = params.payload;
911
+ // 文件发送成功构造 payload 后,在这里留下归档路径文案,供后面写历史时使用。
912
+ let archivedFileLog = null;
876
913
  if (params.file) {
877
914
  if (isHClassPath(params.file.filePath) && !fullAccess) {
878
915
  return {
@@ -894,10 +931,21 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
894
931
  code: error?.code ?? 'AUN_FILE_UPLOAD_FAILED',
895
932
  };
896
933
  }
934
+ // 上传成功后归档到 agent 级附件目录(与 outbox 投递同一落点)。
935
+ // 归档失败不阻断发送:历史退回 payload 分类得到的 `[file] 文件名`。
936
+ if (typeof ch.archiveDaemonFile === 'function') {
937
+ archivedFileLog = ch.archiveDaemonFile(params.to, params.file.filePath, params.file.as);
938
+ }
897
939
  }
898
940
  if (!payload) {
899
941
  return { ok: false, error: 'message payload is required', code: 'INVALID_PAYLOAD' };
900
942
  }
943
+ if (payload.type === 'widget_card') {
944
+ if (params.returnPolicy === 'required' || params.deviceId || selfAddressed) {
945
+ return { ok: false, code: 'INVALID_WIDGET_TARGET', error: 'WidgetCard requires a conversation target without --return required or device targeting' };
946
+ }
947
+ payload = { ...payload, initiator: params.scope === 'group' ? delegation.grant?.actorId : params.to };
948
+ }
901
949
  if (params.rawPayload !== true && runtime?.taskId
902
950
  && typeof payload.type === 'string' && TASK_ID_MESSAGE_PAYLOAD_TYPES.has(payload.type)) {
903
951
  payload = { ...payload, task_id: runtime.taskId };
@@ -920,6 +968,14 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
920
968
  },
921
969
  };
922
970
  }
971
+ // 文件已归档:历史正文改记归档别名路径。是否压过 payload 分类结果只在
972
+ // 交给通道时决定(见 channelLog),不进 IPC 线上契约。
973
+ if (archivedFileLog && params.log) {
974
+ params = { ...params, log: { ...params.log, content: archivedFileLog } };
975
+ }
976
+ const channelLog = (sessionId) => params.log
977
+ ? { ...params.log, sessionId, ...(archivedFileLog ? { contentAuthoritative: true } : {}) }
978
+ : undefined;
923
979
  try {
924
980
  if (params.rawPayload !== true && Object.prototype.hasOwnProperty.call(payload, 'mentions')) {
925
981
  payload = { ...payload, mentions: normalizeAunMentionEntries(payload.mentions) };
@@ -941,6 +997,21 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
941
997
  if (params.rawPayload !== true && isTopicThreadId(params.thread) && typeof payload.thread_id !== 'string') {
942
998
  payload = { ...payload, thread_id: params.thread };
943
999
  }
1000
+ if (params.rawPayload !== true) {
1001
+ payload = withAunTopicSource(payload, {
1002
+ selfAid: params.aid,
1003
+ runtime,
1004
+ targetPeer: threadRoute?.peer ?? params.to,
1005
+ targetChatType: params.scope === 'group' ? 'group' : 'private',
1006
+ targetThreadId: params.thread,
1007
+ resolveName: source => {
1008
+ const entry = source.thread_id
1009
+ ? ThreadService.findThreadById(params.aid, source.thread_id)
1010
+ : ThreadService.findMainSessionEntry(params.aid, source.peer_id);
1011
+ return entry?.peer === source.peer_id ? entry.name : undefined;
1012
+ },
1013
+ });
1014
+ }
944
1015
  // 跨话题自派:在线上载荷显式打标。客户端(尤其观察者转发/入站解析)不必只靠
945
1016
  // `from == to` 推断,可直接认这个字段;同 AID 的其它设备也据此区分「自己派给自己」。
946
1017
  if (selfAddressed && params.rawPayload !== true) {
@@ -979,7 +1050,35 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
979
1050
  payload = preparedRequest.payload;
980
1051
  getAunRequestRegistry().markSending(params.aid, preparedRequest.requestId);
981
1052
  }
982
- let targetSessionId;
1053
+ let contactDelegationId;
1054
+ const contactTarget = threadRoute ?? (gatewayRoute ? {
1055
+ peer: gatewayRoute.peer.id, peerKind: gatewayRoute.peer.peerKind, channelType: gatewayRoute.peer.channelType,
1056
+ } : undefined);
1057
+ if (!selfAddressed && !preparedRequest && params.scope === 'msg' && threadRouted && contactTarget && targetTopicId && delegation.grant) {
1058
+ try {
1059
+ contactDelegationId = prepareContactThreadDelegation({
1060
+ selfAid: params.aid, grant: delegation.grant, runtime, target: contactTarget,
1061
+ targetThreadId: targetTopicId, wireThreadId: payload.thread_id,
1062
+ });
1063
+ }
1064
+ catch (error) {
1065
+ logger.warn(`[AUN] Could not persist contact delegation: ${error instanceof Error ? error.message : String(error)}`);
1066
+ }
1067
+ }
1068
+ const finishContactDelegation = (messageId) => {
1069
+ if (!contactDelegationId)
1070
+ return;
1071
+ try {
1072
+ finishContactThreadDelegation(params.aid, contactDelegationId, messageId);
1073
+ }
1074
+ catch (error) {
1075
+ logger.warn(`[AUN] Could not settle contact delegation: ${error instanceof Error ? error.message : String(error)}`);
1076
+ }
1077
+ };
1078
+ // Topic effects need the destination even when handoff is bypassed. Keep
1079
+ // the legacy log override separate: only handoff resolves that session.
1080
+ const targetSessionId = threadRoute?.sessionId;
1081
+ let handoffSessionId;
983
1082
  // 跨话题自派一律跳过 handoff:目标会话是按话题索引解析出的 (自端, 对端) 会话,
984
1083
  // 而 handoff 用 `to`(=本端)作为 channelId 去 getOrCreateSession,会建出
985
1084
  // 「我↔我」的错误会话目录。话题内与跨话题同此处理(D14)。
@@ -1029,8 +1128,9 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1029
1128
  },
1030
1129
  causation: runtimeCausation,
1031
1130
  });
1032
- targetSessionId = created.targetSession.id;
1131
+ handoffSessionId = created.targetSession.id;
1033
1132
  if (created.crossSession && created.handoff) {
1133
+ finishContactDelegation(created.handoff.target_message_id ?? created.handoff.handoff_id);
1034
1134
  const response = {
1035
1135
  ok: true,
1036
1136
  status: created.handoff.state === 'target_sent' ? 'delivered' : 'queued',
@@ -1055,12 +1155,12 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1055
1155
  }
1056
1156
  // 排队未投递(无 message_id)时也要写 inbox + 建复查:handoff 已不再
1057
1157
  // 承载目标侧上下文,跳过这里就会丢上下文。
1058
- if (threadRouted && threadRoute) {
1158
+ if (threadRouted && targetTopicId) {
1059
1159
  const effects = await applyManagedCrossThreadSendEffects({
1060
1160
  runtime,
1061
1161
  selfAid: params.aid,
1062
- targetThreadId: targetTopicId ?? params.thread ?? "",
1063
- targetSessionId: threadRoute.sessionId,
1162
+ targetThreadId: targetTopicId,
1163
+ targetSessionId: created.targetSession.id,
1064
1164
  targetChannelId: params.to,
1065
1165
  feedbackChatType: params.scope === 'group' ? 'group' : 'private',
1066
1166
  messageId: response.message_id ?? created.handoff.handoff_id,
@@ -1084,6 +1184,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1084
1184
  }
1085
1185
  }
1086
1186
  catch (error) {
1187
+ finishContactDelegation();
1087
1188
  const code = error?.code;
1088
1189
  const handoffId = error?.handoffId
1089
1190
  ?? error?.blockingHandoffId;
@@ -1119,14 +1220,14 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1119
1220
  encrypt,
1120
1221
  debug,
1121
1222
  model: typeof debug?.model === 'string' ? debug.model : undefined,
1122
- log: params.log ? { ...params.log, sessionId: targetSessionId ?? params.log.sessionId } : undefined,
1223
+ log: channelLog(handoffSessionId ?? params.log?.sessionId),
1123
1224
  });
1124
- if (threadRouted && params.thread && sent.ok && sent.message_id && threadRoute) {
1225
+ if (threadRouted && targetTopicId && sent.ok && sent.message_id && targetSessionId) {
1125
1226
  const effects = await applyManagedCrossThreadSendEffects({
1126
1227
  runtime,
1127
1228
  selfAid: params.aid,
1128
- targetThreadId: params.thread,
1129
- targetSessionId: threadRoute.sessionId,
1229
+ targetThreadId: targetTopicId,
1230
+ targetSessionId,
1130
1231
  targetChannelId: params.to,
1131
1232
  feedbackChatType: 'group',
1132
1233
  messageId: sent.message_id,
@@ -1148,6 +1249,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1148
1249
  return sent;
1149
1250
  }
1150
1251
  if (typeof ch.sendDaemonMsg !== 'function') {
1252
+ finishContactDelegation();
1151
1253
  return { ok: false, error: 'AUN channel does not support daemon private sends', code: 'AUN_MSG_UNSUPPORTED' };
1152
1254
  }
1153
1255
  diagLog('aun_out', diagCommon);
@@ -1161,8 +1263,9 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1161
1263
  causation: runtimeCausation,
1162
1264
  debug,
1163
1265
  model: typeof debug?.model === 'string' ? debug.model : undefined,
1164
- log: params.log ? { ...params.log, sessionId: targetSessionId ?? params.log.sessionId } : undefined,
1165
- });
1266
+ log: channelLog(handoffSessionId ?? params.log?.sessionId),
1267
+ }).catch((error) => { finishContactDelegation(); throw error; });
1268
+ finishContactDelegation(sent.ok ? sent.message_id : undefined);
1166
1269
  // send_ok 只看网关是否返回 message_id,与 aun_out 的差值即发送失败次数;
1167
1270
  // 放在各个 return 分支之前,request / self-addressed 路径也不会漏记。
1168
1271
  if (sent.ok && sent.message_id)
@@ -1213,12 +1316,12 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1213
1316
  sent.self_session_id = delivered.sessionId;
1214
1317
  return sent;
1215
1318
  }
1216
- if (threadRouted && params.thread && sent.ok && sent.message_id && threadRoute) {
1319
+ if (threadRouted && targetTopicId && sent.ok && sent.message_id && targetSessionId) {
1217
1320
  const effects = await applyManagedCrossThreadSendEffects({
1218
1321
  runtime,
1219
1322
  selfAid: params.aid,
1220
- targetThreadId: params.thread,
1221
- targetSessionId: threadRoute.sessionId,
1323
+ targetThreadId: targetTopicId,
1324
+ targetSessionId,
1222
1325
  targetChannelId: params.to,
1223
1326
  feedbackChatType: 'private',
1224
1327
  messageId: sent.message_id,
@@ -1238,4 +1341,40 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1238
1341
  return sent;
1239
1342
  };
1240
1343
  ipcServer.setAunMsgSender(sender);
1344
+ ipcServer.setAbilityRequestSender?.(async (params, originGrant) => {
1345
+ try {
1346
+ // This is a daemon-only API, not a public IPC flag or a payload-type
1347
+ // exemption. Retain and verify the approved remote command itself.
1348
+ if (hashDelegatedCommandArgv([MAIN_CLI_BIN, ...params.argv]) !== params.delegationCommandHash) {
1349
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'Ability command hash mismatch', sent: false };
1350
+ }
1351
+ const command = parseRemoteCommand(params.argv);
1352
+ const validation = agentDelegationRegistry.validate(params.delegationToken, params.originSessionId, params.delegationCommandHash);
1353
+ if (!validation.ok)
1354
+ return { ok: false, code: validation.code, error: validation.reason, sent: false };
1355
+ const validated = validation.grant;
1356
+ const grant = originGrant;
1357
+ if (!agentDelegationRegistry.isCurrentTaskGrant(grant) || validated.taskId !== grant.taskId
1358
+ || validated.selfAid !== grant.selfAid || validated.sessionId !== grant.sessionId) {
1359
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'Ability origin task was replaced or revoked', sent: false };
1360
+ }
1361
+ if (grant.selfAid !== params.aid || grant.channelType !== 'aun' || !agentDelegationRegistry.isCurrentTaskGrant(grant)
1362
+ || grant.messageId !== params.originMessageId || !['call', 'discover'].includes(command.action) || command.options['dry-run']
1363
+ || params.payload.type !== 'ability' || params.payload.role !== 'call'
1364
+ || command.provider && command.provider !== params.to
1365
+ || (command.action === 'discover' ? params.payload.ability_path !== 'protocol/discover' : command.path && command.path !== params.payload.ability_path)) {
1366
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'Ability request does not match its approved Caller and command', sent: false };
1367
+ }
1368
+ if (command.action === 'call' && grant.permissionMode === 'readonly') {
1369
+ return { ok: false, code: 'NOT_ALLOWED', error: 'Readonly tasks cannot send business calls', sent: false };
1370
+ }
1371
+ return sender({ aid: params.aid, to: params.to, scope: 'msg', deviceId: params.deviceId, payload: params.payload,
1372
+ rawPayload: true, encrypt: true, returnPolicy: 'required', timeoutMs: params.timeoutMs,
1373
+ originSessionId: params.originSessionId, originMessageId: params.originMessageId,
1374
+ delegationToken: params.delegationToken, delegationCommandHash: params.delegationCommandHash }, undefined, undefined, grant);
1375
+ }
1376
+ catch (error) {
1377
+ return { ok: false, code: error.code ?? 'INVALID_ARGUMENT', error: error instanceof Error ? error.message : String(error), sent: false };
1378
+ }
1379
+ });
1241
1380
  }