evolcore 0.0.40 → 0.0.41-test.1

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 (226) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/baseagent-availability.js +1 -1
  5. package/dist/agents/baseagent.js +20 -43
  6. package/dist/agents/claude-runner.js +197 -197
  7. package/dist/agents/codex-runner.js +535 -259
  8. package/dist/agents/ecagent-runner.js +31 -12
  9. package/dist/agents/gemini-runner.js +27 -7
  10. package/dist/agents/runner-types.js +11 -3
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/group/fs-download.js +39 -0
  14. package/dist/aun/group/identity.js +36 -13
  15. package/dist/aun/group/operations.js +5 -0
  16. package/dist/aun/msg/managed-operation.js +72 -11
  17. package/dist/aun/msg/p2p.js +32 -7
  18. package/dist/aun/service-proxy.js +36 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +367 -24
  22. package/dist/channels/daemon.js +39 -5
  23. package/dist/cli/agent-command.js +2 -0
  24. package/dist/cli/agent-create.js +98 -19
  25. package/dist/cli/agent.js +10 -3
  26. package/dist/cli/aun-commands.js +85 -41
  27. package/dist/cli/daemon-commands.js +678 -688
  28. package/dist/cli/fs-command.js +64 -2
  29. package/dist/cli/index.js +48 -4
  30. package/dist/cli/managed-command-guard.js +4 -0
  31. package/dist/cli/model.js +40 -40
  32. package/dist/cli/proxy-command.js +92 -0
  33. package/dist/cli/restart-monitor.js +17 -0
  34. package/dist/cli/role.js +85 -0
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/trigger-command.js +2 -2
  38. package/dist/config/access-policy.js +8 -1
  39. package/dist/config/boot-log.js +38 -1
  40. package/dist/config/config-field-policy.js +5 -32
  41. package/dist/config/config-manager.js +46 -39
  42. package/dist/config/config-operation-service.js +8 -11
  43. package/dist/config/contact-book-store.js +47 -21
  44. package/dist/config/contact-book.js +18 -12
  45. package/dist/config/contact-operation-service.js +3 -4
  46. package/dist/config/contact-request-service.js +11 -0
  47. package/dist/config/daemon-services.js +11 -0
  48. package/dist/config/gateway-config.js +89 -595
  49. package/dist/config/peer-role-resolver.js +15 -11
  50. package/dist/config/providers-config.js +12 -7
  51. package/dist/config/providers-import.js +3 -21
  52. package/dist/config/resolved-config-op.js +3 -0
  53. package/dist/config/role-command-service.js +166 -0
  54. package/dist/config/role-request-service.js +193 -0
  55. package/dist/config/schema-migration.js +686 -25
  56. package/dist/config-store.js +79 -3
  57. package/dist/contracts/ecweb-instance.js +41 -0
  58. package/dist/contracts/ecweb-service-protocol.js +3 -1
  59. package/dist/core/agent-application-service.js +11 -1
  60. package/dist/core/agent-ipc-registration.js +4 -0
  61. package/dist/core/agent-runtime.js +1 -1
  62. package/dist/core/auth/agent-delegation.js +82 -6
  63. package/dist/core/auth/auth-gateway.js +1 -1
  64. package/dist/core/auth/authorization-audit.js +37 -9
  65. package/dist/core/auth/delegation-authorization.js +3 -1
  66. package/dist/core/auth/operation-authorizer.js +15 -0
  67. package/dist/core/auth/operation-catalog.js +39 -6
  68. package/dist/core/command/agent-control.js +94 -19
  69. package/dist/core/command/agent-storage-menu.js +5 -3
  70. package/dist/core/command/cli-intent-parser.js +2 -1
  71. package/dist/core/command/command-handler.js +105 -145
  72. package/dist/core/command/connect-menu.js +31 -2
  73. package/dist/core/command/data-root-resolver.js +5 -4
  74. package/dist/core/command/memory-slash.js +16 -8
  75. package/dist/core/command/menu-catalog.js +6 -6
  76. package/dist/core/command/menu-handler.js +87 -163
  77. package/dist/core/command/menu-protocol.js +9 -2
  78. package/dist/core/command/role-menu.js +148 -30
  79. package/dist/core/command/slash-gate.js +13 -10
  80. package/dist/core/command/slash-handler.js +157 -352
  81. package/dist/core/daemon-control.js +8 -14
  82. package/dist/core/event-catalog.js +15 -0
  83. package/dist/core/evolagent-registry.js +4 -4
  84. package/dist/core/evolagent.js +2 -2
  85. package/dist/core/inference/text-inference.js +31 -40
  86. package/dist/core/ipc-registration.js +24 -3
  87. package/dist/core/memory/consolidation-context.js +51 -5
  88. package/dist/core/memory/consolidation-ops-records.js +1 -1
  89. package/dist/core/memory/consolidation-trigger.js +190 -190
  90. package/dist/core/memory/consolidation.js +316 -29
  91. package/dist/core/memory/forget-log.js +96 -0
  92. package/dist/core/memory/index-manager.js +27 -5
  93. package/dist/core/memory/memory-admin.js +45 -5
  94. package/dist/core/memory/memory-writer.js +163 -18
  95. package/dist/core/memory/relation-idle-monitor.js +119 -58
  96. package/dist/core/memory/relation-sweep.js +44 -39
  97. package/dist/core/message/aun-ipc-sender.js +34 -7
  98. package/dist/core/message/aun-request-registry.js +97 -3
  99. package/dist/core/message/im-renderer.js +11 -4
  100. package/dist/core/message/message-admission.js +97 -8
  101. package/dist/core/message/message-bridge.js +71 -24
  102. package/dist/core/message/message-log.js +55 -0
  103. package/dist/core/message/message-queue.js +5 -5
  104. package/dist/core/message/response-engine.js +387 -144
  105. package/dist/core/model/catalog-service.js +4 -2
  106. package/dist/core/model/config-scope.js +24 -64
  107. package/dist/core/model/field-scope.js +1 -1
  108. package/dist/core/model/model-catalog.js +37 -47
  109. package/dist/core/model/model-diagnostics.js +4 -3
  110. package/dist/core/model/model-fallback.js +10 -7
  111. package/dist/core/model/model-permission.js +3 -2
  112. package/dist/core/ownership/owner-resolver.js +25 -23
  113. package/dist/core/permission/ec-command-parser.js +138 -5
  114. package/dist/core/permission/sandbox-runtime.js +18 -1
  115. package/dist/core/permission/tool-policy.js +42 -10
  116. package/dist/core/relation/peer-identity.js +64 -1
  117. package/dist/core/role/runtime-policy.js +72 -13
  118. package/dist/core/session/session-capsule.js +197 -0
  119. package/dist/core/session/session-idle-monitor.js +1 -1
  120. package/dist/core/session/session-manager.js +168 -14
  121. package/dist/core/session/session-mapper.js +2 -0
  122. package/dist/core/session/session-renew.js +3 -3
  123. package/dist/core/skill/index-generator.js +15 -5
  124. package/dist/core/system-session/memory.js +6 -1
  125. package/dist/core/thread/thread-service.js +19 -6
  126. package/dist/directory/owner-directory-admission.js +95 -0
  127. package/dist/directory/owner-directory-authorization.js +309 -0
  128. package/dist/directory/owner-directory-cache.js +635 -0
  129. package/dist/eck/kit-renderer.js +2 -2
  130. package/dist/ecweb/basic-settings-service.js +33 -40
  131. package/dist/ecweb/message-context-service.js +110 -0
  132. package/dist/index.js +79 -17
  133. package/dist/ipc.js +189 -17
  134. package/dist/paths.js +4 -0
  135. package/dist/proxy/command.js +122 -0
  136. package/dist/proxy/ipc-service.js +68 -0
  137. package/dist/proxy/manager.js +485 -0
  138. package/dist/proxy/service-supervisor.js +603 -0
  139. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  140. package/dist/stats/budget.js +1 -1
  141. package/dist/stats/db.js +15 -0
  142. package/dist/stats/index.js +2 -2
  143. package/dist/stats/price-resolver.js +304 -5
  144. package/dist/stats/query.js +82 -3
  145. package/dist/stats/writer.js +38 -5
  146. package/dist/trigger/feedback.js +18 -7
  147. package/dist/trigger/manager.js +20 -3
  148. package/dist/trigger/parser.js +6 -3
  149. package/dist/trigger/patch.js +1 -1
  150. package/dist/trigger/system-definitions.js +43 -7
  151. package/dist/trigger/validation.js +13 -5
  152. package/dist/utils/cross-platform.js +14 -0
  153. package/dist/utils/ecweb-supervisor.js +258 -83
  154. package/dist/utils/error-utils.js +16 -2
  155. package/dist/utils/logger.js +24 -5
  156. package/dist/utils/npm-ops.js +2 -1
  157. package/dist/utils/package-version-info.js +5 -3
  158. package/dist/utils/upgrade-jobs.js +45 -5
  159. package/kits/docs/INDEX.md +1 -1
  160. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  161. package/kits/docs/channels/aun.md +9 -0
  162. package/kits/docs/evolcore/INDEX.md +2 -1
  163. package/kits/docs/evolcore/agent-create.md +3 -2
  164. package/kits/docs/evolcore/agent.md +1 -1
  165. package/kits/docs/evolcore/config.md +18 -7
  166. package/kits/docs/evolcore/contact.md +3 -0
  167. package/kits/docs/evolcore/event.md +1 -0
  168. package/kits/docs/evolcore/fs.md +16 -0
  169. package/kits/docs/evolcore/memory-architecture.md +2 -2
  170. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  171. package/kits/docs/evolcore/memory.md +1 -1
  172. package/kits/docs/evolcore/menu-protocol.md +36 -0
  173. package/kits/docs/evolcore/model.md +23 -20
  174. package/kits/docs/evolcore/msg.md +21 -8
  175. package/kits/docs/evolcore/session.md +14 -0
  176. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  177. package/kits/schemas/_meta.json +37 -4
  178. package/kits/schemas/agent-config.schema.13.json +23 -3
  179. package/kits/schemas/agent-config.schema.16.json +891 -0
  180. package/kits/schemas/daemon.schema.9.json +366 -0
  181. package/kits/schemas/defaults.schema.5.json +406 -127
  182. package/kits/schemas/relation-config.schema.11.json +260 -0
  183. package/kits/schemas/role-config.schema.1.json +7 -7
  184. package/kits/skills/.switches.json +3 -7
  185. package/kits/skills/aid-ability/SKILL.md +35 -6
  186. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  187. package/kits/skills/ec-trigger/SKILL.md +13 -5
  188. package/kits/skills/personal-assistant/SKILL.md +176 -0
  189. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  190. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  191. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  192. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  193. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  194. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  195. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  196. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  197. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  198. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  199. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  200. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  201. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  202. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  203. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  204. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  205. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  206. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  207. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  208. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  209. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  210. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  211. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  212. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  213. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  214. package/kits/templates/memory-consolidation/forget.md +19 -6
  215. package/kits/templates/memory-consolidation/notes.md +1 -1
  216. package/kits/templates/memory-consolidation/profile.md +2 -2
  217. package/kits/templates/memory-consolidation/promote.md +20 -3
  218. package/kits/templates/roles/member.json +8 -1
  219. package/kits/templates/session-capsule/recovery.md +5 -0
  220. package/kits/templates/session-capsule/renew.md +5 -0
  221. package/kits/templates/system-fragments/baseagent.md +2 -2
  222. package/kits/templates/system-fragments/bootstrap.md +6 -6
  223. package/kits/templates/system-fragments/channel.md +1 -1
  224. package/kits/templates/system-fragments/memory.md +4 -4
  225. package/package.json +7 -3
  226. package/dist/stats/billing.js +0 -215
@@ -4,6 +4,9 @@ import crypto from 'crypto';
4
4
  import { performance } from 'node:perf_hooks';
5
5
  import fs from 'fs';
6
6
  import { ownerResolver } from '../core/ownership/owner-resolver.js';
7
+ import { OwnerDirectoryCache, parseOwnerDirectoryGrantAbilityResponse } from '../directory/owner-directory-cache.js';
8
+ import { OwnerDirectoryAuthorization } from '../directory/owner-directory-authorization.js';
9
+ import { registerOwnerDirectoryAdmission } from '../directory/owner-directory-admission.js';
7
10
  import path from 'path';
8
11
  import os from 'os';
9
12
  import { logger, localTimestamp } from '../utils/logger.js';
@@ -12,11 +15,14 @@ import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } f
12
15
  import { DEFAULT_FLUSH_DELAY_SECONDS } from '../types.js';
13
16
  import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath } from '../paths.js';
14
17
  import { getAunRequestRegistry, MAX_AUN_VOLATILE_TTL_SECONDS } from '../core/message/aun-request-registry.js';
18
+ import { resolveAunSendDevice } from '../aun/ability-device-routing.js';
15
19
  import { saveToUploads, saveRelationAttachment, sanitizeFileName, bufferToInboundImage, safeFetch } from '../utils/media-cache.js';
16
20
  import { appendAidEvent } from '../utils/instance-registry.js';
17
21
  import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInboundEntry, classifyAunPayloadForLog, findLatestMessageLogOperation, findMessageLogOperationMessageId, hasMessageLogOperation } from '../core/message/message-log.js';
18
22
  import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
19
23
  import { chatDirPath } from '../core/session/session-fs-store.js';
24
+ import { readSessionLoopConfig, resolveSessionLoopTarget } from '../core/session/session-idle-monitor.js';
25
+ import { sessionFullAccessStatus } from '../core/role/runtime-policy.js';
20
26
  import { readTopicLabel, readTopicStatus } from '../core/session/session-mapper.js';
21
27
  import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
22
28
  import { appendAidLifecycle } from '../aun/aid/identity.js';
@@ -45,7 +51,8 @@ import { bindPostBootstrapWelcomeOutboxSession, hasPendingPostBootstrapWelcomeOu
45
51
  import { hasMentionAll, mentionEntryAids, mentionEntryTargets, } from '../core/message/mention-schema.js';
46
52
  import { aunOutboundAttention, normalizeAunMentionEntries, parseAunAttention, withAunAttention, } from '../aun/msg/mention-schema.js';
47
53
  import { isDeliveryTarget, sameDeliveryTarget } from '../core/message/message-utils.js';
48
- import { isTopicThreadId } from '../core/thread/topic-id.js';
54
+ import { isTopicThreadId, sessionTopicThreadId } from '../core/thread/topic-id.js';
55
+ import { ThreadService } from '../core/thread/thread-service.js';
49
56
  import { sentReceipt, suppressedReceipt } from '../core/message/send-receipt.js';
50
57
  export const AUN_HANDOFF_MARKER_FIELD = '_evolcore_handoff_id';
51
58
  const AUN_INTERACTION_CARD_TTL_MS = 24 * 60 * 60 * 1000;
@@ -60,6 +67,11 @@ const AUN_SEND_LOG_TEXT_MAX_LENGTH = 60;
60
67
  const AUN_MAX_PAYLOAD_SIZE = 512 * 1024;
61
68
  const AUN_MAX_FIELD_SIZE = 256 * 1024;
62
69
  const AUN_MIN_FIELD_SIZE = 1024;
70
+ const AUN_SESSION_STATE_PAYLOAD_TYPES = new Set(['text', 'image', 'file', 'video', 'voice', 'audio', 'link']);
71
+ const AUN_TOPIC_NAME_PAYLOAD_TYPES = new Set([
72
+ 'text', 'file', 'image', 'audio', 'voice', 'video', 'quote', 'link', 'merge',
73
+ 'action_card', 'card', 'notice', 'error', 'activity', 'thought',
74
+ ]);
63
75
  function jsonUtf8Size(value) {
64
76
  return Buffer.byteLength(JSON.stringify(value), 'utf8');
65
77
  }
@@ -581,6 +593,24 @@ function appendRawErrorText(text, raw) {
581
593
  return text;
582
594
  return `${text}\n原因:${rawText}`;
583
595
  }
596
+ function structuredErrorSendReceipt(envelope, result, threadId) {
597
+ if (result.messageId)
598
+ return sentReceipt(envelope, [result.messageId], threadId);
599
+ const operationId = envelope.operationId ?? envelope.taskId;
600
+ if ((result.status === 'retry' || result.queued) && result.outboxId) {
601
+ return {
602
+ status: 'queued', operationId, messages: [], outboxId: result.outboxId,
603
+ ...(result.error !== undefined ? { error: result.error } : {}),
604
+ ...(result.code !== undefined ? { code: result.code } : {}),
605
+ };
606
+ }
607
+ return {
608
+ status: 'failed', operationId, messages: [],
609
+ ...(result.outboxId !== undefined ? { outboxId: result.outboxId } : {}),
610
+ error: result.error ?? 'AUN structured error send returned no delivery receipt',
611
+ code: result.code ?? 'MISSING_SEND_RECEIPT',
612
+ };
613
+ }
584
614
  /**
585
615
  * 把 AUNChannel 投递的 opts 映射成渠道无关的 InboundMessage。
586
616
  *
@@ -676,10 +706,12 @@ export class AUNChannel {
676
706
  return this.managedMenuClient.request(options);
677
707
  }
678
708
  client = null;
709
+ ownerDirectoryCache;
679
710
  store = null;
680
711
  /** 实际连接的网关 URL(来自 authenticate() 返回值 / connection.state 事件),替代旧 (client as any)._gatewayUrl。 */
681
712
  gatewayUrl = '';
682
713
  projectPathProvider;
714
+ sessionStateResolver;
683
715
  messageHandler;
684
716
  recallHandler;
685
717
  connected = false;
@@ -1469,6 +1501,147 @@ export class AUNChannel {
1469
1501
  logger.warn(`${this.logPrefix()} topic.renamed failed: ${error instanceof Error ? error.message : String(error)}`);
1470
1502
  });
1471
1503
  }
1504
+ async getOwnerDirectoryRuntime(expectedOwnerAid) {
1505
+ const selfAid = this.config.aid.replace(/^@/, '');
1506
+ const client = this.client;
1507
+ logger.debug(`${this.logPrefix()} getOwnerDirectoryRuntime called: selfAid=${selfAid}, connected=${this.connected}, pureIdentity=${this.config.pureIdentity}`);
1508
+ if (!client || !this.connected || this.config.pureIdentity) {
1509
+ logger.debug(`${this.logPrefix()} getOwnerDirectoryRuntime early return: client=${!!client}, connected=${this.connected}, pureIdentity=${this.config.pureIdentity}`);
1510
+ return;
1511
+ }
1512
+ await ownerResolver.refresh(selfAid, { force: !!expectedOwnerAid });
1513
+ // Fall back to configured owner for agents created before the ownership consensus protocol,
1514
+ // which may not yet have a consensus result but do have owners in config.json.
1515
+ const ownerAid = ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid);
1516
+ logger.info(`${this.logPrefix()} ownerResolver result: selfAid=${selfAid}, ownerAid=${ownerAid || 'undefined'} (protocol=${ownerResolver.owner(selfAid) || 'none'}, known=${ownerResolver.knownOwner(selfAid) || 'none'})`);
1517
+ if (!ownerAid || (expectedOwnerAid && ownerAid !== expectedOwnerAid)
1518
+ || this.client !== client || !this.connected) {
1519
+ logger.warn(`${this.logPrefix()} getOwnerDirectoryRuntime no owner or state changed: ownerAid=${ownerAid}, expectedOwnerAid=${expectedOwnerAid}`);
1520
+ return;
1521
+ }
1522
+ if (this.ownerDirectoryCache?.client !== client || this.ownerDirectoryCache.ownerAid !== ownerAid) {
1523
+ const directory = path.join(this.agentDir, 'directory');
1524
+ const cache = new OwnerDirectoryCache({
1525
+ selfAid,
1526
+ ownerAid,
1527
+ directory,
1528
+ client,
1529
+ onError: (scope, error) => logger.warn(`${this.logPrefix()} Owner ${scope} directory refresh failed: ${error instanceof Error ? error.message : String(error)}`),
1530
+ });
1531
+ const isCurrent = () => this.client === client && this.connected
1532
+ && this.ownerDirectoryCache?.cache === cache
1533
+ && (ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid)) === ownerAid;
1534
+ const authorization = new OwnerDirectoryAuthorization({
1535
+ selfAid, ownerAid, directory, cache, client, isCurrent,
1536
+ send: (payload, deviceId, ttl) => this.sendDaemonMsg({
1537
+ to: ownerAid, payload, deviceId, ttl, rawPayload: true, encrypt: true,
1538
+ }),
1539
+ });
1540
+ this.ownerDirectoryCache = { client, ownerAid, cache, authorization };
1541
+ registerOwnerDirectoryAdmission({ selfAid, ownerAid, cache, isCurrent });
1542
+ }
1543
+ return this.ownerDirectoryCache;
1544
+ }
1545
+ async refreshOwnerDirectoryCache(expectedOwnerAid) {
1546
+ const runtime = await this.getOwnerDirectoryRuntime(expectedOwnerAid);
1547
+ if (!runtime)
1548
+ return;
1549
+ if (expectedOwnerAid)
1550
+ await runtime.cache.handleOwnerChangedEvent(expectedOwnerAid);
1551
+ else {
1552
+ // Active authorization request removed: Owner now pushes grants via the
1553
+ // owner.directory.grant event. Only refresh already-authorized caches here.
1554
+ await runtime.cache.refreshIfNeeded();
1555
+ }
1556
+ }
1557
+ /** Passive refresh: only refresh caches that already have a valid grant. Never initiates a new authorization request. */
1558
+ async passiveOwnerDirectoryRefresh() {
1559
+ const runtime = await this.getOwnerDirectoryRuntime();
1560
+ if (!runtime)
1561
+ return;
1562
+ await runtime.cache.refreshIfNeeded();
1563
+ }
1564
+ // Active authorization request disabled: Owner now pushes grants via the
1565
+ // owner.directory.grant event. Retained for reference / future re-enablement.
1566
+ /* disabled: active authorization removed
1567
+ private async requestOwnerDirectoryAuthorization(senderAid: string): Promise<void> {
1568
+ const runtime = await this.getOwnerDirectoryRuntime(senderAid);
1569
+ await runtime?.authorization.ensureAuthorization();
1570
+ }
1571
+
1572
+ private checkOwnerDirectoryAuthorizationOnMessage(senderAid: string, payload: unknown): void {
1573
+ const currentOwner = ownerResolver.owner(this.config.aid.replace(/^@/, ''));
1574
+ const type = payload && typeof payload === 'object' ? (payload as Record<string, unknown>).type : undefined;
1575
+ if (currentOwner && senderAid !== currentOwner) return;
1576
+ if (typeof payload !== 'string' && !AUN_SESSION_STATE_PAYLOAD_TYPES.has(String(type))
1577
+ && type !== 'merge' && type !== 'quote') return;
1578
+ void this.requestOwnerDirectoryAuthorization(senderAid).catch(error => {
1579
+ logger.warn(`${this.logPrefix()} Owner directory authorization check failed: ${error instanceof Error ? error.message : String(error)}`);
1580
+ });
1581
+ }
1582
+ */
1583
+ async handleOwnerDirectoryAuthorizationResponse(senderAid, record) {
1584
+ const grant = parseOwnerDirectoryGrantAbilityResponse(record.responsePayload);
1585
+ if (!grant && !record.requestId.startsWith('owner-directory-auto-'))
1586
+ return;
1587
+ const runtime = await this.getOwnerDirectoryRuntime(senderAid);
1588
+ if (!runtime)
1589
+ return;
1590
+ if (runtime.authorization.ownsRequest(record)) {
1591
+ await runtime.authorization.acceptResponse(record);
1592
+ return;
1593
+ }
1594
+ if (grant) {
1595
+ runtime.cache.saveAuthorization(grant);
1596
+ if (runtime.cache.scopeAccess('agents') === 'authorized')
1597
+ await runtime.authorization.ensureAuthorization();
1598
+ await runtime.cache.handleOwnerChangedEvent(senderAid);
1599
+ }
1600
+ }
1601
+ handleOwnerDirectoryChangedEvent(payload, senderAid) {
1602
+ const record = payload && typeof payload === 'object' && !Array.isArray(payload)
1603
+ ? payload : undefined;
1604
+ if (record?.data?.schema_version !== 1) {
1605
+ logger.debug(`${this.logPrefix()} owner.directory.changed ignored: invalid schema_version`);
1606
+ return;
1607
+ }
1608
+ void this.refreshOwnerDirectoryCache(senderAid).catch(error => {
1609
+ logger.warn(`${this.logPrefix()} owner.directory.changed processing failed: ${error instanceof Error ? error.message : String(error)}`);
1610
+ });
1611
+ }
1612
+ handleOwnerDirectoryGrantEvent(payload, senderAid) {
1613
+ const record = payload && typeof payload === 'object' && !Array.isArray(payload)
1614
+ ? payload : undefined;
1615
+ if (record?.data?.schema_version !== 1 || !record?.data?.grant) {
1616
+ logger.warn(`${this.logPrefix()} owner.directory.grant ignored: invalid schema (schema_version=${record?.data?.schema_version}, hasGrant=${!!record?.data?.grant})`);
1617
+ return;
1618
+ }
1619
+ logger.info(`${this.logPrefix()} owner.directory.grant received from ${senderAid}`);
1620
+ void this.handleOwnerDirectoryGrantFromOwner(senderAid, record.data.grant).catch(error => {
1621
+ logger.warn(`${this.logPrefix()} owner.directory.grant processing failed: ${error instanceof Error ? error.message : String(error)}`);
1622
+ });
1623
+ }
1624
+ async handleOwnerDirectoryGrantFromOwner(senderAid, grant) {
1625
+ const selfAid = this.config.aid.replace(/^@/, '');
1626
+ await ownerResolver.refresh(selfAid, { force: true });
1627
+ const ownerAid = ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid);
1628
+ if (!ownerAid || senderAid !== ownerAid) {
1629
+ logger.warn(`${this.logPrefix()} owner.directory.grant rejected: sender ${senderAid} is not owner ${ownerAid}`);
1630
+ return;
1631
+ }
1632
+ const parsed = parseOwnerDirectoryGrantAbilityResponse(grant);
1633
+ if (!parsed) {
1634
+ logger.warn(`${this.logPrefix()} owner.directory.grant: invalid grant payload (does not match evol-directory-access-v1 contract)`);
1635
+ return;
1636
+ }
1637
+ const runtime = await this.getOwnerDirectoryRuntime(senderAid);
1638
+ if (!runtime)
1639
+ return;
1640
+ runtime.cache.saveAuthorization(parsed);
1641
+ logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}, pulling directory`);
1642
+ await runtime.cache.handleOwnerChangedEvent(senderAid);
1643
+ logger.info(`${this.logPrefix()} owner.directory.grant: directory sync complete for ${selfAid}`);
1644
+ }
1472
1645
  buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId, label, topicStatus) {
1473
1646
  if (!groupId)
1474
1647
  throw new Error('buildGroupReplyContext requires groupId');
@@ -2103,6 +2276,9 @@ export class AUNChannel {
2103
2276
  this.connected = true;
2104
2277
  this.connectedAt = Date.now();
2105
2278
  this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
2279
+ void this.passiveOwnerDirectoryRefresh().catch(error => {
2280
+ logger.warn(`${this.logPrefix()} Owner directory passive refresh failed: ${error instanceof Error ? error.message : String(error)}`);
2281
+ });
2106
2282
  if (!this.config.pureIdentity) {
2107
2283
  void Promise.resolve(this.groupInviteConnectedHandler?.()).catch(error => {
2108
2284
  logger.warn(`${this.logPrefix()} Group invitation recovery failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -2534,10 +2710,17 @@ export class AUNChannel {
2534
2710
  const responseRecord = getAunRequestRegistry().resolveIncoming({
2535
2711
  selfAid: this._aid || this.config.aid,
2536
2712
  fromAid,
2713
+ fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
2537
2714
  messageId,
2538
2715
  payload,
2539
2716
  });
2540
2717
  if (responseRecord) {
2718
+ // An ignored device response or an ACK must not update authorization state.
2719
+ if (responseRecord.state === 'completed' && responseRecord.responseMessageId === messageId) {
2720
+ void this.handleOwnerDirectoryAuthorizationResponse(fromAid, responseRecord).catch(error => {
2721
+ logger.warn(`${this.logPrefix()} Owner directory authorization result processing failed: ${error instanceof Error ? error.message : String(error)}`);
2722
+ });
2723
+ }
2541
2724
  logger.info(`${this.logPrefix()} AUN request response matched: request_id=${responseRecord.requestId} mid=${messageId}`);
2542
2725
  const responseLog = classifyAunPayloadForLog(payload);
2543
2726
  this.appendInboundPayloadJsonl(fromAid, fromAid, messageId, !!env.encrypted, false, responseLog, undefined, receivedAt, seq);
@@ -2591,6 +2774,8 @@ export class AUNChannel {
2591
2774
  logger.debug(`${this.logPrefix()} P2P dropped: echo from self (from=${fromAid} mid=${messageId})`);
2592
2775
  return;
2593
2776
  }
2777
+ // Active authorization request removed: Owner now pushes grants via owner.directory.grant event.
2778
+ // this.checkOwnerDirectoryAuthorizationOnMessage(fromAid, payload);
2594
2779
  // 记录入站消息加密状态,透传到出站 ReplyContext
2595
2780
  const msgEncrypted = !!env.encrypted;
2596
2781
  if (!msgEncrypted)
@@ -2629,6 +2814,14 @@ export class AUNChannel {
2629
2814
  });
2630
2815
  return;
2631
2816
  }
2817
+ if (p2pPayloadType === 'event' && payload?.event === 'owner.directory.changed') {
2818
+ this.handleOwnerDirectoryChangedEvent(payload, fromAid);
2819
+ return;
2820
+ }
2821
+ if (p2pPayloadType === 'event' && payload?.event === 'owner.directory.grant') {
2822
+ this.handleOwnerDirectoryGrantEvent(payload, fromAid);
2823
+ return;
2824
+ }
2632
2825
  // action_card_reply 已在 extractTextPayload 中消费,不分发给 agent
2633
2826
  if (p2pPayloadType === 'action_card_reply') {
2634
2827
  this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq);
@@ -2758,6 +2951,7 @@ export class AUNChannel {
2758
2951
  const responseRecord = getAunRequestRegistry().resolveIncoming({
2759
2952
  selfAid: this._aid || this.config.aid,
2760
2953
  fromAid: senderAid,
2954
+ fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
2761
2955
  messageId,
2762
2956
  payload,
2763
2957
  });
@@ -2812,6 +3006,8 @@ export class AUNChannel {
2812
3006
  logger.debug(`${this.logPrefix()} Group dropped: own message (group=${groupId} mid=${messageId})`);
2813
3007
  return;
2814
3008
  }
3009
+ // Active authorization request removed: Owner now pushes grants via owner.directory.grant event.
3010
+ // this.checkOwnerDirectoryAuthorizationOnMessage(senderAid, payload);
2815
3011
  // 短 echo 快速通道:连通性测试要尽量低延迟,命中后绕过所有 await(后续 mention 过滤)
2816
3012
  {
2817
3013
  const firstLineFast = text.split('\n')[0] || '';
@@ -3920,6 +4116,9 @@ export class AUNChannel {
3920
4116
  onProjectPathRequest(provider) {
3921
4117
  this.projectPathProvider = provider;
3922
4118
  }
4119
+ setSessionStateResolver(resolver) {
4120
+ this.sessionStateResolver = resolver;
4121
+ }
3923
4122
  onMessage(handler) {
3924
4123
  this.messageHandler = handler;
3925
4124
  }
@@ -4045,6 +4244,57 @@ export class AUNChannel {
4045
4244
  finalPayload.debug = { ...context.debug, sentAt: localTimestamp() };
4046
4245
  return finalPayload;
4047
4246
  }
4247
+ /**
4248
+ * Assemble the wire `ext` dictionary by merging all caller-supplied ext
4249
+ * sources and computing derived fields (turnMessageCount).
4250
+ * loop/fullaccess are intentionally excluded — withSessionState appends them
4251
+ * after querying live session state so they are never stale on retries.
4252
+ */
4253
+ buildWireExt(channelId, threadId, contextExt, payloadExt) {
4254
+ const ext = {
4255
+ ...(contextExt ?? {}),
4256
+ ...(payloadExt ?? {}),
4257
+ };
4258
+ if (ext.isFinal) {
4259
+ const turnKey = `${channelId}\0${threadId ?? ''}`;
4260
+ ext.turnMessageCount = this.sentCount.get(turnKey) ?? 1;
4261
+ }
4262
+ return Object.keys(ext).length > 0 ? ext : undefined;
4263
+ }
4264
+ /** Refresh display hints at delivery, including outbox retries; they never grant permissions. */
4265
+ async withSessionState(channelId, payload, context) {
4266
+ if (!AUN_SESSION_STATE_PAYLOAD_TYPES.has(payload.type))
4267
+ return payload;
4268
+ const threadId = isTopicThreadId(payload.thread_id) ? payload.thread_id : context?.threadId;
4269
+ const ext = {
4270
+ ...(this.buildWireExt(channelId, threadId, context?.ext, payload.ext && typeof payload.ext === 'object' && !Array.isArray(payload.ext)
4271
+ ? payload.ext
4272
+ : undefined) ?? {}),
4273
+ };
4274
+ // Never reuse a caller's or an earlier delivery attempt's state hints.
4275
+ delete ext.loop;
4276
+ delete ext.fullaccess;
4277
+ try {
4278
+ const state = await this.sessionStateResolver?.(channelId, {
4279
+ ...context,
4280
+ ...(!context?.sessionId && typeof payload.session_id === 'string' ? { sessionId: payload.session_id } : {}),
4281
+ ...(isTopicThreadId(payload.thread_id) ? { threadId: payload.thread_id } : {}),
4282
+ });
4283
+ if (typeof state?.loop === 'boolean')
4284
+ ext.loop = state.loop;
4285
+ if (typeof state?.fullaccess === 'boolean')
4286
+ ext.fullaccess = state.fullaccess;
4287
+ }
4288
+ catch (error) {
4289
+ logger.warn(`${this.logPrefix()} Outbound session state unavailable: channel=${channelId} error=${String(error)}`);
4290
+ }
4291
+ const result = { ...payload };
4292
+ if (Object.keys(ext).length > 0)
4293
+ result.ext = ext;
4294
+ else
4295
+ delete result.ext;
4296
+ return result;
4297
+ }
4048
4298
  /**
4049
4299
  * Validate AUN-specific structured fields before crossing the durable
4050
4300
  * send boundary. Return a copy when mentions are present so callers do not
@@ -4140,6 +4390,10 @@ export class AUNChannel {
4140
4390
  fallback.chatmode = truncateUtf8ToBytes(payload.chatmode, 32);
4141
4391
  if (typeof payload.thread_id === 'string')
4142
4392
  fallback.thread_id = payload.thread_id;
4393
+ if (typeof payload.topicName === 'string')
4394
+ fallback.topicName = truncateUtf8ToBytes(payload.topicName, 256);
4395
+ if (typeof payload.name_updated_at === 'number')
4396
+ fallback.name_updated_at = payload.name_updated_at;
4143
4397
  logger.info(`${this.logPrefix()} Thought payload reduced to fallback (${Buffer.byteLength(JSON.stringify(fallback), 'utf8')} bytes)`);
4144
4398
  return fallback;
4145
4399
  }
@@ -4340,6 +4594,9 @@ export class AUNChannel {
4340
4594
  logger.error(`${this.logPrefix()} Dropped durable AUN payload: invalid payload.mentions (${detail}) code=${code} channel=${channelId}`);
4341
4595
  return { ok: false, status: 'permanent', error: detail, code };
4342
4596
  }
4597
+ if (delivery.chatType === 'private') {
4598
+ normalizedPayload = this.withCurrentTopicName(channelId, normalizedPayload);
4599
+ }
4343
4600
  if (!this.client || !this.connected) {
4344
4601
  return { ok: false, status: 'retry', error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
4345
4602
  }
@@ -4360,7 +4617,7 @@ export class AUNChannel {
4360
4617
  if (payloadWithCausationRef.thread_id === '')
4361
4618
  delete payloadWithCausationRef.thread_id;
4362
4619
  // Truncate payload if too large (AUN SDK limit: 1MB)
4363
- const truncatedPayload = this.truncatePayloadIfNeeded(payloadWithCausationRef, label);
4620
+ const truncatedPayload = this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
4364
4621
  const params = { payload: truncatedPayload, encrypt };
4365
4622
  const isMenuPayload = typeof truncatedPayload.type === 'string' && truncatedPayload.type.startsWith('menu.');
4366
4623
  if (!isGroup && ['menu.response', 'menu.event'].includes(truncatedPayload.type))
@@ -4419,6 +4676,31 @@ export class AUNChannel {
4419
4676
  return { ok: false, status: failure.status, error: failure.error, code: failure.code };
4420
4677
  }
4421
4678
  }
4679
+ withCurrentTopicName(peer, payload) {
4680
+ const threadId = payload.thread_id;
4681
+ if (!isTopicThreadId(threadId))
4682
+ return payload;
4683
+ const entry = ThreadService.findThreadById(this.config.aid, threadId);
4684
+ const type = payload.type;
4685
+ if (!entry || typeof threadId !== 'string' || threadId !== entry.threadId
4686
+ || typeof type !== 'string' || !AUN_TOPIC_NAME_PAYLOAD_TYPES.has(type)
4687
+ || entry.peer.trim().toLowerCase() !== peer.trim().toLowerCase()
4688
+ || (entry.channelType && entry.channelType !== 'aun')) {
4689
+ return payload;
4690
+ }
4691
+ const name = entry.name.trim();
4692
+ if (!name || name === '话题会话' || name === '默认会话')
4693
+ return payload;
4694
+ // Older indexes lack a name version; use their stable creation timestamp.
4695
+ const nameUpdatedAt = entry.nameUpdatedAt ?? entry.createdAt;
4696
+ if (!Number.isSafeInteger(nameUpdatedAt) || nameUpdatedAt <= 0)
4697
+ return payload;
4698
+ return {
4699
+ ...payload,
4700
+ topicName: name,
4701
+ name_updated_at: nameUpdatedAt,
4702
+ };
4703
+ }
4422
4704
  recordDurableOutbound(channelId, payload, messageId, encrypt, context, isGroup, contentKind, logText, result, statsContext) {
4423
4705
  const causation = normalizeCausation(context?.metadata?.causation);
4424
4706
  if (!isGroup && causation)
@@ -4802,6 +5084,12 @@ export class AUNChannel {
4802
5084
  return seqInTurn;
4803
5085
  }
4804
5086
  async sendDaemonMsg(args) {
5087
+ try {
5088
+ resolveAunSendDevice(args.deviceId, 'msg', args.payload);
5089
+ }
5090
+ catch (error) {
5091
+ return { ok: false, code: error.code, error: error.message };
5092
+ }
4805
5093
  if (!args.to) {
4806
5094
  return { ok: false, error: 'aun-msg-send requires a private target', code: 'UNSUPPORTED_TARGET' };
4807
5095
  }
@@ -4882,11 +5170,22 @@ export class AUNChannel {
4882
5170
  }
4883
5171
  if (args.debug)
4884
5172
  finalPayload.debug = { ...args.debug, sentAt: localTimestamp() };
5173
+ if (!preserveRawPayload) {
5174
+ finalPayload = this.withCurrentTopicName(args.to, finalPayload);
5175
+ }
5176
+ if (!preserveRawPayload) {
5177
+ finalPayload = await this.withSessionState(args.to, finalPayload, {
5178
+ sessionId: args.log?.sessionId,
5179
+ threadId: args.log?.threadId ?? undefined,
5180
+ delivery: { chatType: 'private' },
5181
+ });
5182
+ }
4885
5183
  const encrypt = args.encrypt ?? this.shouldEncrypt(args.to);
4886
5184
  const sendParams = {
4887
5185
  to: args.to,
4888
5186
  payload: preserveRawPayload ? finalPayload : this.truncatePayloadIfNeeded(finalPayload, 'msg-send-ipc'),
4889
5187
  encrypt,
5188
+ ...(args.deviceId ? { device_id: args.deviceId } : {}),
4890
5189
  ...(args.ttl !== undefined ? { ttl: args.ttl } : {}),
4891
5190
  };
4892
5191
  try {
@@ -4982,7 +5281,7 @@ export class AUNChannel {
4982
5281
  // Validate before deep-cleaning so undefined entries cannot be silently
4983
5282
  // removed from a malformed mentions array.
4984
5283
  const validatedPayload = this.normalizeAunPayloadMentions(args.payload);
4985
- const finalPayload = this.stripUndefinedDeep(validatedPayload);
5284
+ let finalPayload = this.stripUndefinedDeep(validatedPayload);
4986
5285
  if (finalPayload.thread_id === '')
4987
5286
  delete finalPayload.thread_id;
4988
5287
  const payloadMentions = Object.prototype.hasOwnProperty.call(finalPayload, 'mentions')
@@ -5003,6 +5302,11 @@ export class AUNChannel {
5003
5302
  }
5004
5303
  if (args.debug)
5005
5304
  finalPayload.debug = { ...args.debug, sentAt: localTimestamp() };
5305
+ finalPayload = await this.withSessionState(args.groupId, finalPayload, {
5306
+ sessionId: args.log?.sessionId,
5307
+ threadId: args.log?.threadId ?? undefined,
5308
+ delivery: { chatType: 'group', groupId: args.groupId },
5309
+ });
5006
5310
  const encrypt = args.encrypt ?? this.shouldEncrypt(args.groupId);
5007
5311
  const result = await this.callAndTrace('group.send', {
5008
5312
  group_id: args.groupId,
@@ -5150,19 +5454,11 @@ export class AUNChannel {
5150
5454
  }
5151
5455
  // 从 context.metadata.source 读取 source,默认为 'daemon'
5152
5456
  const source = context?.metadata?.source ?? 'daemon';
5153
- // Merge ext hints from context into the wire payload.
5154
- // isFinal: written by response-engine; turnMessageCount: total messages this turn (only on final).
5155
- let ext = context?.ext
5156
- ? { ...context.ext }
5157
- : undefined;
5158
- if (ext?.isFinal) {
5159
- const turnKey = `${channelId}\0${context?.threadId ?? ''}`;
5160
- const total = this.sentCount.get(turnKey) ?? 1;
5161
- ext = { ...ext, turnMessageCount: total };
5162
- }
5163
- const payload = withAunAttention({ type: 'text', text: finalText }, context?.attention);
5164
- if (ext && Object.keys(ext).length > 0)
5165
- payload.ext = ext;
5457
+ // ext assembly (isFinal, seqInTurn, turnMessageCount, loop, fullaccess) is handled
5458
+ // centrally by withSessionState → buildWireExt; nothing to pre-merge here.
5459
+ const payload = await this.withSessionState(channelId, withAunAttention({
5460
+ type: 'text', text: finalText,
5461
+ }, context?.attention), context);
5166
5462
  // sentAt 在每次投递尝试时盖戳(outbox 重发取重发时刻)。服务端会用自己的时间覆盖
5167
5463
  // 顶层 timestamp,两者有毫秒级差异,sentAt 只代表本端时钟。
5168
5464
  if (context?.debug)
@@ -5182,6 +5478,9 @@ export class AUNChannel {
5182
5478
  payload.chatmode = context.metadata.chatmode;
5183
5479
  if (context?.metadata?.forkAnchor)
5184
5480
  payload.fork_anchor = context.metadata.forkAnchor;
5481
+ if (delivery.chatType === 'private') {
5482
+ Object.assign(payload, this.withCurrentTopicName(channelId, payload));
5483
+ }
5185
5484
  const causation = normalizeCausation(context?.metadata?.causation);
5186
5485
  const causationRef = delivery.chatType !== 'group' && causation
5187
5486
  ? `caus_${crypto.randomUUID().replace(/-/g, '')}`
@@ -5568,9 +5867,14 @@ export class AUNChannel {
5568
5867
  // Same diagnostic dictionary as text payloads (sessionId/agentSessionId/model).
5569
5868
  if (context?.debug)
5570
5869
  payloadWithChatmode.debug = { ...context.debug, sentAt: localTimestamp() };
5870
+ let thoughtPayload = payloadWithChatmode;
5871
+ if (delivery.chatType === 'private') {
5872
+ thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
5873
+ }
5874
+ thoughtPayload = this.limitThoughtPayload(thoughtPayload);
5571
5875
  const params = {
5572
5876
  context: { type: 'task', id: taskId },
5573
- payload: this.limitThoughtPayload(payloadWithChatmode),
5877
+ payload: thoughtPayload,
5574
5878
  encrypt,
5575
5879
  };
5576
5880
  try {
@@ -5612,6 +5916,9 @@ export class AUNChannel {
5612
5916
  if (!isThoughtTooLargeError(error))
5613
5917
  throw error;
5614
5918
  thoughtPayload = this.thoughtPayloadFallback(thoughtPayload);
5919
+ if (delivery.chatType === 'private') {
5920
+ thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
5921
+ }
5615
5922
  params.payload = thoughtPayload;
5616
5923
  thoughtText = this.activityLogText(thoughtPayload);
5617
5924
  logger.warn(`${this.logPrefix()} Retrying ${method} with minimal payload after server size rejection`);
@@ -5648,7 +5955,7 @@ export class AUNChannel {
5648
5955
  // Validate before checking connection state so malformed producer payloads
5649
5956
  // are reported deterministically instead of being hidden by a disconnect.
5650
5957
  const validatedPayload = this.normalizeAunPayloadMentions(payload);
5651
- const finalPayload = this.stripUndefinedDeep(withAunAttention(validatedPayload, context?.attention));
5958
+ let finalPayload = this.stripUndefinedDeep(withAunAttention(validatedPayload, context?.attention));
5652
5959
  if (!this.connected || !this.client) {
5653
5960
  return {
5654
5961
  ok: false,
@@ -5670,7 +5977,11 @@ export class AUNChannel {
5670
5977
  finalPayload.thread_id = context.threadId;
5671
5978
  if (context?.replyToMessageId && !finalPayload.ref_message_id)
5672
5979
  finalPayload.ref_message_id = context.replyToMessageId;
5980
+ if (!isGroup) {
5981
+ Object.assign(finalPayload, this.withCurrentTopicName(channelId, finalPayload));
5982
+ }
5673
5983
  const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
5984
+ finalPayload = await this.withSessionState(channelId, finalPayload, context);
5674
5985
  const params = { payload: finalPayload, encrypt };
5675
5986
  if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
5676
5987
  params.to_device_id = context?.toDeviceId;
@@ -5979,13 +6290,16 @@ export class AUNChannel {
5979
6290
  try {
5980
6291
  const { attachment } = await uploadFileAndBuildPayload(this.client, this.config.aid, absPath, { as: 'file' });
5981
6292
  const { filename, size_bytes: size, content_type: contentType } = attachment;
5982
- const filePayload = buildAunFilePayload({
6293
+ const filePayload = await this.withSessionState(channelId, buildAunFilePayload({
5983
6294
  filename,
5984
6295
  size,
5985
6296
  contentType,
5986
6297
  attachment: { ...attachment },
5987
6298
  context,
5988
- });
6299
+ }), context);
6300
+ if (!isGroup) {
6301
+ Object.assign(filePayload, this.withCurrentTopicName(channelId, filePayload));
6302
+ }
5989
6303
  const fileTargetAid = channelId;
5990
6304
  const encryptTarget = isGroup ? channelId : fileTargetAid;
5991
6305
  const encrypt = context?.metadata?.encrypted != null
@@ -6591,6 +6905,10 @@ export class AUNChannelPlugin {
6591
6905
  : (envelope.replyContext || envelope.delivery)
6592
6906
  ? { ...(envelope.replyContext ?? {}), delivery }
6593
6907
  : undefined;
6908
+ if (envelope.sessionId && !replyCtx?.sessionId
6909
+ && (payload.kind === 'result.text' || payload.kind === 'result.image' || payload.kind === 'result.file')) {
6910
+ replyCtx = { ...(replyCtx ?? {}), delivery, sessionId: envelope.sessionId };
6911
+ }
6594
6912
  const attention = aunOutboundAttention(payload);
6595
6913
  if (replyCtx) {
6596
6914
  replyCtx = { ...replyCtx };
@@ -6723,8 +7041,8 @@ export class AUNChannelPlugin {
6723
7041
  ...(payload.reason !== undefined ? { reason: payload.reason } : {}),
6724
7042
  ...(payload.recoverable !== undefined ? { recoverable: payload.recoverable } : {}),
6725
7043
  };
6726
- await channel.sendReliableStructured(channelId, errorPayload, { ...(replyCtx ?? {}), suppressPeerMention: true }, payload.text);
6727
- return;
7044
+ const result = await channel.sendReliableStructured(channelId, errorPayload, { ...(replyCtx ?? {}), suppressPeerMention: true }, payload.text);
7045
+ return structuredErrorSendReceipt(envelope, result, replyCtx?.threadId);
6728
7046
  }
6729
7047
  case 'result.error': {
6730
7048
  const raw = rawErrorText(payload.raw) ?? payload.text;
@@ -6736,8 +7054,9 @@ export class AUNChannelPlugin {
6736
7054
  };
6737
7055
  setIfDefined(errorPayload, 'subtype', payload.subtype);
6738
7056
  setIfDefined(errorPayload, 'reason', payload.reason);
6739
- await channel.sendReliableStructured(channelId, errorPayload, { ...(replyCtx ?? {}), suppressPeerMention: true }, payload.text);
6740
- return;
7057
+ setIfDefined(errorPayload, 'recoverable', payload.recoverable);
7058
+ const result = await channel.sendReliableStructured(channelId, errorPayload, { ...(replyCtx ?? {}), suppressPeerMention: true }, payload.text);
7059
+ return structuredErrorSendReceipt(envelope, result, replyCtx?.threadId);
6741
7060
  }
6742
7061
  case 'result.file': {
6743
7062
  const fileCtx = payload.correlationId
@@ -7077,6 +7396,30 @@ export class AUNChannelPlugin {
7077
7396
  },
7078
7397
  registerHooks(hookCtx) {
7079
7398
  channel.setEventBus(hookCtx.eventBus);
7399
+ channel.setSessionStateResolver(async (channelId, context) => {
7400
+ const delivery = context?.delivery;
7401
+ if (!delivery)
7402
+ return undefined;
7403
+ const threadId = isTopicThreadId(context.threadId) ? context.threadId : undefined;
7404
+ const session = context.sessionId
7405
+ ? await hookCtx.sessionManager.getSessionById(context.sessionId)
7406
+ : threadId
7407
+ ? await hookCtx.sessionManager.getThreadSession(adapter.channelKey, channelId, threadId, aid)
7408
+ : hookCtx.sessionManager.getActiveSessionSync(adapter.channelKey, channelId, 'aun', aid);
7409
+ if (!session || session.selfAID !== aid || session.channel !== adapter.channelKey
7410
+ || session.channelId !== channelId || session.chatType !== delivery.chatType
7411
+ || sessionTopicThreadId(session) !== threadId
7412
+ || (delivery.chatType === 'group' && session.metadata?.groupId !== delivery.groupId))
7413
+ return undefined;
7414
+ const target = resolveSessionLoopTarget(session);
7415
+ if (!target)
7416
+ return undefined;
7417
+ return {
7418
+ loop: readSessionLoopConfig(target)?.enabled === true,
7419
+ ...(session.chatType === 'private'
7420
+ ? { fullaccess: sessionFullAccessStatus(session, channelId).effective } : {}),
7421
+ };
7422
+ });
7080
7423
  // 话题改名通知消费器:直接改本端索引,不经过 Agent 队列。
7081
7424
  channel.setThreadRenameHandler(async (input) => {
7082
7425
  const { ThreadService } = await import('../core/thread/thread-service.js');