evolcore 0.0.43-test.0 → 0.0.43-test.2

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 (172) hide show
  1. package/CHANGELOG.md +31 -2
  2. package/README.md +22 -0
  3. package/dist/agents/claude-runner.js +26 -2
  4. package/dist/agents/codex/app-server-client.js +12 -0
  5. package/dist/agents/codex-runner.js +49 -8
  6. package/dist/agents/ecagent-runner.js +26 -9
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/menu/client.js +1 -1
  11. package/dist/aun/model-headers.js +17 -0
  12. package/dist/aun/msg/p2p.js +3 -0
  13. package/dist/channels/aun.js +484 -43
  14. package/dist/channels/builtin-plugins.js +16 -11
  15. package/dist/channels/dingtalk.js +83 -31
  16. package/dist/channels/feishu.js +29 -13
  17. package/dist/channels/qqbot.js +32 -11
  18. package/dist/channels/wechat.js +13 -3
  19. package/dist/channels/wecom.js +67 -27
  20. package/dist/cli/agent-command.js +3 -86
  21. package/dist/cli/agent-create.js +22 -6
  22. package/dist/cli/agent.js +1 -79
  23. package/dist/cli/aun-commands.js +1 -0
  24. package/dist/cli/config.js +1 -1
  25. package/dist/cli/daemon-commands.js +47 -2
  26. package/dist/cli/data-command.js +9 -1
  27. package/dist/cli/debug-mode.js +1 -1
  28. package/dist/cli/diag.js +1 -1
  29. package/dist/cli/directory.js +77 -64
  30. package/dist/cli/getmeta-command.js +1 -1
  31. package/dist/cli/index.js +79 -22
  32. package/dist/cli/init.js +1 -23
  33. package/dist/cli/link-rules.js +1 -1
  34. package/dist/cli/managed-command-guard.js +0 -1
  35. package/dist/cli/pa-workspace-command.js +36 -2
  36. package/dist/cli/peer.js +1 -1
  37. package/dist/cli/restart-monitor.js +17 -3
  38. package/dist/cli/role.js +1 -1
  39. package/dist/cli/session-command.js +1 -1
  40. package/dist/cli/stats.js +2 -2
  41. package/dist/cli/thread-command.js +1 -1
  42. package/dist/cli/watch-msg.js +1 -1
  43. package/dist/config/access-policy.js +1 -0
  44. package/dist/config/config-field-policy.js +2 -2
  45. package/dist/config/config-manager.js +7 -0
  46. package/dist/config/role-schema.js +4 -3
  47. package/dist/config/role-service.js +3 -3
  48. package/dist/config-store.js +75 -4
  49. package/dist/core/agent-ipc-registration.js +16 -59
  50. package/dist/core/agent-runtime.js +2 -1
  51. package/dist/core/auth/authorization-audit.js +52 -14
  52. package/dist/core/auth/operation-authorizer.js +0 -11
  53. package/dist/core/auth/operation-catalog.js +0 -18
  54. package/dist/core/channel-loader.js +152 -16
  55. package/dist/core/command/agent-control.js +2 -1
  56. package/dist/core/command/cli-intent-parser.js +0 -8
  57. package/dist/core/command/command-handler.js +17 -46
  58. package/dist/core/command/connect-menu.js +7 -3
  59. package/dist/core/command/menu-catalog.js +3 -2
  60. package/dist/core/command/menu-handler.js +51 -8
  61. package/dist/core/command/menu-protocol.js +20 -0
  62. package/dist/core/command/slash-handler.js +101 -40
  63. package/dist/core/daemon-file-cache.js +3 -3
  64. package/dist/core/evolagent-registry.js +5 -4
  65. package/dist/core/evolagent.js +5 -8
  66. package/dist/core/handoff/argv-parse.js +115 -0
  67. package/dist/core/handoff/ipc-registration.js +1 -1
  68. package/dist/core/ipc-registration.js +19 -2
  69. package/dist/core/memory/consolidation.js +8 -1
  70. package/dist/core/memory/relation-sweep.js +20 -8
  71. package/dist/core/message/aun-ipc-sender.js +28 -1
  72. package/dist/core/message/contact-admission.js +548 -0
  73. package/dist/core/message/im-renderer.js +69 -10
  74. package/dist/core/message/message-admission.js +28 -3
  75. package/dist/core/message/message-bridge.js +46 -5
  76. package/dist/core/message/message-utils.js +0 -5
  77. package/dist/core/message/peer-mode.js +44 -10
  78. package/dist/core/message/response-engine.js +268 -69
  79. package/dist/core/message/retry-scheduler.js +4 -0
  80. package/dist/core/permission/ec-command-parser.js +1 -28
  81. package/dist/core/permission/readonly-shell-query.js +34 -8
  82. package/dist/core/permission/tool-policy.js +50 -5
  83. package/dist/core/role/runtime-policy.js +14 -2
  84. package/dist/core/session/session-manager.js +9 -1
  85. package/dist/core/soul.js +66 -0
  86. package/dist/core/system-session/memory.js +2 -2
  87. package/dist/directory/contact-admission-paths.js +9 -0
  88. package/dist/directory/owner-directory-admission.js +128 -29
  89. package/dist/directory/owner-directory-cache.js +364 -50
  90. package/dist/directory/owner-directory-identity.js +60 -0
  91. package/dist/directory/owner-directory-markdown.js +120 -47
  92. package/dist/directory/owner-directory-policy.js +108 -0
  93. package/dist/directory/owner-directory-query-operation.js +219 -32
  94. package/dist/directory/owner-directory-remarks.js +29 -2
  95. package/dist/directory/owner-directory-search.js +50 -18
  96. package/dist/directory/owner-directory-store.js +150 -30
  97. package/dist/eck/kit-renderer.js +12 -5
  98. package/dist/eck/manifest-engine.js +55 -6
  99. package/dist/eck/message-renderer.js +5 -2
  100. package/dist/eck/paactive-context.js +45 -0
  101. package/dist/ecweb/basic-settings-service.js +2 -2
  102. package/dist/ecweb/message-context-service.js +24 -16
  103. package/dist/index.js +9 -5
  104. package/dist/ipc.js +1 -1
  105. package/dist/paths.js +26 -0
  106. package/dist/response-system/config-resolver.js +1 -1
  107. package/dist/response-system/engines/v1/index.js +4 -1
  108. package/dist/response-system/engines/v1/paactive-flow.js +18 -0
  109. package/dist/response-system/modes/single-session/index.js +7 -2
  110. package/dist/trigger/scheduler.js +3 -5
  111. package/dist/trigger/validation.js +4 -0
  112. package/dist/utils/error-utils.js +5 -2
  113. package/dist/utils/logger.js +13 -4
  114. package/dist/utils/npm-ops.js +2 -2
  115. package/dist/utils/windows-autostart.js +1 -1
  116. package/ecagent/dist/agent-loop.js +43 -1
  117. package/kits/docs/INDEX.md +1 -0
  118. package/kits/docs/context-assembly.md +21 -6
  119. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  120. package/kits/docs/evolcore/INDEX.md +1 -1
  121. package/kits/docs/evolcore/agent-create.md +5 -5
  122. package/kits/docs/evolcore/agent.md +4 -9
  123. package/kits/docs/evolcore/directory.md +137 -0
  124. package/kits/docs/evolcore/menu-protocol.md +55 -0
  125. package/kits/docs/evolcore/response.md +7 -1
  126. package/kits/docs/evolcore/tool-authorization.md +1 -1
  127. package/kits/docs/evolcore/trigger.md +4 -0
  128. package/kits/docs/prompt-loading-architecture.md +6 -2
  129. package/kits/eck_manifest.auxiliary.json +1 -0
  130. package/kits/eck_manifest.json +57 -4
  131. package/kits/eck_manifest.memory.json +67 -3
  132. package/kits/eck_manifest.paactive.json +528 -0
  133. package/kits/eck_message_manifest.paactive.json +233 -0
  134. package/kits/rules/01-overview.md +2 -2
  135. package/kits/rules/03-identity.md +10 -9
  136. package/kits/rules/05-venue.md +2 -4
  137. package/kits/rules/06-channel.md +1 -1
  138. package/kits/schemas/_meta.json +31 -3
  139. package/kits/schemas/agent-config.schema.18.json +5 -0
  140. package/kits/schemas/agent-config.schema.19.json +924 -0
  141. package/kits/schemas/relation-config.schema.12.json +289 -0
  142. package/kits/schemas/role-config.schema.2.json +215 -0
  143. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  144. package/kits/skills/ec-trigger/SKILL.md +4 -4
  145. package/kits/skills/personal-assistant/SKILL.md +109 -53
  146. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  147. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  148. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  149. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  150. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  151. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  152. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  153. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  154. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  155. package/kits/templates/message-fragments/paactive/item.md +3 -0
  156. package/kits/templates/soul/00-GUIDE.md +61 -0
  157. package/kits/templates/soul/01-identity.md +5 -0
  158. package/kits/templates/soul/02-persona.md +11 -0
  159. package/kits/templates/soul/03-duties.md +5 -0
  160. package/kits/templates/soul/04-working-style.md +5 -0
  161. package/kits/templates/system-fragments/bootstrap.md +7 -7
  162. package/kits/templates/system-fragments/commands.md +3 -2
  163. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  164. package/kits/templates/system-fragments/memory.md +1 -1
  165. package/kits/templates/system-fragments/paactive/channel.md +25 -0
  166. package/kits/templates/system-fragments/paactive/reply.md +25 -0
  167. package/kits/templates/system-fragments/paactive/session.md +32 -0
  168. package/kits/templates/system-fragments/personal-assistant.md +65 -0
  169. package/package.json +4 -3
  170. package/dist/cli/handoff-command.js +0 -353
  171. package/dist/directory/owner-directory-remark-operation.js +0 -147
  172. package/kits/docs/evolcore/self-summary.md +0 -29
@@ -1,5 +1,7 @@
1
1
  import { E2EEError, validateAIDFormat } from '@agentunion/fastaun';
2
2
  import { sanitizeMenuLogValue } from '../core/command/menu-protocol.js';
3
+ import { appContactAdmissionEnabled, appContactAdmissionActive, buildContactRequest, contactIntroductionText, consumeContactIntroductionBudget, currentContactBinding, verifiedContactBinding, evaluateAppContactAdmission, executeContactGrant, isContactControlPayload, reconcileTemporaryContactGrants, sameContactBinding, isolatedContactSource, saveIsolatedContactSource, contactSourceDigest, CONTACT_EVENT_TTL_MS, FRIEND_INVITE_TYPE, FRIEND_INVITE_RESULT_TYPE, isFriendInvitePayload, parseFriendInvite, recordedFriendInviteDecision, decideFriendInvite, markFriendInviteWelcomed, buildFriendInviteResult, friendPayloadRouteValid, friendInviteWelcomeText } from '../core/message/contact-admission.js';
4
+ import { evaluateOutboundContactAdmission } from '../core/message/message-admission.js';
3
5
  import crypto from 'crypto';
4
6
  import { performance } from 'node:perf_hooks';
5
7
  import fs from 'fs';
@@ -9,7 +11,6 @@ import { registerOwnerDirectoryAdmission } from '../directory/owner-directory-ad
9
11
  import { OwnerDirectoryAgentMdSync } from '../directory/owner-directory-agentmd-sync.js';
10
12
  import { parseNotificationSnapshots } from '../directory/owner-directory-store.js';
11
13
  import { OWNER_DIRECTORY_SCOPES } from '../directory/owner-directory-cache.js';
12
- import { resolveAllowExternalContacts } from '../directory/owner-directory-admission.js';
13
14
  import path from 'path';
14
15
  import os from 'os';
15
16
  import { logger, localTimestamp, logPreview } from '../utils/logger.js';
@@ -41,6 +42,7 @@ import { isManagementRole } from '../config/builtin-roles.js';
41
42
  import { normalizeAunMentionMode, normalizeMentionMode } from '../config/mention-mode.js';
42
43
  import { getProcessStartTime } from '../utils/process-introspect.js';
43
44
  import * as outbox from '../aun/outbox.js';
45
+ import { aunProtectedHeaders } from '../aun/model-headers.js';
44
46
  import { formatSize } from '../utils/media-cache.js';
45
47
  import { formatPeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
46
48
  import { isHClassPath } from '../core/permission/protected-paths.js';
@@ -394,6 +396,7 @@ const AUN_ACCEPTED_DISPATCH_STATUSES = new Set([
394
396
  'debounced', 'dispatched', 'accepted', 'queued', 'queued_batch', 'broadcast', 'sent',
395
397
  ]);
396
398
  const AUN_PERMANENT_STRING_CODES = new Set([
399
+ 'contact_denied', 'contact_ownership_changed',
397
400
  'invalid_params', 'invalid_param', 'invalid_request', 'permission_denied',
398
401
  'unauthorized', 'authentication_failed', 'not_found', 'group_not_found',
399
402
  'group_not_member', 'member_not_found', 'target_not_found', 'agent_not_found',
@@ -703,17 +706,70 @@ function errorCodeForLog(error) {
703
706
  }
704
707
  export class AUNChannel {
705
708
  config;
709
+ contactAdmissionFailureLogAt = 0;
710
+ contactControlPermits = new Map();
711
+ rememberContactControlRequest(target, payload, mid, device) {
712
+ const binding = currentContactBinding(this.config.aid);
713
+ if (!binding || !payload || typeof payload !== 'object')
714
+ return;
715
+ let matches;
716
+ const id = payload.id;
717
+ if (['menu.query', 'menu.options', 'menu.action'].includes(payload.type) && typeof id === 'string' && id.length <= 256) {
718
+ matches = value => (value.type === 'menu.response' && value.id === id)
719
+ || (value.type === 'menu.event' && value.requestId === id);
720
+ }
721
+ else if (payload.type === 'ability' && payload.role === 'call'
722
+ && typeof payload.call_id === 'string' && typeof payload.operation_id === 'string') {
723
+ const { call_id, operation_id, ability_path, definition_id } = payload;
724
+ matches = value => value.type === 'ability' && ['ack', 'result'].includes(value.role)
725
+ && value.call_id === call_id && value.operation_id === operation_id
726
+ && value.ability_path === ability_path && value.definition_id === definition_id;
727
+ }
728
+ else if (payload.type === 'bind.request' && typeof payload.creationId === 'string') {
729
+ const { creationId, bindType } = payload;
730
+ matches = value => value.type === 'bind.response' && value.creationId === creationId && value.bindType === bindType;
731
+ }
732
+ if (!matches)
733
+ return;
734
+ for (const [key, permit] of this.contactControlPermits)
735
+ if (permit.expires <= Date.now())
736
+ this.contactControlPermits.delete(key);
737
+ if (this.contactControlPermits.size >= 512)
738
+ return;
739
+ this.contactControlPermits.set(JSON.stringify([target, mid]), { target, device, binding, matches, expires: Date.now() + 6 * 60_000 });
740
+ }
741
+ hasContactControlPermit(target, payload, params) {
742
+ if (!payload || typeof payload !== 'object')
743
+ return false;
744
+ return [...this.contactControlPermits.values()].some(permit => permit.target === target && permit.expires > Date.now()
745
+ && sameContactBinding(permit.binding, currentContactBinding(this.config.aid)) && permit.matches(payload)
746
+ && (!params || !String(payload.type).startsWith('menu.') || params.encrypt === true)
747
+ && (!params || !permit.device || (params.to_device_id ?? params.device_id) === permit.device));
748
+ }
706
749
  // Keep each target's attempt across channel recreation; reset only on process restart.
707
750
  static configuredOwnerBindAttempts = new Set();
708
- managedMenuClient = new ManagedMenuClient(params => {
751
+ managedMenuClient = new ManagedMenuClient((params, beforeSend) => {
709
752
  if (!this.connected || !this.client)
710
753
  return Promise.reject(new Error('AUN channel is not connected'));
711
- return this.callAndTrace('message.send', params);
754
+ return this.callAndTrace('message.send', params, { beforeSend });
712
755
  });
713
756
  requestRemoteMenu(options) {
714
757
  if (options.fromAid !== (this._aid || this.config.aid))
715
758
  throw new Error('Menu sender does not match channel identity');
716
- return this.managedMenuClient.request(options);
759
+ const target = options.targetAid;
760
+ const request = JSON.stringify(options.request);
761
+ const expires = Date.now() + (options.timeoutMs ?? 15_000) * 2;
762
+ const binding = currentContactBinding(this.config.aid);
763
+ return this.managedMenuClient.request({ ...options, beforeSend: () => {
764
+ options.beforeSend?.();
765
+ if (options.targetAid !== target || JSON.stringify(options.request) !== request || Date.now() >= expires) {
766
+ throw Object.assign(new Error('Managed Menu operation changed or expired'), { code: 'CONTACT_DENIED' });
767
+ }
768
+ if (!this.config.pureIdentity && appContactAdmissionActive(this.config.aid)
769
+ && (!binding || !sameContactBinding(binding, currentContactBinding(this.config.aid)))) {
770
+ throw Object.assign(new Error('Managed Menu Owner relation unavailable or changed'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
771
+ }
772
+ } });
717
773
  }
718
774
  client = null;
719
775
  configuredOwnerBind;
@@ -753,7 +809,14 @@ export class AUNChannel {
753
809
  return;
754
810
  // 自动从 data 推断顶层字段(self_aid / peer_aid / group_id / task_id / chatmode),
755
811
  // 便于 jq 过滤:`jq 'select(.task_id == "task-xxx")'`
756
- const safeData = redactMenuTokensForTrace(data);
812
+ const inbound = data && typeof data === 'object' ? data : {};
813
+ const isolateTrace = dir === 'IN' && event === 'message.received'
814
+ && !this.config.pureIdentity && appContactAdmissionEnabled(this.config.aid);
815
+ const safeData = isolateTrace ? {
816
+ message_id: inbound.message_id, seq: inbound.seq,
817
+ envelope: { from: inbound.envelope?.from, to: inbound.envelope?.to, encrypted: inbound.envelope?.encrypted },
818
+ payload: { type: inbound.payload?.type, body_omitted: true },
819
+ } : redactMenuTokensForTrace(data);
757
820
  const d = (safeData && typeof safeData === 'object') ? safeData : {};
758
821
  const payload = d.payload ?? {};
759
822
  // 入站事件(IN)路由字段在 d.envelope.*(SDK 0.5.*);出站 params(OUT)字段在顶层。两者兼顾。
@@ -790,10 +853,51 @@ export class AUNChannel {
790
853
  * 统一的 RPC 调用包装:自动记录 OUT 发送、.ok 结果、.error 错误(含 trace + daemon.log 失败日志)。
791
854
  * 所有 client.call() 都应通过此方法调用,保证 aun-trace 里每个 OUT 调用都有"发+收/错"成对记录。
792
855
  */
793
- callClient(method, params, lane = 'normal', onStart, onPrepared) {
856
+ callClient(method, params, lane = 'normal', onStart, onPrepared, beforeSend) {
794
857
  params = menuTransportParams(method, params);
858
+ const client = this.client;
859
+ const appOwned = !this.config.pureIdentity && appContactAdmissionActive(this.config.aid);
860
+ const friendPayload = typeof params.payload?.type === 'string' && params.payload.type.startsWith('friend.');
861
+ const binding = appOwned || friendPayload ? currentContactBinding(this.config.aid) : undefined;
795
862
  onPrepared?.(params);
796
- return this.withOutboundSendGate(method, () => (this.client.call(method, params).then(value => value)), lane, onStart);
863
+ return this.withOutboundSendGate(method, async () => {
864
+ if (client !== this.client || !client)
865
+ throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
866
+ if (!this.config.pureIdentity && (friendPayload || appOwned)
867
+ && (method === 'message.send' || method === 'message.thought.put')) {
868
+ if (typeof params.payload?.type === 'string' && params.payload.type.startsWith('friend.')) {
869
+ const refreshed = await ownerResolver.refresh(this.config.aid, { maxAgeMs: 0, source: 'contact.transport' });
870
+ const verified = verifiedContactBinding(this.config.aid, refreshed);
871
+ if (!verified) {
872
+ throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
873
+ }
874
+ if (!friendPayloadRouteValid(params.payload, params.to, params.encrypt, verified)
875
+ || !sameContactBinding(verified, currentContactBinding(this.config.aid))) {
876
+ throw Object.assign(new Error('contact Owner relation changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
877
+ }
878
+ if (client !== this.client)
879
+ throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
880
+ }
881
+ const current = currentContactBinding(this.config.aid);
882
+ if (!current)
883
+ throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
884
+ if (!binding || !sameContactBinding(binding, current))
885
+ throw Object.assign(new Error('Owner relation changed while queued'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
886
+ const payload = params.payload;
887
+ if (typeof payload?.type === 'string' && payload.type.startsWith('friend.')
888
+ && !friendPayloadRouteValid(payload, params.to, params.encrypt, current)) {
889
+ throw Object.assign(new Error('contact event relation or encryption changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
890
+ }
891
+ if (!beforeSend) {
892
+ const blocked = this.appContactOutboundBlock(params.to, { chatType: 'private' }, payload, params);
893
+ if (blocked) {
894
+ throw Object.assign(new Error(blocked.error), { code: blocked.code });
895
+ }
896
+ }
897
+ }
898
+ beforeSend?.();
899
+ return client.call(method, params).then(value => value);
900
+ }, lane, onStart);
797
901
  }
798
902
  withOutboundSendGate(method, run, lane = 'normal', onStart) {
799
903
  if (!AUNChannel.OUTBOUND_SEND_METHODS.has(method)) {
@@ -874,7 +978,7 @@ export class AUNChannel {
874
978
  // passed to the SDK (TTL and device targeting may both be removed).
875
979
  params = preparedParams;
876
980
  this.trace('OUT', method, params);
877
- });
981
+ }, opts?.beforeSend);
878
982
  const durationMs = Date.now() - rpcStart;
879
983
  const rpcDurationMs = Date.now() - callStartedAt;
880
984
  const queueWaitMs = Math.max(0, callStartedAt - rpcStart);
@@ -1657,11 +1761,20 @@ export class AUNChannel {
1657
1761
  logger.debug(`${this.logPrefix()} Owner directory unavailable: owner=${ownerAid ? 'known' : 'unknown'}, connectionChanged=${this.client !== client || !this.connected}`);
1658
1762
  return;
1659
1763
  }
1660
- if (this.ownerDirectoryCache?.client !== client || this.ownerDirectoryCache.ownerAid !== ownerAid) {
1764
+ const appOwned = appContactAdmissionActive(selfAid);
1765
+ const relationVersion = appOwned ? currentContactBinding(selfAid)?.relation_version : undefined;
1766
+ if (appOwned && !relationVersion)
1767
+ return;
1768
+ if (this.ownerDirectoryCache?.client !== client || this.ownerDirectoryCache.ownerAid !== ownerAid
1769
+ || this.ownerDirectoryRelationVersion !== relationVersion) {
1661
1770
  // Keep the already-verified cache instance and its diagnostics, but let
1662
1771
  // the new cache implementation own storage and event synchronization.
1663
1772
  const directory = path.join(this.agentDir, 'directory');
1664
1773
  const cache = new OwnerDirectoryCache({
1774
+ onSnapshotApplying: snapshot => { if (appOwned && isCurrent())
1775
+ reconcileTemporaryContactGrants(selfAid, snapshot); },
1776
+ relationVersion,
1777
+ isCurrent: () => isCurrent(),
1665
1778
  selfAid,
1666
1779
  ownerAid,
1667
1780
  directory,
@@ -1673,19 +1786,11 @@ export class AUNChannel {
1673
1786
  // 名录有新增/变更条目,按差集批量刷新 agent.md(SDK 进程内去重)
1674
1787
  void this.ownerDirectoryCache?.agentMd.refreshAids(aids);
1675
1788
  },
1676
- // 外部联系人默认不注入;个人助理缺省打开,判据与准入共用。
1677
- allowExternalContacts: () => {
1678
- try {
1679
- return resolveAllowExternalContacts(selfAid, this.ownerDirectoryCache?.cache.readSnapshot('contacts'));
1680
- }
1681
- catch {
1682
- return false;
1683
- }
1684
- },
1685
1789
  });
1686
1790
  const isCurrent = () => this.client === client && this.connected
1687
1791
  && this.ownerDirectoryCache?.cache === cache
1688
- && (ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid)) === ownerAid;
1792
+ && (ownerResolver.owner(selfAid) ?? (appOwned ? undefined : ownerResolver.knownOwner(selfAid))) === ownerAid
1793
+ && (!appOwned || currentContactBinding(selfAid)?.relation_version === relationVersion);
1689
1794
  const agentMd = new OwnerDirectoryAgentMdSync({
1690
1795
  selfAid,
1691
1796
  aunPath: this.config.keystorePath || resolveRoot(),
@@ -1694,6 +1799,7 @@ export class AUNChannel {
1694
1799
  onUpdated: aid => this.invalidatePeerAgentMd(aid),
1695
1800
  });
1696
1801
  this.ownerDirectoryCache = { client, ownerAid, cache, agentMd };
1802
+ this.ownerDirectoryRelationVersion = relationVersion;
1697
1803
  registerOwnerDirectoryAdmission({ selfAid, ownerAid, cache, isCurrent });
1698
1804
  }
1699
1805
  return this.ownerDirectoryCache;
@@ -1763,6 +1869,8 @@ export class AUNChannel {
1763
1869
  await runtime.cache.applyFromSharedCacheWithin(OWNER_DIRECTORY_APPLY_WAIT_MS).catch(() => undefined);
1764
1870
  }
1765
1871
  async handleOwnerDirectoryAuthorizationResponse(senderAid, record) {
1872
+ if (record.selfAid !== this.config.aid || record.targetAid !== senderAid || record.state !== 'completed')
1873
+ return;
1766
1874
  // 只认点名发给的那台设备:广播或其它设备的回复不能改写授权状态。
1767
1875
  // 无 targetDeviceId 的是旧记录,无从校验,放行(调用方已确认 state=completed 且消息匹配)。
1768
1876
  if (record.targetDeviceId && record.responseDeviceId !== record.targetDeviceId) {
@@ -1773,9 +1881,16 @@ export class AUNChannel {
1773
1881
  const grant = parseOwnerDirectoryGrantAbilityResponse(record.responsePayload);
1774
1882
  if (!grant)
1775
1883
  return;
1884
+ const view = await ownerResolver.refresh(this.config.aid, { maxAgeMs: 0, source: 'directory.authorization' });
1885
+ const binding = verifiedContactBinding(this.config.aid, view);
1886
+ if (!binding || senderAid !== binding.owner_aid || grant.owner_aid !== senderAid || grant.grantee_aid !== this.config.aid
1887
+ || (appContactAdmissionEnabled(this.config.aid) && grant.relation_version !== binding.relation_version))
1888
+ return;
1776
1889
  const runtime = await this.getOwnerDirectoryRuntime();
1777
1890
  if (!runtime)
1778
1891
  return;
1892
+ if (runtime.ownerAid !== senderAid || !sameContactBinding(binding, currentContactBinding(this.config.aid)))
1893
+ return;
1779
1894
  runtime.cache.saveAuthorization(grant);
1780
1895
  await runtime.cache.handleOwnerChangedEvent(senderAid);
1781
1896
  }
@@ -1845,9 +1960,18 @@ export class AUNChannel {
1845
1960
  logger.warn(`${this.logPrefix()} owner.directory.grant: invalid grant payload (does not match evol-directory-access-v1 contract)`);
1846
1961
  return;
1847
1962
  }
1963
+ const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'directory.grant' });
1964
+ const binding = verifiedContactBinding(selfAid, view);
1965
+ if (!binding || senderAid !== binding.owner_aid || parsed.owner_aid !== senderAid || parsed.grantee_aid !== selfAid
1966
+ || (appContactAdmissionEnabled(selfAid) && parsed.relation_version !== binding.relation_version)) {
1967
+ logger.warn(`${this.logPrefix()} owner.directory.grant ignored: sender or relation binding is not verified`);
1968
+ return;
1969
+ }
1848
1970
  const runtime = await this.getOwnerDirectoryRuntime();
1849
1971
  if (!runtime)
1850
1972
  return;
1973
+ if (runtime.ownerAid !== senderAid || !sameContactBinding(binding, currentContactBinding(selfAid)))
1974
+ return;
1851
1975
  runtime.cache.saveAuthorization(parsed);
1852
1976
  logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}`);
1853
1977
  // 授权被撤销/拒绝时 saveAuthorization 已经清掉凭证和快照,这里无事可做:
@@ -1929,7 +2053,7 @@ export class AUNChannel {
1929
2053
  }
1930
2054
  this.inboundSeenMessages.set(dedupeKey, { seenAt: Date.now(), seq });
1931
2055
  this.appendInboundDedupe(dedupeKey, messageId, kind, seq);
1932
- setTimeout(() => this.inboundSeenMessages.delete(dedupeKey), AUN_INBOUND_DEDUP_TTL_MS);
2056
+ setTimeout(() => this.inboundSeenMessages.delete(dedupeKey), AUN_INBOUND_DEDUP_TTL_MS).unref?.();
1933
2057
  return true;
1934
2058
  }
1935
2059
  inboundDedupeFile() {
@@ -2322,7 +2446,7 @@ export class AUNChannel {
2322
2446
  if (data && typeof data === 'object') {
2323
2447
  const d = data;
2324
2448
  const payloadType = d.payload?.type ?? d.envelope?.type ?? '';
2325
- if (payloadType === 'text') {
2449
+ if (payloadType === 'text' && (this.config.pureIdentity || !appContactAdmissionEnabled(this.config.aid))) {
2326
2450
  const msgId = d.message_id ?? d.id ?? '';
2327
2451
  const from = d.from ?? d.envelope?.from ?? '';
2328
2452
  const to = d.to ?? d.envelope?.to ?? this.config.aid ?? '';
@@ -2933,6 +3057,187 @@ export class AUNChannel {
2933
3057
  return pathname;
2934
3058
  }
2935
3059
  }
3060
+ ownerDirectoryRelationVersion;
3061
+ /** Returns before any ordinary history, observer, attachment or model side effect. */
3062
+ async handleAppContactInbound(fromAid, payload, messageId, receivedAt, encrypted) {
3063
+ const selfAid = this.config.aid;
3064
+ const value = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : undefined;
3065
+ const type = typeof value?.type === 'string' ? value.type : '';
3066
+ const previous = isolatedContactSource(selfAid, fromAid, messageId);
3067
+ const digest = contactSourceDigest(payload);
3068
+ if (previous && (previous.notified || !previous.reason || contactIntroductionText(payload) === undefined
3069
+ || previous.digest !== digest || !previous.binding || previous.at + CONTACT_EVENT_TTL_MS <= Date.now()))
3070
+ return true;
3071
+ if (previous && !sameContactBinding(previous.binding, currentContactBinding(selfAid)))
3072
+ return true;
3073
+ if (previous && !consumeContactIntroductionBudget(selfAid, fromAid))
3074
+ return true;
3075
+ if (type.startsWith('friend.')) {
3076
+ const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.grant' });
3077
+ const binding = verifiedContactBinding(selfAid, view);
3078
+ if (!binding)
3079
+ return true;
3080
+ const result = executeContactGrant(selfAid, fromAid, payload, encrypted, Date.now(), binding);
3081
+ if (result)
3082
+ await this.sendContentPayload(fromAid, result, {
3083
+ contentKind: 'custom', dedupeKey: `friend-result:${result.owner_aid}:${result.relation_version}:${result.type}:${result.grant_id}:${result.status}:${result.error_code ?? ''}`,
3084
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
3085
+ logText: `[${result.type}]`, ttl: CONTACT_EVENT_TTL_MS,
3086
+ });
3087
+ return true;
3088
+ }
3089
+ // These are protocol envelopes. Their existing handlers retain authentication and permission checks.
3090
+ if (isContactControlPayload(payload))
3091
+ return false;
3092
+ if (type.startsWith('contact.request.'))
3093
+ return true; // Retired App protocol; never create legacy pending.
3094
+ if (type === 'text' && typeof value?.text === 'string' && /^\s*\/bind(?:\s|$)/i.test(value.text))
3095
+ return false;
3096
+ // An already isolated source never becomes an ordinary message after approval.
3097
+ await ownerResolver.refresh(selfAid, { maxAgeMs: 30_000, allowTransient: true, source: 'contact.inbound' });
3098
+ await this.getOwnerDirectoryRuntime();
3099
+ await this.settleOwnerDirectoryBeforeTurn();
3100
+ const decision = evaluateAppContactAdmission(selfAid, fromAid);
3101
+ logger.debug(`${this.logPrefix()} Contact admission: mid=${messageId} from=${fromAid} allow=${decision.allow} reason=${decision.reason} elapsedMs=${Math.max(0, Date.now() - receivedAt)}`);
3102
+ if (decision.allow && !previous)
3103
+ return false;
3104
+ const introduction = contactIntroductionText(payload);
3105
+ const binding = currentContactBinding(selfAid);
3106
+ const reason = previous?.reason ?? decision.reason;
3107
+ if (previous && !sameContactBinding(previous.binding, binding))
3108
+ return true;
3109
+ let source = previous ?? { at: receivedAt, digest, binding,
3110
+ ...(reason === 'not_in_contacts' || reason === 'scope_extension' ? { reason } : {}) };
3111
+ // Write the tombstone before budgets, receipt capacity checks or any delivery.
3112
+ if (!previous)
3113
+ source = saveIsolatedContactSource(selfAid, fromAid, messageId, source);
3114
+ if (source.notified || source.digest !== digest || !sameContactBinding(source.binding ?? {}, binding))
3115
+ return true;
3116
+ const eventReason = source.reason;
3117
+ if (binding && introduction !== undefined && (eventReason === 'not_in_contacts' || eventReason === 'scope_extension')
3118
+ && (previous || consumeContactIntroductionBudget(selfAid, fromAid))) {
3119
+ const request = buildContactRequest(binding, fromAid, messageId, source.at, introduction, eventReason);
3120
+ const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
3121
+ if (remainingTtl <= 0)
3122
+ return true;
3123
+ const sent = await this.sendContentPayload(binding.owner_aid, request, {
3124
+ contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1]',
3125
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
3126
+ ttl: remainingTtl,
3127
+ });
3128
+ if (sent.messageId || sent.queued)
3129
+ saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notified: true });
3130
+ logger.info(`${this.logPrefix()} Contact introduction isolated: event=${request.event_id} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
3131
+ }
3132
+ else {
3133
+ logger.info(`${this.logPrefix()} Contact message isolated: mid=${messageId} reason=${decision.reason}`);
3134
+ }
3135
+ return true;
3136
+ }
3137
+ /** friend.invite.v1 never reaches the model, ordinary history, attachments or observers. */
3138
+ async handleFriendInvite(fromAid, payload, messageId, receivedAt, encrypted, seq) {
3139
+ const selfAid = this.config.aid;
3140
+ this.appendInboundPayloadJsonl(fromAid, fromAid, messageId, encrypted, false, classifyAunPayloadForLog(payload), undefined, receivedAt, seq);
3141
+ const invite = parseFriendInvite(payload, fromAid, selfAid);
3142
+ if (!invite || !encrypted) {
3143
+ logger.info(`${this.logPrefix()} Friend invite ignored: code=INVALID_FRIEND_INVITE from=${fromAid} mid=${messageId} encrypted=${encrypted}`);
3144
+ return;
3145
+ }
3146
+ try {
3147
+ const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.invite' });
3148
+ const binding = verifiedContactBinding(selfAid, view);
3149
+ if (!binding) {
3150
+ // The App keeps the invite queued and retries; nothing is decided without a verified relation.
3151
+ logger.info(`${this.logPrefix()} Friend invite deferred: code=CONTACT_OWNERSHIP_UNAVAILABLE invite=${invite.invite_id} from=${fromAid}`);
3152
+ return;
3153
+ }
3154
+ const recorded = recordedFriendInviteDecision(selfAid, binding, invite);
3155
+ if (recorded.conflict) {
3156
+ logger.warn(`${this.logPrefix()} Friend invite ignored: code=FRIEND_INVITE_CONFLICT invite=${invite.invite_id} from=${fromAid}`);
3157
+ return;
3158
+ }
3159
+ if (recorded.decision) {
3160
+ // Re-delivery of a decided invite resends the original result; the welcome is never repeated.
3161
+ await this.sendFriendInviteResult(invite, recorded.decision, messageId);
3162
+ return;
3163
+ }
3164
+ if (invite.expires_at_ms <= Date.now()) {
3165
+ await this.sendFriendInviteResult(invite, decideFriendInvite(selfAid, binding, invite, 'expired'), messageId);
3166
+ return;
3167
+ }
3168
+ await this.getOwnerDirectoryRuntime();
3169
+ await this.settleOwnerDirectoryBeforeTurn();
3170
+ const verdict = await this.judgeFriendInvite(selfAid, fromAid);
3171
+ logger.info(`${this.logPrefix()} Friend invite: invite=${invite.invite_id} from=${fromAid} verdict=${verdict.kind} reason=${verdict.reason}`);
3172
+ if (verdict.kind === 'accept') {
3173
+ const record = decideFriendInvite(selfAid, binding, invite, 'accepted');
3174
+ await this.sendFriendInviteResult(invite, record, messageId);
3175
+ if (!record.welcomed)
3176
+ await this.sendFriendInviteWelcome(invite, binding);
3177
+ return;
3178
+ }
3179
+ // silent: blocked or Owner-denied (the applicant is never told), or state unavailable (the App retries later).
3180
+ if (verdict.kind === 'silent')
3181
+ return;
3182
+ // The Owner decides: not admitted by policy, or only a temporary grant (not a permanent relation).
3183
+ if (!consumeContactIntroductionBudget(selfAid, fromAid)) {
3184
+ logger.info(`${this.logPrefix()} Friend invite dropped: code=INTRODUCTION_BUDGET invite=${invite.invite_id} from=${fromAid}`);
3185
+ return;
3186
+ }
3187
+ const reason = verdict.reason === 'scope_extension' ? 'scope_extension' : 'not_in_contacts';
3188
+ const request = {
3189
+ ...buildContactRequest(binding, fromAid, messageId, receivedAt, invite.introduction, reason, `invite:${invite.invite_id}`),
3190
+ invite: { type: FRIEND_INVITE_TYPE, schema_version: 1, ...invite },
3191
+ };
3192
+ const remainingTtl = Math.min(CONTACT_EVENT_TTL_MS, invite.expires_at_ms - Date.now());
3193
+ const sent = await this.sendContentPayload(binding.owner_aid, request, {
3194
+ contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 invite]',
3195
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } }, ttl: remainingTtl,
3196
+ });
3197
+ logger.info(`${this.logPrefix()} Friend invite forwarded to Owner: event=${request.event_id} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
3198
+ }
3199
+ catch (error) {
3200
+ logger.warn(`${this.logPrefix()} Friend invite isolated: code=CONTACT_STATE_UNAVAILABLE invite=${invite.invite_id} error=${error instanceof Error ? error.message : String(error)}`);
3201
+ }
3202
+ }
3203
+ /**
3204
+ * The same rules this Agent applies to ordinary private messages. app-v1 agents are judged by the
3205
+ * versioned Owner snapshot; legacy agents by deniedAids / allowedAids / allowAllContacts / directory tiers.
3206
+ */
3207
+ async judgeFriendInvite(selfAid, applicantAid) {
3208
+ if (appContactAdmissionActive(selfAid)) {
3209
+ const decision = evaluateAppContactAdmission(selfAid, applicantAid);
3210
+ if (decision.allow)
3211
+ return { kind: decision.reason === 'temporary' ? 'owner' : 'accept', reason: decision.reason };
3212
+ return { kind: decision.reason === 'blocked' || decision.reason === 'unavailable' ? 'silent' : 'owner', reason: decision.reason };
3213
+ }
3214
+ const decision = await evaluateOutboundContactAdmission({ selfAid, targetAid: applicantAid });
3215
+ if (decision.allow)
3216
+ return { kind: decision.status === 'temporary' || decision.status === 'group' ? 'owner' : 'accept', reason: decision.status };
3217
+ const silent = decision.code === 'CONTACT_BLOCKED' || decision.code === 'CONTACT_DENIED'
3218
+ || decision.code === 'CONTACT_DIRECTORY_UNAVAILABLE' || decision.code === 'CONTACT_POLICY_INVALID';
3219
+ return { kind: silent ? 'silent' : 'owner', reason: decision.code };
3220
+ }
3221
+ async sendFriendInviteResult(invite, decision, inboundMessageId) {
3222
+ const result = buildFriendInviteResult(this.config.aid, invite, decision);
3223
+ const sent = await this.sendContentPayload(invite.applicant_aid, result, {
3224
+ contentKind: 'custom', dedupeKey: `friend-invite-result:${decision.decision_id}:${inboundMessageId}`,
3225
+ logText: `[${FRIEND_INVITE_RESULT_TYPE} ${decision.status}]`,
3226
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
3227
+ ttl: Math.max(60_000, invite.expires_at_ms - Date.now()),
3228
+ });
3229
+ logger.info(`${this.logPrefix()} Friend invite result: invite=${invite.invite_id} status=${decision.status} to=${invite.applicant_aid} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
3230
+ return sent;
3231
+ }
3232
+ async sendFriendInviteWelcome(invite, binding) {
3233
+ const text = friendInviteWelcomeText(this._selfName, this.config.aid);
3234
+ const sent = await this.sendContentPayload(invite.applicant_aid, { type: 'text', text }, {
3235
+ contentKind: 'text', dedupeKey: `friend-invite-welcome:${binding.relation_version}:${invite.invite_id}`, logText: text,
3236
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
3237
+ });
3238
+ if (sent.messageId || sent.queued)
3239
+ markFriendInviteWelcomed(this.config.aid, binding, invite.invite_id);
3240
+ }
2936
3241
  async handleIncomingPrivateMessage(data) {
2937
3242
  if (!data || typeof data !== 'object')
2938
3243
  return;
@@ -2959,10 +3264,54 @@ export class AUNChannel {
2959
3264
  }
2960
3265
  return;
2961
3266
  }
2962
- if (!this.claimInboundMessage('private', messageId, seq))
3267
+ const appOwned = !this.config.pureIdentity && appContactAdmissionActive(this.config.aid);
3268
+ if (!appOwned && !this.config.pureIdentity) {
3269
+ try {
3270
+ if (isolatedContactSource(this.config.aid, fromAid, messageId))
3271
+ return;
3272
+ }
3273
+ catch {
3274
+ return;
3275
+ }
3276
+ }
3277
+ if (!appOwned && !this.claimInboundMessage('private', messageId, seq))
2963
3278
  return;
2964
3279
  const protectedHeaders = verifiedProtectedHeaders(msg, env);
2965
3280
  const payload = msg.payload ?? '';
3281
+ // friend.invite.v1(App 主动加好友)不依赖 app-v1 灰度:按 Owner 准入策略已放行的申请人
3282
+ // 由本 Agent 直接回 accepted 并发欢迎语;其余转交 Owner。不进 Agent、不转 observer。
3283
+ if (!this.config.pureIdentity && isFriendInvitePayload(payload)) {
3284
+ if (appOwned && !this.claimInboundMessage('private', messageId, seq))
3285
+ return;
3286
+ await this.handleFriendInvite(fromAid, payload, messageId, receivedAt, !!env.encrypted, seq);
3287
+ return;
3288
+ }
3289
+ const contactControl = appOwned && isContactControlPayload(payload);
3290
+ if (appOwned) {
3291
+ let handled;
3292
+ try {
3293
+ handled = await this.handleAppContactInbound(fromAid, payload, messageId, receivedAt, !!env.encrypted);
3294
+ }
3295
+ catch {
3296
+ // Storage/lock/capacity/conflict failures remain isolated; log metadata only.
3297
+ try {
3298
+ if (!contactControl && !isolatedContactSource(this.config.aid, fromAid, messageId))
3299
+ saveIsolatedContactSource(this.config.aid, fromAid, messageId, { at: receivedAt, digest: contactSourceDigest(payload) });
3300
+ }
3301
+ catch { /* The isolation barrier preserves fail-closed behavior on storage failure. */ }
3302
+ if (Date.now() - this.contactAdmissionFailureLogAt >= 60_000) {
3303
+ this.contactAdmissionFailureLogAt = Date.now();
3304
+ logger.warn(`${this.logPrefix()} Contact admission isolated: code=CONTACT_STATE_UNAVAILABLE`);
3305
+ }
3306
+ return;
3307
+ }
3308
+ if (handled)
3309
+ return;
3310
+ if (!this.claimInboundMessage('private', messageId, seq))
3311
+ return;
3312
+ if (contactControl)
3313
+ this.rememberContactControlRequest(fromAid, payload, messageId, menuSenderDeviceId(msg.sender_device_id));
3314
+ }
2966
3315
  const responseRecord = getAunRequestRegistry().resolveIncoming({
2967
3316
  selfAid: this._aid || this.config.aid,
2968
3317
  fromAid,
@@ -3019,7 +3368,7 @@ export class AUNChannel {
3019
3368
  // forwardInbound 内部排除 self-echo 与 from-owner。
3020
3369
  // 显式排除 observer.inject:它是 owner 对本 agent 的控制消息,不应镜像给观察者
3021
3370
  // (即便日后 from-owner 排除规则调整,也不会泄漏)。
3022
- if (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject')) {
3371
+ if (!contactControl && (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject'))) {
3023
3372
  void this.forwardInbound(msg);
3024
3373
  }
3025
3374
  if (inboundType === 'observer.inject.status' || inboundType === 'observer.inject.ack') {
@@ -3047,7 +3396,7 @@ export class AUNChannel {
3047
3396
  mentions.push({ aid: this._aid });
3048
3397
  }
3049
3398
  // Process attachments (顶层 + 嵌套在 merge.items / quote.quote 中的)
3050
- const { finalText, images: inboundImages } = await this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' });
3399
+ const { finalText, images: inboundImages } = contactControl ? { finalText: text, images: [] } : await this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' });
3051
3400
  // 私聊 channelId = 对端 AID(不再读 payload.chat_id 含 device 三段式)
3052
3401
  // device_id 仅 SDK 内部多实例去重用,evolcore session 层面跨端共享会话
3053
3402
  const chatId = fromAid;
@@ -4932,8 +5281,21 @@ export class AUNChannel {
4932
5281
  this.groupInviteDelivered?.(entry.postSend.requestId, messageId);
4933
5282
  }
4934
5283
  }
5284
+ appContactOutboundBlock(channelId, delivery, payload, params) {
5285
+ if (delivery.chatType === 'group' || this.config.pureIdentity || !appContactAdmissionActive(this.config.aid)
5286
+ || this.hasContactControlPermit(channelId, payload, params))
5287
+ return undefined;
5288
+ const decision = evaluateAppContactAdmission(this.config.aid, channelId);
5289
+ if (decision.allow)
5290
+ return undefined;
5291
+ return { status: decision.reason === 'unavailable' ? 'retry' : 'permanent',
5292
+ code: 'CONTACT_DENIED', error: `联系人准入未通过:${decision.reason}` };
5293
+ }
4935
5294
  async sendAunPayload(channelId, payload, context, label) {
4936
5295
  const delivery = this.requireDelivery(channelId, context);
5296
+ const blocked = this.appContactOutboundBlock(channelId, delivery, payload);
5297
+ if (blocked)
5298
+ return { ok: false, ...blocked };
4937
5299
  let normalizedPayload;
4938
5300
  try {
4939
5301
  normalizedPayload = this.normalizeAunPayloadMentions(payload);
@@ -4967,7 +5329,8 @@ export class AUNChannel {
4967
5329
  if (payloadWithCausationRef.thread_id === '')
4968
5330
  delete payloadWithCausationRef.thread_id;
4969
5331
  // Truncate payload if too large (AUN SDK limit: 1MB)
4970
- const truncatedPayload = this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
5332
+ const friendPayload = typeof payload.type === 'string' && payload.type.startsWith('friend.');
5333
+ const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
4971
5334
  const params = { payload: truncatedPayload, encrypt };
4972
5335
  const isMenuPayload = typeof truncatedPayload.type === 'string' && truncatedPayload.type.startsWith('menu.');
4973
5336
  if (!isGroup && ['menu.response', 'menu.event'].includes(truncatedPayload.type))
@@ -4978,15 +5341,14 @@ export class AUNChannel {
4978
5341
  if (isMenuPayload && context?.metadata?.menuClientVolatileV1 === true) {
4979
5342
  params.menu_client_volatile_v1 = true;
4980
5343
  }
4981
- if (isMenuPayload && encrypt && context?.metadata?.protectedHeaders) {
4982
- params.protected_headers = context.metadata.protectedHeaders;
4983
- }
5344
+ if (encrypt)
5345
+ params.protected_headers = aunProtectedHeaders(context);
4984
5346
  if (isGroup)
4985
5347
  params.group_id = delivery.groupId;
4986
5348
  else
4987
5349
  params.to = targetAid;
4988
5350
  const callOnce = async (sendParams, fallback) => {
4989
- const result = fallback
5351
+ const result = fallback || friendPayload
4990
5352
  ? await this.callClient(method, sendParams)
4991
5353
  : await this.callAndTrace(method, sendParams);
4992
5354
  const mid = this.messageIdFromSendResult(result);
@@ -5001,10 +5363,11 @@ export class AUNChannel {
5001
5363
  return await callOnce(params, false);
5002
5364
  }
5003
5365
  catch (e) {
5004
- if (encrypt && e instanceof E2EEError && !isMenuPayload) {
5366
+ if (encrypt && e instanceof E2EEError && !isMenuPayload && !friendPayload) {
5005
5367
  this.peerE2ee.set(encryptTarget, { ok: false, ts: Date.now() });
5006
5368
  logger.warn(`${this.logPrefix()} E2EE ${label} send failed to ${channelId}, retrying plaintext: ${e}`);
5007
5369
  const fallbackParams = { ...params, encrypt: false };
5370
+ delete fallbackParams.protected_headers;
5008
5371
  try {
5009
5372
  this.trace('OUT', `${method}.${label}.fallback`, fallbackParams);
5010
5373
  const sent = await callOnce(fallbackParams, true);
@@ -5052,6 +5415,10 @@ export class AUNChannel {
5052
5415
  };
5053
5416
  }
5054
5417
  recordDurableOutbound(channelId, payload, messageId, encrypt, context, isGroup, contentKind, logText, result, statsContext) {
5418
+ if (typeof payload.type === 'string' && payload.type.startsWith('friend.')) {
5419
+ logger.info(`${this.logPrefix()} Contact control transport accepted: type=${payload.type} mid=${messageId}`);
5420
+ return;
5421
+ }
5055
5422
  const causation = normalizeCausation(context?.metadata?.causation);
5056
5423
  if (!isGroup && causation)
5057
5424
  registerAunCausation(messageId, this.config.aid, channelId, causation);
@@ -5125,6 +5492,7 @@ export class AUNChannel {
5125
5492
  delivery,
5126
5493
  dedupeKey: opts.dedupeKey,
5127
5494
  critical: opts.critical,
5495
+ processScoped: context?.metadata?.processScopedDelivery === true,
5128
5496
  type: 'payload',
5129
5497
  contentKind: opts.contentKind,
5130
5498
  payload: finalPayload,
@@ -5433,6 +5801,48 @@ export class AUNChannel {
5433
5801
  this.sentCount.set(turnKey, seqInTurn);
5434
5802
  return seqInTurn;
5435
5803
  }
5804
+ /** An unadmitted outbound text becomes an Owner request, never a send to the peer. */
5805
+ async requestOutboundContact(args) {
5806
+ const selfAid = this.config.aid;
5807
+ const binding = currentContactBinding(selfAid);
5808
+ if (!appContactAdmissionActive(selfAid) || !binding) {
5809
+ return { ok: false, code: 'CONTACT_DIRECTORY_UNAVAILABLE', error: '本端 Owner 关系不可用,未发送申请或原消息' };
5810
+ }
5811
+ const decision = evaluateAppContactAdmission(selfAid, args.to);
5812
+ if (decision.allow || (decision.reason !== 'not_in_contacts' && decision.reason !== 'scope_extension')) {
5813
+ return { ok: false, code: 'CONTACT_DENIED', error: `联系人状态不允许提交申请:${decision.reason};原消息未发送` };
5814
+ }
5815
+ const text = contactIntroductionText(args.payload);
5816
+ if (text === undefined) {
5817
+ return { ok: false, code: 'CONTACT_DENIED', error: '只有纯文本可以向本端 Owner 提交联系申请;原消息未发送' };
5818
+ }
5819
+ if (!consumeContactIntroductionBudget(selfAid, `outbound:${args.to}`)) {
5820
+ return { ok: false, code: 'CONTACT_INTRODUCTION_RATE_LIMIT', error: '联系申请过于频繁,请稍后重试;原消息未发送' };
5821
+ }
5822
+ const request = {
5823
+ ...buildContactRequest(binding, args.to, args.sourceMessageId, Date.now(), `申请联系 ${args.to}。以下为本端拟发送的内容,尚未发给对方:\n${text}`, decision.reason),
5824
+ direction: 'outbound',
5825
+ };
5826
+ const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
5827
+ if (remainingTtl <= 0) {
5828
+ return { ok: false, code: 'CONTACT_REQUEST_EXPIRED', error: '联系申请已过期,未重新提交;原消息未发送' };
5829
+ }
5830
+ const sent = await this.sendContentPayload(binding.owner_aid, request, {
5831
+ contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 outbound]',
5832
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
5833
+ ttl: remainingTtl,
5834
+ });
5835
+ if (!sent.messageId && !sent.queued) {
5836
+ return { ok: false, code: sent.code ?? 'CONTACT_OWNER_REQUEST_FAILED',
5837
+ error: `向本端 Owner 提交联系申请失败:${sent.error ?? '未获得发送或排队回执'};原消息未发送` };
5838
+ }
5839
+ return { ok: true, receipt: {
5840
+ event_id: request.event_id, owner_aid: binding.owner_aid, target_aid: args.to,
5841
+ status: sent.messageId ? 'sent' : 'queued',
5842
+ ...(sent.messageId ? { message_id: sent.messageId } : {}),
5843
+ ...(sent.outboxId ? { outbox_id: sent.outboxId } : {}),
5844
+ } };
5845
+ }
5436
5846
  async sendDaemonMsg(args) {
5437
5847
  try {
5438
5848
  resolveAunSendDevice(args.deviceId, 'msg', args.payload);
@@ -5476,6 +5886,9 @@ export class AUNChannel {
5476
5886
  code: 'INVALID_REQUEST_TTL',
5477
5887
  };
5478
5888
  }
5889
+ const contactBlock = this.appContactOutboundBlock(args.to, { chatType: 'private' }, finalPayload);
5890
+ if (contactBlock)
5891
+ return { ok: false, code: contactBlock.code, error: contactBlock.error };
5479
5892
  if (preserveRawPayload && jsonUtf8Size(finalPayload) > AUN_MAX_PAYLOAD_SIZE) {
5480
5893
  return {
5481
5894
  ok: false,
@@ -5537,6 +5950,7 @@ export class AUNChannel {
5537
5950
  encrypt,
5538
5951
  ...(args.deviceId ? { device_id: args.deviceId } : {}),
5539
5952
  ...(args.ttl !== undefined ? { ttl: args.ttl } : {}),
5953
+ ...(encrypt ? { protected_headers: aunProtectedHeaders({ model: args.model }) } : {}),
5540
5954
  };
5541
5955
  try {
5542
5956
  const result = await this.callAndTrace('message.send', sendParams);
@@ -5669,6 +6083,7 @@ export class AUNChannel {
5669
6083
  group_id: args.groupId,
5670
6084
  payload: this.truncatePayloadIfNeeded(finalPayload, 'group-send-ipc'),
5671
6085
  encrypt,
6086
+ ...(encrypt ? { protected_headers: aunProtectedHeaders({ model: args.model }) } : {}),
5672
6087
  });
5673
6088
  const messageId = this.messageIdFromSendResult(result);
5674
6089
  if (!messageId) {
@@ -5787,6 +6202,11 @@ export class AUNChannel {
5787
6202
  const finalText = entry.text;
5788
6203
  const delivery = this.requirePersistedDelivery(channelId, entry.delivery);
5789
6204
  const context = this.withDelivery(entry.context, delivery);
6205
+ if (!entry.deliveryReceipt) {
6206
+ const blocked = this.appContactOutboundBlock(channelId, delivery, { type: 'text', text: entry.text });
6207
+ if (blocked)
6208
+ return blocked;
6209
+ }
5790
6210
  const operationId = entry.dedupeKey
5791
6211
  || (typeof context?.metadata?.operationId === 'string' ? context.metadata.operationId : undefined);
5792
6212
  if (operationId) {
@@ -5872,6 +6292,8 @@ export class AUNChannel {
5872
6292
  ? !!(context.metadata.encrypted)
5873
6293
  : this.shouldEncrypt(encryptTarget);
5874
6294
  const params = { payload, encrypt };
6295
+ if (encrypt)
6296
+ params.protected_headers = aunProtectedHeaders(context);
5875
6297
  if (context?.metadata?.persistRequired === true)
5876
6298
  params.persist_required = true;
5877
6299
  let acceptedMessageId;
@@ -5952,6 +6374,7 @@ export class AUNChannel {
5952
6374
  this.peerE2ee.set(encryptTarget, { ok: false, ts: Date.now() });
5953
6375
  logger.warn(`${this.logPrefix()} E2EE send failed to ${channelId}, retrying plaintext: ${e}`);
5954
6376
  params.encrypt = false;
6377
+ delete params.protected_headers;
5955
6378
  try {
5956
6379
  if (isGroup) {
5957
6380
  this.trace('OUT', 'group.send.fallback', params);
@@ -6053,6 +6476,18 @@ export class AUNChannel {
6053
6476
  }
6054
6477
  }
6055
6478
  async deliverPayloadEntry(entry) {
6479
+ if (!entry.deliveryReceipt && typeof entry.payload?.type === 'string' && entry.payload.type.startsWith('friend.')) {
6480
+ const selfAid = this.config.aid;
6481
+ const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.outbox' });
6482
+ const binding = verifiedContactBinding(selfAid, view);
6483
+ if (!binding)
6484
+ return { ok: false, status: 'retry', code: 'CONTACT_OWNERSHIP_UNAVAILABLE', error: 'current Owner relation could not be verified' };
6485
+ if (!friendPayloadRouteValid(entry.payload, entry.channelId, true, binding)) {
6486
+ return { ok: false, status: 'permanent', code: 'CONTACT_OWNERSHIP_CHANGED', error: 'contact event no longer belongs to the current Owner relation' };
6487
+ }
6488
+ // E2EE is mandatory even for a recovered queue entry.
6489
+ entry.context = { ...entry.context, metadata: { ...entry.context?.metadata, encrypted: true } };
6490
+ }
6056
6491
  const interactionId = entry.postSend?.type === 'register_interaction_card'
6057
6492
  ? entry.postSend.requestId
6058
6493
  : undefined;
@@ -6149,6 +6584,8 @@ export class AUNChannel {
6149
6584
  }
6150
6585
  /** 有效会话正文写入 messages.jsonl(message.send/group.send 成功后调用)。 */
6151
6586
  appendOutboundJsonl(channelId, descriptor) {
6587
+ if (descriptor.payloadType?.startsWith('friend.'))
6588
+ return;
6152
6589
  const operationId = typeof descriptor.context?.metadata?.operationId === 'string'
6153
6590
  ? descriptor.context.metadata.operationId
6154
6591
  : undefined;
@@ -6233,6 +6670,7 @@ export class AUNChannel {
6233
6670
  context: { type: 'task', id: taskId },
6234
6671
  payload: thoughtPayload,
6235
6672
  encrypt,
6673
+ ...(encrypt ? { protected_headers: aunProtectedHeaders(context) } : {}),
6236
6674
  };
6237
6675
  try {
6238
6676
  let thoughtPayload = params.payload;
@@ -6348,18 +6786,8 @@ export class AUNChannel {
6348
6786
  if (isMenuPayload && context?.metadata?.menuClientVolatileV1 === true) {
6349
6787
  params.menu_client_volatile_v1 = true;
6350
6788
  }
6351
- const rawHeaders = context?.metadata?.protectedHeaders;
6352
- if (encrypt && rawHeaders && typeof rawHeaders === 'object' && !Array.isArray(rawHeaders)) {
6353
- const protectedHeaders = {};
6354
- for (const [key, value] of Object.entries(rawHeaders)) {
6355
- const name = key.trim().toLowerCase();
6356
- if (!/^[a-z0-9_-]+$/.test(name) || typeof value !== 'string')
6357
- continue;
6358
- protectedHeaders[name] = value;
6359
- }
6360
- if (Object.keys(protectedHeaders).length > 0)
6361
- params.protected_headers = protectedHeaders;
6362
- }
6789
+ if (encrypt)
6790
+ params.protected_headers = aunProtectedHeaders(context);
6363
6791
  try {
6364
6792
  if (isGroup) {
6365
6793
  params.group_id = delivery.groupId;
@@ -6563,6 +6991,11 @@ export class AUNChannel {
6563
6991
  return imagePayload;
6564
6992
  }
6565
6993
  async deliverImageEntry(entry) {
6994
+ if (!entry.deliveryReceipt) {
6995
+ const blocked = this.appContactOutboundBlock(entry.channelId, this.requirePersistedDelivery(entry.channelId, entry.delivery), { type: 'image' });
6996
+ if (blocked)
6997
+ return blocked;
6998
+ }
6566
6999
  const image = entry.image;
6567
7000
  if (!image || typeof image.dataBase64 !== 'string') {
6568
7001
  logger.warn(`${this.logPrefix()} deliverImageEntry: missing image data (outbox id=${entry.id})`);
@@ -6609,6 +7042,11 @@ export class AUNChannel {
6609
7042
  }
6610
7043
  }
6611
7044
  async deliverFileEntry(entry) {
7045
+ if (!entry.deliveryReceipt) {
7046
+ const blocked = this.appContactOutboundBlock(entry.channelId, this.requirePersistedDelivery(entry.channelId, entry.delivery), { type: 'file' });
7047
+ if (blocked)
7048
+ return blocked;
7049
+ }
6612
7050
  const channelId = entry.channelId;
6613
7051
  if (typeof entry.filePath !== 'string' || !entry.filePath.trim()) {
6614
7052
  logger.warn(`${this.logPrefix()} deliverFileEntry: missing file path (outbox id=${entry.id})`);
@@ -6663,6 +7101,8 @@ export class AUNChannel {
6663
7101
  ? !!(context.metadata.encrypted)
6664
7102
  : this.shouldEncrypt(encryptTarget);
6665
7103
  const params = { payload: filePayload, encrypt };
7104
+ if (encrypt)
7105
+ params.protected_headers = aunProtectedHeaders(context);
6666
7106
  let sendResult = null;
6667
7107
  let sentMid = null;
6668
7108
  try {
@@ -6701,6 +7141,7 @@ export class AUNChannel {
6701
7141
  this.peerE2ee.set(encryptTarget, { ok: false, ts: Date.now() });
6702
7142
  logger.warn(`${this.logPrefix()} E2EE sendFile failed to ${channelId}, retrying plaintext: ${sendErr}`);
6703
7143
  params.encrypt = false;
7144
+ delete params.protected_headers;
6704
7145
  if (isGroup) {
6705
7146
  this.trace('OUT', 'group.send.file.fallback', params);
6706
7147
  const result = await this.callClient('group.send', params);
@@ -7474,7 +7915,7 @@ export class AUNChannelPlugin {
7474
7915
  await channel.sendThought(channelId, envelope.taskId, aunPayload, replyCtx);
7475
7916
  }
7476
7917
  else {
7477
- // Interactive activities are reliable structured payloads;
7918
+ // Interactive and PA activities are reliable structured payloads;
7478
7919
  // sendReliableStructured internally selects the activity
7479
7920
  // outbox queue while preserving the common delivery contract.
7480
7921
  const result = await channel.sendReliableStructured(channelId, aunPayload, replyCtx, channel.activityLogText(item));