evolcore 0.0.43-test.1 → 0.0.43-test.3

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 (200) hide show
  1. package/CHANGELOG.md +31 -1
  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 +39 -15
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/aid/agentmd.js +21 -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 +7 -2
  13. package/dist/channels/aun.js +522 -50
  14. package/dist/channels/builtin-plugins.js +16 -11
  15. package/dist/channels/daemon.js +4 -0
  16. package/dist/channels/dingtalk.js +83 -31
  17. package/dist/channels/feishu.js +29 -13
  18. package/dist/channels/qqbot.js +32 -11
  19. package/dist/channels/wechat.js +13 -3
  20. package/dist/channels/wecom.js +67 -27
  21. package/dist/cli/agent-command.js +3 -86
  22. package/dist/cli/agent-create.js +20 -6
  23. package/dist/cli/agent.js +1 -79
  24. package/dist/cli/aun-commands.js +18 -19
  25. package/dist/cli/config.js +1 -1
  26. package/dist/cli/daemon-commands.js +47 -2
  27. package/dist/cli/data-command.js +9 -1
  28. package/dist/cli/debug-mode.js +1 -1
  29. package/dist/cli/diag.js +1 -1
  30. package/dist/cli/directory.js +149 -91
  31. package/dist/cli/getmeta-command.js +1 -1
  32. package/dist/cli/index.js +79 -22
  33. package/dist/cli/init.js +1 -23
  34. package/dist/cli/link-rules.js +1 -1
  35. package/dist/cli/managed-command-guard.js +0 -1
  36. package/dist/cli/pa-workspace-command.js +36 -2
  37. package/dist/cli/peer.js +3 -2
  38. package/dist/cli/restart-monitor.js +17 -3
  39. package/dist/cli/role.js +1 -1
  40. package/dist/cli/session-command.js +1 -1
  41. package/dist/cli/stats.js +2 -2
  42. package/dist/cli/task-context.js +3 -1
  43. package/dist/cli/thread-command.js +1 -1
  44. package/dist/cli/watch-msg.js +1 -1
  45. package/dist/config/builtin-role-templates.js +2 -2
  46. package/dist/config/builtin-roles.js +2 -1
  47. package/dist/config/config-field-policy.js +7 -2
  48. package/dist/config/config-manager.js +32 -10
  49. package/dist/config/peer-role-resolver.js +23 -1
  50. package/dist/config/role-schema.js +29 -4
  51. package/dist/config/role-service.js +12 -7
  52. package/dist/config/role-store.js +30 -8
  53. package/dist/config-store.js +75 -4
  54. package/dist/core/agent-ipc-registration.js +16 -59
  55. package/dist/core/auth/auth-gateway.js +14 -4
  56. package/dist/core/auth/authorization-audit.js +52 -14
  57. package/dist/core/auth/operation-authorizer.js +17 -11
  58. package/dist/core/auth/operation-catalog.js +5 -13
  59. package/dist/core/channel-loader.js +152 -16
  60. package/dist/core/channel-runtime.js +5 -0
  61. package/dist/core/command/agent-control.js +2 -1
  62. package/dist/core/command/agentmd-menu-request.js +50 -0
  63. package/dist/core/command/agentmd-menu.js +156 -0
  64. package/dist/core/command/cli-intent-parser.js +0 -8
  65. package/dist/core/command/command-handler.js +47 -40
  66. package/dist/core/command/connect-menu.js +7 -3
  67. package/dist/core/command/menu-catalog.js +16 -2
  68. package/dist/core/command/menu-handler.js +107 -14
  69. package/dist/core/command/menu-protocol.js +28 -0
  70. package/dist/core/command/role-menu.js +23 -9
  71. package/dist/core/command/slash-handler.js +139 -51
  72. package/dist/core/daemon-file-cache.js +3 -3
  73. package/dist/core/daemon-lifecycle.js +9 -1
  74. package/dist/core/evolagent-registry.js +5 -4
  75. package/dist/core/evolagent.js +10 -12
  76. package/dist/core/handoff/argv-parse.js +115 -0
  77. package/dist/core/handoff/ipc-registration.js +1 -1
  78. package/dist/core/ipc-registration.js +19 -2
  79. package/dist/core/lifecycle-notice.js +185 -0
  80. package/dist/core/memory/consolidation.js +8 -1
  81. package/dist/core/memory/relation-sweep.js +20 -8
  82. package/dist/core/message/aun-ipc-sender.js +35 -2
  83. package/dist/core/message/contact-admission.js +530 -0
  84. package/dist/core/message/im-renderer.js +111 -16
  85. package/dist/core/message/message-admission.js +29 -54
  86. package/dist/core/message/message-bridge.js +62 -8
  87. package/dist/core/message/message-utils.js +9 -5
  88. package/dist/core/message/peer-mode.js +55 -13
  89. package/dist/core/message/response-engine.js +298 -78
  90. package/dist/core/message/retry-scheduler.js +4 -0
  91. package/dist/core/ownership/owner-resolver.js +72 -34
  92. package/dist/core/permission/ec-command-parser.js +25 -38
  93. package/dist/core/permission/readonly-shell-query.js +34 -8
  94. package/dist/core/permission/tool-policy.js +50 -5
  95. package/dist/core/relation/pa-team.js +127 -0
  96. package/dist/core/role/runtime-policy.js +18 -5
  97. package/dist/core/session/session-manager.js +9 -1
  98. package/dist/core/soul.js +66 -0
  99. package/dist/core/system-session/memory.js +2 -2
  100. package/dist/core/thread/thread-service.js +6 -4
  101. package/dist/directory/contact-admission-paths.js +9 -0
  102. package/dist/directory/owner-directory-admission.js +125 -29
  103. package/dist/directory/owner-directory-cache.js +554 -58
  104. package/dist/directory/owner-directory-identity.js +60 -0
  105. package/dist/directory/owner-directory-markdown.js +154 -58
  106. package/dist/directory/owner-directory-policy.js +108 -0
  107. package/dist/directory/owner-directory-query-operation.js +399 -90
  108. package/dist/directory/owner-directory-remarks.js +29 -2
  109. package/dist/directory/owner-directory-request-operation.js +76 -0
  110. package/dist/directory/owner-directory-scope.js +35 -4
  111. package/dist/directory/owner-directory-search.js +118 -33
  112. package/dist/directory/owner-directory-store.js +117 -30
  113. package/dist/directory/owner-directory-text.js +60 -0
  114. package/dist/eck/kit-renderer.js +18 -8
  115. package/dist/eck/manifest-engine.js +55 -6
  116. package/dist/ecweb/basic-settings-service.js +2 -2
  117. package/dist/ecweb/message-context-service.js +28 -16
  118. package/dist/index.js +20 -5
  119. package/dist/ipc.js +1 -1
  120. package/dist/paths.js +29 -1
  121. package/dist/product.js +1 -0
  122. package/dist/response-system/config-resolver.js +1 -1
  123. package/dist/response-system/engines/v1/index.js +2 -1
  124. package/dist/response-system/modes/single-session/index.js +7 -2
  125. package/dist/trigger/scheduler.js +7 -4
  126. package/dist/trigger/validation.js +4 -0
  127. package/dist/utils/error-utils.js +12 -7
  128. package/dist/utils/logger.js +13 -4
  129. package/dist/utils/npm-ops.js +2 -2
  130. package/dist/utils/windows-autostart.js +1 -1
  131. package/ecagent/README.md +18 -0
  132. package/ecagent/dist/agent-loop.js +43 -1
  133. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  134. package/ecagent/dist/harness/agent-harness.js +24 -8
  135. package/ecagent/dist/harness/compaction/compaction.js +3 -0
  136. package/ecagent/dist/harness/types.d.ts +1 -0
  137. package/kits/docs/INDEX.md +1 -0
  138. package/kits/docs/channels/aun.md +1 -1
  139. package/kits/docs/context-assembly.md +21 -6
  140. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  141. package/kits/docs/evolcore/INDEX.md +4 -1
  142. package/kits/docs/evolcore/agent-create.md +5 -5
  143. package/kits/docs/evolcore/agent.md +4 -9
  144. package/kits/docs/evolcore/directory.md +227 -0
  145. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  146. package/kits/docs/evolcore/file-navigation.md +265 -0
  147. package/kits/docs/evolcore/menu-protocol.md +55 -0
  148. package/kits/docs/evolcore/msg.md +1 -0
  149. package/kits/docs/evolcore/peer.md +2 -1
  150. package/kits/docs/evolcore/response.md +7 -1
  151. package/kits/docs/evolcore/task.md +2 -0
  152. package/kits/docs/evolcore/tool-authorization.md +1 -1
  153. package/kits/docs/evolcore/trigger.md +4 -0
  154. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  155. package/kits/docs/prompt-loading-architecture.md +6 -2
  156. package/kits/eck_manifest.auxiliary.json +1 -0
  157. package/kits/eck_manifest.json +64 -7
  158. package/kits/eck_manifest.memory.json +93 -4
  159. package/kits/rules/01-overview.md +2 -2
  160. package/kits/rules/03-identity.md +10 -9
  161. package/kits/rules/05-venue.md +2 -4
  162. package/kits/rules/06-channel.md +1 -1
  163. package/kits/schemas/_meta.json +44 -3
  164. package/kits/schemas/agent-config.schema.18.json +5 -0
  165. package/kits/schemas/agent-config.schema.19.json +924 -0
  166. package/kits/schemas/agent-config.schema.20.json +925 -0
  167. package/kits/schemas/relation-config.schema.12.json +289 -0
  168. package/kits/schemas/relation-config.schema.13.json +289 -0
  169. package/kits/schemas/role-config.schema.2.json +215 -0
  170. package/kits/schemas/role-config.schema.3.json +1038 -0
  171. package/kits/schemas/role-registry.schema.1.json +3 -2
  172. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  173. package/kits/skills/ec-trigger/SKILL.md +4 -4
  174. package/kits/skills/personal-assistant/SKILL.md +109 -53
  175. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  176. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  177. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  178. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  179. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  180. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  181. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  182. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  183. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  184. package/kits/templates/soul/00-GUIDE.md +39 -0
  185. package/kits/templates/soul/01-identity.md +5 -0
  186. package/kits/templates/soul/02-persona.md +11 -0
  187. package/kits/templates/soul/03-duties.md +5 -0
  188. package/kits/templates/soul/04-working-style.md +5 -0
  189. package/kits/templates/system-fragments/bootstrap.md +7 -7
  190. package/kits/templates/system-fragments/channel.md +2 -2
  191. package/kits/templates/system-fragments/commands.md +3 -2
  192. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  193. package/kits/templates/system-fragments/memory.md +1 -1
  194. package/kits/templates/system-fragments/personal-assistant.md +50 -0
  195. package/kits/templates/system-fragments/reply.md +7 -0
  196. package/kits/templates/system-fragments/session.md +6 -2
  197. package/package.json +3 -2
  198. package/dist/cli/handoff-command.js +0 -353
  199. package/dist/directory/owner-directory-remark-operation.js +0 -147
  200. package/kits/docs/evolcore/self-summary.md +0 -29
@@ -1,5 +1,6 @@
1
1
  import { E2EEError, validateAIDFormat } from '@agentunion/fastaun';
2
2
  import { sanitizeMenuLogValue } from '../core/command/menu-protocol.js';
3
+ import { 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';
3
4
  import crypto from 'crypto';
4
5
  import { performance } from 'node:perf_hooks';
5
6
  import fs from 'fs';
@@ -9,7 +10,6 @@ import { registerOwnerDirectoryAdmission } from '../directory/owner-directory-ad
9
10
  import { OwnerDirectoryAgentMdSync } from '../directory/owner-directory-agentmd-sync.js';
10
11
  import { parseNotificationSnapshots } from '../directory/owner-directory-store.js';
11
12
  import { OWNER_DIRECTORY_SCOPES } from '../directory/owner-directory-cache.js';
12
- import { resolveAllowExternalContacts } from '../directory/owner-directory-admission.js';
13
13
  import path from 'path';
14
14
  import os from 'os';
15
15
  import { logger, localTimestamp, logPreview } from '../utils/logger.js';
@@ -41,8 +41,10 @@ import { isManagementRole } from '../config/builtin-roles.js';
41
41
  import { normalizeAunMentionMode, normalizeMentionMode } from '../config/mention-mode.js';
42
42
  import { getProcessStartTime } from '../utils/process-introspect.js';
43
43
  import * as outbox from '../aun/outbox.js';
44
+ import { aunProtectedHeaders } from '../aun/model-headers.js';
44
45
  import { formatSize } from '../utils/media-cache.js';
45
46
  import { formatPeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
47
+ import { preparePaTeamQualification, registerPaTeamClient, unregisterPaTeamClient } from '../core/relation/pa-team.js';
46
48
  import { isHClassPath } from '../core/permission/protected-paths.js';
47
49
  import { consumeAunCausation, registerAunCausation } from '../core/causation/aun-association.js';
48
50
  import { deriveCausation, normalizeCausation } from '../core/causation/context.js';
@@ -70,6 +72,8 @@ const OBSERVER_GROUP_MEMBERS_PAGE_SIZE = 200;
70
72
  const OBSERVER_GROUP_MEMBERS_MAX_PAGES = 100;
71
73
  const AUN_SEND_LOG_TEXT_MAX_LENGTH = 60;
72
74
  const AUN_MAX_PAYLOAD_SIZE = 512 * 1024;
75
+ /** AUN volatile TTL for online/offline lifecycle notices (gateway cap is 3600s). */
76
+ export const DEFAULT_LIFECYCLE_NOTICE_TTL_SECONDS = 1_800;
73
77
  const OWNER_DIRECTORY_ACK_TTL_SECONDS = 30;
74
78
  const OWNER_DIRECTORY_RETRY_BASE_MS = 1_000;
75
79
  const OWNER_DIRECTORY_RETRY_MAX_MS = 60_000;
@@ -394,6 +398,7 @@ const AUN_ACCEPTED_DISPATCH_STATUSES = new Set([
394
398
  'debounced', 'dispatched', 'accepted', 'queued', 'queued_batch', 'broadcast', 'sent',
395
399
  ]);
396
400
  const AUN_PERMANENT_STRING_CODES = new Set([
401
+ 'contact_denied', 'contact_ownership_changed',
397
402
  'invalid_params', 'invalid_param', 'invalid_request', 'permission_denied',
398
403
  'unauthorized', 'authentication_failed', 'not_found', 'group_not_found',
399
404
  'group_not_member', 'member_not_found', 'target_not_found', 'agent_not_found',
@@ -584,6 +589,22 @@ function sentOutboxResult(messageId) {
584
589
  ? { status: 'sent', messageId }
585
590
  : { status: 'permanent', error: 'AUN send completed without a remote message_id', code: 'MISSING_MESSAGE_ID' };
586
591
  }
592
+ /**
593
+ * Wire contract for agent online/offline notices. Kept in one place so EvolApp
594
+ * and tests can rely on the same field names.
595
+ */
596
+ export function buildAunLifecycleNoticePayload(args) {
597
+ const name = args.agentName.trim() || args.selfAid;
598
+ return {
599
+ type: 'notice',
600
+ subtype: args.online ? 'agent.online' : 'agent.offline',
601
+ severity: 'info',
602
+ text: `${name} ${args.online ? '已上线' : '已下线'}`,
603
+ agent_aid: args.selfAid,
604
+ agent_name: name,
605
+ sent_at: args.sentAt ?? Date.now(),
606
+ };
607
+ }
587
608
  function setIfDefined(target, key, value) {
588
609
  if (value !== undefined)
589
610
  target[key] = value;
@@ -703,17 +724,70 @@ function errorCodeForLog(error) {
703
724
  }
704
725
  export class AUNChannel {
705
726
  config;
727
+ contactAdmissionFailureLogAt = 0;
728
+ contactControlPermits = new Map();
729
+ rememberContactControlRequest(target, payload, mid, device) {
730
+ const binding = currentContactBinding(this.config.aid);
731
+ if (!binding || !payload || typeof payload !== 'object')
732
+ return;
733
+ let matches;
734
+ const id = payload.id;
735
+ if (['menu.query', 'menu.options', 'menu.action'].includes(payload.type) && typeof id === 'string' && id.length <= 256) {
736
+ matches = value => (value.type === 'menu.response' && value.id === id)
737
+ || (value.type === 'menu.event' && value.requestId === id);
738
+ }
739
+ else if (payload.type === 'ability' && payload.role === 'call'
740
+ && typeof payload.call_id === 'string' && typeof payload.operation_id === 'string') {
741
+ const { call_id, operation_id, ability_path, definition_id } = payload;
742
+ matches = value => value.type === 'ability' && ['ack', 'result'].includes(value.role)
743
+ && value.call_id === call_id && value.operation_id === operation_id
744
+ && value.ability_path === ability_path && value.definition_id === definition_id;
745
+ }
746
+ else if (payload.type === 'bind.request' && typeof payload.creationId === 'string') {
747
+ const { creationId, bindType } = payload;
748
+ matches = value => value.type === 'bind.response' && value.creationId === creationId && value.bindType === bindType;
749
+ }
750
+ if (!matches)
751
+ return;
752
+ for (const [key, permit] of this.contactControlPermits)
753
+ if (permit.expires <= Date.now())
754
+ this.contactControlPermits.delete(key);
755
+ if (this.contactControlPermits.size >= 512)
756
+ return;
757
+ this.contactControlPermits.set(JSON.stringify([target, mid]), { target, device, binding, matches, expires: Date.now() + 6 * 60_000 });
758
+ }
759
+ hasContactControlPermit(target, payload, params) {
760
+ if (!payload || typeof payload !== 'object')
761
+ return false;
762
+ return [...this.contactControlPermits.values()].some(permit => permit.target === target && permit.expires > Date.now()
763
+ && sameContactBinding(permit.binding, currentContactBinding(this.config.aid)) && permit.matches(payload)
764
+ && (!params || !String(payload.type).startsWith('menu.') || params.encrypt === true)
765
+ && (!params || !permit.device || (params.to_device_id ?? params.device_id) === permit.device));
766
+ }
706
767
  // Keep each target's attempt across channel recreation; reset only on process restart.
707
768
  static configuredOwnerBindAttempts = new Set();
708
- managedMenuClient = new ManagedMenuClient(params => {
769
+ managedMenuClient = new ManagedMenuClient((params, beforeSend) => {
709
770
  if (!this.connected || !this.client)
710
771
  return Promise.reject(new Error('AUN channel is not connected'));
711
- return this.callAndTrace('message.send', params);
772
+ return this.callAndTrace('message.send', params, { beforeSend });
712
773
  });
713
774
  requestRemoteMenu(options) {
714
775
  if (options.fromAid !== (this._aid || this.config.aid))
715
776
  throw new Error('Menu sender does not match channel identity');
716
- return this.managedMenuClient.request(options);
777
+ const target = options.targetAid;
778
+ const request = JSON.stringify(options.request);
779
+ const expires = Date.now() + (options.timeoutMs ?? 15_000) * 2;
780
+ const binding = currentContactBinding(this.config.aid);
781
+ return this.managedMenuClient.request({ ...options, beforeSend: () => {
782
+ options.beforeSend?.();
783
+ if (options.targetAid !== target || JSON.stringify(options.request) !== request || Date.now() >= expires) {
784
+ throw Object.assign(new Error('Managed Menu operation changed or expired'), { code: 'CONTACT_DENIED' });
785
+ }
786
+ if (!this.config.pureIdentity
787
+ && (!binding || !sameContactBinding(binding, currentContactBinding(this.config.aid)))) {
788
+ throw Object.assign(new Error('Managed Menu Owner relation unavailable or changed'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
789
+ }
790
+ } });
717
791
  }
718
792
  client = null;
719
793
  configuredOwnerBind;
@@ -753,7 +827,13 @@ export class AUNChannel {
753
827
  return;
754
828
  // 自动从 data 推断顶层字段(self_aid / peer_aid / group_id / task_id / chatmode),
755
829
  // 便于 jq 过滤:`jq 'select(.task_id == "task-xxx")'`
756
- const safeData = redactMenuTokensForTrace(data);
830
+ const inbound = data && typeof data === 'object' ? data : {};
831
+ const isolateTrace = dir === 'IN' && event === 'message.received' && !this.config.pureIdentity;
832
+ const safeData = isolateTrace ? {
833
+ message_id: inbound.message_id, seq: inbound.seq,
834
+ envelope: { from: inbound.envelope?.from, to: inbound.envelope?.to, encrypted: inbound.envelope?.encrypted },
835
+ payload: { type: inbound.payload?.type, body_omitted: true },
836
+ } : redactMenuTokensForTrace(data);
757
837
  const d = (safeData && typeof safeData === 'object') ? safeData : {};
758
838
  const payload = d.payload ?? {};
759
839
  // 入站事件(IN)路由字段在 d.envelope.*(SDK 0.5.*);出站 params(OUT)字段在顶层。两者兼顾。
@@ -790,10 +870,51 @@ export class AUNChannel {
790
870
  * 统一的 RPC 调用包装:自动记录 OUT 发送、.ok 结果、.error 错误(含 trace + daemon.log 失败日志)。
791
871
  * 所有 client.call() 都应通过此方法调用,保证 aun-trace 里每个 OUT 调用都有"发+收/错"成对记录。
792
872
  */
793
- callClient(method, params, lane = 'normal', onStart, onPrepared) {
873
+ callClient(method, params, lane = 'normal', onStart, onPrepared, beforeSend) {
794
874
  params = menuTransportParams(method, params);
875
+ const client = this.client;
876
+ const appOwned = !this.config.pureIdentity;
877
+ const friendPayload = typeof params.payload?.type === 'string' && params.payload.type.startsWith('friend.');
878
+ const binding = appOwned || friendPayload ? currentContactBinding(this.config.aid) : undefined;
795
879
  onPrepared?.(params);
796
- return this.withOutboundSendGate(method, () => (this.client.call(method, params).then(value => value)), lane, onStart);
880
+ return this.withOutboundSendGate(method, async () => {
881
+ if (client !== this.client || !client)
882
+ throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
883
+ if (!this.config.pureIdentity && (friendPayload || appOwned)
884
+ && (method === 'message.send' || method === 'message.thought.put')) {
885
+ if (typeof params.payload?.type === 'string' && params.payload.type.startsWith('friend.')) {
886
+ const refreshed = await ownerResolver.refresh(this.config.aid, { maxAgeMs: 0, source: 'contact.transport' });
887
+ const verified = verifiedContactBinding(this.config.aid, refreshed);
888
+ if (!verified) {
889
+ throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
890
+ }
891
+ if (!friendPayloadRouteValid(params.payload, params.to, params.encrypt, verified)
892
+ || !sameContactBinding(verified, currentContactBinding(this.config.aid))) {
893
+ throw Object.assign(new Error('contact Owner relation changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
894
+ }
895
+ if (client !== this.client)
896
+ throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
897
+ }
898
+ const current = currentContactBinding(this.config.aid);
899
+ if (!current)
900
+ throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
901
+ if (!binding || !sameContactBinding(binding, current))
902
+ throw Object.assign(new Error('Owner relation changed while queued'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
903
+ const payload = params.payload;
904
+ if (typeof payload?.type === 'string' && payload.type.startsWith('friend.')
905
+ && !friendPayloadRouteValid(payload, params.to, params.encrypt, current)) {
906
+ throw Object.assign(new Error('contact event relation or encryption changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
907
+ }
908
+ if (!beforeSend) {
909
+ const blocked = this.appContactOutboundBlock(params.to, { chatType: 'private' }, payload, params);
910
+ if (blocked) {
911
+ throw Object.assign(new Error(blocked.error), { code: blocked.code });
912
+ }
913
+ }
914
+ }
915
+ beforeSend?.();
916
+ return client.call(method, params).then(value => value);
917
+ }, lane, onStart);
797
918
  }
798
919
  withOutboundSendGate(method, run, lane = 'normal', onStart) {
799
920
  if (!AUNChannel.OUTBOUND_SEND_METHODS.has(method)) {
@@ -874,7 +995,7 @@ export class AUNChannel {
874
995
  // passed to the SDK (TTL and device targeting may both be removed).
875
996
  params = preparedParams;
876
997
  this.trace('OUT', method, params);
877
- });
998
+ }, opts?.beforeSend);
878
999
  const durationMs = Date.now() - rpcStart;
879
1000
  const rpcDurationMs = Date.now() - callStartedAt;
880
1001
  const queueWaitMs = Math.max(0, callStartedAt - rpcStart);
@@ -1642,10 +1763,8 @@ export class AUNChannel {
1642
1763
  // Let Core and the SDK reuse valid consensus; explicit authorization/bind operations
1643
1764
  // own their fresh checks. Material changes invalidate the SDK cache themselves.
1644
1765
  const ownership = await ownerResolver.refresh(selfAid, { allowTransient: true, source: 'directory.runtime' });
1645
- // Fall back to configured owner for agents created before the ownership consensus protocol,
1646
- // which may not yet have a consensus result but do have owners in config.json.
1647
- const ownerAid = ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid);
1648
- logger.info(`${this.logPrefix()} ownerResolver result: selfAid=${selfAid}, ownerAid=${ownerAid || 'undefined'} (protocol=${ownerResolver.owner(selfAid) || 'none'}, known=${ownerResolver.knownOwner(selfAid) || 'none'})`);
1766
+ const ownerAid = ownerResolver.owner(selfAid);
1767
+ logger.info(`${this.logPrefix()} ownerResolver result: selfAid=${selfAid}, ownerAid=${ownerAid || 'undefined'}`);
1649
1768
  if (ownership.refreshFailure) {
1650
1769
  const code = ownership.refreshFailure.code || 'UNKNOWN';
1651
1770
  logger.warn(`${this.logPrefix()} Owner relationship refresh failed: status=${ownership.consensusStatus} code=${code}`);
@@ -1657,11 +1776,19 @@ export class AUNChannel {
1657
1776
  logger.debug(`${this.logPrefix()} Owner directory unavailable: owner=${ownerAid ? 'known' : 'unknown'}, connectionChanged=${this.client !== client || !this.connected}`);
1658
1777
  return;
1659
1778
  }
1660
- if (this.ownerDirectoryCache?.client !== client || this.ownerDirectoryCache.ownerAid !== ownerAid) {
1779
+ const relationVersion = currentContactBinding(selfAid)?.relation_version;
1780
+ if (!relationVersion)
1781
+ return;
1782
+ if (this.ownerDirectoryCache?.client !== client || this.ownerDirectoryCache.ownerAid !== ownerAid
1783
+ || this.ownerDirectoryRelationVersion !== relationVersion) {
1661
1784
  // Keep the already-verified cache instance and its diagnostics, but let
1662
1785
  // the new cache implementation own storage and event synchronization.
1663
1786
  const directory = path.join(this.agentDir, 'directory');
1664
1787
  const cache = new OwnerDirectoryCache({
1788
+ onSnapshotApplying: snapshot => { if (isCurrent())
1789
+ reconcileTemporaryContactGrants(selfAid, snapshot); },
1790
+ relationVersion,
1791
+ isCurrent: () => isCurrent(),
1665
1792
  selfAid,
1666
1793
  ownerAid,
1667
1794
  directory,
@@ -1673,19 +1800,11 @@ export class AUNChannel {
1673
1800
  // 名录有新增/变更条目,按差集批量刷新 agent.md(SDK 进程内去重)
1674
1801
  void this.ownerDirectoryCache?.agentMd.refreshAids(aids);
1675
1802
  },
1676
- // 外部联系人默认不注入;个人助理缺省打开,判据与准入共用。
1677
- allowExternalContacts: () => {
1678
- try {
1679
- return resolveAllowExternalContacts(selfAid, this.ownerDirectoryCache?.cache.readSnapshot('contacts'));
1680
- }
1681
- catch {
1682
- return false;
1683
- }
1684
- },
1685
1803
  });
1686
1804
  const isCurrent = () => this.client === client && this.connected
1687
1805
  && this.ownerDirectoryCache?.cache === cache
1688
- && (ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid)) === ownerAid;
1806
+ && ownerResolver.owner(selfAid) === ownerAid
1807
+ && currentContactBinding(selfAid)?.relation_version === relationVersion;
1689
1808
  const agentMd = new OwnerDirectoryAgentMdSync({
1690
1809
  selfAid,
1691
1810
  aunPath: this.config.keystorePath || resolveRoot(),
@@ -1694,6 +1813,7 @@ export class AUNChannel {
1694
1813
  onUpdated: aid => this.invalidatePeerAgentMd(aid),
1695
1814
  });
1696
1815
  this.ownerDirectoryCache = { client, ownerAid, cache, agentMd };
1816
+ this.ownerDirectoryRelationVersion = relationVersion;
1697
1817
  registerOwnerDirectoryAdmission({ selfAid, ownerAid, cache, isCurrent });
1698
1818
  }
1699
1819
  return this.ownerDirectoryCache;
@@ -1763,6 +1883,8 @@ export class AUNChannel {
1763
1883
  await runtime.cache.applyFromSharedCacheWithin(OWNER_DIRECTORY_APPLY_WAIT_MS).catch(() => undefined);
1764
1884
  }
1765
1885
  async handleOwnerDirectoryAuthorizationResponse(senderAid, record) {
1886
+ if (record.selfAid !== this.config.aid || record.targetAid !== senderAid || record.state !== 'completed')
1887
+ return;
1766
1888
  // 只认点名发给的那台设备:广播或其它设备的回复不能改写授权状态。
1767
1889
  // 无 targetDeviceId 的是旧记录,无从校验,放行(调用方已确认 state=completed 且消息匹配)。
1768
1890
  if (record.targetDeviceId && record.responseDeviceId !== record.targetDeviceId) {
@@ -1773,9 +1895,16 @@ export class AUNChannel {
1773
1895
  const grant = parseOwnerDirectoryGrantAbilityResponse(record.responsePayload);
1774
1896
  if (!grant)
1775
1897
  return;
1898
+ const view = await ownerResolver.refresh(this.config.aid, { maxAgeMs: 0, source: 'directory.authorization' });
1899
+ const binding = verifiedContactBinding(this.config.aid, view);
1900
+ if (!binding || senderAid !== binding.owner_aid || grant.owner_aid !== senderAid || grant.grantee_aid !== this.config.aid
1901
+ || grant.relation_version !== binding.relation_version)
1902
+ return;
1776
1903
  const runtime = await this.getOwnerDirectoryRuntime();
1777
1904
  if (!runtime)
1778
1905
  return;
1906
+ if (runtime.ownerAid !== senderAid || !sameContactBinding(binding, currentContactBinding(this.config.aid)))
1907
+ return;
1779
1908
  runtime.cache.saveAuthorization(grant);
1780
1909
  await runtime.cache.handleOwnerChangedEvent(senderAid);
1781
1910
  }
@@ -1845,9 +1974,18 @@ export class AUNChannel {
1845
1974
  logger.warn(`${this.logPrefix()} owner.directory.grant: invalid grant payload (does not match evol-directory-access-v1 contract)`);
1846
1975
  return;
1847
1976
  }
1977
+ const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'directory.grant' });
1978
+ const binding = verifiedContactBinding(selfAid, view);
1979
+ if (!binding || senderAid !== binding.owner_aid || parsed.owner_aid !== senderAid || parsed.grantee_aid !== selfAid
1980
+ || parsed.relation_version !== binding.relation_version) {
1981
+ logger.warn(`${this.logPrefix()} owner.directory.grant ignored: sender or relation binding is not verified`);
1982
+ return;
1983
+ }
1848
1984
  const runtime = await this.getOwnerDirectoryRuntime();
1849
1985
  if (!runtime)
1850
1986
  return;
1987
+ if (runtime.ownerAid !== senderAid || !sameContactBinding(binding, currentContactBinding(selfAid)))
1988
+ return;
1851
1989
  runtime.cache.saveAuthorization(parsed);
1852
1990
  logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}`);
1853
1991
  // 授权被撤销/拒绝时 saveAuthorization 已经清掉凭证和快照,这里无事可做:
@@ -1858,7 +1996,7 @@ export class AUNChannel {
1858
1996
  // 不再等"下一条入站消息"——那条消息可能几小时后才来。
1859
1997
  await runtime.cache.handleOwnerChangedEvent(senderAid);
1860
1998
  try {
1861
- await runtime.cache.processPendingIfNeeded();
1999
+ await runtime.cache.processPendingIfNeeded('grant');
1862
2000
  await runtime.cache.applyFromSharedCache();
1863
2001
  logger.info(`${this.logPrefix()} owner.directory.grant: pulled and applied after authorization (total=${runtime.cache.readSnapshot('contacts')?.total ?? 'none'})`);
1864
2002
  }
@@ -1929,7 +2067,7 @@ export class AUNChannel {
1929
2067
  }
1930
2068
  this.inboundSeenMessages.set(dedupeKey, { seenAt: Date.now(), seq });
1931
2069
  this.appendInboundDedupe(dedupeKey, messageId, kind, seq);
1932
- setTimeout(() => this.inboundSeenMessages.delete(dedupeKey), AUN_INBOUND_DEDUP_TTL_MS);
2070
+ setTimeout(() => this.inboundSeenMessages.delete(dedupeKey), AUN_INBOUND_DEDUP_TTL_MS).unref?.();
1933
2071
  return true;
1934
2072
  }
1935
2073
  inboundDedupeFile() {
@@ -1995,7 +2133,8 @@ export class AUNChannel {
1995
2133
  }
1996
2134
  }
1997
2135
  shouldEncrypt(_peerId) {
1998
- return this.config.defaultEncrypt ?? true;
2136
+ // 默认明文:只有显式 --encrypt 或 daemon.json 配置 aun.defaultEncrypt 才加密。
2137
+ return this.config.defaultEncrypt ?? false;
1999
2138
  }
2000
2139
  /** Effective channel default for callers that must persist a concrete transport choice. */
2001
2140
  getDefaultEncrypt() {
@@ -2213,6 +2352,7 @@ export class AUNChannel {
2213
2352
  this.observerGroupMemberFetches.clear();
2214
2353
  // Clean up existing client if any
2215
2354
  if (this.client) {
2355
+ unregisterPaTeamClient(this.config.aid, this.client);
2216
2356
  ownerResolver.detachClient(this.config.aid, this.client);
2217
2357
  this.trace('OUT', 'client.close', { reason: 'initClient' });
2218
2358
  try {
@@ -2254,6 +2394,7 @@ export class AUNChannel {
2254
2394
  const localConfig = loadAgent(aidName);
2255
2395
  ownerResolver.setAgentConfiguredOwners(aidName, configuredOwnerList(localConfig));
2256
2396
  ownerResolver.attachClient(aidName, client);
2397
+ registerPaTeamClient(aidName, client, store);
2257
2398
  try {
2258
2399
  await this.config.onClientReady?.(client);
2259
2400
  }
@@ -2322,7 +2463,7 @@ export class AUNChannel {
2322
2463
  if (data && typeof data === 'object') {
2323
2464
  const d = data;
2324
2465
  const payloadType = d.payload?.type ?? d.envelope?.type ?? '';
2325
- if (payloadType === 'text') {
2466
+ if (payloadType === 'text' && this.config.pureIdentity) {
2326
2467
  const msgId = d.message_id ?? d.id ?? '';
2327
2468
  const from = d.from ?? d.envelope?.from ?? '';
2328
2469
  const to = d.to ?? d.envelope?.to ?? this.config.aid ?? '';
@@ -2933,6 +3074,178 @@ export class AUNChannel {
2933
3074
  return pathname;
2934
3075
  }
2935
3076
  }
3077
+ ownerDirectoryRelationVersion;
3078
+ /** Returns before any ordinary history, observer, attachment or model side effect. */
3079
+ async handleAppContactInbound(fromAid, payload, messageId, receivedAt, encrypted) {
3080
+ const selfAid = this.config.aid;
3081
+ const value = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : undefined;
3082
+ const type = typeof value?.type === 'string' ? value.type : '';
3083
+ const previous = isolatedContactSource(selfAid, fromAid, messageId);
3084
+ const digest = contactSourceDigest(payload);
3085
+ if (previous && (previous.notified || !previous.reason || contactIntroductionText(payload) === undefined
3086
+ || previous.digest !== digest || !previous.binding || previous.at + CONTACT_EVENT_TTL_MS <= Date.now()))
3087
+ return true;
3088
+ if (previous && !sameContactBinding(previous.binding, currentContactBinding(selfAid)))
3089
+ return true;
3090
+ if (previous && !consumeContactIntroductionBudget(selfAid, fromAid))
3091
+ return true;
3092
+ if (type.startsWith('friend.')) {
3093
+ const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.grant' });
3094
+ const binding = verifiedContactBinding(selfAid, view);
3095
+ if (!binding)
3096
+ return true;
3097
+ const result = executeContactGrant(selfAid, fromAid, payload, encrypted, Date.now(), binding);
3098
+ if (result)
3099
+ await this.sendContentPayload(fromAid, result, {
3100
+ contentKind: 'custom', dedupeKey: `friend-result:${result.owner_aid}:${result.relation_version}:${result.type}:${result.grant_id}:${result.status}:${result.error_code ?? ''}`,
3101
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
3102
+ logText: `[${result.type}]`, ttl: CONTACT_EVENT_TTL_MS,
3103
+ });
3104
+ return true;
3105
+ }
3106
+ // These are protocol envelopes. Their existing handlers retain authentication and permission checks.
3107
+ if (isContactControlPayload(payload))
3108
+ return false;
3109
+ if (type.startsWith('contact.request.'))
3110
+ return true; // Retired App protocol; never create legacy pending.
3111
+ if (type === 'text' && typeof value?.text === 'string' && /^\s*\/bind(?:\s|$)/i.test(value.text))
3112
+ return false;
3113
+ // An already isolated source never becomes an ordinary message after approval.
3114
+ await ownerResolver.refresh(selfAid, { maxAgeMs: 30_000, allowTransient: true, source: 'contact.inbound' });
3115
+ await this.getOwnerDirectoryRuntime();
3116
+ await this.settleOwnerDirectoryBeforeTurn();
3117
+ const decision = evaluateAppContactAdmission(selfAid, fromAid);
3118
+ logger.debug(`${this.logPrefix()} Contact admission: mid=${messageId} from=${fromAid} allow=${decision.allow} reason=${decision.reason} elapsedMs=${Math.max(0, Date.now() - receivedAt)}`);
3119
+ if (decision.allow && !previous)
3120
+ return false;
3121
+ const introduction = contactIntroductionText(payload);
3122
+ const binding = currentContactBinding(selfAid);
3123
+ const reason = previous?.reason ?? decision.reason;
3124
+ if (previous && !sameContactBinding(previous.binding, binding))
3125
+ return true;
3126
+ let source = previous ?? { at: receivedAt, digest, binding,
3127
+ ...(reason === 'not_in_contacts' || reason === 'scope_extension' ? { reason } : {}) };
3128
+ // Write the tombstone before budgets, receipt capacity checks or any delivery.
3129
+ if (!previous)
3130
+ source = saveIsolatedContactSource(selfAid, fromAid, messageId, source);
3131
+ if (source.notified || source.digest !== digest || !sameContactBinding(source.binding ?? {}, binding))
3132
+ return true;
3133
+ const eventReason = source.reason;
3134
+ if (binding && introduction !== undefined && (eventReason === 'not_in_contacts' || eventReason === 'scope_extension')
3135
+ && (previous || consumeContactIntroductionBudget(selfAid, fromAid))) {
3136
+ const request = buildContactRequest(binding, fromAid, messageId, source.at, introduction, eventReason);
3137
+ const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
3138
+ if (remainingTtl <= 0)
3139
+ return true;
3140
+ const sent = await this.sendContentPayload(binding.owner_aid, request, {
3141
+ contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1]',
3142
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
3143
+ ttl: remainingTtl,
3144
+ });
3145
+ if (sent.messageId || sent.queued)
3146
+ saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notified: true });
3147
+ logger.info(`${this.logPrefix()} Contact introduction isolated: event=${request.event_id} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
3148
+ }
3149
+ else {
3150
+ logger.info(`${this.logPrefix()} Contact message isolated: mid=${messageId} reason=${decision.reason}`);
3151
+ }
3152
+ return true;
3153
+ }
3154
+ /** friend.invite.v1 never reaches the model, ordinary history, attachments or observers. */
3155
+ async handleFriendInvite(fromAid, payload, messageId, receivedAt, encrypted, seq) {
3156
+ const selfAid = this.config.aid;
3157
+ this.appendInboundPayloadJsonl(fromAid, fromAid, messageId, encrypted, false, classifyAunPayloadForLog(payload), undefined, receivedAt, seq);
3158
+ const invite = parseFriendInvite(payload, fromAid, selfAid);
3159
+ if (!invite || !encrypted) {
3160
+ logger.info(`${this.logPrefix()} Friend invite ignored: code=INVALID_FRIEND_INVITE from=${fromAid} mid=${messageId} encrypted=${encrypted}`);
3161
+ return;
3162
+ }
3163
+ try {
3164
+ const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.invite' });
3165
+ const binding = verifiedContactBinding(selfAid, view);
3166
+ if (!binding) {
3167
+ // The App keeps the invite queued and retries; nothing is decided without a verified relation.
3168
+ logger.info(`${this.logPrefix()} Friend invite deferred: code=CONTACT_OWNERSHIP_UNAVAILABLE invite=${invite.invite_id} from=${fromAid}`);
3169
+ return;
3170
+ }
3171
+ const recorded = recordedFriendInviteDecision(selfAid, binding, invite);
3172
+ if (recorded.conflict) {
3173
+ logger.warn(`${this.logPrefix()} Friend invite ignored: code=FRIEND_INVITE_CONFLICT invite=${invite.invite_id} from=${fromAid}`);
3174
+ return;
3175
+ }
3176
+ if (recorded.decision) {
3177
+ // Re-delivery of a decided invite resends the original result; the welcome is never repeated.
3178
+ await this.sendFriendInviteResult(invite, recorded.decision, messageId);
3179
+ return;
3180
+ }
3181
+ if (invite.expires_at_ms <= Date.now()) {
3182
+ await this.sendFriendInviteResult(invite, decideFriendInvite(selfAid, binding, invite, 'expired'), messageId);
3183
+ return;
3184
+ }
3185
+ await this.getOwnerDirectoryRuntime();
3186
+ await this.settleOwnerDirectoryBeforeTurn();
3187
+ const verdict = await this.judgeFriendInvite(selfAid, fromAid);
3188
+ logger.info(`${this.logPrefix()} Friend invite: invite=${invite.invite_id} from=${fromAid} verdict=${verdict.kind} reason=${verdict.reason}`);
3189
+ if (verdict.kind === 'accept') {
3190
+ const record = decideFriendInvite(selfAid, binding, invite, 'accepted');
3191
+ await this.sendFriendInviteResult(invite, record, messageId);
3192
+ if (!record.welcomed)
3193
+ await this.sendFriendInviteWelcome(invite, binding);
3194
+ return;
3195
+ }
3196
+ // silent: blocked or Owner-denied (the applicant is never told), or state unavailable (the App retries later).
3197
+ if (verdict.kind === 'silent')
3198
+ return;
3199
+ // The Owner decides: not admitted by policy, or only a temporary grant (not a permanent relation).
3200
+ if (!consumeContactIntroductionBudget(selfAid, fromAid)) {
3201
+ logger.info(`${this.logPrefix()} Friend invite dropped: code=INTRODUCTION_BUDGET invite=${invite.invite_id} from=${fromAid}`);
3202
+ return;
3203
+ }
3204
+ const reason = verdict.reason === 'scope_extension' ? 'scope_extension' : 'not_in_contacts';
3205
+ const request = {
3206
+ ...buildContactRequest(binding, fromAid, messageId, receivedAt, invite.introduction, reason, `invite:${invite.invite_id}`),
3207
+ invite: { type: FRIEND_INVITE_TYPE, schema_version: 1, ...invite },
3208
+ };
3209
+ const remainingTtl = Math.min(CONTACT_EVENT_TTL_MS, invite.expires_at_ms - Date.now());
3210
+ const sent = await this.sendContentPayload(binding.owner_aid, request, {
3211
+ contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 invite]',
3212
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } }, ttl: remainingTtl,
3213
+ });
3214
+ 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'}`);
3215
+ }
3216
+ catch (error) {
3217
+ logger.warn(`${this.logPrefix()} Friend invite isolated: code=CONTACT_STATE_UNAVAILABLE invite=${invite.invite_id} error=${error instanceof Error ? error.message : String(error)}`);
3218
+ }
3219
+ }
3220
+ /**
3221
+ * Friend invites use the same app-v1 decision as ordinary private messages.
3222
+ */
3223
+ async judgeFriendInvite(selfAid, applicantAid) {
3224
+ const decision = evaluateAppContactAdmission(selfAid, applicantAid);
3225
+ if (decision.allow)
3226
+ return { kind: decision.reason === 'temporary' ? 'owner' : 'accept', reason: decision.reason };
3227
+ return { kind: decision.reason === 'blocked' || decision.reason === 'unavailable' ? 'silent' : 'owner', reason: decision.reason };
3228
+ }
3229
+ async sendFriendInviteResult(invite, decision, inboundMessageId) {
3230
+ const result = buildFriendInviteResult(this.config.aid, invite, decision);
3231
+ const sent = await this.sendContentPayload(invite.applicant_aid, result, {
3232
+ contentKind: 'custom', dedupeKey: `friend-invite-result:${decision.decision_id}:${inboundMessageId}`,
3233
+ logText: `[${FRIEND_INVITE_RESULT_TYPE} ${decision.status}]`,
3234
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
3235
+ ttl: Math.max(60_000, invite.expires_at_ms - Date.now()),
3236
+ });
3237
+ 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'}`);
3238
+ return sent;
3239
+ }
3240
+ async sendFriendInviteWelcome(invite, binding) {
3241
+ const text = friendInviteWelcomeText(this._selfName, this.config.aid);
3242
+ const sent = await this.sendContentPayload(invite.applicant_aid, { type: 'text', text }, {
3243
+ contentKind: 'text', dedupeKey: `friend-invite-welcome:${binding.relation_version}:${invite.invite_id}`, logText: text,
3244
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
3245
+ });
3246
+ if (sent.messageId || sent.queued)
3247
+ markFriendInviteWelcomed(this.config.aid, binding, invite.invite_id);
3248
+ }
2936
3249
  async handleIncomingPrivateMessage(data) {
2937
3250
  if (!data || typeof data !== 'object')
2938
3251
  return;
@@ -2959,10 +3272,45 @@ export class AUNChannel {
2959
3272
  }
2960
3273
  return;
2961
3274
  }
2962
- if (!this.claimInboundMessage('private', messageId, seq))
3275
+ const appOwned = !this.config.pureIdentity;
3276
+ if (!appOwned && !this.claimInboundMessage('private', messageId, seq))
2963
3277
  return;
2964
3278
  const protectedHeaders = verifiedProtectedHeaders(msg, env);
2965
3279
  const payload = msg.payload ?? '';
3280
+ // friend.invite.v1(App 主动加好友)不依赖 app-v1 灰度:按 Owner 准入策略已放行的申请人
3281
+ // 由本 Agent 直接回 accepted 并发欢迎语;其余转交 Owner。不进 Agent、不转 observer。
3282
+ if (!this.config.pureIdentity && isFriendInvitePayload(payload)) {
3283
+ if (appOwned && !this.claimInboundMessage('private', messageId, seq))
3284
+ return;
3285
+ await this.handleFriendInvite(fromAid, payload, messageId, receivedAt, !!env.encrypted, seq);
3286
+ return;
3287
+ }
3288
+ const contactControl = appOwned && isContactControlPayload(payload);
3289
+ if (appOwned) {
3290
+ let handled;
3291
+ try {
3292
+ handled = await this.handleAppContactInbound(fromAid, payload, messageId, receivedAt, !!env.encrypted);
3293
+ }
3294
+ catch {
3295
+ // Storage/lock/capacity/conflict failures remain isolated; log metadata only.
3296
+ try {
3297
+ if (!contactControl && !isolatedContactSource(this.config.aid, fromAid, messageId))
3298
+ saveIsolatedContactSource(this.config.aid, fromAid, messageId, { at: receivedAt, digest: contactSourceDigest(payload) });
3299
+ }
3300
+ catch { /* The isolation barrier preserves fail-closed behavior on storage failure. */ }
3301
+ if (Date.now() - this.contactAdmissionFailureLogAt >= 60_000) {
3302
+ this.contactAdmissionFailureLogAt = Date.now();
3303
+ logger.warn(`${this.logPrefix()} Contact admission isolated: code=CONTACT_STATE_UNAVAILABLE`);
3304
+ }
3305
+ return;
3306
+ }
3307
+ if (handled)
3308
+ return;
3309
+ if (!this.claimInboundMessage('private', messageId, seq))
3310
+ return;
3311
+ if (contactControl)
3312
+ this.rememberContactControlRequest(fromAid, payload, messageId, menuSenderDeviceId(msg.sender_device_id));
3313
+ }
2966
3314
  const responseRecord = getAunRequestRegistry().resolveIncoming({
2967
3315
  selfAid: this._aid || this.config.aid,
2968
3316
  fromAid,
@@ -3019,7 +3367,7 @@ export class AUNChannel {
3019
3367
  // forwardInbound 内部排除 self-echo 与 from-owner。
3020
3368
  // 显式排除 observer.inject:它是 owner 对本 agent 的控制消息,不应镜像给观察者
3021
3369
  // (即便日后 from-owner 排除规则调整,也不会泄漏)。
3022
- if (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject')) {
3370
+ if (!contactControl && (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject'))) {
3023
3371
  void this.forwardInbound(msg);
3024
3372
  }
3025
3373
  if (inboundType === 'observer.inject.status' || inboundType === 'observer.inject.ack') {
@@ -3047,13 +3395,14 @@ export class AUNChannel {
3047
3395
  mentions.push({ aid: this._aid });
3048
3396
  }
3049
3397
  // Process attachments (顶层 + 嵌套在 merge.items / quote.quote 中的)
3050
- const { finalText, images: inboundImages } = await this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' });
3398
+ const { finalText, images: inboundImages } = contactControl ? { finalText: text, images: [] } : await this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' });
3051
3399
  // 私聊 channelId = 对端 AID(不再读 payload.chat_id 含 device 三段式)
3052
3400
  // device_id 仅 SDK 内部多实例去重用,evolcore session 层面跨端共享会话
3053
3401
  const chatId = fromAid;
3054
3402
  // 解析对端身份(30天缓存)
3055
3403
  const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
3056
3404
  const peerIdentity = await PeerIdentityCache.resolve('aun', fromAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
3405
+ await preparePaTeamQualification(this.config.aid, fromAid);
3057
3406
  const shortAid = this.getShortAid(fromAid);
3058
3407
  const displayName = peerIdentity.name || shortAid;
3059
3408
  // 详细 dispatch 决策日志:记录消息为何被路由到 agent
@@ -4395,6 +4744,7 @@ export class AUNChannel {
4395
4744
  }
4396
4745
  // Force close SDK client,中断它内部的重连循环
4397
4746
  if (this.client) {
4747
+ unregisterPaTeamClient(this.config.aid, this.client);
4398
4748
  ownerResolver.detachClient(this.config.aid, this.client);
4399
4749
  this.trace('OUT', 'client.close', { reason: `takeover_${reason}` });
4400
4750
  this.client.close().catch(() => { });
@@ -4421,6 +4771,7 @@ export class AUNChannel {
4421
4771
  logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) succeeded but generation stale, closing stale client`);
4422
4772
  this.stopOwnerDirectoryRefresh();
4423
4773
  if (this.client) {
4774
+ unregisterPaTeamClient(this.config.aid, this.client);
4424
4775
  ownerResolver.detachClient(this.config.aid, this.client);
4425
4776
  this.client.close().catch(() => { });
4426
4777
  this.client = null;
@@ -4932,8 +5283,24 @@ export class AUNChannel {
4932
5283
  this.groupInviteDelivered?.(entry.postSend.requestId, messageId);
4933
5284
  }
4934
5285
  }
5286
+ appContactOutboundBlock(channelId, delivery, payload, params) {
5287
+ if (delivery.chatType === 'group' || this.config.pureIdentity
5288
+ || this.hasContactControlPermit(channelId, payload, params))
5289
+ return undefined;
5290
+ const decision = evaluateAppContactAdmission(this.config.aid, channelId);
5291
+ if (params?.encrypt === true && params?.rawPayload === true && parseFriendInvite(payload, this.config.aid, channelId)
5292
+ && decision.reason === 'not_in_contacts')
5293
+ return undefined;
5294
+ if (decision.allow)
5295
+ return undefined;
5296
+ return { status: decision.reason === 'unavailable' ? 'retry' : 'permanent',
5297
+ code: 'CONTACT_DENIED', error: `联系人准入未通过:${decision.reason}` };
5298
+ }
4935
5299
  async sendAunPayload(channelId, payload, context, label) {
4936
5300
  const delivery = this.requireDelivery(channelId, context);
5301
+ const blocked = this.appContactOutboundBlock(channelId, delivery, payload);
5302
+ if (blocked)
5303
+ return { ok: false, ...blocked };
4937
5304
  let normalizedPayload;
4938
5305
  try {
4939
5306
  normalizedPayload = this.normalizeAunPayloadMentions(payload);
@@ -4967,7 +5334,8 @@ export class AUNChannel {
4967
5334
  if (payloadWithCausationRef.thread_id === '')
4968
5335
  delete payloadWithCausationRef.thread_id;
4969
5336
  // Truncate payload if too large (AUN SDK limit: 1MB)
4970
- const truncatedPayload = this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
5337
+ const friendPayload = typeof payload.type === 'string' && payload.type.startsWith('friend.');
5338
+ const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
4971
5339
  const params = { payload: truncatedPayload, encrypt };
4972
5340
  const isMenuPayload = typeof truncatedPayload.type === 'string' && truncatedPayload.type.startsWith('menu.');
4973
5341
  if (!isGroup && ['menu.response', 'menu.event'].includes(truncatedPayload.type))
@@ -4978,15 +5346,14 @@ export class AUNChannel {
4978
5346
  if (isMenuPayload && context?.metadata?.menuClientVolatileV1 === true) {
4979
5347
  params.menu_client_volatile_v1 = true;
4980
5348
  }
4981
- if (isMenuPayload && encrypt && context?.metadata?.protectedHeaders) {
4982
- params.protected_headers = context.metadata.protectedHeaders;
4983
- }
5349
+ if (encrypt)
5350
+ params.protected_headers = aunProtectedHeaders(context);
4984
5351
  if (isGroup)
4985
5352
  params.group_id = delivery.groupId;
4986
5353
  else
4987
5354
  params.to = targetAid;
4988
5355
  const callOnce = async (sendParams, fallback) => {
4989
- const result = fallback
5356
+ const result = fallback || friendPayload
4990
5357
  ? await this.callClient(method, sendParams)
4991
5358
  : await this.callAndTrace(method, sendParams);
4992
5359
  const mid = this.messageIdFromSendResult(result);
@@ -5001,10 +5368,11 @@ export class AUNChannel {
5001
5368
  return await callOnce(params, false);
5002
5369
  }
5003
5370
  catch (e) {
5004
- if (encrypt && e instanceof E2EEError && !isMenuPayload) {
5371
+ if (encrypt && e instanceof E2EEError && !isMenuPayload && !friendPayload) {
5005
5372
  this.peerE2ee.set(encryptTarget, { ok: false, ts: Date.now() });
5006
5373
  logger.warn(`${this.logPrefix()} E2EE ${label} send failed to ${channelId}, retrying plaintext: ${e}`);
5007
5374
  const fallbackParams = { ...params, encrypt: false };
5375
+ delete fallbackParams.protected_headers;
5008
5376
  try {
5009
5377
  this.trace('OUT', `${method}.${label}.fallback`, fallbackParams);
5010
5378
  const sent = await callOnce(fallbackParams, true);
@@ -5052,6 +5420,10 @@ export class AUNChannel {
5052
5420
  };
5053
5421
  }
5054
5422
  recordDurableOutbound(channelId, payload, messageId, encrypt, context, isGroup, contentKind, logText, result, statsContext) {
5423
+ if (typeof payload.type === 'string' && payload.type.startsWith('friend.')) {
5424
+ logger.info(`${this.logPrefix()} Contact control transport accepted: type=${payload.type} mid=${messageId}`);
5425
+ return;
5426
+ }
5055
5427
  const causation = normalizeCausation(context?.metadata?.causation);
5056
5428
  if (!isGroup && causation)
5057
5429
  registerAunCausation(messageId, this.config.aid, channelId, causation);
@@ -5125,6 +5497,7 @@ export class AUNChannel {
5125
5497
  delivery,
5126
5498
  dedupeKey: opts.dedupeKey,
5127
5499
  critical: opts.critical,
5500
+ processScoped: context?.metadata?.processScopedDelivery === true,
5128
5501
  type: 'payload',
5129
5502
  contentKind: opts.contentKind,
5130
5503
  payload: finalPayload,
@@ -5433,6 +5806,48 @@ export class AUNChannel {
5433
5806
  this.sentCount.set(turnKey, seqInTurn);
5434
5807
  return seqInTurn;
5435
5808
  }
5809
+ /** An unadmitted outbound text becomes an Owner request, never a send to the peer. */
5810
+ async requestOutboundContact(args) {
5811
+ const selfAid = this.config.aid;
5812
+ const binding = currentContactBinding(selfAid);
5813
+ if (!binding) {
5814
+ return { ok: false, code: 'CONTACT_DIRECTORY_UNAVAILABLE', error: '本端 Owner 关系不可用,未发送申请或原消息' };
5815
+ }
5816
+ const decision = evaluateAppContactAdmission(selfAid, args.to);
5817
+ if (decision.allow || (decision.reason !== 'not_in_contacts' && decision.reason !== 'scope_extension')) {
5818
+ return { ok: false, code: 'CONTACT_DENIED', error: `联系人状态不允许提交申请:${decision.reason};原消息未发送` };
5819
+ }
5820
+ const text = contactIntroductionText(args.payload);
5821
+ if (text === undefined) {
5822
+ return { ok: false, code: 'CONTACT_DENIED', error: '只有纯文本可以向本端 Owner 提交联系申请;原消息未发送' };
5823
+ }
5824
+ if (!consumeContactIntroductionBudget(selfAid, `outbound:${args.to}`)) {
5825
+ return { ok: false, code: 'CONTACT_INTRODUCTION_RATE_LIMIT', error: '联系申请过于频繁,请稍后重试;原消息未发送' };
5826
+ }
5827
+ const request = {
5828
+ ...buildContactRequest(binding, args.to, args.sourceMessageId, Date.now(), `申请联系 ${args.to}。以下为本端拟发送的内容,尚未发给对方:\n${text}`, decision.reason),
5829
+ direction: 'outbound',
5830
+ };
5831
+ const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
5832
+ if (remainingTtl <= 0) {
5833
+ return { ok: false, code: 'CONTACT_REQUEST_EXPIRED', error: '联系申请已过期,未重新提交;原消息未发送' };
5834
+ }
5835
+ const sent = await this.sendContentPayload(binding.owner_aid, request, {
5836
+ contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 outbound]',
5837
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
5838
+ ttl: remainingTtl,
5839
+ });
5840
+ if (!sent.messageId && !sent.queued) {
5841
+ return { ok: false, code: sent.code ?? 'CONTACT_OWNER_REQUEST_FAILED',
5842
+ error: `向本端 Owner 提交联系申请失败:${sent.error ?? '未获得发送或排队回执'};原消息未发送` };
5843
+ }
5844
+ return { ok: true, receipt: {
5845
+ event_id: request.event_id, owner_aid: binding.owner_aid, target_aid: args.to,
5846
+ status: sent.messageId ? 'sent' : 'queued',
5847
+ ...(sent.messageId ? { message_id: sent.messageId } : {}),
5848
+ ...(sent.outboxId ? { outbox_id: sent.outboxId } : {}),
5849
+ } };
5850
+ }
5436
5851
  async sendDaemonMsg(args) {
5437
5852
  try {
5438
5853
  resolveAunSendDevice(args.deviceId, 'msg', args.payload);
@@ -5476,6 +5891,9 @@ export class AUNChannel {
5476
5891
  code: 'INVALID_REQUEST_TTL',
5477
5892
  };
5478
5893
  }
5894
+ const contactBlock = this.appContactOutboundBlock(args.to, { chatType: 'private' }, finalPayload, { encrypt: args.encrypt, rawPayload: preserveRawPayload });
5895
+ if (contactBlock)
5896
+ return { ok: false, code: contactBlock.code, error: contactBlock.error };
5479
5897
  if (preserveRawPayload && jsonUtf8Size(finalPayload) > AUN_MAX_PAYLOAD_SIZE) {
5480
5898
  return {
5481
5899
  ok: false,
@@ -5493,6 +5911,7 @@ export class AUNChannel {
5493
5911
  let peerRole = null;
5494
5912
  try {
5495
5913
  const { resolvePeerRoleDetail } = await import('../config/peer-role-resolver.js');
5914
+ await preparePaTeamQualification(this.config.aid, args.to);
5496
5915
  peerRole = resolvePeerRoleDetail({
5497
5916
  selfAid: this.config.aid,
5498
5917
  channelKey: `aun#${this.config.aid}#main`,
@@ -5537,6 +5956,7 @@ export class AUNChannel {
5537
5956
  encrypt,
5538
5957
  ...(args.deviceId ? { device_id: args.deviceId } : {}),
5539
5958
  ...(args.ttl !== undefined ? { ttl: args.ttl } : {}),
5959
+ ...(encrypt ? { protected_headers: aunProtectedHeaders({ model: args.model }) } : {}),
5540
5960
  };
5541
5961
  try {
5542
5962
  const result = await this.callAndTrace('message.send', sendParams);
@@ -5598,6 +6018,29 @@ export class AUNChannel {
5598
6018
  };
5599
6019
  }
5600
6020
  }
6021
+ /**
6022
+ * Send an online/offline system notice to the bound Owner as an AUN volatile
6023
+ * message: nothing is persisted in the outbox or the local message log, and
6024
+ * the gateway drops it after the TTL. Best-effort by design.
6025
+ */
6026
+ async sendLifecycleNotice(args) {
6027
+ const requested = Math.trunc(args.ttlSeconds ?? DEFAULT_LIFECYCLE_NOTICE_TTL_SECONDS);
6028
+ const ttl = Number.isFinite(requested)
6029
+ ? Math.min(MAX_AUN_VOLATILE_TTL_SECONDS, Math.max(1, requested))
6030
+ : DEFAULT_LIFECYCLE_NOTICE_TTL_SECONDS;
6031
+ return this.sendDaemonMsg({
6032
+ to: args.to,
6033
+ payload: buildAunLifecycleNoticePayload({
6034
+ selfAid: this.getAid() || this.config.aid,
6035
+ agentName: args.agentName,
6036
+ online: args.online,
6037
+ sentAt: args.now?.() ?? Date.now(),
6038
+ }),
6039
+ // Preserve the notice verbatim: no session state, topic name or mentions.
6040
+ rawPayload: true,
6041
+ ttl,
6042
+ });
6043
+ }
5601
6044
  /** Public contracts use this AID's existing authenticated storage connection. */
5602
6045
  get abilityPublisherAid() { return this._aid || this.config.aid; }
5603
6046
  async publishAbilityDocuments(documents, expectedIndexes = []) {
@@ -5669,6 +6112,7 @@ export class AUNChannel {
5669
6112
  group_id: args.groupId,
5670
6113
  payload: this.truncatePayloadIfNeeded(finalPayload, 'group-send-ipc'),
5671
6114
  encrypt,
6115
+ ...(encrypt ? { protected_headers: aunProtectedHeaders({ model: args.model }) } : {}),
5672
6116
  });
5673
6117
  const messageId = this.messageIdFromSendResult(result);
5674
6118
  if (!messageId) {
@@ -5787,6 +6231,11 @@ export class AUNChannel {
5787
6231
  const finalText = entry.text;
5788
6232
  const delivery = this.requirePersistedDelivery(channelId, entry.delivery);
5789
6233
  const context = this.withDelivery(entry.context, delivery);
6234
+ if (!entry.deliveryReceipt) {
6235
+ const blocked = this.appContactOutboundBlock(channelId, delivery, { type: 'text', text: entry.text });
6236
+ if (blocked)
6237
+ return blocked;
6238
+ }
5790
6239
  const operationId = entry.dedupeKey
5791
6240
  || (typeof context?.metadata?.operationId === 'string' ? context.metadata.operationId : undefined);
5792
6241
  if (operationId) {
@@ -5872,6 +6321,8 @@ export class AUNChannel {
5872
6321
  ? !!(context.metadata.encrypted)
5873
6322
  : this.shouldEncrypt(encryptTarget);
5874
6323
  const params = { payload, encrypt };
6324
+ if (encrypt)
6325
+ params.protected_headers = aunProtectedHeaders(context);
5875
6326
  if (context?.metadata?.persistRequired === true)
5876
6327
  params.persist_required = true;
5877
6328
  let acceptedMessageId;
@@ -5952,6 +6403,7 @@ export class AUNChannel {
5952
6403
  this.peerE2ee.set(encryptTarget, { ok: false, ts: Date.now() });
5953
6404
  logger.warn(`${this.logPrefix()} E2EE send failed to ${channelId}, retrying plaintext: ${e}`);
5954
6405
  params.encrypt = false;
6406
+ delete params.protected_headers;
5955
6407
  try {
5956
6408
  if (isGroup) {
5957
6409
  this.trace('OUT', 'group.send.fallback', params);
@@ -6053,6 +6505,18 @@ export class AUNChannel {
6053
6505
  }
6054
6506
  }
6055
6507
  async deliverPayloadEntry(entry) {
6508
+ if (!entry.deliveryReceipt && typeof entry.payload?.type === 'string' && entry.payload.type.startsWith('friend.')) {
6509
+ const selfAid = this.config.aid;
6510
+ const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.outbox' });
6511
+ const binding = verifiedContactBinding(selfAid, view);
6512
+ if (!binding)
6513
+ return { ok: false, status: 'retry', code: 'CONTACT_OWNERSHIP_UNAVAILABLE', error: 'current Owner relation could not be verified' };
6514
+ if (!friendPayloadRouteValid(entry.payload, entry.channelId, true, binding)) {
6515
+ return { ok: false, status: 'permanent', code: 'CONTACT_OWNERSHIP_CHANGED', error: 'contact event no longer belongs to the current Owner relation' };
6516
+ }
6517
+ // E2EE is mandatory even for a recovered queue entry.
6518
+ entry.context = { ...entry.context, metadata: { ...entry.context?.metadata, encrypted: true } };
6519
+ }
6056
6520
  const interactionId = entry.postSend?.type === 'register_interaction_card'
6057
6521
  ? entry.postSend.requestId
6058
6522
  : undefined;
@@ -6149,6 +6613,8 @@ export class AUNChannel {
6149
6613
  }
6150
6614
  /** 有效会话正文写入 messages.jsonl(message.send/group.send 成功后调用)。 */
6151
6615
  appendOutboundJsonl(channelId, descriptor) {
6616
+ if (descriptor.payloadType?.startsWith('friend.'))
6617
+ return;
6152
6618
  const operationId = typeof descriptor.context?.metadata?.operationId === 'string'
6153
6619
  ? descriptor.context.metadata.operationId
6154
6620
  : undefined;
@@ -6233,6 +6699,7 @@ export class AUNChannel {
6233
6699
  context: { type: 'task', id: taskId },
6234
6700
  payload: thoughtPayload,
6235
6701
  encrypt,
6702
+ ...(encrypt ? { protected_headers: aunProtectedHeaders(context) } : {}),
6236
6703
  };
6237
6704
  try {
6238
6705
  let thoughtPayload = params.payload;
@@ -6348,18 +6815,8 @@ export class AUNChannel {
6348
6815
  if (isMenuPayload && context?.metadata?.menuClientVolatileV1 === true) {
6349
6816
  params.menu_client_volatile_v1 = true;
6350
6817
  }
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
- }
6818
+ if (encrypt)
6819
+ params.protected_headers = aunProtectedHeaders(context);
6363
6820
  try {
6364
6821
  if (isGroup) {
6365
6822
  params.group_id = delivery.groupId;
@@ -6563,6 +7020,11 @@ export class AUNChannel {
6563
7020
  return imagePayload;
6564
7021
  }
6565
7022
  async deliverImageEntry(entry) {
7023
+ if (!entry.deliveryReceipt) {
7024
+ const blocked = this.appContactOutboundBlock(entry.channelId, this.requirePersistedDelivery(entry.channelId, entry.delivery), { type: 'image' });
7025
+ if (blocked)
7026
+ return blocked;
7027
+ }
6566
7028
  const image = entry.image;
6567
7029
  if (!image || typeof image.dataBase64 !== 'string') {
6568
7030
  logger.warn(`${this.logPrefix()} deliverImageEntry: missing image data (outbox id=${entry.id})`);
@@ -6609,6 +7071,11 @@ export class AUNChannel {
6609
7071
  }
6610
7072
  }
6611
7073
  async deliverFileEntry(entry) {
7074
+ if (!entry.deliveryReceipt) {
7075
+ const blocked = this.appContactOutboundBlock(entry.channelId, this.requirePersistedDelivery(entry.channelId, entry.delivery), { type: 'file' });
7076
+ if (blocked)
7077
+ return blocked;
7078
+ }
6612
7079
  const channelId = entry.channelId;
6613
7080
  if (typeof entry.filePath !== 'string' || !entry.filePath.trim()) {
6614
7081
  logger.warn(`${this.logPrefix()} deliverFileEntry: missing file path (outbox id=${entry.id})`);
@@ -6663,6 +7130,8 @@ export class AUNChannel {
6663
7130
  ? !!(context.metadata.encrypted)
6664
7131
  : this.shouldEncrypt(encryptTarget);
6665
7132
  const params = { payload: filePayload, encrypt };
7133
+ if (encrypt)
7134
+ params.protected_headers = aunProtectedHeaders(context);
6666
7135
  let sendResult = null;
6667
7136
  let sentMid = null;
6668
7137
  try {
@@ -6701,6 +7170,7 @@ export class AUNChannel {
6701
7170
  this.peerE2ee.set(encryptTarget, { ok: false, ts: Date.now() });
6702
7171
  logger.warn(`${this.logPrefix()} E2EE sendFile failed to ${channelId}, retrying plaintext: ${sendErr}`);
6703
7172
  params.encrypt = false;
7173
+ delete params.protected_headers;
6704
7174
  if (isGroup) {
6705
7175
  this.trace('OUT', 'group.send.file.fallback', params);
6706
7176
  const result = await this.callClient('group.send', params);
@@ -7012,8 +7482,10 @@ export class AUNChannel {
7012
7482
  async disconnect() {
7013
7483
  this.stopOwnerDirectoryRefresh();
7014
7484
  this.configuredOwnerBindEpoch++;
7015
- if (this.client)
7485
+ if (this.client) {
7486
+ unregisterPaTeamClient(this.config.aid, this.client);
7016
7487
  ownerResolver.detachClient(this.config.aid, this.client);
7488
+ }
7017
7489
  this.managedMenuClient.close();
7018
7490
  this.intentionalDisconnect = true;
7019
7491
  if (this.reconnectTimer) {
@@ -7474,7 +7946,7 @@ export class AUNChannelPlugin {
7474
7946
  await channel.sendThought(channelId, envelope.taskId, aunPayload, replyCtx);
7475
7947
  }
7476
7948
  else {
7477
- // Interactive activities are reliable structured payloads;
7949
+ // Interactive and PA activities are reliable structured payloads;
7478
7950
  // sendReliableStructured internally selects the activity
7479
7951
  // outbox queue while preserving the common delivery contract.
7480
7952
  const result = await channel.sendReliableStructured(channelId, aunPayload, replyCtx, channel.activityLogText(item));