evolcore 0.0.43-test.5 → 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 (116) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +126 -43
  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 +6 -6
  8. package/dist/aun/group/invite-service.js +3 -2
  9. package/dist/aun/service-proxy.js +18 -6
  10. package/dist/channels/aun.js +73 -10
  11. package/dist/cli/agent-create.js +16 -6
  12. package/dist/cli/aun-commands.js +9 -1
  13. package/dist/cli/daemon-commands.js +30 -1
  14. package/dist/cli/ecmsg-gateway.js +3 -1
  15. package/dist/cli/init.js +75 -0
  16. package/dist/cli/provider-command.js +1 -1
  17. package/dist/cli/restart-monitor.js +24 -5
  18. package/dist/cli/task-context.js +38 -1
  19. package/dist/cli/watch-logs.js +6 -4
  20. package/dist/config/boot-log.js +6 -4
  21. package/dist/config/builtin-roles.js +2 -2
  22. package/dist/config/config-manager.js +1 -1
  23. package/dist/config/peer-role-resolver.js +1 -1
  24. package/dist/config/provider-identity-migration.js +92 -17
  25. package/dist/config/provider-local-sync.js +2 -0
  26. package/dist/config/providers-config.js +13 -0
  27. package/dist/config/providers-management.js +100 -10
  28. package/dist/config/role-service.js +8 -8
  29. package/dist/config/role-store.js +22 -22
  30. package/dist/config/schema-migration.js +80 -87
  31. package/dist/config/snapshot.js +70 -41
  32. package/dist/core/agent-runtime.js +44 -7
  33. package/dist/core/baseagent-loader.js +114 -11
  34. package/dist/core/channel-loader.js +36 -13
  35. package/dist/core/channel-runtime.js +112 -42
  36. package/dist/core/command/command-handler.js +5 -5
  37. package/dist/core/command/menu-handler.js +8 -3
  38. package/dist/core/command/menu-protocol.js +82 -11
  39. package/dist/core/command/role-menu.js +27 -15
  40. package/dist/core/daemon-control.js +42 -15
  41. package/dist/core/daemon-lifecycle.js +411 -67
  42. package/dist/core/handoff/dispatcher.js +9 -3
  43. package/dist/core/handoff/runtime.js +130 -42
  44. package/dist/core/handoff/store.js +190 -2
  45. package/dist/core/handoff/types.js +5 -0
  46. package/dist/core/initialization/service.js +4 -4
  47. package/dist/core/ipc-registration.js +5 -4
  48. package/dist/core/lifecycle-notice.js +10 -4
  49. package/dist/core/message/aun-ipc-sender.js +2 -2
  50. package/dist/core/message/message-bridge.js +53 -4
  51. package/dist/core/message/message-queue.js +46 -4
  52. package/dist/core/message/pending-hints.js +4 -10
  53. package/dist/core/message/response-engine.js +10 -2
  54. package/dist/core/message/send-routing.js +12 -2
  55. package/dist/core/ownership/owner-resolver.js +1 -0
  56. package/dist/core/permission/ec-command-parser.js +11 -1
  57. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  58. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  59. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  60. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  61. package/dist/core/session/session-fs-store.js +164 -3
  62. package/dist/core/session/session-idle-monitor.js +9 -1
  63. package/dist/core/session/session-manager.js +36 -2
  64. package/dist/directory/owner-directory-admission.js +26 -1
  65. package/dist/directory/owner-directory-cache.js +57 -16
  66. package/dist/directory/owner-directory-query-operation.js +4 -1
  67. package/dist/ecweb/runtime/lifecycle.js +9 -7
  68. package/dist/ecweb/runtime/supervisor.js +44 -27
  69. package/dist/index.js +548 -251
  70. package/dist/proxy/manager.js +38 -17
  71. package/dist/proxy/service-supervisor.js +65 -31
  72. package/dist/trigger/application-service.js +3 -1
  73. package/dist/trigger/audit.js +19 -4
  74. package/dist/trigger/authorization.js +14 -5
  75. package/dist/trigger/history.js +176 -7
  76. package/dist/trigger/manager.js +1 -3
  77. package/dist/trigger/scheduler.js +78 -5
  78. package/dist/utils/cross-platform.js +152 -4
  79. package/dist/utils/host-info.js +11 -8
  80. package/dist/utils/npm-ops.js +48 -0
  81. package/dist/utils/process-introspect.js +64 -1
  82. package/dist/utils/startup-trace.js +160 -19
  83. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  84. package/kits/docs/evolcore/INDEX.md +3 -2
  85. package/kits/docs/evolcore/ctl.md +2 -1
  86. package/kits/docs/evolcore/group.md +2 -2
  87. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  88. package/kits/docs/evolcore/msg.md +13 -6
  89. package/kits/docs/evolcore/provider.md +21 -3
  90. package/kits/docs/evolcore/response.md +1 -1
  91. package/kits/eck_manifest.json +19 -7
  92. package/kits/eck_message_manifest.json +3 -3
  93. package/kits/rules/06-channel.md +5 -6
  94. package/kits/schemas/daemon.schema.1.json +5 -0
  95. package/kits/schemas/daemon.schema.2.json +5 -0
  96. package/kits/schemas/daemon.schema.3.json +2 -1
  97. package/kits/schemas/daemon.schema.4.json +2 -1
  98. package/kits/schemas/daemon.schema.5.json +2 -1
  99. package/kits/schemas/daemon.schema.6.json +1 -1
  100. package/kits/schemas/daemon.schema.7.json +1 -1
  101. package/kits/schemas/daemon.schema.8.json +2 -1
  102. package/kits/schemas/daemon.schema.9.json +2 -1
  103. package/kits/schemas/role-registry.schema.1.json +2 -2
  104. package/kits/schemas/single-session.schema.1.json +1 -1
  105. package/kits/schemas/single-session.schema.2.json +1 -1
  106. package/kits/schemas/single-session.schema.3.json +1 -1
  107. package/kits/skills/aid-ability/SKILL.md +7 -7
  108. package/kits/skills/ec-group/SKILL.md +8 -5
  109. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  110. package/kits/skills/ec-trigger/SKILL.md +4 -4
  111. package/kits/skills/thread-ops/SKILL.md +10 -10
  112. package/kits/templates/system-fragments/commands.md +5 -5
  113. package/kits/templates/system-fragments/reply.md +2 -1
  114. package/kits/templates/system-fragments/session.md +1 -1
  115. package/kits/templates/system-fragments/thread.md +1 -1
  116. package/package.json +4 -3
@@ -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. */
@@ -632,6 +633,16 @@ export class HandoffRuntime {
632
633
  expired += this.dispatcher.expireQueued(selfAid).length;
633
634
  return expired;
634
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
+ }
635
646
  async discardSession(selfAid, sessionId) {
636
647
  this.sessionDiscardSequence.set(this.sessionKey(selfAid, sessionId), ++this.lifecycleSequence);
637
648
  const candidates = this.store.list(selfAid)
@@ -647,61 +658,131 @@ export class HandoffRuntime {
647
658
  return discarded;
648
659
  }
649
660
  async discardExpired(selfAids, retentionMs = HANDOFF_RETENTION_MS) {
650
- const now = this.now?.() ?? Date.now();
651
661
  let discarded = 0;
652
662
  for (const selfAid of selfAids) {
653
- const latestEventVersions = new Map();
654
- for (const event of this.store.events(selfAid)) {
655
- if (!event.handoff_id || event.to_version === undefined)
656
- continue;
657
- latestEventVersions.set(event.handoff_id, Math.max(latestEventVersions.get(event.handoff_id) ?? 0, event.to_version));
658
- }
659
- for (const instance of this.store.list(selfAid)) {
660
- if (instance.state === 'failed' || instance.state === 'completed' || instance.state === 'discarded')
661
- continue;
662
- if (now - instance.created_at <= retentionMs)
663
- continue;
664
- if ((latestEventVersions.get(instance.handoff_id) ?? 0) !== instance.version)
665
- continue;
666
- const result = await this.discardWithTargetLock(selfAid, instance.handoff_id, 'retention_expired', {
667
- retention_ms: retentionMs,
668
- age_ms: now - instance.created_at,
669
- }, instance.version, now);
670
- if (result) {
671
- discarded++;
672
- logger.info(`[Handoff] discarded expired handoff: ${instance.handoff_id}`);
673
- }
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}`);
674
693
  }
675
694
  }
676
695
  return discarded;
677
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
+ }
678
721
  async recover(selfAids, options = {}) {
722
+ if (options.snapshots && selfAids.length !== 1)
723
+ throw new Error('recovery snapshots require exactly one Agent');
679
724
  const originEnqueues = [];
680
725
  for (const selfAid of selfAids) {
681
- if (options.discardExpired !== false)
682
- await this.discardExpired([selfAid]);
683
- // v1 initially represented return=none as return_pending and required an
684
- // empty manual return. It has already been shown to a target turn, so
685
- // finish it before version reconciliation instead of prompting again.
686
- this.store.migrateLegacyNonePending(selfAid, this.now?.());
687
- 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;
688
731
  // 单次读取事件流并建索引:下面每个 instance 都要用它,逐条 filter 是 O(实例×事件),
689
732
  // 在实例数上百的 AID 上足以把启动拖慢数秒。
690
- 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();
691
737
  const lastSendEvent = new Map();
692
738
  const latestEventVersion = new Map();
693
- for (const event of events) {
694
- if (!event.handoff_id)
695
- continue;
696
- if (event.event_type.startsWith('target_send_')) {
697
- lastSendEvent.set(event.handoff_id, event.event_type);
698
- }
699
- if (event.to_version !== undefined) {
700
- 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
+ }
701
749
  }
702
- }
703
- 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;
704
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
+ }
705
786
  const instanceVersion = latestEventVersion.get(instance.handoff_id) ?? 0;
706
787
  if (instanceVersion !== instance.version) {
707
788
  if (!instance.attention_required) {
@@ -711,6 +792,10 @@ export class HandoffRuntime {
711
792
  continue;
712
793
  }
713
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;
714
799
  if (instance.attention_required) {
715
800
  this.dispatcher.notify(selfAid, instance.target_session_id);
716
801
  }
@@ -731,8 +816,11 @@ export class HandoffRuntime {
731
816
  }
732
817
  }
733
818
  }
819
+ options.onPhase?.('reconcile', started, Date.now());
734
820
  }
821
+ const started = Date.now();
735
822
  await Promise.all(originEnqueues);
823
+ options.onPhase?.('origin', started, Date.now());
736
824
  }
737
825
  async discardWithTargetLock(selfAid, handoffId, reason, details, expectedVersion, now = this.now?.()) {
738
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,7 +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 { resolveProviderId } from '../../config/providers-config.js';
14
+ import { initializationRuntimePlan, resolveProviderId } from '../../config/providers-config.js';
15
15
  import { readInstalledEvolcoreVersion } from '../../utils/evolcore-version.js';
16
16
  import { agentProjectRootFromDefaults, defaultProjectsRoot } from '../../utils/project-path.js';
17
17
  import { resolveControlAidDomain } from '../../aun/aid/control-aid.js';
@@ -260,7 +260,7 @@ export class EcwebInitializationService {
260
260
  ...(state.agent ? { agent: state.agent } : {}),
261
261
  ...(state.agent && this.agentInitializer ? { creation: this.agentInitializer.status(state.agent.aid) } : {}),
262
262
  ...(state.creation ? { agentConfiguration: {
263
- baseagent: state.creation.plan.baseagent, provider: state.creation.plan.provider ?? null,
263
+ baseagent: state.creation.plan.baseagent, provider: initializationRuntimePlan(state.creation).provider ?? null,
264
264
  model: state.creation.plan.model ?? 'auto', effort: state.creation.plan.effort ?? 'auto',
265
265
  } } : {}),
266
266
  };
@@ -539,7 +539,7 @@ export class EcwebInitializationService {
539
539
  if (state.creation) {
540
540
  if (state.creation.operationId !== body.operationId || state.creation.fingerprint !== fingerprint)
541
541
  fail('CREATE_CONFLICT', '已有 Agent 创建请求,请查询进度', 409);
542
- this.agentInitializer.start(state.creation.plan, 'local-control');
542
+ this.agentInitializer.start(state.creation.plan, 'local-control', false, state.creation.providerMigration);
543
543
  return { status: 200, body: { success: true, data: await this.view(state) } };
544
544
  }
545
545
  if (state.step !== 'configuration' && state.step !== 'agent')
@@ -600,7 +600,7 @@ export class EcwebInitializationService {
600
600
  fail('NOT_FOUND', '没有可恢复的创建任务', 404);
601
601
  const current = this.agentInitializer.status(state.agent.aid);
602
602
  if (current.code === 'NOT_FOUND' && state.creation)
603
- this.agentInitializer.start(state.creation.plan, 'local-control');
603
+ this.agentInitializer.start(state.creation.plan, 'local-control', false, state.creation.providerMigration);
604
604
  else
605
605
  this.agentInitializer.resume(state.agent.aid, 'local-control');
606
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();
@@ -348,11 +348,11 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
348
348
  const session = await sessionManager.getSessionById(params.originSessionId);
349
349
  if (session) {
350
350
  const { buildDebugTaskContext } = await import('../auth/debug-context.js');
351
- const { ensureSessionRuntimeDir } = await import('../../cli/task-context.js');
351
+ const { ensureSessionRuntimeDirAsync } = await import('../../cli/task-context.js');
352
352
  runtime = buildDebugTaskContext({
353
353
  session,
354
354
  getTrigger: (agentAid, triggerId) => new TriggerDefinitionManager(agentAid).get(triggerId),
355
- sessionRuntimeDir: ensureSessionRuntimeDir(session.id),
355
+ sessionRuntimeDir: await ensureSessionRuntimeDirAsync(session.id),
356
356
  });
357
357
  }
358
358
  }