evolcore 0.0.49 → 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 (250) hide show
  1. package/CHANGELOG.md +64 -1
  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 +280 -6
  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 +4 -1
  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 +29 -1
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +537 -189
  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/ecmsg-gateway.js +11 -9
  54. package/dist/cli/index.js +23 -4
  55. package/dist/cli/init.js +39 -63
  56. package/dist/cli/managed-command-guard.js +1 -0
  57. package/dist/cli/menu-client.js +32 -7
  58. package/dist/cli/pay-command.js +30 -0
  59. package/dist/cli/provider-command.js +6 -2
  60. package/dist/cli/restart-monitor.js +2 -2
  61. package/dist/cli/services-command.js +11 -9
  62. package/dist/cli/thread-command.js +78 -12
  63. package/dist/config/access-policy.js +16 -3
  64. package/dist/config/config-field-policy.js +17 -8
  65. package/dist/config/config-manager.js +86 -46
  66. package/dist/config/config-operation-service.js +22 -1
  67. package/dist/config/gateway-config.js +9 -8
  68. package/dist/config/owner-config.js +0 -16
  69. package/dist/config/peer-role-resolver.js +1 -7
  70. package/dist/config/providers-config.js +99 -16
  71. package/dist/config/providers-management.js +35 -19
  72. package/dist/config/resolved-config-op.js +1 -42
  73. package/dist/config/schema-migration.js +78 -5
  74. package/dist/config/schema-registry.js +52 -7
  75. package/dist/config-store.js +1309 -17
  76. package/dist/core/agent-application-service.js +220 -1
  77. package/dist/core/agent-ipc-registration.js +19 -2
  78. package/dist/core/agent-reload-coordinator.js +5 -0
  79. package/dist/core/agent-runtime.js +198 -54
  80. package/dist/core/auth/agent-delegation.js +14 -0
  81. package/dist/core/auth/operation-authorizer.js +16 -1
  82. package/dist/core/auth/operation-catalog.js +50 -7
  83. package/dist/core/baseagent-loader.js +30 -3
  84. package/dist/core/capability/capability-manager.js +16 -7
  85. package/dist/core/channel-runtime.js +4 -2
  86. package/dist/core/command/agent-control.js +20 -2
  87. package/dist/core/command/agent-template-menu.js +4 -3
  88. package/dist/core/command/cli-intent-parser.js +15 -0
  89. package/dist/core/command/menu-catalog.js +20 -4
  90. package/dist/core/command/menu-file-path.js +70 -0
  91. package/dist/core/command/menu-handler.js +91 -72
  92. package/dist/core/command/menu-protocol.js +5 -0
  93. package/dist/core/command/menu-query-batch.js +2 -2
  94. package/dist/core/command/private-mention-menu.js +71 -0
  95. package/dist/core/command/slash-handler.js +17 -26
  96. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  97. package/dist/core/command/topic-slash.js +7 -1
  98. package/dist/core/daemon-bootstrap.js +0 -4
  99. package/dist/core/daemon-control.js +2 -1
  100. package/dist/core/daemon-lifecycle.js +13 -5
  101. package/dist/core/evolagent-registry.js +12 -7
  102. package/dist/core/handoff/runtime.js +1 -1
  103. package/dist/core/host-snapshot.js +8 -3
  104. package/dist/core/initialization/service.js +3 -0
  105. package/dist/core/interaction-router.js +130 -0
  106. package/dist/core/ipc-registration.js +4 -0
  107. package/dist/core/memory/consolidation-context.js +2 -1
  108. package/dist/core/memory/consolidation.js +35 -64
  109. package/dist/core/message/aun-ipc-sender.js +98 -21
  110. package/dist/core/message/aun-request-registry.js +31 -0
  111. package/dist/core/message/message-bridge.js +105 -6
  112. package/dist/core/message/message-log.js +8 -0
  113. package/dist/core/message/message-queue.js +5 -3
  114. package/dist/core/message/peer-mode.js +15 -4
  115. package/dist/core/message/response-engine.js +23 -8
  116. package/dist/core/message/send-options.js +37 -3
  117. package/dist/core/message/send-routing.js +11 -7
  118. package/dist/core/model/model-catalog.js +5 -5
  119. package/dist/core/ownership/owner-resolver.js +12 -86
  120. package/dist/core/pack-auth.js +4 -0
  121. package/dist/core/permission/ec-command-parser.js +182 -58
  122. package/dist/core/permission/protected-paths.js +64 -9
  123. package/dist/core/permission/services-path-acl.js +9 -2
  124. package/dist/core/permission/tool-policy.js +21 -9
  125. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  126. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  127. package/dist/core/session/session-manager.js +47 -10
  128. package/dist/core/session/session-mapper.js +16 -0
  129. package/dist/core/skill/index-generator.js +2 -3
  130. package/dist/core/skill/switch-resolver.js +3 -0
  131. package/dist/core/thread/command-parser.js +4 -1
  132. package/dist/core/thread/ipc-operation.js +4 -2
  133. package/dist/core/thread/thread-operation.js +25 -10
  134. package/dist/core/thread/thread-service.js +294 -55
  135. package/dist/core/thread/topic-id.js +52 -2
  136. package/dist/core/thread/types.js +15 -1
  137. package/dist/eck/kit-renderer.js +2 -1
  138. package/dist/ecweb/basic-settings-service.js +5 -9
  139. package/dist/ecweb/providers-service.js +4 -2
  140. package/dist/index.js +116 -41
  141. package/dist/ipc.js +58 -2
  142. package/dist/paths.js +48 -1
  143. package/dist/pay/command.js +38 -0
  144. package/dist/pay/protocol.js +136 -0
  145. package/dist/pay/runtime.js +188 -0
  146. package/dist/pay/service.js +384 -0
  147. package/dist/pay/store.js +81 -0
  148. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  149. package/dist/services/dispatcher.js +23 -5
  150. package/dist/services/host/main.js +388 -0
  151. package/dist/services/host/protocol.js +118 -0
  152. package/dist/services/host/resident.js +310 -0
  153. package/dist/services/host-client.js +386 -0
  154. package/dist/services/host-deploy.js +180 -0
  155. package/dist/services/host-launch.js +117 -0
  156. package/dist/services/host-recycle.js +203 -0
  157. package/dist/services/host-runtime.js +802 -0
  158. package/dist/services/idempotency.js +44 -86
  159. package/dist/services/index-generator.js +4 -3
  160. package/dist/services/index.js +176 -18
  161. package/dist/services/ipc-operation.js +204 -44
  162. package/dist/services/script-runner.js +515 -83
  163. package/dist/services/validation.js +109 -4
  164. package/dist/trigger/application-service.js +6 -4
  165. package/dist/trigger/local-files.js +19 -9
  166. package/dist/trigger/scheduler.js +22 -12
  167. package/dist/trigger/script-sandbox.js +51 -20
  168. package/dist/utils/aid-bind.js +3 -0
  169. package/dist/utils/evolcore-version.js +2 -2
  170. package/dist/utils/host-info.js +73 -0
  171. package/dist/utils/logger.js +2 -2
  172. package/dist/utils/media-cache.js +190 -43
  173. package/dist/utils/restart-safety.js +14 -1
  174. package/dist/utils/system-memory.js +113 -25
  175. package/dist/utils/systemd-lifecycle.js +154 -0
  176. package/dist/utils/windows-shell-trust.js +7 -3
  177. package/kits/docs/INDEX.md +3 -2
  178. 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
  179. package/kits/docs/channels/aun.md +1 -1
  180. package/kits/docs/evolcore/INDEX.md +7 -6
  181. package/kits/docs/evolcore/agent.md +36 -1
  182. package/kits/docs/evolcore/aid.md +20 -3
  183. package/kits/docs/evolcore/config.md +1 -1
  184. package/kits/docs/evolcore/group.md +2 -1
  185. package/kits/docs/evolcore/memory-tags.md +2 -0
  186. package/kits/docs/evolcore/menu-client.md +3 -3
  187. package/kits/docs/evolcore/menu-protocol.md +7 -0
  188. package/kits/docs/evolcore/model.md +3 -0
  189. package/kits/docs/evolcore/msg.md +68 -10
  190. package/kits/docs/evolcore/pay.md +34 -0
  191. package/kits/docs/evolcore/provider.md +21 -0
  192. package/kits/docs/evolcore/services.md +46 -18
  193. package/kits/docs/evolcore/thread-chain.md +2 -0
  194. package/kits/docs/evolcore/tool-authorization.md +10 -0
  195. package/kits/rules/01-overview.md +11 -32
  196. package/kits/rules/02-navigation.md +7 -0
  197. package/kits/rules/06-channel.md +3 -3
  198. package/kits/schemas/_meta.json +38 -5
  199. package/kits/schemas/agent-config.schema.21.json +974 -0
  200. package/kits/schemas/agent-config.schema.22.json +977 -0
  201. package/kits/schemas/agent-config.schema.23.json +958 -0
  202. package/kits/schemas/daemon.schema.10.json +373 -0
  203. package/kits/schemas/daemon.schema.9.json +12 -0
  204. package/kits/schemas/defaults.schema.7.json +472 -0
  205. package/kits/schemas/providers.schema.3.json +18 -2
  206. package/kits/schemas/relation-config.schema.13.json +289 -0
  207. package/kits/skills/.switches.json +13 -1
  208. package/kits/skills/ability/SKILL.md +229 -34
  209. package/kits/skills/ability/STRUCTURE.md +333 -0
  210. package/kits/skills/ability/references/cli.md +208 -0
  211. package/kits/skills/ability/references/development.md +107 -37
  212. package/kits/skills/ability/references/management.md +106 -46
  213. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  214. package/kits/skills/agent-output-cards/SKILL.md +12 -5
  215. package/kits/skills/ec-group/SKILL.md +8 -6
  216. package/kits/skills/ec-group/TASK.md +186 -0
  217. package/kits/skills/ec-group/WORKLOG.md +180 -0
  218. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  219. package/kits/skills/ec-pay/SKILL.md +101 -0
  220. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  221. package/kits/skills/ec-provider/SKILL.md +1 -1
  222. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  223. package/kits/skills/ec-service-call/SKILL.md +135 -0
  224. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  225. package/kits/skills/ec-trigger/SKILL.md +1 -1
  226. package/kits/templates/memory-consolidation/notes.md +2 -2
  227. package/kits/templates/memory-consolidation/workflow.md +46 -0
  228. package/kits/templates/system-fragments/channel.md +13 -4
  229. package/kits/templates/system-fragments/commands.md +4 -3
  230. package/kits/templates/system-fragments/reply.md +1 -0
  231. package/kits/templates/system-fragments/session.md +1 -1
  232. package/kits/templates/system-fragments/thread.md +27 -129
  233. package/kits/templates/system-fragments/venue.md +16 -0
  234. package/package.json +4 -5
  235. package/scripts/agent-template/inspect.mjs +37 -23
  236. package/scripts/agent-template/overlay.mjs +20 -2
  237. package/scripts/agent-template/shared/common.mjs +16 -4
  238. package/scripts/agent-template/shared/team-schema.json +20 -4
  239. package/scripts/agent-template/shared/template-contract.mjs +53 -13
  240. package/scripts/agent-template/shared/template-package.mjs +90 -26
  241. package/scripts/agent-template/shared/template-runtime.mjs +111 -1
  242. package/scripts/agent-template/shared/template.mjs +65 -7
  243. package/scripts/agent-template/team-pack.mjs +89 -33
  244. package/scripts/agent-template/team-preview.mjs +249 -5
  245. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  246. package/kits/docs/evolcore/ability.md +0 -185
  247. package/kits/skills/ability/references/calling.md +0 -56
  248. package/kits/skills/ability/references/contract-checklist.md +0 -37
  249. package/kits/skills/ability/references/recovery.md +0 -27
  250. /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,7 +1,7 @@
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';
@@ -22,7 +22,8 @@ import { getAunRequestRegistry, requestDiagnostics, requestTtlSeconds } from './
22
22
  import { canonicalizeEvolcoreCommandArgv, parseJsonObjectArgument } from '../permission/ec-command-parser.js';
23
23
  import { formatPeerKey, parsePeerKey, readAunPeerKind, resolveAunPeerKind } from '../relation/peer-identity.js';
24
24
  import { logger } from '../../utils/logger.js';
25
- 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';
26
27
  import { buildDownstreamArgv, expandGroupBase, parseGatewayArgs } from '../../cli/ecmsg-gateway.js';
27
28
  import { resolveSendRoute } from './send-routing.js';
28
29
  import { agentDir } from '../../paths.js';
@@ -30,7 +31,7 @@ import { chatDirPath, readAllJsonlLines } from '../session/session-fs-store.js';
30
31
  import { prepareContactThreadDelegation, finishContactThreadDelegation, findContactThreadReturn } from './contact-thread-approval.js';
31
32
  import { currentContactBinding } from './contact-admission.js';
32
33
  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
+ const TOPIC_SOURCE_MESSAGE_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file', 'action_card', 'widget_card']);
34
35
  /** Stamp the actual runtime source before handoff/outbox persistence, including retries. */
35
36
  export function withAunTopicSource(payload, input) {
36
37
  // A caller's payload can be copied from another message. Its old provenance
@@ -616,7 +617,7 @@ async function resolveGatewaySend(argv, grant, runtime, session) {
616
617
  return { route, argv: buildDownstreamArgv(route, text, passthrough) };
617
618
  }
618
619
  export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegationRegistry, responseEngine, handoffRuntime, sessionManager, messageQueue, createCrossThreadReviewTrigger, }) {
619
- ipcServer.setAunRequestGetExecutor(async (params) => {
620
+ const getRequest = async (params, abilityGrant) => {
620
621
  if (!params.sessionId || !params.delegationToken) {
621
622
  return { ok: false, code: 'DELEGATION_REQUIRED', error: 'Request queries require an active delegated session' };
622
623
  }
@@ -633,6 +634,14 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
633
634
  || request.origin.peerKey !== authorization.grant.peerKey || request.origin.threadId !== runtime.threadId) {
634
635
  return { ok: false, code: 'REQUEST_NOT_FOUND', error: 'Request is not available in this session' };
635
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
+ }
636
645
  const targetRoute = request.origin.targetThreadId
637
646
  ? resolveThreadRouteTarget(params.aid, request.origin.targetThreadId, 'msg', request.targetAid)
638
647
  : undefined;
@@ -649,8 +658,10 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
649
658
  return { ok: false, code: permitted.code, error: permitted.reason };
650
659
  return request ? { ok: true, request: request }
651
660
  : { ok: false, code: 'REQUEST_NOT_FOUND', error: `request not found: ${params.requestId}` };
652
- });
653
- 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) => {
654
665
  let textFile;
655
666
  let payloadFile;
656
667
  try {
@@ -731,6 +742,10 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
731
742
  }
732
743
  }
733
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
+ }
734
749
  // 跨话题自派(self-address):收件人是本端自己,话题归属仍是 (自端, 对端)。
735
750
  // 此时 `params.to` 不是「话题对端」,不能拿它做话题一致性校验。
736
751
  const selfAddressed = isSelfAidTarget(params.aid, params.to);
@@ -789,18 +804,19 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
789
804
  sessionId: '',
790
805
  },
791
806
  }
792
- : await authorizeDelegatedAunMsgSend(agentDelegationRegistry, {
793
- delegationToken: params.delegationToken,
794
- delegationCommandHash: params.delegationCommandHash,
795
- sessionId: params.originSessionId,
796
- messageId: params.originMessageId,
797
- aid: params.aid,
798
- to: params.to,
799
- scope: params.scope,
800
- action: params.file ? 'file' : 'send',
801
- threadRouted: authorizationTargetRouted,
802
- isSystemEvent,
803
- });
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
+ });
804
820
  if (!delegation.ok) {
805
821
  return {
806
822
  ok: false,
@@ -884,10 +900,16 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
884
900
  // The IPC command already carries the caller-selected transport scope.
885
901
  // Never reclassify the target by parsing its AID string: a private AID may
886
902
  // look group-like and a group identifier may use a future format.
903
+ // `auto` 不能在本层塌成渠道默认值:它要求「被对端消息触发时沿用该消息的
904
+ // 加密状态,否则明文」。入站态只有处理这条消息的一侧知道,从这里取。
887
905
  const encrypt = typeof params.encrypt === 'boolean'
888
906
  ? params.encrypt
889
- : (typeof ch.getDefaultEncrypt === 'function' ? ch.getDefaultEncrypt() : false);
907
+ : params.encrypt === 'auto'
908
+ ? runtime?.inboundEncrypted === true
909
+ : (typeof ch.getDefaultEncrypt === 'function' ? ch.getDefaultEncrypt() : false);
890
910
  let payload = params.payload;
911
+ // 文件发送成功构造 payload 后,在这里留下归档路径文案,供后面写历史时使用。
912
+ let archivedFileLog = null;
891
913
  if (params.file) {
892
914
  if (isHClassPath(params.file.filePath) && !fullAccess) {
893
915
  return {
@@ -909,10 +931,21 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
909
931
  code: error?.code ?? 'AUN_FILE_UPLOAD_FAILED',
910
932
  };
911
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
+ }
912
939
  }
913
940
  if (!payload) {
914
941
  return { ok: false, error: 'message payload is required', code: 'INVALID_PAYLOAD' };
915
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
+ }
916
949
  if (params.rawPayload !== true && runtime?.taskId
917
950
  && typeof payload.type === 'string' && TASK_ID_MESSAGE_PAYLOAD_TYPES.has(payload.type)) {
918
951
  payload = { ...payload, task_id: runtime.taskId };
@@ -935,6 +968,14 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
935
968
  },
936
969
  };
937
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;
938
979
  try {
939
980
  if (params.rawPayload !== true && Object.prototype.hasOwnProperty.call(payload, 'mentions')) {
940
981
  payload = { ...payload, mentions: normalizeAunMentionEntries(payload.mentions) };
@@ -1179,7 +1220,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1179
1220
  encrypt,
1180
1221
  debug,
1181
1222
  model: typeof debug?.model === 'string' ? debug.model : undefined,
1182
- log: params.log ? { ...params.log, sessionId: handoffSessionId ?? params.log.sessionId } : undefined,
1223
+ log: channelLog(handoffSessionId ?? params.log?.sessionId),
1183
1224
  });
1184
1225
  if (threadRouted && targetTopicId && sent.ok && sent.message_id && targetSessionId) {
1185
1226
  const effects = await applyManagedCrossThreadSendEffects({
@@ -1222,7 +1263,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1222
1263
  causation: runtimeCausation,
1223
1264
  debug,
1224
1265
  model: typeof debug?.model === 'string' ? debug.model : undefined,
1225
- log: params.log ? { ...params.log, sessionId: handoffSessionId ?? params.log.sessionId } : undefined,
1266
+ log: channelLog(handoffSessionId ?? params.log?.sessionId),
1226
1267
  }).catch((error) => { finishContactDelegation(); throw error; });
1227
1268
  finishContactDelegation(sent.ok ? sent.message_id : undefined);
1228
1269
  // send_ok 只看网关是否返回 message_id,与 aun_out 的差值即发送失败次数;
@@ -1300,4 +1341,40 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
1300
1341
  return sent;
1301
1342
  };
1302
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
+ });
1303
1380
  }
@@ -62,6 +62,7 @@ function normalizeTimeoutMs(value) {
62
62
  export class AunRequestRegistry {
63
63
  records = new Map();
64
64
  waiters = new Map();
65
+ observers = new Map();
65
66
  loaded = new Set();
66
67
  appends = new Map();
67
68
  key(selfAid, requestId) {
@@ -165,6 +166,12 @@ export class AunRequestRegistry {
165
166
  }
166
167
  }
167
168
  notify(record) {
169
+ if (['completed', 'failed'].includes(record.state)) {
170
+ const key = this.key(record.selfAid, record.requestId);
171
+ for (const observer of this.observers.get(key) ?? [])
172
+ observer(record);
173
+ this.observers.delete(key);
174
+ }
168
175
  if (!['completed', 'failed', 'unknown', 'pending'].includes(record.state))
169
176
  return;
170
177
  const waiters = this.waiters.get(this.key(record.selfAid, record.requestId));
@@ -394,6 +401,30 @@ export class AunRequestRegistry {
394
401
  }, waitMs);
395
402
  });
396
403
  }
404
+ /** Observe late results without extending the original transmission/collection TTL. */
405
+ async observe(selfAid, requestId, timeoutMs) {
406
+ const current = this.get(selfAid, requestId);
407
+ if (!current || ['completed', 'failed'].includes(current.state))
408
+ return current;
409
+ return new Promise(resolve => {
410
+ const key = this.key(selfAid, requestId);
411
+ const waiters = this.observers.get(key) ?? new Set();
412
+ const done = (record) => {
413
+ clearTimeout(timer);
414
+ waiters.delete(callback);
415
+ if (waiters.size === 0)
416
+ this.observers.delete(key);
417
+ resolve(record);
418
+ };
419
+ const callback = (record) => {
420
+ if (['completed', 'failed'].includes(record.state))
421
+ done(record);
422
+ };
423
+ const timer = setTimeout(() => done(this.get(selfAid, requestId)), Math.max(1, Math.min(timeoutMs, 60_000)));
424
+ waiters.add(callback);
425
+ this.observers.set(key, waiters);
426
+ });
427
+ }
397
428
  }
398
429
  let defaultRegistry;
399
430
  export function getAunRequestRegistry() {
@@ -8,7 +8,7 @@ import path from 'path';
8
8
  import { agentStorageMenuService, isAgentStorageMenuRequest } from '../command/agent-storage-menu.js';
9
9
  import { agentMdMenuService } from '../command/agentmd-menu.js';
10
10
  import { containsAgentMdMenuRequest } from '../command/agentmd-menu-request.js';
11
- import { currentContactBinding, sameContactBinding } from './contact-admission.js';
11
+ import { currentContactBinding, sameContactBinding, verifiedContactBinding } from './contact-admission.js';
12
12
  import { logger, logPreview } from '../../utils/logger.js';
13
13
  import { StreamDebouncer } from './stream-debouncer.js';
14
14
  import { appendMessageLog, appendMessageLogStrict, appendInboundMessageLogOnce, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
@@ -40,6 +40,7 @@ import { guardGroupSlashCommand, parseFullAccessCommand } from '../command/slash
40
40
  import { createAgentPolicyAuthorization, createSessionFullAccessAuthorization } from '../role/runtime-policy.js';
41
41
  import { auditFullAccessEvent } from '../auth/authorization-audit.js';
42
42
  import { DIAGNOSTIC_AGENT_AID, DiagnosticSessionRouter, parseDiagnosticEvent, isDiagnosticSessionActive } from '../command/diag-service.js';
43
+ import { isCcAgentAid, routeToGateway, stopGatewayOutputs } from '../../agents/claude-gateway/router.js';
43
44
  import { consumeAdmissionReplyBudget, clearAdmissionReplyBudgets, evaluateInboundAdmissionPreflight, evaluateOrdinaryInboundAdmission, evaluateOwnerDirectoryInboundAdmission, } from './message-admission.js';
44
45
  const CONTACT_REJECTION_NOTICE = '[rejection] Not accepting messages from you.';
45
46
  const REJECTABLE_PEER_TYPES = new Set(['ai', 'bot', 'agent', 'service']);
@@ -104,6 +105,61 @@ export function clearContactRejectionRateLimits() {
104
105
  rejectionState.clear();
105
106
  clearAdmissionReplyBudgets();
106
107
  }
108
+ /**
109
+ * 网关的回复文本。
110
+ *
111
+ * 成功投递不回话——那时用户看到的是 Claude Code 终端里真正的输出。
112
+ * 主会话回会话列表;话题会话不在线时如实说明(不自动拉起)。
113
+ */
114
+ function gatewayNotice(result) {
115
+ switch (result.kind) {
116
+ case 'listing': {
117
+ const sessions = result.sessions ?? [];
118
+ if (sessions.length === 0) {
119
+ return '这台机器上还没有可用的 Claude Code 会话。\n\n'
120
+ + '发「新建」可以选一个项目目录,在那里开一个新会话。';
121
+ }
122
+ const lines = sessions.map((s, i) => {
123
+ const state = s.online ? (s.status ?? 'online') : '未运行';
124
+ const preview = s.lastMessage ? `\n ${s.lastMessage}` : '';
125
+ return `${i + 1}. ${s.title} (${state})${preview}`;
126
+ });
127
+ return `这台机器上的 Claude Code 会话:\n\n${lines.join('\n')}\n\n`
128
+ + '发序号或会话 ID 就能打开它(会带上之前的对话记录)。\n'
129
+ + '发「新建」可以在某个项目目录开一个新会话。';
130
+ }
131
+ case 'directory_listing': {
132
+ const directories = result.directories ?? [];
133
+ if (directories.length === 0) {
134
+ return '还没有记录到用过的项目目录。先在终端里用 Claude Code 打开一个目录,之后这里就能看到。';
135
+ }
136
+ const lines = directories.map((d, i) => `${i + 1}. ${d.path} (${d.sessionCount} 个会话)`);
137
+ return `用过的项目目录:\n\n${lines.join('\n')}\n\n发「新建 序号」就在那个目录开一个新会话。`;
138
+ }
139
+ case 'launched':
140
+ return result.alreadyOnline
141
+ ? `「${result.title}」正在运行,已经可以对话了。`
142
+ : `已打开「${result.title}」,之前的对话记录都在里面。`;
143
+ case 'new_session': {
144
+ const where = result.cwd;
145
+ if (result.bound) {
146
+ return `已在 ${where} 开好新会话,接下来的消息都会发给它。`;
147
+ }
148
+ if (result.sessionId) {
149
+ return `已在 ${where} 开好新会话(${result.sessionId.slice(0, 8)})。`
150
+ + '在话题里发「新建 序号」可以直接绑定它。';
151
+ }
152
+ return `窗口已在 ${where} 打开,但没等到会话上线——检查一下那个终端里的提示。`;
153
+ }
154
+ case 'offline':
155
+ return `这个会话目前没有运行(${result.title ?? result.sessionId?.slice(0, 8) ?? '未知'})。`
156
+ + '在终端里重新打开它之后,消息才会送达。';
157
+ case 'unbound':
158
+ return result.message ?? '该话题尚未绑定 Claude Code 会话。';
159
+ default:
160
+ return result.message ?? '网关处理失败。';
161
+ }
162
+ }
107
163
  /**
108
164
  * MessageBridge — Channel 与 Core 之间的消息桥梁
109
165
  *
@@ -259,8 +315,8 @@ export class MessageBridge {
259
315
  }
260
316
  /**
261
317
  * Handle AUN's two slash-bind forms: bare `/bind` requests protocol
262
- * ownership from the first configured Owner; `/bind <channel>` creates an
263
- * external-channel contact mapping.
318
+ * ownership on behalf of the sending Daemon Owner; `/bind <channel>` creates
319
+ * an external-channel contact mapping.
264
320
  */
265
321
  async handleAunBindCommand(input) {
266
322
  const match = /^\s*\/bind(?:\s+(.+?))?\s*$/i.exec(input.content);
@@ -284,9 +340,11 @@ export class MessageBridge {
284
340
  }
285
341
  const args = String(match[1] || '').trim().split(/\s+/).filter(Boolean);
286
342
  if (args.length === 0) {
287
- const configuredOwner = ownerResolver.configuredOwnerList(selfAid)[0];
288
- if (configuredOwner !== actorId) {
289
- return { handled: true, status: 'not-first-owner', reply: '仅兼容绑定目标中的首个 AID 可在 AUN 私聊发送 /bind 发起 ownership 绑定。' };
343
+ // Ownership is granted by the protocol, never by a configured field. An
344
+ // unbound Agent therefore has no Owner to name here, so only the host
345
+ // Daemon Owner may nominate itself as the binding target.
346
+ if (!ownerResolver.daemonOwners().includes(actorId)) {
347
+ return { handled: true, status: 'not-daemon-owner', reply: '当前 Agent 尚未绑定协议 Owner。纯 /bind 仅接受本机 Daemon Owner 发起;其它 AID 请由 Daemon Owner 在宿主端为该 Agent 指定绑定目标。' };
290
348
  }
291
349
  try {
292
350
  const current = await ownerResolver.refresh(selfAid, { force: true });
@@ -885,6 +943,46 @@ export class MessageBridge {
885
943
  await this.sendAccessDenied(adapter, channelName, msg, sendReply);
886
944
  return;
887
945
  }
946
+ // ccagent:消息不进 baseagent、不跑模型,直接投递到绑定的 Claude Code 会话。
947
+ // AID 从 defaults.json 读,每台机器可能不同,所以按配置判断而不是写死常量。
948
+ if (isCcAgentAid(selfAid)) {
949
+ try {
950
+ const authorizeGateway = async () => {
951
+ if (resolvedChannelType !== 'aun' || chatType !== 'private' || msg.encrypted !== true || !msg.peerDeviceId)
952
+ return false;
953
+ await refreshOwnershipForAuthorization(selfAid, { includeDaemon: true, allowTransient: false, maxAgeMs: 30_000, source: 'claude-gateway' });
954
+ const binding = verifiedContactBinding(selfAid, ownerResolver.snapshot(selfAid));
955
+ const daemonAid = ownerResolver.getDaemonAid();
956
+ return !!binding && binding.owner_aid === actorId && !!daemonAid
957
+ && ownerResolver.protocolOwners(daemonAid).includes(actorId ?? '');
958
+ };
959
+ if (!await authorizeGateway()) {
960
+ await sendReply(msg.channelId, 'Claude 网关仅接受同时拥有本机与网关的 Owner 通过加密设备私聊操作。', msg.replyContext);
961
+ return;
962
+ }
963
+ const routed = await routeToGateway(selfAid, {
964
+ from: actorId ?? '',
965
+ fromName: msg.peerName,
966
+ threadId: msg.threadId,
967
+ content,
968
+ ownerBinding: currentContactBinding(selfAid),
969
+ deviceId: msg.peerDeviceId,
970
+ authorize: authorizeGateway,
971
+ sendOutput: text => sendReply(msg.channelId, text, { ...msg.replyContext,
972
+ metadata: { ...msg.replyContext?.metadata, encrypted: true }, toDeviceId: msg.peerDeviceId }),
973
+ });
974
+ if (routed.kind === 'delivered') {
975
+ // 已经写进对方会话,回复由那边的输出驱动,这里不再回话。
976
+ return;
977
+ }
978
+ await sendReply(msg.channelId, gatewayNotice(routed), msg.replyContext);
979
+ }
980
+ catch (error) {
981
+ logger.warn(`[MessageBridge] 网关路由失败: ${error instanceof Error ? error.message : String(error)}`);
982
+ await sendReply(msg.channelId, '网关处理失败,请稍后重试。', msg.replyContext);
983
+ }
984
+ return;
985
+ }
888
986
  // Diagnostic invitations carry their own execution boundary. Resolve
889
987
  // that boundary before ordinary command/session routing so a new case
890
988
  // cannot inherit an older Codex thread.
@@ -2272,6 +2370,7 @@ export class MessageBridge {
2272
2370
  }
2273
2371
  /** 清理资源 */
2274
2372
  dispose() {
2373
+ stopGatewayOutputs();
2275
2374
  for (const d of this.debouncers.values())
2276
2375
  d.dispose();
2277
2376
  this.debouncers.clear();
@@ -34,6 +34,8 @@ const KNOWN_AUN_PAYLOAD_TYPES = new Set([
34
34
  'link',
35
35
  'action_card',
36
36
  'action_card_reply',
37
+ 'widget_card',
38
+ 'widget_card_reply',
37
39
  'merge',
38
40
  'personal_card',
39
41
  'status',
@@ -103,6 +105,9 @@ export function classifyAunPayloadForLog(payload) {
103
105
  if (record.type === 'action_card_reply') {
104
106
  return { msgType: 'action_card_reply', payloadType: 'action_card_reply', content: '[卡片回复]' };
105
107
  }
108
+ if (record.type === 'widget_card_reply') {
109
+ return { msgType: 'widget_card_reply', payloadType: 'widget_card_reply', content: '[WidgetCard 回复]' };
110
+ }
106
111
  const rawType = typeof record.type === 'string' && record.type.trim()
107
112
  ? record.type.trim()
108
113
  : undefined;
@@ -156,9 +161,11 @@ export function classifyAunPayloadForLog(payload) {
156
161
  content = prefixedPayloadSummary('link', title ?? url ?? text);
157
162
  break;
158
163
  case 'action_card':
164
+ case 'widget_card':
159
165
  content = prefixedPayloadSummary('card', title ?? text);
160
166
  break;
161
167
  case 'action_card_reply':
168
+ case 'widget_card_reply':
162
169
  content = firstPayloadString(record, ['text', 'action_value', 'value', 'action_label', 'label']) ?? '[action_card_reply]';
163
170
  break;
164
171
  case 'merge':
@@ -446,6 +453,7 @@ export function buildInboundEntry(opts) {
446
453
  payloadSummary: opts.payloadSummary,
447
454
  groupAttention: opts.groupAttention,
448
455
  groupDelivery: opts.groupDelivery,
456
+ privateAttention: opts.privateAttention,
449
457
  attentionDecision: opts.attentionDecision,
450
458
  content: opts.content,
451
459
  replyTo: opts.replyTo ?? null,
@@ -1120,10 +1120,12 @@ export class MessageQueue {
1120
1120
  shouldRestoreMessage(message, sessionId) {
1121
1121
  if (message.source === 'owner-inject')
1122
1122
  return false;
1123
- // The Trigger scheduler records open runs as daemon_restart. Replaying their
1124
- // queued work afterwards would execute side effects for an already-failed run.
1125
- if (message.executionPermissionOverride)
1123
+ // One-shot grants do not survive a restart. Persistent Agent/session policy
1124
+ // tasks do: ResponseEngine revalidates the current policy before execution.
1125
+ const authorization = message.executionPermissionOverride;
1126
+ if (authorization && authorization.source !== 'agent-policy' && authorization.source !== 'session-policy')
1126
1127
  return false;
1128
+ // Trigger continuations belong to the scheduler's durable run checkpoint.
1127
1129
  if (message.source !== 'trigger' && !message.triggerMeta)
1128
1130
  return true;
1129
1131
  this.droppedTriggerSessionIds.add(sessionId);