evolcore 0.0.41-test.0 → 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 (177) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +20 -43
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +84 -28
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/group/fs-download.js +39 -0
  9. package/dist/aun/group/identity.js +36 -21
  10. package/dist/aun/group/operations.js +5 -0
  11. package/dist/aun/msg/managed-operation.js +68 -7
  12. package/dist/aun/msg/p2p.js +5 -0
  13. package/dist/aun/service-proxy.js +36 -12
  14. package/dist/channels/aun.js +334 -20
  15. package/dist/channels/daemon.js +15 -1
  16. package/dist/cli/aun-commands.js +4 -20
  17. package/dist/cli/daemon-commands.js +678 -697
  18. package/dist/cli/fs-command.js +64 -2
  19. package/dist/cli/index.js +48 -4
  20. package/dist/cli/managed-command-guard.js +4 -0
  21. package/dist/cli/model.js +40 -40
  22. package/dist/cli/proxy-command.js +92 -0
  23. package/dist/cli/role.js +85 -0
  24. package/dist/config/access-policy.js +7 -2
  25. package/dist/config/boot-log.js +38 -1
  26. package/dist/config/config-field-policy.js +5 -32
  27. package/dist/config/config-manager.js +46 -39
  28. package/dist/config/config-operation-service.js +5 -19
  29. package/dist/config/contact-book-store.js +47 -21
  30. package/dist/config/contact-book.js +18 -12
  31. package/dist/config/contact-operation-service.js +3 -4
  32. package/dist/config/contact-request-service.js +11 -0
  33. package/dist/config/daemon-services.js +11 -0
  34. package/dist/config/gateway-config.js +88 -594
  35. package/dist/config/peer-role-resolver.js +13 -11
  36. package/dist/config/providers-config.js +12 -7
  37. package/dist/config/providers-import.js +3 -21
  38. package/dist/config/resolved-config-op.js +3 -0
  39. package/dist/config/role-command-service.js +166 -0
  40. package/dist/config/role-request-service.js +193 -0
  41. package/dist/config/schema-migration.js +686 -25
  42. package/dist/config-store.js +79 -3
  43. package/dist/contracts/ecweb-instance.js +41 -0
  44. package/dist/contracts/ecweb-service-protocol.js +3 -1
  45. package/dist/core/agent-runtime.js +1 -1
  46. package/dist/core/auth/agent-delegation.js +2 -1
  47. package/dist/core/auth/auth-gateway.js +1 -1
  48. package/dist/core/auth/authorization-audit.js +17 -6
  49. package/dist/core/auth/delegation-authorization.js +3 -1
  50. package/dist/core/auth/operation-authorizer.js +15 -0
  51. package/dist/core/auth/operation-catalog.js +31 -6
  52. package/dist/core/command/agent-control.js +3 -7
  53. package/dist/core/command/agent-storage-menu.js +5 -3
  54. package/dist/core/command/cli-intent-parser.js +2 -1
  55. package/dist/core/command/command-handler.js +48 -99
  56. package/dist/core/command/connect-menu.js +11 -3
  57. package/dist/core/command/data-root-resolver.js +5 -4
  58. package/dist/core/command/memory-slash.js +16 -8
  59. package/dist/core/command/menu-catalog.js +5 -6
  60. package/dist/core/command/menu-handler.js +49 -62
  61. package/dist/core/command/role-menu.js +147 -30
  62. package/dist/core/command/slash-handler.js +123 -254
  63. package/dist/core/daemon-control.js +8 -14
  64. package/dist/core/evolagent-registry.js +4 -4
  65. package/dist/core/evolagent.js +2 -2
  66. package/dist/core/inference/text-inference.js +31 -40
  67. package/dist/core/ipc-registration.js +6 -2
  68. package/dist/core/memory/consolidation-context.js +51 -5
  69. package/dist/core/memory/consolidation-ops-records.js +1 -1
  70. package/dist/core/memory/consolidation-trigger.js +189 -189
  71. package/dist/core/memory/consolidation.js +316 -29
  72. package/dist/core/memory/forget-log.js +96 -0
  73. package/dist/core/memory/index-manager.js +27 -5
  74. package/dist/core/memory/memory-admin.js +45 -5
  75. package/dist/core/memory/memory-writer.js +163 -18
  76. package/dist/core/memory/relation-idle-monitor.js +119 -58
  77. package/dist/core/memory/relation-sweep.js +44 -39
  78. package/dist/core/message/aun-ipc-sender.js +8 -2
  79. package/dist/core/message/im-renderer.js +7 -4
  80. package/dist/core/message/message-admission.js +89 -4
  81. package/dist/core/message/message-bridge.js +31 -18
  82. package/dist/core/message/response-engine.js +77 -8
  83. package/dist/core/model/catalog-service.js +4 -2
  84. package/dist/core/model/config-scope.js +24 -64
  85. package/dist/core/model/field-scope.js +1 -1
  86. package/dist/core/model/model-catalog.js +30 -41
  87. package/dist/core/model/model-diagnostics.js +4 -3
  88. package/dist/core/model/model-fallback.js +10 -7
  89. package/dist/core/model/model-permission.js +3 -2
  90. package/dist/core/ownership/owner-resolver.js +23 -21
  91. package/dist/core/permission/ec-command-parser.js +30 -2
  92. package/dist/core/permission/sandbox-runtime.js +18 -1
  93. package/dist/core/permission/tool-policy.js +14 -3
  94. package/dist/core/relation/peer-identity.js +64 -1
  95. package/dist/core/role/runtime-policy.js +72 -13
  96. package/dist/core/session/session-capsule.js +1 -1
  97. package/dist/core/session/session-idle-monitor.js +1 -1
  98. package/dist/core/session/session-manager.js +20 -0
  99. package/dist/core/session/session-renew.js +3 -3
  100. package/dist/core/skill/index-generator.js +15 -5
  101. package/dist/core/system-session/memory.js +6 -1
  102. package/dist/core/thread/thread-service.js +19 -6
  103. package/dist/directory/owner-directory-admission.js +95 -0
  104. package/dist/directory/owner-directory-authorization.js +309 -0
  105. package/dist/directory/owner-directory-cache.js +635 -0
  106. package/dist/eck/kit-renderer.js +2 -2
  107. package/dist/ecweb/basic-settings-service.js +33 -40
  108. package/dist/ecweb/message-context-service.js +110 -0
  109. package/dist/index.js +76 -14
  110. package/dist/ipc.js +170 -12
  111. package/dist/paths.js +4 -0
  112. package/dist/proxy/command.js +122 -0
  113. package/dist/proxy/ipc-service.js +68 -0
  114. package/dist/proxy/manager.js +485 -0
  115. package/dist/proxy/service-supervisor.js +603 -0
  116. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  117. package/dist/utils/cross-platform.js +14 -0
  118. package/dist/utils/ecweb-supervisor.js +258 -83
  119. package/dist/utils/error-utils.js +2 -2
  120. package/dist/utils/logger.js +24 -5
  121. package/dist/utils/package-version-info.js +4 -2
  122. package/kits/docs/channels/aun.md +9 -0
  123. package/kits/docs/evolcore/agent.md +1 -1
  124. package/kits/docs/evolcore/config.md +17 -6
  125. package/kits/docs/evolcore/contact.md +3 -0
  126. package/kits/docs/evolcore/fs.md +11 -0
  127. package/kits/docs/evolcore/memory-architecture.md +2 -2
  128. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  129. package/kits/docs/evolcore/memory.md +1 -1
  130. package/kits/docs/evolcore/menu-protocol.md +4 -0
  131. package/kits/docs/evolcore/model.md +23 -20
  132. package/kits/docs/evolcore/msg.md +4 -7
  133. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  134. package/kits/schemas/_meta.json +37 -4
  135. package/kits/schemas/agent-config.schema.13.json +8 -3
  136. package/kits/schemas/agent-config.schema.16.json +891 -0
  137. package/kits/schemas/daemon.schema.9.json +366 -0
  138. package/kits/schemas/defaults.schema.5.json +406 -127
  139. package/kits/schemas/relation-config.schema.11.json +260 -0
  140. package/kits/schemas/role-config.schema.1.json +7 -7
  141. package/kits/skills/.switches.json +3 -7
  142. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  143. package/kits/skills/ec-trigger/SKILL.md +13 -5
  144. package/kits/skills/personal-assistant/SKILL.md +176 -0
  145. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  146. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  147. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  148. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  149. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  150. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  151. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  152. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  153. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  154. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  155. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  156. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  157. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  158. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  159. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  160. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  161. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  162. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  163. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  164. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  165. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  166. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  167. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  168. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  169. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  170. package/kits/templates/memory-consolidation/forget.md +19 -6
  171. package/kits/templates/memory-consolidation/notes.md +1 -1
  172. package/kits/templates/memory-consolidation/profile.md +2 -2
  173. package/kits/templates/memory-consolidation/promote.md +20 -3
  174. package/kits/templates/roles/member.json +8 -1
  175. package/kits/templates/system-fragments/baseagent.md +2 -2
  176. package/kits/templates/system-fragments/memory.md +4 -4
  177. package/package.json +6 -2
@@ -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';
@@ -18,6 +21,8 @@ import { appendAidEvent } from '../utils/instance-registry.js';
18
21
  import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInboundEntry, classifyAunPayloadForLog, findLatestMessageLogOperation, findMessageLogOperationMessageId, hasMessageLogOperation } from '../core/message/message-log.js';
19
22
  import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
20
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';
21
26
  import { readTopicLabel, readTopicStatus } from '../core/session/session-mapper.js';
22
27
  import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
23
28
  import { appendAidLifecycle } from '../aun/aid/identity.js';
@@ -46,7 +51,8 @@ import { bindPostBootstrapWelcomeOutboxSession, hasPendingPostBootstrapWelcomeOu
46
51
  import { hasMentionAll, mentionEntryAids, mentionEntryTargets, } from '../core/message/mention-schema.js';
47
52
  import { aunOutboundAttention, normalizeAunMentionEntries, parseAunAttention, withAunAttention, } from '../aun/msg/mention-schema.js';
48
53
  import { isDeliveryTarget, sameDeliveryTarget } from '../core/message/message-utils.js';
49
- 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';
50
56
  import { sentReceipt, suppressedReceipt } from '../core/message/send-receipt.js';
51
57
  export const AUN_HANDOFF_MARKER_FIELD = '_evolcore_handoff_id';
52
58
  const AUN_INTERACTION_CARD_TTL_MS = 24 * 60 * 60 * 1000;
@@ -61,6 +67,11 @@ const AUN_SEND_LOG_TEXT_MAX_LENGTH = 60;
61
67
  const AUN_MAX_PAYLOAD_SIZE = 512 * 1024;
62
68
  const AUN_MAX_FIELD_SIZE = 256 * 1024;
63
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
+ ]);
64
75
  function jsonUtf8Size(value) {
65
76
  return Buffer.byteLength(JSON.stringify(value), 'utf8');
66
77
  }
@@ -695,10 +706,12 @@ export class AUNChannel {
695
706
  return this.managedMenuClient.request(options);
696
707
  }
697
708
  client = null;
709
+ ownerDirectoryCache;
698
710
  store = null;
699
711
  /** 实际连接的网关 URL(来自 authenticate() 返回值 / connection.state 事件),替代旧 (client as any)._gatewayUrl。 */
700
712
  gatewayUrl = '';
701
713
  projectPathProvider;
714
+ sessionStateResolver;
702
715
  messageHandler;
703
716
  recallHandler;
704
717
  connected = false;
@@ -1488,6 +1501,147 @@ export class AUNChannel {
1488
1501
  logger.warn(`${this.logPrefix()} topic.renamed failed: ${error instanceof Error ? error.message : String(error)}`);
1489
1502
  });
1490
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
+ }
1491
1645
  buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId, label, topicStatus) {
1492
1646
  if (!groupId)
1493
1647
  throw new Error('buildGroupReplyContext requires groupId');
@@ -2122,6 +2276,9 @@ export class AUNChannel {
2122
2276
  this.connected = true;
2123
2277
  this.connectedAt = Date.now();
2124
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
+ });
2125
2282
  if (!this.config.pureIdentity) {
2126
2283
  void Promise.resolve(this.groupInviteConnectedHandler?.()).catch(error => {
2127
2284
  logger.warn(`${this.logPrefix()} Group invitation recovery failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -2558,6 +2715,12 @@ export class AUNChannel {
2558
2715
  payload,
2559
2716
  });
2560
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
+ }
2561
2724
  logger.info(`${this.logPrefix()} AUN request response matched: request_id=${responseRecord.requestId} mid=${messageId}`);
2562
2725
  const responseLog = classifyAunPayloadForLog(payload);
2563
2726
  this.appendInboundPayloadJsonl(fromAid, fromAid, messageId, !!env.encrypted, false, responseLog, undefined, receivedAt, seq);
@@ -2611,6 +2774,8 @@ export class AUNChannel {
2611
2774
  logger.debug(`${this.logPrefix()} P2P dropped: echo from self (from=${fromAid} mid=${messageId})`);
2612
2775
  return;
2613
2776
  }
2777
+ // Active authorization request removed: Owner now pushes grants via owner.directory.grant event.
2778
+ // this.checkOwnerDirectoryAuthorizationOnMessage(fromAid, payload);
2614
2779
  // 记录入站消息加密状态,透传到出站 ReplyContext
2615
2780
  const msgEncrypted = !!env.encrypted;
2616
2781
  if (!msgEncrypted)
@@ -2649,6 +2814,14 @@ export class AUNChannel {
2649
2814
  });
2650
2815
  return;
2651
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
+ }
2652
2825
  // action_card_reply 已在 extractTextPayload 中消费,不分发给 agent
2653
2826
  if (p2pPayloadType === 'action_card_reply') {
2654
2827
  this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq);
@@ -2833,6 +3006,8 @@ export class AUNChannel {
2833
3006
  logger.debug(`${this.logPrefix()} Group dropped: own message (group=${groupId} mid=${messageId})`);
2834
3007
  return;
2835
3008
  }
3009
+ // Active authorization request removed: Owner now pushes grants via owner.directory.grant event.
3010
+ // this.checkOwnerDirectoryAuthorizationOnMessage(senderAid, payload);
2836
3011
  // 短 echo 快速通道:连通性测试要尽量低延迟,命中后绕过所有 await(后续 mention 过滤)
2837
3012
  {
2838
3013
  const firstLineFast = text.split('\n')[0] || '';
@@ -3941,6 +4116,9 @@ export class AUNChannel {
3941
4116
  onProjectPathRequest(provider) {
3942
4117
  this.projectPathProvider = provider;
3943
4118
  }
4119
+ setSessionStateResolver(resolver) {
4120
+ this.sessionStateResolver = resolver;
4121
+ }
3944
4122
  onMessage(handler) {
3945
4123
  this.messageHandler = handler;
3946
4124
  }
@@ -4066,6 +4244,57 @@ export class AUNChannel {
4066
4244
  finalPayload.debug = { ...context.debug, sentAt: localTimestamp() };
4067
4245
  return finalPayload;
4068
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
+ }
4069
4298
  /**
4070
4299
  * Validate AUN-specific structured fields before crossing the durable
4071
4300
  * send boundary. Return a copy when mentions are present so callers do not
@@ -4161,6 +4390,10 @@ export class AUNChannel {
4161
4390
  fallback.chatmode = truncateUtf8ToBytes(payload.chatmode, 32);
4162
4391
  if (typeof payload.thread_id === 'string')
4163
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;
4164
4397
  logger.info(`${this.logPrefix()} Thought payload reduced to fallback (${Buffer.byteLength(JSON.stringify(fallback), 'utf8')} bytes)`);
4165
4398
  return fallback;
4166
4399
  }
@@ -4361,6 +4594,9 @@ export class AUNChannel {
4361
4594
  logger.error(`${this.logPrefix()} Dropped durable AUN payload: invalid payload.mentions (${detail}) code=${code} channel=${channelId}`);
4362
4595
  return { ok: false, status: 'permanent', error: detail, code };
4363
4596
  }
4597
+ if (delivery.chatType === 'private') {
4598
+ normalizedPayload = this.withCurrentTopicName(channelId, normalizedPayload);
4599
+ }
4364
4600
  if (!this.client || !this.connected) {
4365
4601
  return { ok: false, status: 'retry', error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
4366
4602
  }
@@ -4381,7 +4617,7 @@ export class AUNChannel {
4381
4617
  if (payloadWithCausationRef.thread_id === '')
4382
4618
  delete payloadWithCausationRef.thread_id;
4383
4619
  // Truncate payload if too large (AUN SDK limit: 1MB)
4384
- const truncatedPayload = this.truncatePayloadIfNeeded(payloadWithCausationRef, label);
4620
+ const truncatedPayload = this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
4385
4621
  const params = { payload: truncatedPayload, encrypt };
4386
4622
  const isMenuPayload = typeof truncatedPayload.type === 'string' && truncatedPayload.type.startsWith('menu.');
4387
4623
  if (!isGroup && ['menu.response', 'menu.event'].includes(truncatedPayload.type))
@@ -4440,6 +4676,31 @@ export class AUNChannel {
4440
4676
  return { ok: false, status: failure.status, error: failure.error, code: failure.code };
4441
4677
  }
4442
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
+ }
4443
4704
  recordDurableOutbound(channelId, payload, messageId, encrypt, context, isGroup, contentKind, logText, result, statsContext) {
4444
4705
  const causation = normalizeCausation(context?.metadata?.causation);
4445
4706
  if (!isGroup && causation)
@@ -4909,6 +5170,16 @@ export class AUNChannel {
4909
5170
  }
4910
5171
  if (args.debug)
4911
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
+ }
4912
5183
  const encrypt = args.encrypt ?? this.shouldEncrypt(args.to);
4913
5184
  const sendParams = {
4914
5185
  to: args.to,
@@ -5010,7 +5281,7 @@ export class AUNChannel {
5010
5281
  // Validate before deep-cleaning so undefined entries cannot be silently
5011
5282
  // removed from a malformed mentions array.
5012
5283
  const validatedPayload = this.normalizeAunPayloadMentions(args.payload);
5013
- const finalPayload = this.stripUndefinedDeep(validatedPayload);
5284
+ let finalPayload = this.stripUndefinedDeep(validatedPayload);
5014
5285
  if (finalPayload.thread_id === '')
5015
5286
  delete finalPayload.thread_id;
5016
5287
  const payloadMentions = Object.prototype.hasOwnProperty.call(finalPayload, 'mentions')
@@ -5031,6 +5302,11 @@ export class AUNChannel {
5031
5302
  }
5032
5303
  if (args.debug)
5033
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
+ });
5034
5310
  const encrypt = args.encrypt ?? this.shouldEncrypt(args.groupId);
5035
5311
  const result = await this.callAndTrace('group.send', {
5036
5312
  group_id: args.groupId,
@@ -5178,19 +5454,11 @@ export class AUNChannel {
5178
5454
  }
5179
5455
  // 从 context.metadata.source 读取 source,默认为 'daemon'
5180
5456
  const source = context?.metadata?.source ?? 'daemon';
5181
- // Merge ext hints from context into the wire payload.
5182
- // isFinal: written by response-engine; turnMessageCount: total messages this turn (only on final).
5183
- let ext = context?.ext
5184
- ? { ...context.ext }
5185
- : undefined;
5186
- if (ext?.isFinal) {
5187
- const turnKey = `${channelId}\0${context?.threadId ?? ''}`;
5188
- const total = this.sentCount.get(turnKey) ?? 1;
5189
- ext = { ...ext, turnMessageCount: total };
5190
- }
5191
- const payload = withAunAttention({ type: 'text', text: finalText }, context?.attention);
5192
- if (ext && Object.keys(ext).length > 0)
5193
- 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);
5194
5462
  // sentAt 在每次投递尝试时盖戳(outbox 重发取重发时刻)。服务端会用自己的时间覆盖
5195
5463
  // 顶层 timestamp,两者有毫秒级差异,sentAt 只代表本端时钟。
5196
5464
  if (context?.debug)
@@ -5210,6 +5478,9 @@ export class AUNChannel {
5210
5478
  payload.chatmode = context.metadata.chatmode;
5211
5479
  if (context?.metadata?.forkAnchor)
5212
5480
  payload.fork_anchor = context.metadata.forkAnchor;
5481
+ if (delivery.chatType === 'private') {
5482
+ Object.assign(payload, this.withCurrentTopicName(channelId, payload));
5483
+ }
5213
5484
  const causation = normalizeCausation(context?.metadata?.causation);
5214
5485
  const causationRef = delivery.chatType !== 'group' && causation
5215
5486
  ? `caus_${crypto.randomUUID().replace(/-/g, '')}`
@@ -5596,9 +5867,14 @@ export class AUNChannel {
5596
5867
  // Same diagnostic dictionary as text payloads (sessionId/agentSessionId/model).
5597
5868
  if (context?.debug)
5598
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);
5599
5875
  const params = {
5600
5876
  context: { type: 'task', id: taskId },
5601
- payload: this.limitThoughtPayload(payloadWithChatmode),
5877
+ payload: thoughtPayload,
5602
5878
  encrypt,
5603
5879
  };
5604
5880
  try {
@@ -5640,6 +5916,9 @@ export class AUNChannel {
5640
5916
  if (!isThoughtTooLargeError(error))
5641
5917
  throw error;
5642
5918
  thoughtPayload = this.thoughtPayloadFallback(thoughtPayload);
5919
+ if (delivery.chatType === 'private') {
5920
+ thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
5921
+ }
5643
5922
  params.payload = thoughtPayload;
5644
5923
  thoughtText = this.activityLogText(thoughtPayload);
5645
5924
  logger.warn(`${this.logPrefix()} Retrying ${method} with minimal payload after server size rejection`);
@@ -5676,7 +5955,7 @@ export class AUNChannel {
5676
5955
  // Validate before checking connection state so malformed producer payloads
5677
5956
  // are reported deterministically instead of being hidden by a disconnect.
5678
5957
  const validatedPayload = this.normalizeAunPayloadMentions(payload);
5679
- const finalPayload = this.stripUndefinedDeep(withAunAttention(validatedPayload, context?.attention));
5958
+ let finalPayload = this.stripUndefinedDeep(withAunAttention(validatedPayload, context?.attention));
5680
5959
  if (!this.connected || !this.client) {
5681
5960
  return {
5682
5961
  ok: false,
@@ -5698,7 +5977,11 @@ export class AUNChannel {
5698
5977
  finalPayload.thread_id = context.threadId;
5699
5978
  if (context?.replyToMessageId && !finalPayload.ref_message_id)
5700
5979
  finalPayload.ref_message_id = context.replyToMessageId;
5980
+ if (!isGroup) {
5981
+ Object.assign(finalPayload, this.withCurrentTopicName(channelId, finalPayload));
5982
+ }
5701
5983
  const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
5984
+ finalPayload = await this.withSessionState(channelId, finalPayload, context);
5702
5985
  const params = { payload: finalPayload, encrypt };
5703
5986
  if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
5704
5987
  params.to_device_id = context?.toDeviceId;
@@ -6007,13 +6290,16 @@ export class AUNChannel {
6007
6290
  try {
6008
6291
  const { attachment } = await uploadFileAndBuildPayload(this.client, this.config.aid, absPath, { as: 'file' });
6009
6292
  const { filename, size_bytes: size, content_type: contentType } = attachment;
6010
- const filePayload = buildAunFilePayload({
6293
+ const filePayload = await this.withSessionState(channelId, buildAunFilePayload({
6011
6294
  filename,
6012
6295
  size,
6013
6296
  contentType,
6014
6297
  attachment: { ...attachment },
6015
6298
  context,
6016
- });
6299
+ }), context);
6300
+ if (!isGroup) {
6301
+ Object.assign(filePayload, this.withCurrentTopicName(channelId, filePayload));
6302
+ }
6017
6303
  const fileTargetAid = channelId;
6018
6304
  const encryptTarget = isGroup ? channelId : fileTargetAid;
6019
6305
  const encrypt = context?.metadata?.encrypted != null
@@ -6619,6 +6905,10 @@ export class AUNChannelPlugin {
6619
6905
  : (envelope.replyContext || envelope.delivery)
6620
6906
  ? { ...(envelope.replyContext ?? {}), delivery }
6621
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
+ }
6622
6912
  const attention = aunOutboundAttention(payload);
6623
6913
  if (replyCtx) {
6624
6914
  replyCtx = { ...replyCtx };
@@ -7106,6 +7396,30 @@ export class AUNChannelPlugin {
7106
7396
  },
7107
7397
  registerHooks(hookCtx) {
7108
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
+ });
7109
7423
  // 话题改名通知消费器:直接改本端索引,不经过 Agent 队列。
7110
7424
  channel.setThreadRenameHandler(async (input) => {
7111
7425
  const { ThreadService } = await import('../core/thread/thread-service.js');
@@ -1,10 +1,12 @@
1
1
  import { appendExpireEntry, recordNextLaunchCleanup, cleanupPreviousByKind, runExpireCleanup, cleanupSessionRecord, } from '../core/background-session/session-cleanup.js';
2
2
  import { ExecutionTimeoutError } from '../utils/error-utils.js';
3
+ import { logger } from '../utils/logger.js';
3
4
  import { normalizeExecutionMode } from '../trigger/validation.js';
4
5
  import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
5
6
  import { assertSystemSessionLaunchable } from '../core/system-session/registry.js';
6
7
  import { sessionTopicThreadId } from '../core/thread/topic-id.js';
7
8
  const DEFAULT_WATCHDOG_MS = 11 * 60 * 1000;
9
+ const EXPIRE_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
8
10
  export class DaemonChannel {
9
11
  sessionManager;
10
12
  messageQueue;
@@ -23,15 +25,27 @@ export class DaemonChannel {
23
25
  bgPending = new Map();
24
26
  watchdogMs;
25
27
  totalExecutionMs;
28
+ expireCleanupTimer;
26
29
  constructor(sessionManager, messageQueue, opts = {}) {
27
30
  this.sessionManager = sessionManager;
28
31
  this.messageQueue = messageQueue;
29
32
  this.watchdogMs = normalizeWatchdogMs(opts.watchdogMs);
30
33
  this.totalExecutionMs = normalizeTotalExecutionMs(opts.totalExecutionMs);
34
+ // expire 扫描不能只挂在 converse / bg-session 启动上:script 与 target_session 类 trigger
35
+ // 不走 converse,记忆整理走 on_next_launch,实际几乎没有调用方,到期登记会一直不被消费。
36
+ // 启动时扫一次,之后每小时一次。
37
+ this.runExpireCleanupSafely();
38
+ this.expireCleanupTimer = setInterval(() => this.runExpireCleanupSafely(), EXPIRE_CLEANUP_INTERVAL_MS);
39
+ this.expireCleanupTimer.unref?.();
40
+ }
41
+ runExpireCleanupSafely() {
42
+ void runExpireCleanup(this.sessionManager).catch((e) => {
43
+ logger.warn(`[DaemonChannel] expire 清理失败: ${e?.message}`);
44
+ });
31
45
  }
32
46
  async converse(prompt, ctx) {
33
47
  // 启动前跑一次 expire 扫描(成本低,只读少量小文件)
34
- void runExpireCleanup(this.sessionManager).catch(() => { });
48
+ this.runExpireCleanupSafely();
35
49
  const runId = ctx.runId;
36
50
  const pendingId = ctx.attemptId ?? runId;
37
51
  const messageId = pendingId;
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import crypto from 'crypto';
4
4
  import { agentMdPath, resolvePaths, resolveRoot } from '../paths.js';
5
- import { isExplicitGroupId, normalizeGroupAid, sameGroupAid } from '../aun/group/index.js';
5
+ import { normalizeGroupAid, sameGroupAid } from '../aun/group/index.js';
6
6
  import { getArgValue, isHelpFlag, wantsHelp } from './help.js';
7
7
  import { daemonUnavailableMessage, queryDaemon } from './help.js';
8
8
  import { isValidAid as validSendAid } from '../aun/aid/validation.js';
@@ -2190,7 +2190,7 @@ Options:
2190
2190
  };
2191
2191
  // `--thread` 的原文只用于解析;发出的必须是规范 id(历史写法 `<peer>/<id>`
2192
2192
  // 若原样上线,对端会把它当成一个不存在的话题 id)。
2193
- const result = await msgSend({ from, to, body, encrypt, deviceId: getArgValue(args, '--device-id'), thread: thread ? threadTopicId : undefined, returnPolicy: returnPolicyRaw, timeoutMs, handoffContext: getArgValue(args, '--handoff-context'), onUploadProgress, ...commonOpts });
2193
+ const result = await msgSend({ from, to, body, encrypt, deviceId: getArgValue(args, '--device-id'), thread: thread ? threadTopicId : undefined, timeoutMs, handoffContext: getArgValue(args, '--handoff-context'), onUploadProgress, ...commonOpts });
2194
2194
  if (!result.ok) {
2195
2195
  if (formatJson) {
2196
2196
  console.log(JSON.stringify(result));
@@ -2526,25 +2526,9 @@ g- 是名称的一部分,会完整保留;默认命名格式为 g-10000 至 g
2526
2526
  console.error('❌ 缺少 <from-aid> 参数');
2527
2527
  process.exit(1);
2528
2528
  }
2529
- // 第 1 个位置参数必须是「发送方 AID」。群 ID 与私聊 AID 语法相同,isValidAid
2530
- // 会放行,随后在加载证书时抛 CERT_NOT_FOUND——这条路径既不说明原因也不给出
2531
- // 正确写法。因此先用明确的群 ID 形态判定,把"参数写反了"当场指出来。
2532
- // 例外:invites 是多值标志/邀请列表,第 1 个位置参数不是 from;create/list 的
2533
- // 形态不同,也在下面各自的用法里处理,这里只拦截"以群 ID 打头"这一种错位。
2529
+ // A sender's AID spelling cannot establish its type. Delegation or the local
2530
+ // authenticated client validates the sender after this syntax check.
2534
2531
  const { isValidAid } = await import('../aun/aid/index.js');
2535
- if (isExplicitGroupId(from)) {
2536
- const second = args[2];
2537
- console.error(`❌ 第 1 个位置参数 <from-aid> 无效:收到了群 ID: ${from}`);
2538
- if (second && isValidAid(second) && !isExplicitGroupId(second)) {
2539
- console.error(`检测到参数顺序写反了:第 2 个参数 ${second} 才是发送方 AID。`);
2540
- console.error(`请改成: ec group ${sub} ${second} ${from}` + (sub === 'send' ? ' <正文>' : ''));
2541
- }
2542
- else {
2543
- console.error('当前命令缺少发送方 AID,后续参数发生了错位。');
2544
- }
2545
- printGroupArgsHint(sub);
2546
- process.exit(1);
2547
- }
2548
2532
  if (!isValidAid(from)) {
2549
2533
  console.error(`❌ 第 1 个位置参数 <from-aid> 无效: ${from}`);
2550
2534
  printGroupArgsHint(sub);