evolcore 0.0.46 → 0.0.48

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 (237) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +139 -39
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +43 -18
  8. package/dist/agents/codex/app-server-client.js +32 -23
  9. package/dist/agents/codex-runner.js +31 -16
  10. package/dist/agents/ecagent-runner.js +7 -4
  11. package/dist/agents/gemini-runner.js +5 -2
  12. package/dist/agents/runner-types.js +5 -21
  13. package/dist/aun/aid/agentmd.js +5 -1
  14. package/dist/aun/group/fs-download.js +1 -1
  15. package/dist/aun/service-proxy.js +4 -2
  16. package/dist/build-identity.json +1 -0
  17. package/dist/channels/aun.js +100 -32
  18. package/dist/channels/daemon.js +10 -26
  19. package/dist/cli/aun-commands.js +86 -51
  20. package/dist/cli/code-stats.js +19 -8
  21. package/dist/cli/command-log.js +1 -1
  22. package/dist/cli/daemon-commands.js +65 -76
  23. package/dist/cli/daemon-lifecycle-client.js +17 -3
  24. package/dist/cli/directory.js +7 -1
  25. package/dist/cli/ecmsg-gateway.js +5 -2
  26. package/dist/cli/index.js +2 -8
  27. package/dist/cli/init-channel.js +6 -8
  28. package/dist/cli/init.js +74 -46
  29. package/dist/cli/invoke-command.js +1 -1
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/restart-monitor.js +104 -28
  32. package/dist/cli/role.js +61 -17
  33. package/dist/cli/stats.js +3 -3
  34. package/dist/cli/task-context.js +83 -15
  35. package/dist/cli/thread-command.js +16 -51
  36. package/dist/cli/upgrade-command.js +4 -2
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-manager.js +31 -23
  40. package/dist/config/daemon-services.js +30 -3
  41. package/dist/config/gateway-config.js +2 -2
  42. package/dist/config/invoke-ipc-service.js +6 -4
  43. package/dist/config/peer-bind-code.js +3 -4
  44. package/dist/config/peer-book-store.js +59 -218
  45. package/dist/config/peer-book.js +26 -27
  46. package/dist/config/peer-role-resolver.js +16 -1
  47. package/dist/config/provider-identity-migration.js +161 -6
  48. package/dist/config/provider-ipc-service.js +56 -11
  49. package/dist/config/provider-menu-request.js +24 -5
  50. package/dist/config/provider-templates.js +127 -0
  51. package/dist/config/providers-config.js +59 -8
  52. package/dist/config/providers-management.js +467 -49
  53. package/dist/config/role-command-service.js +248 -1
  54. package/dist/config/schema-migration.js +228 -20
  55. package/dist/config/schema-registry.js +6 -2
  56. package/dist/core/agent-application-service.js +6 -1
  57. package/dist/core/agent-runtime.js +10 -5
  58. package/dist/core/auth/agent-delegation.js +10 -4
  59. package/dist/core/auth/auth-gateway.js +2 -1
  60. package/dist/core/auth/delegation-authorization.js +3 -0
  61. package/dist/core/auth/delegation-diagnostics.js +56 -15
  62. package/dist/core/auth/operation-authorizer.js +26 -1
  63. package/dist/core/auth/operation-catalog.js +28 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/command-handler.js +81 -85
  68. package/dist/core/command/menu-catalog.js +1 -0
  69. package/dist/core/command/menu-handler.js +65 -153
  70. package/dist/core/command/menu-protocol.js +7 -1
  71. package/dist/core/command/provider-menu.js +13 -3
  72. package/dist/core/command/role-menu.js +47 -23
  73. package/dist/core/command/slash-handler.js +30 -49
  74. package/dist/core/command/team-workspace-items.js +81 -12
  75. package/dist/core/command/team-workspace-team.js +9 -71
  76. package/dist/core/command/topic-slash.js +9 -30
  77. package/dist/core/daemon-bootstrap.js +19 -10
  78. package/dist/core/daemon-control.js +8 -10
  79. package/dist/core/daemon-lifecycle.js +50 -40
  80. package/dist/core/evolagent-registry.js +22 -3
  81. package/dist/core/file-integrity/store.js +2 -0
  82. package/dist/core/handoff/runtime.js +37 -1
  83. package/dist/core/host-snapshot.js +9 -4
  84. package/dist/core/inference/text-inference.js +3 -1
  85. package/dist/core/initialization/service.js +31 -8
  86. package/dist/core/interaction-router.js +3 -0
  87. package/dist/core/invoke/executors/text.js +72 -19
  88. package/dist/core/ipc-registration.js +6 -4
  89. package/dist/core/memory/consolidation.js +6 -6
  90. package/dist/core/message/aun-ipc-sender.js +165 -55
  91. package/dist/core/message/im-renderer.js +1 -1
  92. package/dist/core/message/message-bridge.js +51 -334
  93. package/dist/core/message/message-log.js +5 -0
  94. package/dist/core/message/message-queue.js +22 -0
  95. package/dist/core/message/message-utils.js +8 -0
  96. package/dist/core/message/response-engine.js +429 -116
  97. package/dist/core/message/send-routing.js +5 -1
  98. package/dist/core/model/catalog-service.js +31 -11
  99. package/dist/core/model/model-capabilities.js +22 -4
  100. package/dist/core/model/model-catalog.js +1 -0
  101. package/dist/core/ownership/owner-resolver.js +355 -60
  102. package/dist/core/permission/protected-paths.js +6 -6
  103. package/dist/core/relation/peer-identity.js +28 -2
  104. package/dist/core/relation/same-owner-proof.js +81 -111
  105. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  106. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  107. package/dist/core/session/session-file-health.js +49 -14
  108. package/dist/core/session/session-fs-store.js +91 -35
  109. package/dist/core/session/session-manager.js +68 -24
  110. package/dist/core/session/session-mapper.js +14 -34
  111. package/dist/core/session/session-transcript.js +5 -1
  112. package/dist/core/task/task-activity-store.js +84 -0
  113. package/dist/core/task/task-image-resources.js +1 -1
  114. package/dist/core/task/task-recovery-service.js +12 -0
  115. package/dist/core/thread/command-parser.js +7 -12
  116. package/dist/core/thread/thread-context-storage.js +3 -2
  117. package/dist/core/thread/thread-operation.js +2 -13
  118. package/dist/core/thread/thread-service.js +15 -46
  119. package/dist/directory/owner-directory-admission.js +1 -1
  120. package/dist/directory/owner-directory-cache.js +45 -28
  121. package/dist/directory/owner-directory-markdown.js +13 -1
  122. package/dist/directory/owner-directory-query-operation.js +29 -3
  123. package/dist/directory/owner-directory-remarks.js +11 -3
  124. package/dist/eck/message-renderer.js +84 -24
  125. package/dist/ecweb/basic-settings-service.js +3 -1
  126. package/dist/ecweb/message-context-service.js +1 -1
  127. package/dist/ecweb/pairing.js +4 -3
  128. package/dist/ecweb/providers-service.js +26 -1
  129. package/dist/ecweb/runtime/lifecycle.js +82 -23
  130. package/dist/ecweb/runtime/proxy-access.js +74 -0
  131. package/dist/ecweb/runtime/supervisor.js +6 -17
  132. package/dist/event-center/registry.js +13 -2
  133. package/dist/event-center/runtime.js +103 -11
  134. package/dist/event-center/script-runner.js +5 -5
  135. package/dist/index.js +129 -93
  136. package/dist/ipc.js +15 -3
  137. package/dist/outputs/events.js +62 -0
  138. package/dist/outputs/protocol.js +102 -0
  139. package/dist/outputs/service.js +279 -0
  140. package/dist/paths.js +3 -0
  141. package/dist/proxy/manager.js +43 -13
  142. package/dist/services/index.js +89 -4
  143. package/dist/services/ipc-operation.js +4 -15
  144. package/dist/services/pack-manager.js +12 -1
  145. package/dist/services/router.js +21 -6
  146. package/dist/services/script-runner.js +5 -4
  147. package/dist/services/validation.js +1 -1
  148. package/dist/stats/budget.js +1 -1
  149. package/dist/stats/db.js +19 -0
  150. package/dist/stats/index.js +1 -1
  151. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  152. package/dist/stats/normalizer.js +2 -0
  153. package/dist/stats/query.js +35 -27
  154. package/dist/stats/role-budget.js +5 -2
  155. package/dist/stats/writer.js +10 -6
  156. package/dist/trigger/audit.js +7 -0
  157. package/dist/trigger/authorization.js +105 -11
  158. package/dist/trigger/feedback.js +10 -0
  159. package/dist/trigger/history.js +37 -11
  160. package/dist/trigger/ipc-service.js +12 -1
  161. package/dist/trigger/manager.js +1 -0
  162. package/dist/trigger/scheduler.js +11 -5
  163. package/dist/trigger/script-executor.js +2 -1
  164. package/dist/trigger/script-sandbox.js +9 -3
  165. package/dist/trigger/state.js +7 -0
  166. package/dist/trigger/validation.js +22 -0
  167. package/dist/utils/aid-bind.js +155 -18
  168. package/dist/utils/atomic-write.js +3 -3
  169. package/dist/utils/cross-platform.js +97 -31
  170. package/dist/utils/error-dict.json +94 -4
  171. package/dist/utils/error-utils.js +40 -4
  172. package/dist/utils/evolcore-version.js +36 -65
  173. package/dist/utils/instance-registry.js +61 -0
  174. package/dist/utils/msg-diag.js +1 -0
  175. package/dist/utils/process-introspect.js +158 -8
  176. package/dist/utils/process-tree.js +50 -2
  177. package/dist/utils/upgrade-jobs.js +4 -4
  178. package/dist/utils/windows-shell-trust.js +2 -0
  179. package/dist/workbench/protocol.js +80 -0
  180. package/dist/workbench/service.js +359 -0
  181. package/ecagent/dist/types.d.ts +6 -2
  182. package/kits/docs/context-assembly.md +1 -1
  183. package/kits/docs/evolcore/INDEX.md +2 -2
  184. package/kits/docs/evolcore/aid.md +3 -1
  185. package/kits/docs/evolcore/config.md +12 -0
  186. package/kits/docs/evolcore/directory.md +22 -3
  187. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  188. package/kits/docs/evolcore/model.md +10 -0
  189. package/kits/docs/evolcore/peer.md +19 -65
  190. package/kits/docs/evolcore/provider.md +133 -5
  191. package/kits/docs/evolcore/role.md +80 -0
  192. package/kits/docs/evolcore/services.md +6 -6
  193. package/kits/docs/evolcore/team-workspace.md +1 -1
  194. package/kits/docs/evolcore/thread-chain.md +14 -15
  195. package/kits/docs/evolcore/tool-authorization.md +5 -0
  196. package/kits/docs/evolcore/trigger.md +10 -0
  197. package/kits/eck_message_manifest.json +12 -0
  198. package/kits/provider-templates.json +1213 -0
  199. package/kits/rules/04-relation.md +3 -3
  200. package/kits/schemas/_meta.json +14 -2
  201. package/kits/schemas/contact-book.schema.4.json +52 -0
  202. package/kits/schemas/providers.schema.3.json +200 -0
  203. package/kits/skills/.switches.json +4 -0
  204. package/kits/skills/ability/references/calling.md +1 -1
  205. package/kits/skills/ec-group/SKILL.md +2 -2
  206. package/kits/skills/ec-identity/SKILL.md +19 -72
  207. package/kits/skills/ec-provider/SKILL.md +221 -0
  208. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  209. package/kits/skills/ec-trigger/SKILL.md +1 -1
  210. package/kits/skills/thread-ops/SKILL.md +34 -21
  211. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  212. package/kits/templates/message-fragments/group-batch.md +1 -1
  213. package/kits/templates/message-fragments/inject-default.md +1 -1
  214. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  215. package/kits/templates/message-fragments/item-group.md +1 -1
  216. package/kits/templates/message-fragments/item-private.md +1 -1
  217. package/kits/templates/message-fragments/thread-context.md +1 -1
  218. package/kits/templates/message-fragments/trigger-session.md +1 -1
  219. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  220. package/kits/templates/roles/admin.json +2 -19
  221. package/kits/templates/roles/member.json +0 -3
  222. package/kits/templates/system-fragments/baseagent.md +6 -0
  223. package/kits/templates/system-fragments/commands.md +3 -3
  224. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  225. package/kits/templates/system-fragments/relation.md +1 -1
  226. package/kits/templates/system-fragments/thread.md +6 -5
  227. package/package.json +6 -4
  228. package/scripts/agent-template/inspect.mjs +4 -1
  229. package/scripts/agent-template/shared/common.mjs +2 -3
  230. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  231. package/scripts/agent-template/shared/template-package.mjs +9 -2
  232. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  233. package/scripts/agent-template/team-pack.mjs +6 -3
  234. package/dist/cli/peer.js +0 -127
  235. package/dist/config/peer-operation-service.js +0 -132
  236. package/dist/config/peer-request-service.js +0 -532
  237. package/dist/core/command/connect-menu.js +0 -624
@@ -15,11 +15,15 @@ export class BaseagentRunnerUnavailableError extends Error {
15
15
  }
16
16
  /** Codex's native asynchronous reply envelope used by its rich clients. */
17
17
  export function formatAsyncQuestionAnswer(answer) {
18
- return '<send_user_message_question_reply>' + JSON.stringify({
18
+ const reply = '<send_user_message_question_reply>' + JSON.stringify({
19
19
  questionItemId: answer.questionItemId,
20
20
  question: answer.question,
21
21
  answer: answer.answer,
22
22
  }) + '</send_user_message_question_reply>';
23
+ if (!answer.interruptedTools?.length)
24
+ return reply;
25
+ return reply + '\n以下工具在提问暂停前已发起,尚未确认完成。请先核验实际执行状态和结果,不要直接重跑:\n'
26
+ + JSON.stringify(answer.interruptedTools);
23
27
  }
24
28
  export function parseAsyncUserQuestions(value) {
25
29
  if (!Array.isArray(value) || value.length === 0 || value.length > 20) {
@@ -173,23 +177,3 @@ export function isOneMillionContextModel(model) {
173
177
  export function realContextWindowForModel(model) {
174
178
  return isOneMillionContextModel(model) ? 1000000 : 200000;
175
179
  }
176
- /**
177
- * EvolCore auto-compact threshold: fixed at 650k tokens regardless of model
178
- * context window. Large-window models (1M) compress at 650k; small-window
179
- * models (200k/128k) never reach this threshold and rely on the SDK's own
180
- * built-in compaction instead.
181
- */
182
- export function autoCompactWindowForModel(_model) {
183
- return 650_000;
184
- }
185
- /**
186
- * Threshold passed to the Claude Code SDK's autoCompactWindow option.
187
- * Kept window-aware so the SDK's own built-in compaction continues to fire
188
- * at the right point for small-context models (200k/128k), where EvolCore's
189
- * fixed 650k threshold would never trigger.
190
- */
191
- export function sdkAutoCompactWindowForModel(model, resolvedContextWindow) {
192
- const contextWindow = resolvedContextWindow ?? realContextWindowForModel(model);
193
- const reserve = Math.min(10_000, Math.floor(contextWindow * 0.05));
194
- return Math.min(650_000, Math.max(1, contextWindow - reserve));
195
- }
@@ -724,10 +724,14 @@ export async function agentmdGet(aid, opts) {
724
724
  if (opts?.remoteOnly) {
725
725
  const code = String(r.error?.code ?? '');
726
726
  const message = String(r.error?.message ?? r.error);
727
+ const retryable = r.error.retryable;
727
728
  if (code === 'AGENTMD_NOT_FOUND' || /not found|404|missing/i.test(message)) {
728
729
  throw Object.assign(new Error(`agent.md not found for ${aid}`), { code: 'AGENTMD_NOT_FOUND' });
729
730
  }
730
- throw new Error(`Remote agent.md verification unavailable for ${aid}`);
731
+ throw Object.assign(new Error(`Remote agent.md verification unavailable for ${aid}: ${message}`), {
732
+ code: code || 'UNAVAILABLE',
733
+ ...(typeof retryable === 'boolean' ? { retryable } : {}),
734
+ });
731
735
  }
732
736
  // Network/fetch failed — fall back to local file.
733
737
  if (!fs.existsSync(localPath)) {
@@ -1,5 +1,4 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { StorageLowLevel, StorageVFS } from '@agentunion/fastaun';
3
2
  export const DEFAULT_FS_CAT_BYTES = 128 * 1024;
4
3
  export const MAX_FS_CAT_BYTES = 128 * 1024;
5
4
  export class FsReadBudgetError extends Error {
@@ -46,6 +45,7 @@ async function downloadWithinBudget(url, maxBytes, headers) {
46
45
  }
47
46
  export async function readPersonalFsBytesWithinBudget(client, path, maxBytes, options) {
48
47
  validateFsReadBudget(maxBytes);
48
+ const { StorageLowLevel, StorageVFS } = await import('@agentunion/fastaun');
49
49
  const lowlevel = new StorageLowLevel(client);
50
50
  const getObject = lowlevel.getObject.bind(lowlevel);
51
51
  lowlevel.getObject = params => getObject({ ...params, offset: 0, limit: maxBytes + 1 });
@@ -18,6 +18,7 @@ import fs from 'fs';
18
18
  import path from 'path';
19
19
  import { setTimeout as delay } from 'node:timers/promises';
20
20
  import { ServiceProxyClient, EndpointPolicy } from '@agentunion/fastaun';
21
+ import { DEFAULT_ECWEB_PROXY_VISIBILITY } from '../config/daemon-services.js';
21
22
  import { resolvePaths } from '../paths.js';
22
23
  import { logger } from '../utils/logger.js';
23
24
  import { parseEcwebInstanceRecord } from '../contracts/ecweb-instance.js';
@@ -226,15 +227,16 @@ export function startServiceProxy(controlChannel, providerAid, configuredService
226
227
  return { registered: 0, gatewayRegistered: false };
227
228
  if (!endpoint)
228
229
  continue;
230
+ const visibility = svc.proxy?.visibility ?? (svc.name === 'ecweb' ? DEFAULT_ECWEB_PROXY_VISIBILITY : 'private');
229
231
  try {
230
232
  proxyClient.registerService(svc.name, endpoint, {
231
233
  serviceType: svc.proxy?.serviceType ?? 'http',
232
- visibility: svc.proxy?.visibility ?? 'private',
234
+ visibility,
233
235
  metadata: svc.proxy?.metadata ?? {},
234
236
  });
235
237
  registered += 1;
236
238
  endpoints[svc.name] = endpoint;
237
- logger.info(`${LOG} 注册服务 "${svc.name}" → ${endpoint} (type=${svc.proxy?.serviceType ?? 'http'}, visibility=${svc.proxy?.visibility ?? 'private'})`);
239
+ logger.info(`${LOG} 注册服务 "${svc.name}" → ${endpoint} (type=${svc.proxy?.serviceType ?? 'http'}, visibility=${visibility})`);
238
240
  }
239
241
  catch (e) {
240
242
  logger.warn(`${LOG} 注册服务 "${svc.name}" 失败: ${e?.message || e}`);
@@ -0,0 +1 @@
1
+ {"id":"sha256:76e20a438d3936bb3420763f","builtAt":"2026-11-14T05:54:02.439Z"}
@@ -28,7 +28,7 @@ import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
28
28
  import { chatDirPath } from '../core/session/session-fs-store.js';
29
29
  import { readSessionLoopConfig, resolveSessionLoopTarget } from '../core/session/session-idle-monitor.js';
30
30
  import { resolveRuntimePermissionMode, sessionFullAccessStatus } from '../core/role/runtime-policy.js';
31
- import { readTopicLabel, readTopicStatus } from '../core/session/session-mapper.js';
31
+ import { readTopicStatus } from '../core/session/session-mapper.js';
32
32
  import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
33
33
  import { appendAidLifecycle } from '../aun/aid/identity.js';
34
34
  import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
@@ -955,7 +955,7 @@ export class AUNChannel {
955
955
  ownerDirectoryRetryAttempts = 0;
956
956
  ownerDirectoryResolvedSignature;
957
957
  store = null;
958
- /** 服务路由实例(懒建;services-config.json 不存在时也建,只是总闸关闭)。 */
958
+ /** 服务路由实例(懒建;缺少 services-config.json 时默认开启,内置查询无需装包)。 */
959
959
  serviceRouter = null;
960
960
  /**
961
961
  * 本 agent 的工程目录,由插件从 `ChannelBuildContext.defaultProjectPath` 注入。
@@ -998,7 +998,8 @@ export class AUNChannel {
998
998
  // 自动从 data 推断顶层字段(self_aid / peer_aid / group_id / task_id / chatmode),
999
999
  // 便于 jq 过滤:`jq 'select(.task_id == "task-xxx")'`
1000
1000
  const inbound = data && typeof data === 'object' ? data : {};
1001
- const isolateTrace = dir === 'IN' && event === 'message.received' && !this.config.pureIdentity;
1001
+ const isolateTrace = dir === 'IN' && event === 'message.received'
1002
+ && (!this.config.pureIdentity || inbound.payload?.type === 'action_card_reply');
1002
1003
  const safeData = isolateTrace ? {
1003
1004
  message_id: inbound.message_id, seq: inbound.seq,
1004
1005
  envelope: { from: inbound.envelope?.from, to: inbound.envelope?.to, encrypted: inbound.envelope?.encrypted },
@@ -1320,7 +1321,7 @@ export class AUNChannel {
1320
1321
  logger.info(`${this.logPrefix()} ActionInteraction audit: behavior=${behavior ?? 'reply'} `
1321
1322
  + `cardId=${cardMessageId} interactionId=${interactionId} result=${result} textLength=${textLength}`);
1322
1323
  }
1323
- extractTextPayload(payload, channelId, senderAid, delivery) {
1324
+ extractTextPayload(payload, channelId, senderAid, delivery, encrypted) {
1324
1325
  if (typeof payload === 'string')
1325
1326
  return payload;
1326
1327
  if (payload && typeof payload === 'object') {
@@ -1331,6 +1332,11 @@ export class AUNChannel {
1331
1332
  const cardMsgId = typeof obj.ref_message_id === 'string' ? obj.ref_message_id
1332
1333
  : typeof obj.card_message_id === 'string' ? obj.card_message_id : '';
1333
1334
  const cardInfo = cardMsgId ? this.cardMessageIdMap.get(cardMsgId) : undefined;
1335
+ if (cardInfo?.sensitive && (encrypted !== true || delivery?.chatType !== 'private'
1336
+ || !senderAid || senderAid !== cardInfo.initiatorAid || channelId !== cardInfo.channelId)) {
1337
+ this.notifyCardActionFailure(channelId, '凭据仅接受卡片发起者通过加密私聊提交', senderAid, channelId === cardInfo.channelId ? cardInfo.replyContext?.threadId : undefined, delivery);
1338
+ return '';
1339
+ }
1334
1340
  const cardDelivery = cardInfo?.delivery ?? delivery;
1335
1341
  const savedTopic = this.ownedCardTopics.get(cardMsgId);
1336
1342
  // Keep the topic after the actionable mapping expires, including for
@@ -1463,6 +1469,7 @@ export class AUNChannel {
1463
1469
  ...(isComposeReply ? { custom_text: text } : {}),
1464
1470
  },
1465
1471
  operatorId: cardClickerAid || undefined,
1472
+ ...(cardInfo.sensitive ? { encrypted: encrypted === true } : {}),
1466
1473
  };
1467
1474
  const settle = (accepted) => {
1468
1475
  this.interactionActionsInFlight.delete(cardMsgId);
@@ -2036,6 +2043,26 @@ export class AUNChannel {
2036
2043
  invalidateAgentDisplayName(aid);
2037
2044
  PeerIdentityCache.invalidate('aun', aid, path.join(resolvePaths().agentsDir, this.config.aid));
2038
2045
  }
2046
+ /**
2047
+ * 入站发件人展示名:Owner 备注名 > 名片名 > AID 短名。
2048
+ *
2049
+ * 备注名来自 Owner 名录快照(App 里给联系人改的备注),比名片更贴近 Owner
2050
+ * 平时的称呼;名录取不到该条目时才回落到名片名。名录读取是本地快照、
2051
+ * 有文件戳缓存,不产生网络请求。
2052
+ */
2053
+ inboundDisplayName(fromAid, cardName, shortAid) {
2054
+ let directoryName;
2055
+ try {
2056
+ const entry = this.ownerDirectoryCache?.cache.readSnapshot('contacts')?.entries
2057
+ .find(item => item.aid === fromAid);
2058
+ const remark = entry?.remark?.trim();
2059
+ if (remark)
2060
+ return remark;
2061
+ directoryName = entry?.name?.trim() || undefined;
2062
+ }
2063
+ catch { /* 名录不可用不影响消息处理 */ }
2064
+ return cardName?.trim() || directoryName || shortAid || fromAid;
2065
+ }
2039
2066
  /**
2040
2067
  * 每条进入消息队列的消息都走这里。分两段,代价完全不同:
2041
2068
  *
@@ -2199,7 +2226,7 @@ export class AUNChannel {
2199
2226
  logger.warn(`${this.logPrefix()} owner.directory.grant: initial pull failed (pending kept): ${error instanceof Error ? error.message : String(error)}`);
2200
2227
  }
2201
2228
  }
2202
- buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId, label, topicStatus) {
2229
+ buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId, topicStatus) {
2203
2230
  if (!groupId)
2204
2231
  throw new Error('buildGroupReplyContext requires groupId');
2205
2232
  const replyContext = {
@@ -2217,13 +2244,11 @@ export class AUNChannel {
2217
2244
  replyContext.metadata = {};
2218
2245
  replyContext.metadata.topicName = topicName;
2219
2246
  }
2220
- if (label && threadId)
2221
- replyContext.metadata.label = label;
2222
2247
  if (topicStatus && threadId)
2223
2248
  replyContext.metadata.topicStatus = topicStatus;
2224
2249
  return replyContext;
2225
2250
  }
2226
- buildPrivateReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, refMessageId, label, topicStatus) {
2251
+ buildPrivateReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, refMessageId, topicStatus) {
2227
2252
  const replyContext = {
2228
2253
  metadata: { encrypted, chatmode, refMessageId },
2229
2254
  delivery: { chatType: 'private' },
@@ -2235,8 +2260,6 @@ export class AUNChannel {
2235
2260
  replyContext.replyToMessageId = messageId;
2236
2261
  if (topicName && threadId)
2237
2262
  replyContext.metadata.topicName = topicName;
2238
- if (label && threadId)
2239
- replyContext.metadata.label = label;
2240
2263
  if (topicStatus && threadId)
2241
2264
  replyContext.metadata.topicStatus = topicStatus;
2242
2265
  return replyContext;
@@ -3373,7 +3396,7 @@ export class AUNChannel {
3373
3396
  if (type === 'text' && typeof value?.text === 'string' && /^\s*\/bind(?:\s|$)/i.test(value.text))
3374
3397
  return false;
3375
3398
  // An already isolated source never becomes an ordinary message after approval.
3376
- await ownerResolver.refresh(selfAid, { maxAgeMs: 30_000, allowTransient: true, source: 'contact.inbound' });
3399
+ await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true, source: 'contact.inbound' });
3377
3400
  await this.getOwnerDirectoryRuntime();
3378
3401
  await this.settleOwnerDirectoryBeforeTurn();
3379
3402
  const decision = evaluateAppContactAdmission(selfAid, fromAid);
@@ -3582,6 +3605,18 @@ export class AUNChannel {
3582
3605
  return;
3583
3606
  const protectedHeaders = verifiedProtectedHeaders(msg, env);
3584
3607
  const payload = msg.payload ?? '';
3608
+ // Credential answers must be consumed before contact/request persistence,
3609
+ // observer forwarding or generic message logging. Card binding is server-owned.
3610
+ if (payload && typeof payload === 'object' && payload.type === 'action_card_reply') {
3611
+ const ref = payload.ref_message_id ?? payload.card_message_id;
3612
+ const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
3613
+ if (!card || card.sensitive) {
3614
+ if (appOwned && !this.claimInboundMessage('private', messageId, seq))
3615
+ return;
3616
+ this.extractTextPayload(payload, fromAid, fromAid, { chatType: 'private' }, !!env.encrypted);
3617
+ return;
3618
+ }
3619
+ }
3585
3620
  // friend.invite.v1(App 主动加好友)不依赖 app-v1 灰度:按 Owner 准入策略已放行的申请人
3586
3621
  // 由本 Agent 直接回 accepted 并发欢迎语;其余转交 Owner。不进 Agent、不转 observer。
3587
3622
  if (!this.config.pureIdentity && isFriendInvitePayload(payload)) {
@@ -3651,7 +3686,7 @@ export class AUNChannel {
3651
3686
  ? payload._evolcore_causation_ref
3652
3687
  : undefined;
3653
3688
  const logDescriptor = classifyAunPayloadForLog(payload);
3654
- const text = this.extractTextPayload(payload, fromAid, fromAid, { chatType: 'private' });
3689
+ const text = this.extractTextPayload(payload, fromAid, fromAid, { chatType: 'private' }, !!env.encrypted);
3655
3690
  const threadId = typeof payload === 'object' && payload !== null ? payload.thread_id : undefined;
3656
3691
  const refMessageId = typeof payload === 'object' && payload !== null && typeof payload.ref_message_id === 'string'
3657
3692
  ? payload.ref_message_id
@@ -3684,7 +3719,8 @@ export class AUNChannel {
3684
3719
  // forwardInbound 内部排除 self-echo 与 from-owner。
3685
3720
  // 显式排除 observer.inject:它是 owner 对本 agent 的控制消息,不应镜像给观察者
3686
3721
  // (即便日后 from-owner 排除规则调整,也不会泄漏)。
3687
- if (!contactControl && (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject'))) {
3722
+ if (!contactControl && inboundType !== 'action_card_reply'
3723
+ && (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject'))) {
3688
3724
  void this.forwardInbound(msg);
3689
3725
  }
3690
3726
  if (inboundType === 'observer.inject.status' || inboundType === 'observer.inject.ack') {
@@ -3721,7 +3757,7 @@ export class AUNChannel {
3721
3757
  const peerIdentity = await PeerIdentityCache.resolve('aun', fromAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
3722
3758
  await prepareSameOwnerProof(this.config.aid, fromAid);
3723
3759
  const shortAid = this.getShortAid(fromAid);
3724
- const displayName = peerIdentity.name || shortAid;
3760
+ const displayName = this.inboundDisplayName(fromAid, peerIdentity.name, shortAid);
3725
3761
  // 详细 dispatch 决策日志:记录消息为何被路由到 agent
3726
3762
  const p2pPayloadType = (payload && typeof payload === 'object' && typeof payload.type === 'string')
3727
3763
  ? payload.type
@@ -3794,7 +3830,7 @@ export class AUNChannel {
3794
3830
  return;
3795
3831
  }
3796
3832
  // bind.request:Evol App 绑定请求。绕过白名单透传原始 payload JSON 给 bridge,
3797
- // 由控制 AID 的 onMessage 处理器(BindService.handleRequest)解析并回 bind.response。
3833
+ // 由控制 AID 的 BindService 校验扫码凭证,再通过统一 Ownership 服务发起协议绑定。
3798
3834
  // 透传 encrypted:bind.response 须与请求的加密/明文对称(见 onMessage 处理)。
3799
3835
  if (p2pPayloadType === AUNChannel.BIND_REQUEST_TYPE) {
3800
3836
  this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq);
@@ -3826,7 +3862,7 @@ export class AUNChannel {
3826
3862
  appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'message_in', aid: this.config.aid, from: fromAid, msgId: messageId, kind: 'text', len: finalText.length });
3827
3863
  const isSystemP2P = p2pPayloadType === 'event';
3828
3864
  this.aidStatsCollector?.recordInbound(this.config.aid, fromAid, Buffer.byteLength(finalText, 'utf-8'), finalText, isSystemP2P, msgEncrypted, msgChatmode, isSystemP2P ? 'notify' : 'send');
3829
- const replyContext = this.buildPrivateReplyContext(threadId, fromAid, msgEncrypted, messageId, msgChatmode, topicName, refMessageId, readTopicLabel(payload), readTopicStatus(payload));
3865
+ const replyContext = this.buildPrivateReplyContext(threadId, fromAid, msgEncrypted, messageId, msgChatmode, topicName, refMessageId, readTopicStatus(payload));
3830
3866
  this.dispatchMessage({
3831
3867
  channelId: chatId,
3832
3868
  userId: fromAid,
@@ -3874,6 +3910,14 @@ export class AUNChannel {
3874
3910
  const groupId = env.group_id ?? '';
3875
3911
  const senderAid = env.from ?? '';
3876
3912
  const payload = msg.payload ?? '';
3913
+ if (payload && typeof payload === 'object' && payload.type === 'action_card_reply') {
3914
+ const ref = payload.ref_message_id ?? payload.card_message_id;
3915
+ const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
3916
+ if (!card || card.sensitive) {
3917
+ this.extractTextPayload(payload, groupId, senderAid, { chatType: 'group', groupId }, !!env.encrypted);
3918
+ return;
3919
+ }
3920
+ }
3877
3921
  const responseRecord = getAunRequestRegistry().resolveIncoming({
3878
3922
  selfAid: this._aid || this.config.aid,
3879
3923
  fromAid: senderAid,
@@ -3903,7 +3947,7 @@ export class AUNChannel {
3903
3947
  return;
3904
3948
  const payloadMentionAids = mentionEntryAids(payloadMentionEntries);
3905
3949
  const logDescriptor = classifyAunPayloadForLog(payload);
3906
- const text = this.extractTextPayload(payload, groupId, senderAid, { chatType: 'group', groupId });
3950
+ const text = this.extractTextPayload(payload, groupId, senderAid, { chatType: 'group', groupId }, !!env.encrypted);
3907
3951
  const threadId = typeof payload === 'object' && payload !== null ? payload.thread_id : undefined;
3908
3952
  const topicName = (typeof payload === 'object' && payload !== null)
3909
3953
  ? this.sanitizeTopicName(payload.topicName)
@@ -3915,8 +3959,10 @@ export class AUNChannel {
3915
3959
  }
3916
3960
  // Observer forward (inbound):群聊消息在所有过滤之前转发原始明文 payload。
3917
3961
  // forwardInbound 内部排除 self-echo 与 from-owner。
3918
- void this.forwardInbound(msg);
3919
- logger.debug(`${this.logPrefix()}[DIAG-GRP] full_msg=${JSON.stringify(msg).substring(0, 500)}`);
3962
+ if (inboundType !== 'action_card_reply') {
3963
+ void this.forwardInbound(msg);
3964
+ logger.debug(`${this.logPrefix()}[DIAG-GRP] full_msg=${JSON.stringify(msg).substring(0, 500)}`);
3965
+ }
3920
3966
  if (!groupId || !senderAid) {
3921
3967
  logger.debug(`${this.logPrefix()} Group dropped: missing groupId or senderAid (mid=${messageId})`);
3922
3968
  return;
@@ -3944,7 +3990,7 @@ export class AUNChannel {
3944
3990
  const msgChatmodeFast = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
3945
3991
  const peerInfo = this.peerInfoCached(senderAid);
3946
3992
  const shortAid = this.getShortAid(senderAid);
3947
- const displayName = peerInfo?.name || shortAid;
3993
+ const displayName = this.inboundDisplayName(senderAid, peerInfo?.name, shortAid);
3948
3994
  const createdAt = data.created_at;
3949
3995
  if (!peerInfo)
3950
3996
  this.prefetchPeerInfo(senderAid);
@@ -3957,7 +4003,7 @@ export class AUNChannel {
3957
4003
  peerName: displayName,
3958
4004
  peerType: peerInfo?.type || 'unknown',
3959
4005
  seq,
3960
- replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncryptedFast, messageId, msgChatmodeFast, topicName, groupId, readTopicLabel(payload), readTopicStatus(payload)),
4006
+ replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncryptedFast, messageId, msgChatmodeFast, topicName, groupId, readTopicStatus(payload)),
3961
4007
  createdAt,
3962
4008
  });
3963
4009
  return;
@@ -4035,7 +4081,7 @@ export class AUNChannel {
4035
4081
  extra: `from=${senderAid} mid=${messageId} chat=group self=${this._aid || 'unknown'} conn_uptime=${this.connectedAt ? Math.round((echoReceiveTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoInboundLegLabel(echoCreatedAt, receivedAt)}`,
4036
4082
  })}`;
4037
4083
  const msgChatmodeEcho = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
4038
- const groupProbeContext = this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmodeEcho, topicName, groupId, readTopicLabel(payload), readTopicStatus(payload));
4084
+ const groupProbeContext = this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmodeEcho, topicName, groupId, readTopicStatus(payload));
4039
4085
  this.registerProbe(messageId, echoKindGroup ?? 'ask', echoText, groupId, groupProbeContext, echoReceiveTs);
4040
4086
  // 继续走正常 Agent 流程(下面的代码会 dispatch)
4041
4087
  }
@@ -4092,7 +4138,7 @@ export class AUNChannel {
4092
4138
  const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
4093
4139
  const peerIdentity = await PeerIdentityCache.resolve('aun', senderAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
4094
4140
  const shortAid = this.getShortAid(senderAid);
4095
- const displayName = peerIdentity.name || shortAid;
4141
+ const displayName = this.inboundDisplayName(senderAid, peerIdentity.name, shortAid);
4096
4142
  // 详细 dispatch 决策日志:记录消息为何被路由到 agent
4097
4143
  const payloadType = (payload && typeof payload === 'object') ? payload.type ?? '' : '';
4098
4144
  const textMentionSelf = this._aid ? this.hasExplicitMention(text, this._aid) : false;
@@ -4126,7 +4172,7 @@ export class AUNChannel {
4126
4172
  const senderGroupRole = memberRoles?.get(String(senderAid).toLowerCase());
4127
4173
  const myGroupRole = memberRoles?.get(String(this._aid || '').toLowerCase());
4128
4174
  const groupRoles = memberRoles ? Object.fromEntries(memberRoles) : undefined;
4129
- // 「与发言人」:发言人本人的关系 → 联系人 → visitor。
4175
+ // 「关系角色」:发言人本人的关系 → 联系人 → visitor。
4130
4176
  const speakerRelation = resolveSenderRelationRole({
4131
4177
  selfAid: this.config.aid,
4132
4178
  channelKey: `aun#${this.config.aid}#main`,
@@ -4163,7 +4209,7 @@ export class AUNChannel {
4163
4209
  isMentioned: isOwnHandoff || mentionedSelf || mentionedAll,
4164
4210
  source: isOwnHandoff ? 'handoff' : undefined,
4165
4211
  encrypted: msgEncrypted,
4166
- replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmode, topicName, groupId, readTopicLabel(payload), readTopicStatus(payload)),
4212
+ replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmode, topicName, groupId, readTopicStatus(payload)),
4167
4213
  mentionMode: serverMentionMode,
4168
4214
  images: inboundImages.length > 0 ? inboundImages : undefined,
4169
4215
  msgType: logDescriptor.msgType,
@@ -5042,8 +5088,8 @@ export class AUNChannel {
5042
5088
  if (!config)
5043
5089
  return undefined;
5044
5090
  const lifecycle = resolveAgentLifecycle(config);
5045
- // Legacy Owner hints are initialization inputs; active Agents need no automatic bind reconciliation.
5046
- if (lifecycle === null || lifecycle === 'active')
5091
+ // Existing active Agents may still carry an unfulfilled configured binding target.
5092
+ if (lifecycle === null)
5047
5093
  return undefined;
5048
5094
  return firstConfiguredOwner(config);
5049
5095
  }
@@ -5108,12 +5154,23 @@ export class AUNChannel {
5108
5154
  const attemptKey = JSON.stringify([subjectAid, ownerAid]);
5109
5155
  if (AUNChannel.configuredOwnerBindAttempts.has(attemptKey))
5110
5156
  return;
5111
- // Claim before awaiting submission: an error or lost receipt must not cause automatic resends.
5157
+ // Reserve across channel recreation while preparation is in flight. Only entering
5158
+ // an SDK mutation consumes the attempt; a lost receipt must never release it.
5112
5159
  AUNChannel.configuredOwnerBindAttempts.add(attemptKey);
5113
- logger.info(`${this.logPrefix()} Submitting configured Owner binding invitation: `
5114
- + `subject=${subjectAid} owner=${ownerAid} consensus=${current.consensusStatus}`);
5115
- await ownerResolver.bind(subjectAid, ownerAid, () => this.isCurrentConfiguredOwnerBind(client, epoch) && this.configuredOwnerAid() === ownerAid
5116
- && !ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid));
5160
+ let submissionStarted = false;
5161
+ try {
5162
+ await ownerResolver.bind(subjectAid, ownerAid, () => this.isCurrentConfiguredOwnerBind(client, epoch) && this.configuredOwnerAid() === ownerAid
5163
+ && !ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid), () => {
5164
+ submissionStarted = true;
5165
+ logger.info(`${this.logPrefix()} Submitting configured Owner binding invitation: `
5166
+ + `subject=${subjectAid} owner=${ownerAid} consensus=${current.consensusStatus}`);
5167
+ });
5168
+ }
5169
+ catch (error) {
5170
+ if (!submissionStarted)
5171
+ AUNChannel.configuredOwnerBindAttempts.delete(attemptKey);
5172
+ throw error;
5173
+ }
5117
5174
  }
5118
5175
  /** 判断 terminal_failed 的 reason 是否属于"被踢"类 */
5119
5176
  isKickReason(reason) {
@@ -5753,6 +5810,7 @@ export class AUNChannel {
5753
5810
  this.registerCardPostSend(messageId, {
5754
5811
  type: 'register_interaction_card', requestId: interaction.id,
5755
5812
  isCommandCard: false, initiatorAid: interaction.initiatorId,
5813
+ sensitive: interaction.sensitive,
5756
5814
  expiresAt: interaction.expiresAt, delivery,
5757
5815
  }, channelId, delivery, envelope.replyContext);
5758
5816
  }
@@ -5816,6 +5874,7 @@ export class AUNChannel {
5816
5874
  channelId,
5817
5875
  delivery: delivery ?? action.delivery,
5818
5876
  replyContext: callbackContext,
5877
+ sensitive: action.sensitive,
5819
5878
  });
5820
5879
  this.ownedCardMsgIds.add(messageId);
5821
5880
  if (typeof replyContext?.threadId === 'string') {
@@ -7594,6 +7653,8 @@ export class AUNChannel {
7594
7653
  Object.assign(finalPayload, this.withCurrentTopicName(channelId, finalPayload));
7595
7654
  }
7596
7655
  const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
7656
+ const isOutputServicePayload = delivery.chatType === 'private' && !!delivery.service
7657
+ && /^services\.outputs\.(snapshot|list|detail|changes)\.result$/.test(finalPayload.type ?? '');
7597
7658
  finalPayload = await this.withSessionState(channelId, finalPayload, context);
7598
7659
  const params = { payload: finalPayload, encrypt };
7599
7660
  if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
@@ -7606,6 +7667,10 @@ export class AUNChannel {
7606
7667
  }
7607
7668
  if (encrypt)
7608
7669
  params.protected_headers = aunProtectedHeaders(context);
7670
+ if (isOutputServicePayload) {
7671
+ params.message_class = 'control';
7672
+ params.protected_headers = { ...(params.protected_headers ?? {}), message_class: 'control' };
7673
+ }
7609
7674
  try {
7610
7675
  if (isGroup) {
7611
7676
  params.group_id = delivery.groupId;
@@ -8921,6 +8986,7 @@ export class AUNChannelPlugin {
8921
8986
  const aunCard = withAunAttention({
8922
8987
  type: 'action_card',
8923
8988
  title: action.title,
8989
+ ...(req.sensitive ? { sensitive: true } : {}),
8924
8990
  ...(req.blocking === true ? { blocking: true } : {}),
8925
8991
  ...(action.recommendedOption ? { recommended_option: action.recommendedOption } : {}),
8926
8992
  actions: action.buttons.map(btn => ({
@@ -8934,6 +9000,7 @@ export class AUNChannelPlugin {
8934
9000
  if (action.allowCustomInput) {
8935
9001
  aunCard.actions.push({
8936
9002
  label: '✏️ 手动输入', style: 'default', behavior: 'compose',
9003
+ ...(req.sensitive ? { sensitive: true } : {}),
8937
9004
  ...(cardExpiresAt !== undefined ? { compose_timeout_ms: Math.max(0, cardExpiresAt - Date.now()) } : {}),
8938
9005
  });
8939
9006
  }
@@ -8961,6 +9028,7 @@ export class AUNChannelPlugin {
8961
9028
  type: 'register_interaction_card',
8962
9029
  requestId: req.id,
8963
9030
  isCommandCard: false,
9031
+ sensitive: req.sensitive,
8964
9032
  initiatorAid: req.initiatorId,
8965
9033
  delivery: replyCtx?.delivery,
8966
9034
  expiresAt: cardExpiresAt,
@@ -2,8 +2,7 @@ import { appendExpireEntry, recordNextLaunchCleanup, cleanupPreviousByKind, runE
2
2
  import { ExecutionTimeoutError } from '../utils/error-utils.js';
3
3
  import { logger } from '../utils/logger.js';
4
4
  import { normalizeExecutionMode } from '../trigger/validation.js';
5
- import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
6
- import { prepareSameOwnerProof } from '../core/relation/same-owner-proof.js';
5
+ import { bindTriggerExecutionIdentity, currentTriggerExecutionIdentity } from '../trigger/authorization.js';
7
6
  import { assertSystemSessionLaunchable } from '../core/system-session/registry.js';
8
7
  import { sessionTopicThreadId } from '../core/thread/topic-id.js';
9
8
  const DEFAULT_WATCHDOG_MS = 11 * 60 * 1000;
@@ -48,7 +47,7 @@ export class DaemonChannel {
48
47
  // 启动前跑一次 expire 扫描(成本低,只读少量小文件)
49
48
  this.runExpireCleanupSafely();
50
49
  const runId = ctx.runId;
51
- const pendingId = ctx.attemptId ?? runId;
50
+ const pendingId = ctx.deliveryId ?? ctx.attemptId ?? runId;
52
51
  const messageId = pendingId;
53
52
  const startedAt = Date.now();
54
53
  const remainingExecutionMs = typeof ctx.executionDeadlineAt === 'number'
@@ -147,16 +146,21 @@ export class DaemonChannel {
147
146
  }
148
147
  if (ctx.signal?.aborted)
149
148
  onAbort();
150
- if (message.triggerMeta?.originChannelType === 'aun' && message.triggerMeta.originChatType !== 'group') {
151
- await prepareSameOwnerProof(ctx.trigger.agentAid, message.triggerMeta.originPeerId);
149
+ try {
150
+ await bindTriggerExecutionIdentity(message, ctx.trigger, ctx.executionIdentity);
152
151
  }
152
+ catch (error) {
153
+ this.fail(pendingId, 'authorization_denied', error instanceof Error ? error.message : String(error));
154
+ return promise;
155
+ }
156
+ const executionIdentity = await currentTriggerExecutionIdentity(message, ctx.trigger.agentAid);
153
157
  if (!slot?.terminalClaim) {
154
158
  void this.messageQueue.enqueue(ctx.session.id, message, ctx.projectPath, {
155
159
  interruptible: false,
156
160
  agentName: ctx.trigger.agentAid,
157
161
  sessionKeyField: ctx.session.sessionKey,
158
162
  selfAID: ctx.trigger.agentAid,
159
- role: this.triggerOriginRole(ctx.trigger),
163
+ role: executionIdentity?.role,
160
164
  signal: ctx.signal,
161
165
  }).catch((err) => {
162
166
  if (ctx.signal?.aborted)
@@ -357,26 +361,6 @@ export class DaemonChannel {
357
361
  slot.acc.seenToolCallIds.add(callId);
358
362
  slot.acc.toolCallCount += 1;
359
363
  }
360
- triggerOriginRole(trigger) {
361
- const origin = trigger.origin;
362
- if (!origin?.peerId)
363
- return undefined;
364
- if (origin.channelKey === 'daemon')
365
- return 'owner';
366
- const channelType = origin.channelType
367
- ?? (origin.channelKey ? channelTypeFromKey(origin.channelKey) : undefined);
368
- if (!channelType)
369
- return undefined;
370
- const chatType = origin.delivery?.chatType ?? 'private';
371
- return resolvePeerRoleDetail({
372
- selfAid: trigger.agentAid,
373
- channelKey: origin.channelKey,
374
- channelType,
375
- chatType,
376
- actorId: origin.peerId,
377
- conversationId: chatType === 'group' ? origin.channelId : origin.peerId,
378
- }).effectiveRole ?? undefined;
379
- }
380
364
  finish(runId, status, metadata) {
381
365
  const slot = this.pending.get(runId);
382
366
  if (!slot || !this.claimTerminal(slot, status, metadata))