evolcore 0.0.43-test.3 → 0.0.43-test.4

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 (109) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/bin/ecmsg.js +229 -0
  3. package/bin/install-codex-managed-hooks.mjs +130 -8
  4. package/dist/ability/application-service.js +37 -0
  5. package/dist/ability/resources.js +28 -0
  6. package/dist/ability/runtime.js +6 -1
  7. package/dist/agents/claude-runner.js +7 -5
  8. package/dist/agents/codex/app-server-client.js +0 -12
  9. package/dist/agents/codex-runner.js +0 -37
  10. package/dist/agents/ecagent-runner.js +130 -35
  11. package/dist/aun/aid/agentmd.js +31 -12
  12. package/dist/aun/menu/client.js +8 -7
  13. package/dist/aun/menu/index.js +1 -1
  14. package/dist/aun/menu/transport.js +8 -5
  15. package/dist/aun/service-proxy.js +3 -0
  16. package/dist/channels/aun.js +26 -5
  17. package/dist/channels/daemon.js +10 -2
  18. package/dist/cli/agent-command.js +5 -0
  19. package/dist/cli/agent-create.js +28 -6
  20. package/dist/cli/agent.js +9 -3
  21. package/dist/cli/aun-commands.js +2 -2
  22. package/dist/cli/daemon-commands.js +30 -18
  23. package/dist/cli/directory.js +4 -7
  24. package/dist/cli/getmeta-command.js +2 -1
  25. package/dist/cli/init.js +13 -5
  26. package/dist/cli/trigger-command.js +20 -14
  27. package/dist/config/boot-log.js +12 -2
  28. package/dist/config/config-field-policy.js +2 -0
  29. package/dist/config/config-manager.js +9 -4
  30. package/dist/config/peer-role-resolver.js +1 -1
  31. package/dist/config/role-schema.js +3 -3
  32. package/dist/config/schema-migration.js +121 -0
  33. package/dist/core/agent-application-service.js +11 -0
  34. package/dist/core/agent-ipc-registration.js +2 -0
  35. package/dist/core/agent-runtime.js +41 -9
  36. package/dist/core/auth/auth-gateway.js +3 -3
  37. package/dist/core/auth/operation-authorizer.js +2 -1
  38. package/dist/core/baseagent-loader.js +11 -3
  39. package/dist/core/bootstrap-service.js +8 -0
  40. package/dist/core/channel-loader.js +61 -23
  41. package/dist/core/command/agent-control.js +4 -1
  42. package/dist/core/command/chatmode-config.js +46 -0
  43. package/dist/core/command/command-handler.js +5 -14
  44. package/dist/core/command/daemon-diagnostics.js +2 -1
  45. package/dist/core/command/menu-catalog.js +1 -1
  46. package/dist/core/command/menu-handler.js +16 -16
  47. package/dist/core/command/slash-handler.js +4 -26
  48. package/dist/core/daemon-lifecycle.js +35 -17
  49. package/dist/core/event-catalog.js +19 -0
  50. package/dist/core/evolagent-registry.js +3 -0
  51. package/dist/core/ipc-registration.js +6 -0
  52. package/dist/core/message/im-renderer.js +24 -19
  53. package/dist/core/message/message-admission.js +11 -2
  54. package/dist/core/message/response-engine.js +17 -18
  55. package/dist/core/model/model-capabilities.js +37 -0
  56. package/dist/core/model/model-catalog.js +6 -2
  57. package/dist/core/ownership/owner-resolver.js +6 -6
  58. package/dist/core/permission/ec-command-parser.js +47 -12
  59. package/dist/core/plugin-lifecycle.js +6 -2
  60. package/dist/core/relation/pa-team.js +7 -2
  61. package/dist/directory/owner-directory-cache.js +4 -2
  62. package/dist/directory/owner-directory-query-operation.js +5 -7
  63. package/dist/ecweb/runtime/lifecycle.js +29 -5
  64. package/dist/ecweb/runtime/supervisor.js +83 -27
  65. package/dist/index.js +198 -38
  66. package/dist/proxy/service-supervisor.js +377 -141
  67. package/dist/trigger/audit.js +3 -2
  68. package/dist/trigger/authorization.js +2 -3
  69. package/dist/trigger/history.js +4 -3
  70. package/dist/trigger/ipc-service.js +24 -19
  71. package/dist/trigger/manager.js +3 -5
  72. package/dist/trigger/parser.js +4 -21
  73. package/dist/trigger/patch.js +3 -15
  74. package/dist/trigger/scheduler.js +45 -10
  75. package/dist/trigger/validation.js +0 -13
  76. package/dist/utils/error-utils.js +8 -0
  77. package/dist/utils/macos-autostart.js +31 -0
  78. package/dist/utils/model-prices.jsonl +15 -8
  79. package/dist/utils/process-introspect.js +21 -1
  80. package/dist/utils/startup-trace.js +7 -1
  81. package/dist/utils/windows-autostart.js +1 -0
  82. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  83. package/ecagent/dist/harness/compaction/compaction.js +4 -4
  84. package/kits/docs/evolcore/INDEX.md +1 -1
  85. package/kits/docs/evolcore/file-navigation.md +63 -49
  86. package/kits/docs/evolcore/menu-protocol.md +1 -0
  87. package/kits/docs/evolcore/model.md +5 -3
  88. package/kits/docs/evolcore/response.md +2 -0
  89. package/kits/docs/evolcore/thread-chain.md +1 -1
  90. package/kits/docs/evolcore/tool-authorization.md +4 -1
  91. package/kits/docs/evolcore/trigger.md +10 -7
  92. package/kits/eck_manifest.json +0 -21
  93. package/kits/rules/01-overview.md +42 -44
  94. package/kits/rules/02-navigation.md +44 -53
  95. package/kits/rules/03-identity.md +21 -25
  96. package/kits/rules/04-relation.md +23 -33
  97. package/kits/rules/05-venue.md +24 -25
  98. package/kits/schemas/_meta.json +13 -26
  99. package/kits/schemas/agent-config.schema.19.json +10 -6
  100. package/kits/schemas/relation-config.schema.12.json +2 -2
  101. package/kits/schemas/role-config.schema.2.json +5 -5
  102. package/kits/skills/ec-service-proxy/SKILL.md +10 -0
  103. package/kits/skills/ec-trigger/SKILL.md +1 -1
  104. package/kits/templates/system-fragments/commands.md +1 -1
  105. package/kits/templates/system-fragments/identity.md +0 -1
  106. package/package.json +18 -13
  107. package/kits/schemas/agent-config.schema.20.json +0 -925
  108. package/kits/schemas/relation-config.schema.13.json +0 -289
  109. package/kits/schemas/role-config.schema.3.json +0 -1038
@@ -137,6 +137,9 @@ export function createEcwebSupervisor(options) {
137
137
  let childStartedAt = 0;
138
138
  let childIdentityStartedAt = null;
139
139
  let stopping = false;
140
+ let stopInFlight = null;
141
+ const stopTimingListeners = new Set();
142
+ const completedStopTimings = [];
140
143
  let checkInFlight = null;
141
144
  let startup = null;
142
145
  let restartInFlight = null;
@@ -148,6 +151,15 @@ export function createEcwebSupervisor(options) {
148
151
  let hasBeenReady = false;
149
152
  let configureQueue = Promise.resolve();
150
153
  const logFile = path.join(resolvePaths().logs, 'ecweb-daemon.log');
154
+ const reportStopTiming = (timing) => {
155
+ completedStopTimings.push(timing);
156
+ for (const listener of stopTimingListeners) {
157
+ try {
158
+ listener(timing);
159
+ }
160
+ catch { }
161
+ }
162
+ };
151
163
  const setActiveFromEntry = (entry, owned) => {
152
164
  active = {
153
165
  pid: entry.record.pid,
@@ -199,7 +211,7 @@ export function createEcwebSupervisor(options) {
199
211
  catch { }
200
212
  logFd = null;
201
213
  };
202
- const killActive = async () => {
214
+ const killActive = async (onTiming) => {
203
215
  intentionalStop = true;
204
216
  const current = active;
205
217
  if (!current) {
@@ -208,14 +220,14 @@ export function createEcwebSupervisor(options) {
208
220
  // owns the child and must not leave it behind on shutdown.
209
221
  const pendingPid = child?.pid;
210
222
  if (pendingPid && platform.isProcessRunning(pendingPid)) {
211
- await stopEcwebProcess({ pid: pendingPid, startedAt: childIdentityStartedAt });
223
+ await stopEcwebProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, undefined, onTiming);
212
224
  }
213
225
  child = null;
214
226
  childIdentityStartedAt = null;
215
227
  healthy = false;
216
228
  return;
217
229
  }
218
- await stopEcwebProcess({ pid: current.pid, startedAt: current.startedAt });
230
+ await stopEcwebProcess({ pid: current.pid, startedAt: current.startedAt }, undefined, onTiming);
219
231
  removeEntriesForPid(current.pid);
220
232
  active = null;
221
233
  child = null;
@@ -223,6 +235,8 @@ export function createEcwebSupervisor(options) {
223
235
  healthy = false;
224
236
  };
225
237
  const spawnEcweb = async () => {
238
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
239
+ return;
226
240
  intentionalStop = false;
227
241
  hasBeenReady = false;
228
242
  const root = resolvePaths().root;
@@ -353,6 +367,14 @@ export function createEcwebSupervisor(options) {
353
367
  // Allow the child to bind and publish its instance record before treating
354
368
  // it as crashed. Daemon readiness is not required for HTTP liveness.
355
369
  const instance = await findHealthyInstance();
370
+ if (stopping) {
371
+ // 保留已核验的实例身份供 stop 清理,但不再接管运行状态或进入恢复分支。
372
+ if (instance)
373
+ setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
374
+ return;
375
+ }
376
+ if (!desiredEnabled || runtimeMode !== 'managed')
377
+ return;
356
378
  healthy = instance !== null;
357
379
  if (instance) {
358
380
  launchRequested = false;
@@ -428,7 +450,11 @@ export function createEcwebSupervisor(options) {
428
450
  await checkInFlight.catch(() => { });
429
451
  if (startInFlight)
430
452
  await startInFlight.catch(() => { });
453
+ if (stopping)
454
+ return;
431
455
  await killActive();
456
+ if (stopping)
457
+ return;
432
458
  failureCount = failureThreshold;
433
459
  launchRequested = true;
434
460
  await check();
@@ -456,8 +482,11 @@ export function createEcwebSupervisor(options) {
456
482
  }
457
483
  // Give an independently started ECWeb time to publish its instance record.
458
484
  const existing = await waitForHealthyInstance(1_500);
459
- if (stopping)
485
+ if (stopping) {
486
+ if (existing)
487
+ setActiveFromEntry(existing, false);
460
488
  return;
489
+ }
461
490
  if (existing) {
462
491
  healthy = true;
463
492
  hasBeenReady = true;
@@ -547,38 +576,65 @@ export function createEcwebSupervisor(options) {
547
576
  ...(running ? { pid: active.pid } : {}),
548
577
  };
549
578
  },
550
- async stop() {
551
- if (stopping)
552
- return;
579
+ stop(onTiming) {
580
+ if (onTiming) {
581
+ stopTimingListeners.add(onTiming);
582
+ for (const timing of completedStopTimings) {
583
+ try {
584
+ onTiming(timing);
585
+ }
586
+ catch { }
587
+ }
588
+ }
589
+ if (stopInFlight)
590
+ return stopInFlight;
553
591
  stopping = true;
592
+ launchRequested = false;
554
593
  cancelRecovery();
555
594
  if (timer)
556
595
  clearTimeout(timer);
557
596
  timer = null;
558
- if (startup)
559
- await startup.catch(() => { });
560
- if (checkInFlight)
561
- await checkInFlight.catch(() => { });
562
- if (restartInFlight)
563
- await restartInFlight.catch(() => { });
564
- await configureQueue.catch(() => { });
565
- if (startInFlight) {
597
+ const waitForOperation = async (phase, operation) => {
598
+ if (!operation)
599
+ return;
600
+ const startMs = Date.now();
601
+ let detail;
566
602
  try {
567
- await startInFlight;
603
+ await operation;
568
604
  }
569
- catch { }
570
- }
571
- if (runtimeMode === 'managed')
572
- await killActive();
573
- if (child) {
605
+ catch (error) {
606
+ detail = `失败: ${error instanceof Error ? error.message : String(error)}`;
607
+ }
608
+ finally {
609
+ try {
610
+ onTiming?.({ phase, startMs, endMs: Date.now(), detail });
611
+ }
612
+ catch { }
613
+ }
614
+ };
615
+ stopInFlight = (async () => {
574
616
  try {
575
- child.removeAllListeners();
617
+ await waitForOperation('startup', startup);
618
+ await waitForOperation('healthCheck', checkInFlight);
619
+ await waitForOperation('restart', restartInFlight);
620
+ await waitForOperation('configure', configureQueue);
621
+ await waitForOperation('launch', startInFlight);
622
+ if (runtimeMode === 'managed')
623
+ await killActive(reportStopTiming);
576
624
  }
577
- catch { }
578
- child = null;
579
- childStartedAt = 0;
580
- }
581
- closeLogStream();
625
+ finally {
626
+ if (child) {
627
+ try {
628
+ child.removeAllListeners();
629
+ }
630
+ catch { }
631
+ child = null;
632
+ childStartedAt = 0;
633
+ }
634
+ closeLogStream();
635
+ }
636
+ })();
637
+ return stopInFlight;
582
638
  },
583
639
  };
584
640
  }
package/dist/index.js CHANGED
@@ -78,7 +78,7 @@ import { EvolAgentRegistry } from './core/evolagent-registry.js';
78
78
  import { createAgentInitializationRuntime, createAgentReloadRuntime, createAgentRuntimeOperations, createStartupAgentRunners, completeStartupAgentRuntime, bindAgentCreationOwner, loadStartupAgentRegistry, recoverIncompleteAgentInitializations, } from './core/agent-runtime.js';
79
79
  import { IpcServer } from './ipc.js';
80
80
  import { installChannelSdkConsoleFilter, logger, logOwnershipEvent, ownershipErrorCode, setChannelLogsEnabled, setLogLevel } from './utils/logger.js';
81
- import { StartupTracer, STARTUP_TRACE_ID_ENV } from './utils/startup-trace.js';
81
+ import { StartupTracer } from './utils/startup-trace.js';
82
82
  import { DiagService } from './core/command/diag-service.js';
83
83
  import { createEcwebSupervisor } from './ecweb/runtime/supervisor.js';
84
84
  import { writeMain, removeAll, isMainWinner, scanInstances } from './utils/instance-registry.js';
@@ -102,11 +102,10 @@ export function readEvolcoreVersion() {
102
102
  }
103
103
  async function main() {
104
104
  // 启动甘特图埋点。firstPhase 之前的时间(node 启动 + 模块加载 + tsx/dist 编译)
105
- // 全部记进 daemon.bootstrap;traceId 由 `ec start` 通过环境变量传进来,
105
+ // 全部记进 daemon.bootstrap;计时器消费 `ec start` 传入的一次性 traceId,
106
106
  // 没传说明是 restart-monitor 或其它途径拉起的,自己生成一个。
107
107
  const trace = new StartupTracer('daemon', {
108
108
  firstPhase: 'daemon.bootstrap',
109
- traceId: process.env[STARTUP_TRACE_ID_ENV] || undefined,
110
109
  });
111
110
  trace.setMeta('launchedBy', process.env.EVOLCORE_LAUNCHED_BY || 'start');
112
111
  trace.setMeta('node', process.version);
@@ -289,6 +288,7 @@ async function main() {
289
288
  const { primaryAgent, runtimeStatus } = loadStartupAgentRegistry(agentRegistry);
290
289
  let agentRuntimeState = runtimeStatus.state;
291
290
  let agentRuntimeError = runtimeStatus.error;
291
+ const startupAgents = [...agentRegistry.runnableAgents()];
292
292
  // 进程级设置独立来自 daemon.json,不进入 Agent 覆盖链。
293
293
  const globalSettings = {
294
294
  idleMonitor: daemonCfg.idleMonitor,
@@ -335,16 +335,114 @@ async function main() {
335
335
  agentLoader.register(new CodexAgentPlugin());
336
336
  agentLoader.register(new GeminiAgentPlugin());
337
337
  agentLoader.register(new EcagentAgentPluginLazy());
338
- trace.mark('daemon.agentRunners');
339
- const { agentInstances, agentMap, primaryBaseagent, primaryRunnerKey, runtimeError: runnerStartupError, } = await createStartupAgentRunners({ agentRegistry, agentLoader, sessionManager, primaryAgent });
340
- if (runnerStartupError) {
341
- agentRuntimeState = 'error';
342
- agentRuntimeError = runnerStartupError;
343
- }
344
338
  // 权限审批网关
345
339
  const permissionGateway = new PermissionGateway();
346
340
  permissionGateway.setEventBus(eventBus);
347
341
  const removePermissionConfigListener = permissionGateway.registerConfigRevalidation();
342
+ const agentInstances = [];
343
+ const agentMap = new Map();
344
+ const primaryBaseagent = primaryAgent?.baseagent ?? 'claude';
345
+ const primaryRunnerKey = primaryAgent ? `${primaryAgent.aid}::${primaryBaseagent}` : '<empty>::claude';
346
+ const startupRunnerInstances = new Map();
347
+ const startupRunnerReadyResolvers = new Map();
348
+ const startupRunnerReady = new Map();
349
+ const startupOperationReadyResolvers = new Map();
350
+ const startupOperationReady = new Map();
351
+ const channelInstancesByAgent = new Map();
352
+ const runnerResultsByAgent = new Map();
353
+ const runnerSettledAgents = new Set();
354
+ let startupChannelsRegistered = false;
355
+ let startupCancelled = false;
356
+ const resolveStartupOperation = (aid) => {
357
+ if (startupCancelled || (startupChannelsRegistered && runnerSettledAgents.has(aid))) {
358
+ startupOperationReadyResolvers.get(aid)?.(runnerResultsByAgent.get(aid) ?? []);
359
+ }
360
+ };
361
+ const boundStartupAgents = new Set();
362
+ const bindStartupAgentChannels = (agent, runners) => {
363
+ if (boundStartupAgents.has(agent.aid) || startupCancelled
364
+ || agent.status === 'error' || agent.status === 'disabled' || runners.length === 0)
365
+ return;
366
+ const channels = channelInstancesByAgent.get(agent.aid);
367
+ if (!channels)
368
+ return;
369
+ bindStartupChannelsToAgents(channels, agentRegistry, runners);
370
+ boundStartupAgents.add(agent.aid);
371
+ };
372
+ for (const agent of startupAgents) {
373
+ startupRunnerReady.set(agent.aid, new Promise(resolve => {
374
+ startupRunnerReadyResolvers.set(agent.aid, resolve);
375
+ }));
376
+ startupOperationReady.set(agent.aid, new Promise(resolve => {
377
+ startupOperationReadyResolvers.set(agent.aid, resolve);
378
+ }));
379
+ }
380
+ let baseagentSnapshot;
381
+ const refreshLoadedBaseagents = () => {
382
+ if (!baseagentSnapshot)
383
+ return;
384
+ const loaded = new Set(loadedBaseagentIds(agentMap.keys()));
385
+ for (const baseagent of baseagentSnapshot.baseagents)
386
+ baseagent.loaded = loaded.has(baseagent.id);
387
+ };
388
+ let configureRunnerCallbacks;
389
+ const agentDelegationRegistry = new AgentDelegationRegistry();
390
+ process.env[DAEMON_RUNTIME_EPOCH_ENV] = agentDelegationRegistry.getRuntimeEpoch();
391
+ const startupRunnersStartedAtMs = Date.now();
392
+ trace.mark('daemon.agentRunnerDispatch');
393
+ const baseagentSnapshotPromise = getBaseagentSnapshot({ loaded: [], probe: true });
394
+ const startupRunnersPromise = createStartupAgentRunners({
395
+ agentRegistry,
396
+ agentLoader,
397
+ sessionManager,
398
+ primaryAgent,
399
+ agentInstances,
400
+ agentMap,
401
+ isCancelled: () => startupCancelled,
402
+ configureInstances: instances => {
403
+ for (const instance of instances) {
404
+ instance.agent.setPermissionGateway?.(permissionGateway);
405
+ configureRunnerCallbacks?.(instance);
406
+ }
407
+ },
408
+ onAgentCreated: (agent, instances, timing) => {
409
+ runnerResultsByAgent.set(agent.aid, instances);
410
+ runnerSettledAgents.add(agent.aid);
411
+ startupRunnerInstances.set(agent.aid, instances);
412
+ bindStartupAgentChannels(agent, instances);
413
+ refreshLoadedBaseagents();
414
+ startupRunnerReadyResolvers.get(agent.aid)?.(instances);
415
+ resolveStartupOperation(agent.aid);
416
+ trace.addSpan('daemon.agentRunner', timing.startedAtMs, timing.completedAtMs, `aid=${agent.aid}; runners=${instances.map(instance => instance.baseagent).join(',') || 'none'}`);
417
+ logger.info(`[startup] Agent runners ready: aid=${agent.aid} runners=${instances.length}`
418
+ + ` duration=${timing.completedAtMs - timing.startedAtMs}ms`);
419
+ },
420
+ }).then(result => {
421
+ if (result.runtimeError) {
422
+ agentRuntimeState = 'error';
423
+ agentRuntimeError = result.runtimeError;
424
+ }
425
+ logger.info(`[startup] Agent runner batch complete: agents=${startupAgents.length}`
426
+ + ` runners=${agentMap.size} duration=${Date.now() - startupRunnersStartedAtMs}ms`);
427
+ trace.addSpan('daemon.agentRunners', startupRunnersStartedAtMs, Date.now(), `${startupAgents.length} 个 Agent; ${agentMap.size} 个 runner`);
428
+ return result;
429
+ });
430
+ void startupRunnersPromise.catch(error => {
431
+ const message = error instanceof Error ? error.message : String(error);
432
+ agentRuntimeState = 'error';
433
+ agentRuntimeError = message;
434
+ logger.error(`[startup] Agent runner batch failed: ${message}`);
435
+ for (const agent of startupAgents) {
436
+ if (!startupRunnerInstances.has(agent.aid)) {
437
+ agent.status = 'error';
438
+ agent.error = message;
439
+ runnerSettledAgents.add(agent.aid);
440
+ runnerResultsByAgent.set(agent.aid, []);
441
+ startupRunnerReadyResolvers.get(agent.aid)?.([]);
442
+ resolveStartupOperation(agent.aid);
443
+ }
444
+ }
445
+ });
348
446
  // 交互路由器
349
447
  const interactionRouter = new InteractionRouter();
350
448
  const groupInviteReviewService = new GroupInviteReviewService(interactionRouter);
@@ -352,10 +450,6 @@ async function main() {
352
450
  if (target === ConfigTarget.Agent && selector.self)
353
451
  groupInviteReviewService.configurationChanged(selector.self);
354
452
  });
355
- // 为所有支持权限的 agent 设置 gateway
356
- for (const inst of agentInstances) {
357
- inst.agent.setPermissionGateway?.(permissionGateway);
358
- }
359
453
  // 创建消息缓存
360
454
  trace.mark('daemon.messageCache');
361
455
  const messageCache = new MessageCache();
@@ -370,10 +464,12 @@ async function main() {
370
464
  await registerBuiltinChannelPlugins(channelLoader);
371
465
  // Create channel instances: 每个 self-agent 各自的 channels
372
466
  const evolagentInstances = [];
373
- for (const agent of agentRegistry.runnableAgents()) {
467
+ for (const agent of startupAgents) {
374
468
  try {
375
469
  const instances = await channelLoader.createForAgent(agent);
470
+ channelInstancesByAgent.set(agent.aid, instances);
376
471
  evolagentInstances.push(...instances);
472
+ bindStartupAgentChannels(agent, startupRunnerInstances.get(agent.aid) ?? []);
377
473
  }
378
474
  catch (e) {
379
475
  logger.error(`[Agent ${agent.aid}] Failed to create channels: ${e}`);
@@ -431,10 +527,6 @@ async function main() {
431
527
  }
432
528
  });
433
529
  onShutdown(() => { stopOwnerNotifications(); ownerResolver.stop(); });
434
- const agentDelegationRegistry = new AgentDelegationRegistry();
435
- // Replace any inherited marker from a parent/previous daemon before child
436
- // runners or in-process IPC clients are created.
437
- process.env[DAEMON_RUNTIME_EPOCH_ENV] = agentDelegationRegistry.getRuntimeEpoch();
438
530
  // 创建命令处理器
439
531
  const cmdHandler = new CommandHandler(sessionManager, agentMap, messageCache, eventBus, primaryRunnerKey);
440
532
  cmdHandler.setAgentDelegationRegistry(agentDelegationRegistry);
@@ -457,6 +549,13 @@ async function main() {
457
549
  }, primaryRunnerKey);
458
550
  responseEngine.setAgentDelegationRegistry(agentDelegationRegistry);
459
551
  const processor = responseEngine;
552
+ configureRunnerCallbacks = instance => {
553
+ instance.agent.setCompactStartCallback?.((sessionId) => {
554
+ processor.handleCompactStart(sessionId);
555
+ });
556
+ };
557
+ for (const inst of agentInstances)
558
+ configureRunnerCallbacks(inst);
460
559
  responseEngine.setObserverHintConsumed((hint, target, meta) => {
461
560
  const observerChannel = channelInstances.find(candidate => candidate.adapter.channelKey === target.channelKey
462
561
  && candidate.channelType === 'aun')?.channel;
@@ -478,14 +577,13 @@ async function main() {
478
577
  }
479
578
  // 设置交互路由器
480
579
  processor.setInteractionRouter(interactionRouter);
481
- // 设置 compact 开始回调(对所有支持的 agent)
482
- for (const inst of agentInstances) {
483
- inst.agent.setCompactStartCallback?.((sessionId) => {
484
- processor.handleCompactStart(sessionId);
485
- });
486
- }
487
580
  // 创建消息队列
488
581
  const messageQueue = new MessageQueue(async (message) => {
582
+ const owner = message.selfAID || agentRegistry.resolveByChannel(message.channel)?.aid;
583
+ if (owner)
584
+ await startupRunnerReady.get(owner);
585
+ if (startupCancelled)
586
+ return;
489
587
  await processor.processMessage(message);
490
588
  }, {
491
589
  persistencePath: daemonQueuePath(),
@@ -599,7 +697,7 @@ async function main() {
599
697
  fs.chmodSync(resolvePaths().controlToken, 0o600);
600
698
  }
601
699
  catch { }
602
- const triggerStartupAgents = [...agentRegistry.runnableAgents()];
700
+ const triggerStartupAgents = startupAgents;
603
701
  const controlAid = daemonCfg.aid || '__daemon__';
604
702
  const daemonTriggerOwner = {
605
703
  aid: triggerStartupAgents.some(agent => agent.aid === controlAid) ? `${controlAid}#daemon` : controlAid,
@@ -670,9 +768,17 @@ async function main() {
670
768
  };
671
769
  cmdHandler.setTriggerSchedulerResolver((agentAid) => triggerSchedulers.get(agentAid));
672
770
  const ensureTriggerSchedulerStarted = async (agent) => {
771
+ await startupRunnerReady.get(agent.aid);
772
+ if (startupCancelled || agent.status === 'error' || agent.status === 'disabled')
773
+ return;
673
774
  await triggerSchedulers.ensureStarted(agent.aid, () => startTriggerScheduler(agent));
674
775
  };
675
776
  const ensureDaemonTriggerSchedulerStarted = async () => {
777
+ const primaryRunners = primaryAgent ? await startupRunnerReady.get(primaryAgent.aid) : undefined;
778
+ if (startupCancelled)
779
+ return;
780
+ if (primaryAgent && (!primaryRunners?.length || primaryAgent.status === 'error'))
781
+ return;
676
782
  await triggerSchedulers.ensureStarted(daemonTriggerOwner.aid, () => startTriggerScheduler(daemonTriggerOwner, { seedUpgradeCheck: true }));
677
783
  };
678
784
  const defaultPolicy = createDefaultChannelPolicy();
@@ -737,9 +843,18 @@ async function main() {
737
843
  for (const inst of channelInstances) {
738
844
  registerChannelInstance(inst);
739
845
  }
740
- // Bind adapters to their owning agents and mark running
741
- bindStartupChannelsToAgents(channelInstances, agentRegistry, agentInstances);
742
- ({ state: agentRuntimeState, error: agentRuntimeError } = await completeStartupAgentRuntime(agentRegistry, { state: agentRuntimeState, error: agentRuntimeError }));
846
+ startupChannelsRegistered = true;
847
+ for (const aid of startupRunnerReady.keys())
848
+ resolveStartupOperation(aid);
849
+ const startupAgentRuntimePromise = startupRunnersPromise.then(async (result) => {
850
+ if (startupCancelled)
851
+ return;
852
+ ({ state: agentRuntimeState, error: agentRuntimeError } = await completeStartupAgentRuntime(agentRegistry, { state: agentRuntimeState, error: result.runtimeError ?? agentRuntimeError }));
853
+ }).catch(error => {
854
+ agentRuntimeState = 'error';
855
+ agentRuntimeError = error instanceof Error ? error.message : String(error);
856
+ logger.error(`[startup] Agent runtime initialization failed: ${agentRuntimeError}`);
857
+ });
743
858
  // ── 配置快照 + 启动日志(启动完毕锚点,网络无关)──────────────────
744
859
  trace.mark('daemon.startupConfigRecord');
745
860
  recordStartupConfig(configSnapshotsEnabled);
@@ -798,7 +913,8 @@ async function main() {
798
913
  let pendingShutdownReason;
799
914
  let pendingShutdownTraceId;
800
915
  trace.mark('daemon.baseagentProbe');
801
- const baseagentSnapshot = await getBaseagentSnapshot({ loaded: loadedBaseagentIds(agentMap.keys()), probe: true });
916
+ baseagentSnapshot = await baseagentSnapshotPromise;
917
+ refreshLoadedBaseagents();
802
918
  const getStatusSnapshot = () => {
803
919
  const now = Date.now();
804
920
  const todayStart = new Date(new Date(now).getFullYear(), new Date(now).getMonth(), new Date(now).getDate()).getTime();
@@ -907,6 +1023,7 @@ async function main() {
907
1023
  aidStatsCollector,
908
1024
  handoffRuntime,
909
1025
  messageQueue,
1026
+ awaitStartupAgent: async (aid) => { await startupOperationReady.get(aid); },
910
1027
  });
911
1028
  registerRelationConsolidationEvents({ eventBus, agentRegistry, responseEngine, enqueueConsolidation });
912
1029
  globalThis.__evolcore_reloadHooks = reloadHooks;
@@ -932,8 +1049,18 @@ async function main() {
932
1049
  setAgentRuntimeState: state => { agentRuntimeState = state; },
933
1050
  setAgentRuntimeError: error => { agentRuntimeError = error; },
934
1051
  });
935
- globalThis.__evolcore_hotLoadAgent = agentRuntimeOperations.hotLoad;
936
- globalThis.__evolcore_resyncAgents = agentRuntimeOperations.resync;
1052
+ globalThis.__evolcore_hotLoadAgent = async (aid) => {
1053
+ await startupRunnerReady.get(aid);
1054
+ if (startupCancelled)
1055
+ throw new Error('Daemon is shutting down');
1056
+ return agentRuntimeOperations.hotLoad(aid);
1057
+ };
1058
+ globalThis.__evolcore_resyncAgents = async () => {
1059
+ await Promise.all(startupRunnerReady.values());
1060
+ if (startupCancelled)
1061
+ throw new Error('Daemon is shutting down');
1062
+ return agentRuntimeOperations.resync();
1063
+ };
937
1064
  const coreHotLoadAgent = async (aid) => {
938
1065
  const hotLoad = globalThis.__evolcore_hotLoadAgent;
939
1066
  if (typeof hotLoad !== 'function')
@@ -968,6 +1095,12 @@ async function main() {
968
1095
  return state ? [state] : [];
969
1096
  }),
970
1097
  aunAidStats: () => aidStatsCollector.getAllSnapshots(),
1098
+ beforeAgentOperation: async (aid) => {
1099
+ if (aid)
1100
+ await startupOperationReady.get(aid);
1101
+ else
1102
+ await Promise.all(startupOperationReady.values());
1103
+ },
971
1104
  });
972
1105
  const agentInitializationService = createAgentInitializationRuntime({
973
1106
  agentRegistry,
@@ -1056,6 +1189,27 @@ async function main() {
1056
1189
  logger.info(`🚀 EvolCore core is ready; connecting ${channelInstances.length} channel(s) in background`);
1057
1190
  const connectAllPromise = channelLoader.connectAll(channelInstances, {
1058
1191
  concurrency: 10,
1192
+ beforeConnect: async (instance) => {
1193
+ const owner = agentRegistry.resolveByChannel(instance.adapter.channelKey)
1194
+ ?? agentRegistry.resolveByChannel(instance.adapter.channelName);
1195
+ if (!owner)
1196
+ return !startupCancelled;
1197
+ const readiness = startupRunnerReady.get(owner.aid);
1198
+ if (!readiness)
1199
+ return false;
1200
+ const runners = await readiness;
1201
+ if (startupCancelled || runners.length === 0 || owner.status === 'error' || owner.status === 'disabled')
1202
+ return false;
1203
+ bindStartupAgentChannels(owner, runners);
1204
+ return true;
1205
+ },
1206
+ shouldConnect: instance => {
1207
+ if (startupCancelled || !channelInstances.includes(instance))
1208
+ return false;
1209
+ const owner = agentRegistry.resolveByChannel(instance.adapter.channelKey)
1210
+ ?? agentRegistry.resolveByChannel(instance.adapter.channelName);
1211
+ return !owner || owner.status === 'running';
1212
+ },
1059
1213
  onConnected: markChannelConnected,
1060
1214
  onFailed: (inst, error) => {
1061
1215
  logger.warn(`[startup] ${inst.adapter.channelName} initial connect failed: ${error}`);
@@ -1200,13 +1354,11 @@ async function main() {
1200
1354
  startRestoredQueue: () => messageQueue.startRestored(),
1201
1355
  }).catch(error => logger.error('[Queue] restored queue release failed:', error));
1202
1356
  trace.mark('daemon.resumeSessions');
1203
- resumePendingSessions({
1204
- sessionManager,
1205
- messageQueue,
1206
- droppedTriggerSessionIds,
1207
- agentRegistry,
1208
- agentMap,
1209
- });
1357
+ void startupRunnersPromise.then(() => {
1358
+ if (startupCancelled)
1359
+ return;
1360
+ resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap });
1361
+ }).catch(error => logger.error(`[Resume] startup runner gate failed: ${error instanceof Error ? error.message : String(error)}`));
1210
1362
  trace.mark('daemon.cpuTracking');
1211
1363
  ipcServer.startCpuTracking();
1212
1364
  // IPC was bound before channel connection. At this point all handlers are
@@ -1256,6 +1408,14 @@ async function main() {
1256
1408
  groupInviteReviewService,
1257
1409
  channelLoader,
1258
1410
  channelInstances,
1411
+ startupRunners: Promise.allSettled([startupRunnersPromise, startupAgentRuntimePromise]),
1412
+ cancelStartup: () => {
1413
+ startupCancelled = true;
1414
+ for (const aid of startupRunnerReady.keys()) {
1415
+ startupRunnerReadyResolvers.get(aid)?.([]);
1416
+ startupOperationReadyResolvers.get(aid)?.([]);
1417
+ }
1418
+ },
1259
1419
  controlChannel,
1260
1420
  sessionManager,
1261
1421
  removeAll,