evolcore 0.0.43-test.4 → 0.0.43-test.6

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 (186) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ecmsg.js +437 -91
  3. package/dist/agents/baseagent-availability.js +19 -4
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +14 -3
  7. package/dist/agents/codex-runner.js +18 -23
  8. package/dist/aun/aid/agentmd.js +25 -0
  9. package/dist/aun/aid/control-aid.js +15 -0
  10. package/dist/aun/aid/identity.js +8 -0
  11. package/dist/aun/aid/ownership-operation.js +12 -3
  12. package/dist/aun/group/invite-service.js +3 -2
  13. package/dist/aun/service-proxy.js +18 -6
  14. package/dist/channels/aun.js +99 -23
  15. package/dist/channels/daemon.js +2 -2
  16. package/dist/cli/agent-create.js +19 -7
  17. package/dist/cli/aid-bind-command.js +3 -0
  18. package/dist/cli/aun-commands.js +19 -4
  19. package/dist/cli/code-stats.js +451 -213
  20. package/dist/cli/ctl-command.js +1 -3
  21. package/dist/cli/daemon-commands.js +42 -4
  22. package/dist/cli/directory.js +3 -1
  23. package/dist/cli/ecmsg-gateway.js +206 -0
  24. package/dist/cli/index.js +6 -0
  25. package/dist/cli/init.js +120 -13
  26. package/dist/cli/provider-command.js +82 -5
  27. package/dist/cli/restart-monitor.js +35 -24
  28. package/dist/cli/stats.js +8 -1
  29. package/dist/cli/task-context.js +41 -1
  30. package/dist/cli/watch-logs.js +6 -4
  31. package/dist/config/boot-log.js +16 -3
  32. package/dist/config/builtin-roles.js +2 -2
  33. package/dist/config/config-manager.js +5 -14
  34. package/dist/config/daemon-services.js +1 -0
  35. package/dist/config/peer-role-resolver.js +6 -6
  36. package/dist/config/provider-identity-migration.js +277 -0
  37. package/dist/config/provider-identity.js +37 -0
  38. package/dist/config/provider-ipc-service.js +40 -3
  39. package/dist/config/provider-local-sync.js +155 -0
  40. package/dist/config/providers-config.js +45 -4
  41. package/dist/config/providers-management.js +242 -76
  42. package/dist/config/providers.js +4 -1
  43. package/dist/config/role-service.js +8 -8
  44. package/dist/config/role-store.js +22 -22
  45. package/dist/config/schema-migration.js +143 -86
  46. package/dist/config/snapshot.js +70 -41
  47. package/dist/core/agent-runtime.js +48 -9
  48. package/dist/core/auth/auth-gateway.js +5 -3
  49. package/dist/core/auth/delegation-diagnostics.js +6 -2
  50. package/dist/core/auth/operation-authorizer.js +3 -1
  51. package/dist/core/auth/operation-catalog.js +6 -4
  52. package/dist/core/baseagent-loader.js +114 -11
  53. package/dist/core/channel-loader.js +36 -13
  54. package/dist/core/channel-runtime.js +112 -42
  55. package/dist/core/command/cli-intent-parser.js +2 -1
  56. package/dist/core/command/command-handler.js +16 -11
  57. package/dist/core/command/menu-handler.js +8 -3
  58. package/dist/core/command/menu-protocol.js +80 -7
  59. package/dist/core/command/provider-menu.js +4 -2
  60. package/dist/core/command/role-menu.js +29 -17
  61. package/dist/core/command/slash-handler.js +52 -16
  62. package/dist/core/daemon-control.js +42 -15
  63. package/dist/core/daemon-lifecycle.js +411 -67
  64. package/dist/core/handoff/dispatcher.js +9 -3
  65. package/dist/core/handoff/runtime.js +139 -45
  66. package/dist/core/handoff/store.js +190 -2
  67. package/dist/core/handoff/types.js +5 -0
  68. package/dist/core/initialization/service.js +7 -6
  69. package/dist/core/ipc-registration.js +5 -4
  70. package/dist/core/lifecycle-notice.js +10 -4
  71. package/dist/core/message/aun-ipc-sender.js +83 -5
  72. package/dist/core/message/message-admission.js +2 -0
  73. package/dist/core/message/message-bridge.js +53 -4
  74. package/dist/core/message/message-queue.js +46 -4
  75. package/dist/core/message/pending-hints.js +4 -10
  76. package/dist/core/message/response-engine.js +33 -25
  77. package/dist/core/message/send-options.js +40 -0
  78. package/dist/core/message/send-routing.js +320 -0
  79. package/dist/core/ownership/owner-resolver.js +112 -8
  80. package/dist/core/permission/ec-command-parser.js +159 -16
  81. package/dist/core/permission/readonly-shell-query.js +66 -7
  82. package/dist/core/permission/tool-error-code.js +13 -1
  83. package/dist/core/permission/tool-policy.js +74 -20
  84. package/dist/core/relation/same-owner-proof.js +131 -0
  85. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  86. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  87. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  88. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  89. package/dist/core/session/session-fs-store.js +164 -3
  90. package/dist/core/session/session-idle-monitor.js +103 -17
  91. package/dist/core/session/session-manager.js +105 -18
  92. package/dist/core/thread/thread-route.js +5 -2
  93. package/dist/directory/owner-directory-admission.js +26 -1
  94. package/dist/directory/owner-directory-cache.js +739 -109
  95. package/dist/directory/owner-directory-markdown.js +146 -36
  96. package/dist/directory/owner-directory-query-operation.js +6 -3
  97. package/dist/directory/owner-directory-scope.js +12 -0
  98. package/dist/directory/owner-directory-search.js +5 -1
  99. package/dist/directory/owner-directory-store.js +28 -0
  100. package/dist/ecweb/basic-settings-service.js +15 -1
  101. package/dist/ecweb/message-context-service.js +2 -2
  102. package/dist/ecweb/providers-service.js +3 -1
  103. package/dist/ecweb/runtime/lifecycle.js +26 -15
  104. package/dist/ecweb/runtime/supervisor.js +120 -51
  105. package/dist/index.js +551 -250
  106. package/dist/paths.js +2 -1
  107. package/dist/proxy/manager.js +40 -17
  108. package/dist/proxy/service-supervisor.js +67 -33
  109. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  110. package/dist/trigger/application-service.js +4 -1
  111. package/dist/trigger/audit.js +19 -4
  112. package/dist/trigger/authorization.js +14 -5
  113. package/dist/trigger/event-source.js +4 -0
  114. package/dist/trigger/feedback.js +26 -2
  115. package/dist/trigger/history.js +176 -7
  116. package/dist/trigger/manager.js +1 -3
  117. package/dist/trigger/scheduler.js +81 -8
  118. package/dist/trigger/system-definitions.js +2 -2
  119. package/dist/trigger/validation.js +4 -0
  120. package/dist/utils/autostart.js +2 -2
  121. package/dist/utils/cross-platform.js +188 -12
  122. package/dist/utils/host-info.js +11 -8
  123. package/dist/utils/npm-ops.js +48 -0
  124. package/dist/utils/process-introspect.js +64 -1
  125. package/dist/utils/public-suffix.js +5811 -0
  126. package/dist/utils/startup-trace.js +160 -19
  127. package/dist/utils/windows-autostart.js +41 -7
  128. package/ecagent/dist/harness/env/nodejs.js +46 -2
  129. package/kits/docs/aun/ABILITY_CALLING.md +6 -6
  130. package/kits/docs/channels/aun.md +1 -1
  131. package/kits/docs/channels/feishu.md +2 -2
  132. package/kits/docs/context-assembly.md +20 -4
  133. package/kits/docs/evolcore/INDEX.md +5 -3
  134. package/kits/docs/evolcore/agent.md +2 -2
  135. package/kits/docs/evolcore/aid.md +8 -2
  136. package/kits/docs/evolcore/ctl.md +15 -5
  137. package/kits/docs/evolcore/directory.md +48 -15
  138. package/kits/docs/evolcore/group.md +8 -8
  139. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  140. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  141. package/kits/docs/evolcore/menu-protocol.md +32 -3
  142. package/kits/docs/evolcore/msg.md +38 -30
  143. package/kits/docs/evolcore/provider.md +57 -5
  144. package/kits/docs/evolcore/response.md +2 -2
  145. package/kits/docs/evolcore/thread-chain.md +11 -13
  146. package/kits/docs/evolcore/tool-authorization.md +17 -0
  147. package/kits/docs/evolcore/trigger.md +2 -2
  148. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  149. package/kits/docs/prompt-loading-architecture.md +30 -20
  150. package/kits/eck_manifest.auxiliary.json +5 -5
  151. package/kits/eck_manifest.json +44 -32
  152. package/kits/eck_manifest.memory.json +18 -18
  153. package/kits/eck_message_manifest.json +3 -3
  154. package/kits/rules/01-overview.md +1 -1
  155. package/kits/rules/06-channel.md +7 -8
  156. package/kits/schemas/_meta.json +7 -1
  157. package/kits/schemas/daemon.schema.1.json +5 -0
  158. package/kits/schemas/daemon.schema.2.json +5 -0
  159. package/kits/schemas/daemon.schema.3.json +2 -1
  160. package/kits/schemas/daemon.schema.4.json +2 -1
  161. package/kits/schemas/daemon.schema.5.json +2 -1
  162. package/kits/schemas/daemon.schema.6.json +1 -1
  163. package/kits/schemas/daemon.schema.7.json +1 -1
  164. package/kits/schemas/daemon.schema.8.json +2 -1
  165. package/kits/schemas/daemon.schema.9.json +2 -1
  166. package/kits/schemas/providers.schema.2.json +74 -0
  167. package/kits/schemas/role-registry.schema.1.json +2 -2
  168. package/kits/schemas/single-session.schema.1.json +1 -1
  169. package/kits/schemas/single-session.schema.2.json +1 -1
  170. package/kits/schemas/single-session.schema.3.json +1 -1
  171. package/kits/skills/aid-ability/SKILL.md +7 -7
  172. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  173. package/kits/skills/ec-group/SKILL.md +8 -5
  174. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  175. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  176. package/kits/skills/ec-trigger/SKILL.md +9 -9
  177. package/kits/skills/ec-trigger/references/examples.md +1 -1
  178. package/kits/skills/thread-ops/SKILL.md +10 -10
  179. package/kits/templates/system-fragments/channel.md +5 -5
  180. package/kits/templates/system-fragments/commands.md +7 -6
  181. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  182. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  183. package/kits/templates/system-fragments/reply.md +48 -28
  184. package/kits/templates/system-fragments/session.md +3 -10
  185. package/kits/templates/system-fragments/thread.md +5 -5
  186. package/package.json +4 -4
@@ -1,4 +1,4 @@
1
- import { formatChannelKey } from '../channel-loader.js';
1
+ import { formatChannelKey, tryParseChannelKey } from '../channel-loader.js';
2
2
  import { classifyAunPayloadForLog } from '../message/message-log.js';
3
3
  import { HandoffDispatcher } from './dispatcher.js';
4
4
  import { KeyedFairMutex } from './mutex.js';
@@ -6,10 +6,11 @@ import { HandoffStore } from './store.js';
6
6
  import { createRootCausation, deriveCausation, normalizeCausation } from '../causation/context.js';
7
7
  import { recordCausationSpan } from '../causation/audit.js';
8
8
  import { logger } from '../../utils/logger.js';
9
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
9
10
  import { replyContextFromSession } from '../message/message-utils.js';
10
11
  import { sessionTopicThreadId } from '../thread/topic-id.js';
11
- const HANDOFF_STALE_WARN_MS = 72 * 60 * 60 * 1000;
12
- const HANDOFF_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
12
+ const HANDOFF_STALE_WARN_MS = 12 * 60 * 60 * 1000;
13
+ const HANDOFF_RETENTION_MS = 72 * 60 * 60 * 1000;
13
14
  const HANDOFF_LARGE_AGGREGATE_COUNT = 10;
14
15
  const HANDOFF_LARGE_AGGREGATE_CHARS = 50_000;
15
16
  /** Keep origin-side context bounded; the persisted handoff remains complete. */
@@ -75,7 +76,13 @@ export class HandoffRuntime {
75
76
  throwIfAborted(input.signal);
76
77
  if (!origin || origin.selfAID !== input.selfAid)
77
78
  throw new Error('origin session not found');
78
- const targetChannelKey = formatChannelKey({ type: 'aun', selfAID: input.selfAid, name: 'main' });
79
+ // 目标渠道:缺省 AUN 主渠(历史行为);跨会话投递给其它渠道的会话时,
80
+ // 由调用方显式传入该会话真实的 channelKey / channelType。
81
+ const targetChannelKey = input.targetChannelKey
82
+ ?? formatChannelKey({ type: 'aun', selfAID: input.selfAid, name: 'main' });
83
+ const targetChannelType = input.targetChannelType
84
+ ?? tryParseChannelKey(targetChannelKey)?.type
85
+ ?? 'aun';
79
86
  if (!input.targetChatType) {
80
87
  throw Object.assign(new Error('AUN handoff requires an explicit target chat type'), {
81
88
  code: 'AUN_OUTBOUND_ROUTE_REQUIRED',
@@ -86,7 +93,7 @@ export class HandoffRuntime {
86
93
  channelKey: targetChannelKey,
87
94
  peerId: input.to,
88
95
  ...(targetChatType === 'group' ? { groupId: input.to } : {}),
89
- }, undefined, input.to, targetChatType, origin.baseagent, input.selfAid, 'aun', targetChatType === 'group' ? 'group' : 'agent');
96
+ }, undefined, input.to, targetChatType, origin.baseagent, input.selfAid, targetChannelType, targetChatType === 'group' ? 'group' : 'agent');
90
97
  throwIfAborted(input.signal);
91
98
  if (target.id === origin.id) {
92
99
  if (input.handoffContext !== undefined)
@@ -626,6 +633,16 @@ export class HandoffRuntime {
626
633
  expired += this.dispatcher.expireQueued(selfAid).length;
627
634
  return expired;
628
635
  }
636
+ async expireQueuedAsync(selfAids) {
637
+ let expired = 0;
638
+ for (const selfAid of selfAids) {
639
+ for (const snapshot of await this.store.listAsync(selfAid)) {
640
+ await yieldToIo();
641
+ expired += this.dispatcher.expireQueued(selfAid, undefined, [snapshot]).length;
642
+ }
643
+ }
644
+ return expired;
645
+ }
629
646
  async discardSession(selfAid, sessionId) {
630
647
  this.sessionDiscardSequence.set(this.sessionKey(selfAid, sessionId), ++this.lifecycleSequence);
631
648
  const candidates = this.store.list(selfAid)
@@ -641,61 +658,131 @@ export class HandoffRuntime {
641
658
  return discarded;
642
659
  }
643
660
  async discardExpired(selfAids, retentionMs = HANDOFF_RETENTION_MS) {
644
- const now = this.now?.() ?? Date.now();
645
661
  let discarded = 0;
646
662
  for (const selfAid of selfAids) {
647
- const latestEventVersions = new Map();
648
- for (const event of this.store.events(selfAid)) {
649
- if (!event.handoff_id || event.to_version === undefined)
650
- continue;
651
- latestEventVersions.set(event.handoff_id, Math.max(latestEventVersions.get(event.handoff_id) ?? 0, event.to_version));
652
- }
653
- for (const instance of this.store.list(selfAid)) {
654
- if (instance.state === 'failed' || instance.state === 'completed' || instance.state === 'discarded')
655
- continue;
656
- if (now - instance.created_at <= retentionMs)
657
- continue;
658
- if ((latestEventVersions.get(instance.handoff_id) ?? 0) !== instance.version)
659
- continue;
660
- const result = await this.discardWithTargetLock(selfAid, instance.handoff_id, 'retention_expired', {
661
- retention_ms: retentionMs,
662
- age_ms: now - instance.created_at,
663
- }, instance.version, now);
664
- if (result) {
665
- discarded++;
666
- logger.info(`[Handoff] discarded expired handoff: ${instance.handoff_id}`);
667
- }
663
+ discarded += await this.discardExpiredCandidates(selfAid, await this.store.listAsync(selfAid), retentionMs);
664
+ }
665
+ return discarded;
666
+ }
667
+ async discardExpiredCandidates(selfAid, snapshots, retentionMs = HANDOFF_RETENTION_MS) {
668
+ const now = this.now?.() ?? Date.now();
669
+ const candidates = snapshots.filter(instance => !['failed', 'completed', 'discarded'].includes(instance.state)
670
+ && now - instance.created_at >= retentionMs);
671
+ // Most restarts contain only terminal or young snapshots. Their journal
672
+ // is needed by reconciliation, not by retention cleanup.
673
+ if (!candidates.length)
674
+ return 0;
675
+ let discarded = 0;
676
+ const latestEventVersions = new Map();
677
+ for (const event of await this.store.eventsAsync(selfAid)) {
678
+ if (!event.handoff_id || event.to_version === undefined)
679
+ continue;
680
+ latestEventVersions.set(event.handoff_id, Math.max(latestEventVersions.get(event.handoff_id) ?? 0, event.to_version));
681
+ }
682
+ for (const instance of candidates) {
683
+ await yieldToIo();
684
+ if ((latestEventVersions.get(instance.handoff_id) ?? 0) !== instance.version)
685
+ continue;
686
+ const result = await this.discardWithTargetLock(selfAid, instance.handoff_id, 'retention_expired', {
687
+ retention_ms: retentionMs,
688
+ age_ms: now - instance.created_at,
689
+ }, instance.version, now);
690
+ if (result) {
691
+ discarded++;
692
+ logger.info(`[Handoff] discarded expired handoff: ${instance.handoff_id}`);
668
693
  }
669
694
  }
670
695
  return discarded;
671
696
  }
697
+ async prepareRecovery(selfAid, options = {}) {
698
+ let started = Date.now();
699
+ let scanDetail;
700
+ const snapshots = options.snapshots ?? await this.store.listAsync(selfAid, stats => {
701
+ scanDetail = Object.entries(stats).map(([key, value]) => `${key}=${Math.round(value)}`).join('; ');
702
+ });
703
+ options.onPhase?.('scan', started, Date.now(), scanDetail);
704
+ started = Date.now();
705
+ if (options.discardExpired !== false)
706
+ await this.discardExpiredCandidates(selfAid, snapshots);
707
+ for (const snapshot of snapshots.filter(instance => instance.state === 'queued'
708
+ || (instance.return_policy === 'none' && instance.state === 'return_pending'))) {
709
+ // Only legacy return=none entries can need this migration. Its store
710
+ // method rechecks the current state before changing anything.
711
+ if (snapshot.return_policy === 'none' && snapshot.state === 'return_pending') {
712
+ this.store.migrateLegacyNonePending(selfAid, this.now?.(), [snapshot]);
713
+ }
714
+ if (snapshot.state === 'queued')
715
+ this.dispatcher.expireQueued(selfAid, undefined, [snapshot]);
716
+ await yieldToIo();
717
+ }
718
+ options.onPhase?.('cleanup', started, Date.now());
719
+ return snapshots;
720
+ }
672
721
  async recover(selfAids, options = {}) {
722
+ if (options.snapshots && selfAids.length !== 1)
723
+ throw new Error('recovery snapshots require exactly one Agent');
673
724
  const originEnqueues = [];
674
725
  for (const selfAid of selfAids) {
675
- if (options.discardExpired !== false)
676
- await this.discardExpired([selfAid]);
677
- // v1 initially represented return=none as return_pending and required an
678
- // empty manual return. It has already been shown to a target turn, so
679
- // finish it before version reconciliation instead of prompting again.
680
- this.store.migrateLegacyNonePending(selfAid, this.now?.());
681
- this.expireQueued([selfAid]);
726
+ if (options.isCancelled?.())
727
+ break;
728
+ const snapshots = options.snapshots ?? await this.prepareRecovery(selfAid, options);
729
+ if (!snapshots.length)
730
+ continue;
682
731
  // 单次读取事件流并建索引:下面每个 instance 都要用它,逐条 filter 是 O(实例×事件),
683
732
  // 在实例数上百的 AID 上足以把启动拖慢数秒。
684
- const events = this.store.events(selfAid);
733
+ let started = Date.now();
734
+ const events = await this.store.eventsAsync(selfAid);
735
+ options.onPhase?.('journal', started, Date.now());
736
+ started = Date.now();
685
737
  const lastSendEvent = new Map();
686
738
  const latestEventVersion = new Map();
687
- for (const event of events) {
688
- if (!event.handoff_id)
689
- continue;
690
- if (event.event_type.startsWith('target_send_')) {
691
- lastSendEvent.set(event.handoff_id, event.event_type);
692
- }
693
- if (event.to_version !== undefined) {
694
- latestEventVersion.set(event.handoff_id, Math.max(latestEventVersion.get(event.handoff_id) ?? 0, event.to_version));
739
+ const indexEvents = (entries) => {
740
+ for (const event of entries) {
741
+ if (!event.handoff_id)
742
+ continue;
743
+ if (event.event_type.startsWith('target_send_')) {
744
+ lastSendEvent.set(event.handoff_id, event.event_type);
745
+ }
746
+ if (event.to_version !== undefined) {
747
+ latestEventVersion.set(event.handoff_id, Math.max(latestEventVersion.get(event.handoff_id) ?? 0, event.to_version));
748
+ }
695
749
  }
696
- }
697
- for (const instance of this.store.list(selfAid)) {
750
+ };
751
+ indexEvents(events);
752
+ for (const snapshot of snapshots) {
753
+ await yieldToIo();
754
+ if (options.isCancelled?.())
755
+ break;
756
+ let instance;
757
+ let revision;
758
+ do {
759
+ revision = this.store.mutationRevision(selfAid, snapshot.handoff_id);
760
+ instance = await this.store.getAsync(selfAid, snapshot.handoff_id);
761
+ } while (!options.isCancelled?.() && revision !== this.store.mutationRevision(selfAid, snapshot.handoff_id));
762
+ if (options.isCancelled?.())
763
+ break;
764
+ if (!instance)
765
+ continue;
698
766
  this.warnIfStale(instance);
767
+ // Other work may advance a snapshot between scan batches. Recheck the
768
+ // journal asynchronously before reporting a conflict. Refresh send
769
+ // outcomes too, so an old target_send_started cannot misclassify a retry.
770
+ if ((latestEventVersion.get(instance.handoff_id) ?? 0) !== instance.version
771
+ || (instance.state === 'queued' && lastSendEvent.get(instance.handoff_id) === 'target_send_started')) {
772
+ const observedVersion = instance.version;
773
+ do {
774
+ revision = this.store.mutationRevision(selfAid, snapshot.handoff_id);
775
+ indexEvents(await this.store.eventsAsync(selfAid));
776
+ instance = await this.store.getAsync(selfAid, snapshot.handoff_id);
777
+ // Send retries append events without changing the snapshot version.
778
+ // They must invalidate this journal view just like snapshot writes.
779
+ } while (!options.isCancelled?.() && instance?.version === observedVersion
780
+ && revision !== this.store.mutationRevision(selfAid, snapshot.handoff_id));
781
+ if (options.isCancelled?.())
782
+ break;
783
+ if (!instance || instance.version !== observedVersion)
784
+ continue;
785
+ }
699
786
  const instanceVersion = latestEventVersion.get(instance.handoff_id) ?? 0;
700
787
  if (instanceVersion !== instance.version) {
701
788
  if (!instance.attention_required) {
@@ -705,6 +792,10 @@ export class HandoffRuntime {
705
792
  continue;
706
793
  }
707
794
  if (instance.state === 'queued') {
795
+ // A live dispatcher owns the current send; it is not an uncertain
796
+ // delivery left over from the previous daemon.
797
+ if (this.dispatcher.isRunning(selfAid, instance.target_session_id))
798
+ continue;
708
799
  if (instance.attention_required) {
709
800
  this.dispatcher.notify(selfAid, instance.target_session_id);
710
801
  }
@@ -725,8 +816,11 @@ export class HandoffRuntime {
725
816
  }
726
817
  }
727
818
  }
819
+ options.onPhase?.('reconcile', started, Date.now());
728
820
  }
821
+ const started = Date.now();
729
822
  await Promise.all(originEnqueues);
823
+ options.onPhase?.('origin', started, Date.now());
730
824
  }
731
825
  async discardWithTargetLock(selfAid, handoffId, reason, details, expectedVersion, now = this.now?.()) {
732
826
  const snapshot = this.store.get(selfAid, handoffId);
@@ -6,6 +6,9 @@
6
6
  import crypto from 'crypto';
7
7
  import fs from 'fs';
8
8
  import path from 'path';
9
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
10
+ import { createInterface } from 'node:readline';
11
+ import { performance } from 'node:perf_hooks';
9
12
  import { resolvePaths } from '../../paths.js';
10
13
  import { atomicReadJson } from '../../utils/atomic-write.js';
11
14
  import { appendJsonl, readAllJsonlLines } from '../session/session-fs-store.js';
@@ -49,6 +52,49 @@ function boundedQueryLimit(limit) {
49
52
  export class HandoffStore {
50
53
  rootDir;
51
54
  perAgentLayout;
55
+ activeSnapshotReads = 0;
56
+ snapshotReadWaiters = new Map();
57
+ snapshotReadScheduled = false;
58
+ mutationRevisions = new Map();
59
+ mutationRevision(selfAid, handoffId) {
60
+ return this.mutationRevisions.get(this.instancePath(selfAid, handoffId)) ?? 0;
61
+ }
62
+ noteMutation(selfAid, handoffId) {
63
+ const file = this.instancePath(selfAid, handoffId);
64
+ this.mutationRevisions.set(file, (this.mutationRevisions.get(file) ?? 0) + 1);
65
+ }
66
+ withSnapshotRead(selfAid, read) {
67
+ return new Promise((resolve, reject) => {
68
+ const waiters = this.snapshotReadWaiters.get(selfAid) ?? [];
69
+ waiters.push(() => {
70
+ this.activeSnapshotReads++;
71
+ void Promise.resolve().then(read).then(resolve, reject).finally(() => {
72
+ this.activeSnapshotReads--;
73
+ this.scheduleSnapshotReads();
74
+ });
75
+ });
76
+ this.snapshotReadWaiters.set(selfAid, waiters);
77
+ this.scheduleSnapshotReads();
78
+ });
79
+ }
80
+ scheduleSnapshotReads() {
81
+ if (this.snapshotReadScheduled || this.activeSnapshotReads >= 8 || !this.snapshotReadWaiters.size)
82
+ return;
83
+ this.snapshotReadScheduled = true;
84
+ // Rotate queued Agents before admitting their next read, so one history
85
+ // cannot take every free slot while other Agents are already waiting.
86
+ setImmediate(() => {
87
+ this.snapshotReadScheduled = false;
88
+ while (this.activeSnapshotReads < 8 && this.snapshotReadWaiters.size) {
89
+ const [aid, waiters] = this.snapshotReadWaiters.entries().next().value;
90
+ this.snapshotReadWaiters.delete(aid);
91
+ const next = waiters.shift();
92
+ if (waiters.length)
93
+ this.snapshotReadWaiters.set(aid, waiters);
94
+ next();
95
+ }
96
+ });
97
+ }
52
98
  /**
53
99
  * The default store follows the runtime layout. An explicit root remains a
54
100
  * self-contained test/embedding store with the historical `<root>/<aid>`
@@ -73,6 +119,8 @@ export class HandoffStore {
73
119
  return path.join(this.agentDir(selfAid), 'history.jsonl');
74
120
  }
75
121
  appendEvent(selfAid, eventType, handoffId, opts = {}) {
122
+ if (handoffId)
123
+ this.noteMutation(selfAid, handoffId);
76
124
  fs.mkdirSync(this.agentDir(selfAid), { recursive: true });
77
125
  const event = {
78
126
  event_id: newEventId(),
@@ -88,6 +136,8 @@ export class HandoffStore {
88
136
  return event;
89
137
  }
90
138
  write(selfAid, instance) {
139
+ // An async reader must retry even if a live write fails partway through.
140
+ this.noteMutation(selfAid, instance.handoff_id);
91
141
  const filePath = this.instancePath(selfAid, instance.handoff_id);
92
142
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
93
143
  const pendingPath = `${filePath}__`;
@@ -173,6 +223,56 @@ export class HandoffStore {
173
223
  }
174
224
  return parsed;
175
225
  }
226
+ getAsync(selfAid, handoffId) {
227
+ if (!HANDOFF_ID_RE.test(handoffId))
228
+ return Promise.resolve(null);
229
+ return this.withSnapshotRead(selfAid, () => this.readSnapshotAsync(selfAid, handoffId));
230
+ }
231
+ async readSnapshotAsync(selfAid, handoffId, interrupted) {
232
+ const file = this.instancePath(selfAid, handoffId);
233
+ for (;;) {
234
+ const sequence = this.mutationRevision(selfAid, handoffId);
235
+ let instance;
236
+ try {
237
+ if (interrupted === undefined) {
238
+ try {
239
+ await fs.promises.access(`${file}__`);
240
+ interrupted = true;
241
+ }
242
+ catch (error) {
243
+ if (error.code !== 'ENOENT')
244
+ throw error;
245
+ interrupted = false;
246
+ }
247
+ }
248
+ // Only interrupted writes/hot backups retain synchronous atomic recovery.
249
+ if (interrupted)
250
+ instance = this.get(selfAid, handoffId);
251
+ else {
252
+ instance = JSON.parse(await fs.promises.readFile(file, 'utf8'));
253
+ if (!instance)
254
+ throw new Error('invalid handoff snapshot');
255
+ }
256
+ }
257
+ catch (error) {
258
+ if (sequence !== this.mutationRevision(selfAid, handoffId)) {
259
+ interrupted = undefined;
260
+ continue;
261
+ }
262
+ if (error.code !== 'ENOENT')
263
+ throw error;
264
+ instance = this.get(selfAid, handoffId);
265
+ }
266
+ if (sequence !== this.mutationRevision(selfAid, handoffId)) {
267
+ interrupted = undefined;
268
+ continue;
269
+ }
270
+ if (instance && (instance.schema_version !== HANDOFF_SCHEMA_VERSION || instance.handoff_id !== handoffId)) {
271
+ throw new Error('invalid handoff snapshot');
272
+ }
273
+ return instance;
274
+ }
275
+ }
176
276
  list(selfAid) {
177
277
  const dir = this.agentDir(selfAid);
178
278
  if (!fs.existsSync(dir))
@@ -196,6 +296,64 @@ export class HandoffStore {
196
296
  listByTarget(selfAid, targetSessionId, state) {
197
297
  return this.list(selfAid).filter(item => item.target_session_id === targetSessionId && (!state || item.state === state));
198
298
  }
299
+ /** Normal reads use async I/O; interrupted writes retain the existing recovery path. */
300
+ async listAsync(selfAid, onStats) {
301
+ const stats = { snapshots: 0, directoryMs: 0, readCallbackMaxMs: 0, readCallbackTotalMs: 0, queueMaxMs: 0 };
302
+ const directoryStarted = performance.now();
303
+ let entries;
304
+ try {
305
+ entries = await fs.promises.readdir(this.agentDir(selfAid), { withFileTypes: true });
306
+ }
307
+ catch (error) {
308
+ if (error.code === 'ENOENT') {
309
+ stats.directoryMs = performance.now() - directoryStarted;
310
+ onStats?.(stats);
311
+ return [];
312
+ }
313
+ throw error;
314
+ }
315
+ stats.directoryMs = performance.now() - directoryStarted;
316
+ const ids = new Set();
317
+ const interrupted = new Set();
318
+ for (const entry of entries) {
319
+ const match = entry.isFile() && HANDOFF_SNAPSHOT_FILE_RE.exec(entry.name);
320
+ if (match && HANDOFF_ID_RE.test(match[1])) {
321
+ ids.add(match[1]);
322
+ if (entry.name.endsWith('__'))
323
+ interrupted.add(match[1]);
324
+ }
325
+ }
326
+ const instances = [];
327
+ const candidates = [...ids];
328
+ for (let offset = 0; offset < candidates.length; offset += 4) {
329
+ const results = await Promise.allSettled(candidates.slice(offset, offset + 4).map(id => {
330
+ const queuedAt = performance.now();
331
+ return this.withSnapshotRead(selfAid, async () => {
332
+ const readStarted = performance.now();
333
+ stats.queueMaxMs = Math.max(stats.queueMaxMs, readStarted - queuedAt);
334
+ try {
335
+ return await this.readSnapshotAsync(selfAid, id, interrupted.has(id));
336
+ }
337
+ finally {
338
+ const elapsed = performance.now() - readStarted;
339
+ stats.readCallbackMaxMs = Math.max(stats.readCallbackMaxMs, elapsed);
340
+ stats.readCallbackTotalMs += elapsed;
341
+ }
342
+ });
343
+ }));
344
+ // Settle all reads before propagating a failure; retries never overlap a previous batch.
345
+ for (const result of results) {
346
+ if (result.status === 'rejected')
347
+ throw result.reason;
348
+ if (result.value)
349
+ instances.push(result.value);
350
+ }
351
+ await yieldToIo();
352
+ }
353
+ stats.snapshots = instances.length;
354
+ onStats?.(stats);
355
+ return instances.sort((a, b) => a.created_at - b.created_at || a.handoff_id.localeCompare(b.handoff_id));
356
+ }
199
357
  listByOrigin(selfAid, originSessionId, state) {
200
358
  return this.list(selfAid).filter(item => item.origin_session_id === originSessionId && (!state || item.state === state));
201
359
  }
@@ -211,6 +369,33 @@ export class HandoffStore {
211
369
  events(selfAid) {
212
370
  return readAllJsonlLines(this.historyPath(selfAid));
213
371
  }
372
+ async eventsAsync(selfAid) {
373
+ const stream = fs.createReadStream(this.historyPath(selfAid), { encoding: 'utf8' });
374
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
375
+ const events = [];
376
+ let batch = 0;
377
+ try {
378
+ for await (const line of lines) {
379
+ if (++batch % 256 === 0)
380
+ await yieldToIo();
381
+ if (!line.trim())
382
+ continue;
383
+ try {
384
+ events.push(JSON.parse(line));
385
+ }
386
+ catch { /* Match the legacy reader's corrupt-line handling. */ }
387
+ }
388
+ }
389
+ catch (error) {
390
+ if (error.code !== 'ENOENT')
391
+ throw error;
392
+ }
393
+ finally {
394
+ lines.close();
395
+ stream.destroy();
396
+ }
397
+ return events;
398
+ }
214
399
  trace(selfAid, handoffId, limit) {
215
400
  if (!this.get(selfAid, handoffId))
216
401
  return null;
@@ -369,9 +554,12 @@ export class HandoffStore {
369
554
  this.write(selfAid, instance);
370
555
  return instance;
371
556
  }
372
- migrateLegacyNonePending(selfAid, now = Date.now()) {
557
+ migrateLegacyNonePending(selfAid, now = Date.now(), instances = this.list(selfAid)) {
373
558
  const migrated = [];
374
- for (const instance of this.list(selfAid)) {
559
+ for (const snapshot of instances) {
560
+ const instance = this.get(selfAid, snapshot.handoff_id);
561
+ if (!instance)
562
+ continue;
375
563
  if (instance.return_policy !== 'none' || instance.state !== 'return_pending')
376
564
  continue;
377
565
  const previous = instance.version;
@@ -12,3 +12,8 @@ export const HANDOFF_STATES = [
12
12
  ];
13
13
  export const HANDOFF_QUERY_DEFAULT_LIMIT = 100;
14
14
  export const HANDOFF_QUERY_MAX_LIMIT = 500;
15
+ /** A completed parent can still contain a newly appended, undelivered result. */
16
+ export function needsHandoffRecovery(instance) {
17
+ return !['failed', 'completed', 'discarded'].includes(instance.state)
18
+ || instance.return_results?.some(result => result.state === 'origin_queued') === true;
19
+ }
@@ -11,6 +11,7 @@ import { isValidAid } from '../../aun/aid/validation.js';
11
11
  import { listBaseagentImportSources, providerFromBaseagent } from '../../config/providers-import.js';
12
12
  import { importOrMergeBaseagentProvider, readProvidersSnapshot } from '../../config/providers-management.js';
13
13
  import { providerServiceTypesForBaseagent } from '../../config/providers.js';
14
+ import { initializationRuntimePlan, resolveProviderId } from '../../config/providers-config.js';
14
15
  import { readInstalledEvolcoreVersion } from '../../utils/evolcore-version.js';
15
16
  import { agentProjectRootFromDefaults, defaultProjectsRoot } from '../../utils/project-path.js';
16
17
  import { resolveControlAidDomain } from '../../aun/aid/control-aid.js';
@@ -170,9 +171,9 @@ export class EcwebInitializationService {
170
171
  config.baseagents = record(config.baseagents) ? config.baseagents : {};
171
172
  for (const id of available) {
172
173
  const previous = record(config.baseagents[id]) ? config.baseagents[id] : {};
173
- const previousProvider = typeof previous.provider === 'string' ? previous.provider : '';
174
+ const previousProvider = typeof previous.provider === 'string' ? resolveProviderId(previous.provider, providers) : '';
174
175
  const provider = id === 'ecagent' ? ecagentProvider
175
- : state.providerIds?.[id]
176
+ : (state.providerIds?.[id] ? resolveProviderId(state.providerIds[id], providers) : undefined)
176
177
  || (providerSupportsBaseagent(providers.providers[previousProvider], id) ? previousProvider : undefined)
177
178
  || firstProvider(id);
178
179
  if (provider && providerSupportsBaseagent(providers.providers[provider], id))
@@ -199,7 +200,7 @@ export class EcwebInitializationService {
199
200
  const defaultsComplete = configured.every(item => {
200
201
  const selected = defaults[item.id];
201
202
  return !!selected?.provider
202
- && providerSupportsBaseagent(providers.providers[selected.provider], item.id)
203
+ && providerSupportsBaseagent(providers.providers[resolveProviderId(selected.provider, providers)], item.id)
203
204
  && (item.id !== 'ecagent' || !!selected.model?.trim());
204
205
  });
205
206
  const active = inventory.baseagents.find(item => item.id === inventory.active && item.detected);
@@ -259,7 +260,7 @@ export class EcwebInitializationService {
259
260
  ...(state.agent ? { agent: state.agent } : {}),
260
261
  ...(state.agent && this.agentInitializer ? { creation: this.agentInitializer.status(state.agent.aid) } : {}),
261
262
  ...(state.creation ? { agentConfiguration: {
262
- baseagent: state.creation.plan.baseagent, provider: state.creation.plan.provider ?? null,
263
+ baseagent: state.creation.plan.baseagent, provider: initializationRuntimePlan(state.creation).provider ?? null,
263
264
  model: state.creation.plan.model ?? 'auto', effort: state.creation.plan.effort ?? 'auto',
264
265
  } } : {}),
265
266
  };
@@ -538,7 +539,7 @@ export class EcwebInitializationService {
538
539
  if (state.creation) {
539
540
  if (state.creation.operationId !== body.operationId || state.creation.fingerprint !== fingerprint)
540
541
  fail('CREATE_CONFLICT', '已有 Agent 创建请求,请查询进度', 409);
541
- this.agentInitializer.start(state.creation.plan, 'local-control');
542
+ this.agentInitializer.start(state.creation.plan, 'local-control', false, state.creation.providerMigration);
542
543
  return { status: 200, body: { success: true, data: await this.view(state) } };
543
544
  }
544
545
  if (state.step !== 'configuration' && state.step !== 'agent')
@@ -599,7 +600,7 @@ export class EcwebInitializationService {
599
600
  fail('NOT_FOUND', '没有可恢复的创建任务', 404);
600
601
  const current = this.agentInitializer.status(state.agent.aid);
601
602
  if (current.code === 'NOT_FOUND' && state.creation)
602
- this.agentInitializer.start(state.creation.plan, 'local-control');
603
+ this.agentInitializer.start(state.creation.plan, 'local-control', false, state.creation.providerMigration);
603
604
  else
604
605
  this.agentInitializer.resume(state.agent.aid, 'local-control');
605
606
  return { status: 202, body: { success: true, data: await this.view(state) } };
@@ -1,6 +1,6 @@
1
1
  import { ecwebInitializationService } from './initialization/service.js';
2
2
  import { TriggerDefinitionManager } from '../trigger/manager.js';
3
- import { ensureSessionRuntimeDir } from '../cli/task-context.js';
3
+ import { ensureSessionRuntimeDirAsync } from '../cli/task-context.js';
4
4
  import { logger } from '../utils/logger.js';
5
5
  import crypto from 'crypto';
6
6
  import fs from 'fs';
@@ -102,7 +102,7 @@ export function registerDaemonIpc({ lifecycle, ipcServer, agentRegistry, agentDe
102
102
  runtimeContext = buildDebugTaskContext({
103
103
  session,
104
104
  getTrigger: (agentAid, triggerId) => new TriggerDefinitionManager(agentAid).get(triggerId),
105
- sessionRuntimeDir: ensureSessionRuntimeDir(session.id),
105
+ sessionRuntimeDir: await ensureSessionRuntimeDirAsync(session.id),
106
106
  });
107
107
  }
108
108
  if (!runtimeContext.selfAid)
@@ -354,6 +354,7 @@ export function createIpcStatusProvider(dependencies) {
354
354
  version: dependencies.runtimeBuildIdentity.version,
355
355
  },
356
356
  controlPlane: { ready: true, owned: dependencies.getProcessOwners().length > 0 },
357
+ ...(dependencies.getStartupProgress ? { startup: dependencies.getStartupProgress() } : {}),
357
358
  agentRuntime: {
358
359
  state: dependencies.getAgentRuntimeState(),
359
360
  runnableAgents: agents.filter(agent => agent.status !== 'error' && agent.status !== 'disabled').length,
@@ -456,11 +457,11 @@ export function registerRuntimeIpcProviders({ ipcServer, channelInstances, messa
456
457
  if (!session)
457
458
  return null;
458
459
  const { buildDebugTaskContext } = await import('./auth/debug-context.js');
459
- const { ensureSessionRuntimeDir } = await import('../cli/task-context.js');
460
+ const { ensureSessionRuntimeDirAsync } = await import('../cli/task-context.js');
460
461
  return buildDebugTaskContext({
461
462
  session,
462
463
  getTrigger: (agentAid, triggerId) => new TriggerDefinitionManager(agentAid).get(triggerId),
463
- sessionRuntimeDir: ensureSessionRuntimeDir(session.id),
464
+ sessionRuntimeDir: await ensureSessionRuntimeDirAsync(session.id),
464
465
  });
465
466
  });
466
467
  logger.info('[Memory] 开发仓安装:已启用 ec memory --debug <sessionId>');
@@ -52,6 +52,7 @@ async function settleWithin(promise, ms) {
52
52
  }
53
53
  }
54
54
  export function createLifecycleNoticeService(deps) {
55
+ const enabled = deps.enabled ?? true;
55
56
  const log = deps.log ?? logger;
56
57
  const retryDelaysMs = deps.timing?.retryDelaysMs ?? ONLINE_OWNER_RETRY_DELAYS_MS;
57
58
  const onlineSendMs = deps.timing?.onlineSendMs ?? OFFLINE_SINGLE_SEND_MS;
@@ -66,8 +67,9 @@ export function createLifecycleNoticeService(deps) {
66
67
  onChange: listener => ownerResolver.onChange(listener),
67
68
  };
68
69
  /**
69
- * SIGINT/SIGTERM 会先跑 `onShutdown(() => ownerResolver.stop())`,进入 daemon
70
- * shutdown 时共识缓存已被清空。上下线通知都依赖这份进程内缓存。
70
+ * 下线时用的 Owner 取自这份进程内缓存,不依赖 shutdown 时 resolver 是否还在。
71
+ * 注意出站准入本身仍读 resolver 的共识,所以 daemon shutdown 必须在
72
+ * sendOffline 发起之后才调 ownerResolver.stop()(见 createDaemonShutdown)。
71
73
  */
72
74
  const confirmedOwners = new Map();
73
75
  const onlineInFlight = new Set();
@@ -94,6 +96,10 @@ export function createLifecycleNoticeService(deps) {
94
96
  agentName: agentNameFor(selfAid),
95
97
  online,
96
98
  ttlSeconds: LIFECYCLE_NOTICE_TTL_SECONDS,
99
+ // ownerAid came from a live consensus (confirmedOwners / resolver), so the
100
+ // notice may skip admission's refresh. During shutdown that refresh would
101
+ // compete with the connection teardown for the same 1.5s budget.
102
+ ownershipVerified: true,
97
103
  });
98
104
  if (result?.ok !== true) {
99
105
  log.warn(`[Lifecycle] ${online ? 'online' : 'offline'} notice ${selfAid} -> ${ownerAid} failed: `
@@ -128,7 +134,7 @@ export function createLifecycleNoticeService(deps) {
128
134
  log.info(`[Lifecycle] ${selfAid} has no Ownership consensus; online notice skipped`);
129
135
  }
130
136
  function online(instance) {
131
- if (onlineStopped || !isAun(instance))
137
+ if (!enabled || onlineStopped || !isAun(instance))
132
138
  return;
133
139
  const agent = deps.resolveAgent(instance.adapter.channelKey, instance.adapter.channelName);
134
140
  if (!agent)
@@ -147,7 +153,7 @@ export function createLifecycleNoticeService(deps) {
147
153
  unsubscribe();
148
154
  }
149
155
  async function sendOffline(signal) {
150
- if (offlineSent)
156
+ if (!enabled || offlineSent)
151
157
  return;
152
158
  offlineSent = true;
153
159
  const seen = new Set();