evolcore 0.0.45 → 0.0.47

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +22 -6
  12. package/dist/agents/codex/app-server-client.js +34 -27
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/group/fs-download.js +1 -1
  18. package/dist/aun/menu/client.js +142 -182
  19. package/dist/aun/rpc/client.js +33 -17
  20. package/dist/aun/service-proxy.js +6 -23
  21. package/dist/channels/aun.js +675 -120
  22. package/dist/channels/daemon.js +1 -1
  23. package/dist/cli/agent-create.js +37 -10
  24. package/dist/cli/agent-template.js +105 -84
  25. package/dist/cli/agent.js +31 -18
  26. package/dist/cli/daemon-commands.js +42 -56
  27. package/dist/cli/daemon-lifecycle-client.js +55 -19
  28. package/dist/cli/directory.js +12 -4
  29. package/dist/cli/ecmsg-gateway.js +5 -2
  30. package/dist/cli/events-command.js +2 -1
  31. package/dist/cli/init-channel.js +2 -2
  32. package/dist/cli/init.js +57 -21
  33. package/dist/cli/integrity-command.js +2 -0
  34. package/dist/cli/managed-command-guard.js +20 -1
  35. package/dist/cli/menu-client.js +7 -5
  36. package/dist/cli/restart-monitor.js +135 -46
  37. package/dist/cli/services-command.js +28 -5
  38. package/dist/cli/task-context.js +83 -15
  39. package/dist/cli/upgrade-command.js +4 -2
  40. package/dist/config/config-field-policy.js +24 -0
  41. package/dist/config/config-manager.js +49 -19
  42. package/dist/config/peer-book-store.js +167 -127
  43. package/dist/config/peer-role-resolver.js +24 -4
  44. package/dist/config/provider-identity-migration.js +158 -6
  45. package/dist/config/provider-identity.js +10 -4
  46. package/dist/config/provider-ipc-service.js +10 -2
  47. package/dist/config/provider-local-sync.js +2 -2
  48. package/dist/config/providers-config.js +95 -10
  49. package/dist/config/providers-import.js +4 -6
  50. package/dist/config/providers.js +14 -3
  51. package/dist/config/role-store.js +1 -1
  52. package/dist/config/schema-migration.js +123 -16
  53. package/dist/config/schema-registry.js +6 -2
  54. package/dist/config-store.js +9 -1
  55. package/dist/core/agent-application-service.js +56 -29
  56. package/dist/core/agent-create-status.js +3 -1
  57. package/dist/core/agent-creation-claim.js +1 -0
  58. package/dist/core/agent-ipc-registration.js +2 -2
  59. package/dist/core/agent-reload-coordinator.js +38 -1
  60. package/dist/core/agent-runtime.js +91 -43
  61. package/dist/core/auth/agent-delegation.js +13 -3
  62. package/dist/core/auth/delegation-diagnostics.js +56 -15
  63. package/dist/core/auth/operation-authorizer.js +2 -2
  64. package/dist/core/auth/operation-catalog.js +3 -3
  65. package/dist/core/bootstrap-service.js +3 -0
  66. package/dist/core/capability/capability-manager.js +3 -1
  67. package/dist/core/channel-loader.js +29 -3
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-control.js +6 -5
  70. package/dist/core/command/agent-template-menu.js +32 -97
  71. package/dist/core/command/eventcenter-menu.js +61 -13
  72. package/dist/core/command/menu-catalog.js +11 -4
  73. package/dist/core/command/menu-handler.js +39 -12
  74. package/dist/core/command/menu-protocol.js +8 -16
  75. package/dist/core/command/skill-slash.js +6 -2
  76. package/dist/core/command/slash-handler.js +4 -6
  77. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  78. package/dist/core/command/team-workspace-management-store.js +83 -0
  79. package/dist/core/command/team-workspace-management.js +1 -2
  80. package/dist/core/command/team-workspace-team.js +26 -3
  81. package/dist/core/daemon-bootstrap.js +11 -9
  82. package/dist/core/daemon-control.js +4 -7
  83. package/dist/core/daemon-lifecycle.js +189 -143
  84. package/dist/core/evolagent-registry.js +50 -2
  85. package/dist/core/evolagent.js +2 -1
  86. package/dist/core/file-integrity/read.js +9 -16
  87. package/dist/core/file-integrity/store.js +94 -34
  88. package/dist/core/handoff/dispatcher.js +33 -7
  89. package/dist/core/handoff/runtime.js +8 -0
  90. package/dist/core/host-snapshot.js +9 -4
  91. package/dist/core/inference/text-inference.js +12 -2
  92. package/dist/core/initialization/service.js +22 -4
  93. package/dist/core/invoke/invoke-service.js +24 -3
  94. package/dist/core/ipc-registration.js +7 -3
  95. package/dist/core/memory/consolidation.js +6 -6
  96. package/dist/core/message/aun-ipc-sender.js +109 -7
  97. package/dist/core/message/contact-admission.js +6 -2
  98. package/dist/core/message/message-bridge.js +13 -0
  99. package/dist/core/message/message-queue.js +131 -30
  100. package/dist/core/message/pending-hints.js +8 -0
  101. package/dist/core/message/response-engine.js +48 -2
  102. package/dist/core/message/send-routing.js +3 -12
  103. package/dist/core/model/catalog-service.js +13 -0
  104. package/dist/core/model/model-catalog.js +57 -18
  105. package/dist/core/ownership/owner-resolver.js +27 -10
  106. package/dist/core/pack-auth.js +163 -31
  107. package/dist/core/pack-install.js +42 -1
  108. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  109. package/dist/core/permission/ec-command-parser.js +3 -1
  110. package/dist/core/permission/shell-environment.js +23 -0
  111. package/dist/core/rate-window.js +6 -1
  112. package/dist/core/relation/peer-identity.js +5 -1
  113. package/dist/core/relation/same-owner-proof.js +2 -1
  114. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  115. package/dist/core/session/session-file-health.js +36 -7
  116. package/dist/core/session/session-idle-monitor.js +0 -1
  117. package/dist/core/session/session-manager.js +14 -0
  118. package/dist/core/session/session-title.js +26 -6
  119. package/dist/core/skill/index-generator.js +3 -4
  120. package/dist/core/task/task-image-resources.js +1 -1
  121. package/dist/core/thread/thread-service.js +0 -1
  122. package/dist/core/thread/topic-id.js +8 -0
  123. package/dist/directory/owner-directory-admission.js +17 -0
  124. package/dist/directory/owner-directory-cache.js +3 -1
  125. package/dist/directory/owner-directory-markdown.js +145 -23
  126. package/dist/directory/owner-directory-policy.js +23 -0
  127. package/dist/directory/owner-directory-query-operation.js +20 -6
  128. package/dist/directory/owner-directory-search.js +47 -0
  129. package/dist/eck/message-renderer.js +171 -32
  130. package/dist/ecweb/basic-settings-service.js +7 -3
  131. package/dist/ecweb/providers-service.js +17 -10
  132. package/dist/ecweb/runtime/lifecycle.js +65 -16
  133. package/dist/ecweb/runtime/supervisor.js +79 -50
  134. package/dist/event-center/admission-materializer.js +1 -1
  135. package/dist/event-center/bus-gate.js +48 -4
  136. package/dist/event-center/bus-host.js +3 -3
  137. package/dist/event-center/center-config.js +57 -28
  138. package/dist/event-center/dispatcher.js +8 -0
  139. package/dist/event-center/event-log.js +69 -27
  140. package/dist/event-center/index-generator.js +6 -1
  141. package/dist/event-center/ipc-operation.js +66 -25
  142. package/dist/event-center/pack-loader.js +12 -55
  143. package/dist/event-center/pack-manager.js +5 -3
  144. package/dist/event-center/registry.js +48 -52
  145. package/dist/event-center/runtime.js +219 -81
  146. package/dist/event-center/script-runner.js +18 -7
  147. package/dist/event-center/types.js +9 -1
  148. package/dist/event-center/validation.js +33 -4
  149. package/dist/index.js +132 -75
  150. package/dist/ipc.js +35 -8
  151. package/dist/product.js +1 -0
  152. package/dist/proxy/manager.js +52 -11
  153. package/dist/proxy/service-supervisor.js +265 -67
  154. package/dist/services/dispatcher.js +26 -3
  155. package/dist/services/idempotency.js +128 -0
  156. package/dist/services/identity.js +3 -27
  157. package/dist/services/index-generator.js +5 -1
  158. package/dist/services/index.js +244 -45
  159. package/dist/services/ipc-operation.js +164 -20
  160. package/dist/services/pack-manager.js +37 -9
  161. package/dist/services/router.js +100 -31
  162. package/dist/services/script-runner.js +15 -4
  163. package/dist/services/service-payload.js +50 -2
  164. package/dist/services/validation.js +107 -3
  165. package/dist/trigger/scheduler.js +18 -4
  166. package/dist/trigger/script-sandbox.js +39 -2
  167. package/dist/trigger/state.js +7 -0
  168. package/dist/utils/aid-bind.js +155 -18
  169. package/dist/utils/atomic-write.js +3 -3
  170. package/dist/utils/cross-platform.js +59 -16
  171. package/dist/utils/error-utils.js +26 -1
  172. package/dist/utils/instance-registry.js +94 -35
  173. package/dist/utils/process-introspect.js +187 -27
  174. package/dist/utils/project-path.js +47 -3
  175. package/dist/utils/upgrade-jobs.js +4 -4
  176. package/dist/utils/windows-shell-trust.js +174 -68
  177. package/kits/docs/context-assembly.md +3 -3
  178. package/kits/docs/evolcore/agent.md +28 -10
  179. package/kits/docs/evolcore/aid.md +3 -1
  180. package/kits/docs/evolcore/config.md +22 -0
  181. package/kits/docs/evolcore/directory.md +46 -12
  182. package/kits/docs/evolcore/event-center.md +6 -6
  183. package/kits/docs/evolcore/group-collaboration.md +1 -1
  184. package/kits/docs/evolcore/menu-client.md +7 -5
  185. package/kits/docs/evolcore/menu-protocol.md +5 -3
  186. package/kits/docs/evolcore/msg.md +10 -3
  187. package/kits/docs/evolcore/provider.md +17 -5
  188. package/kits/docs/evolcore/services.md +145 -12
  189. package/kits/docs/evolcore/thread-chain.md +17 -9
  190. package/kits/docs/prompt-loading-architecture.md +4 -4
  191. package/kits/eck_message_manifest.json +46 -3
  192. package/kits/rules/04-relation.md +10 -2
  193. package/kits/rules/06-channel.md +2 -1
  194. package/kits/schemas/providers.schema.2.json +1 -0
  195. package/kits/skills/ec-group/SKILL.md +4 -0
  196. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  197. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  198. package/kits/skills/thread-ops/SKILL.md +8 -5
  199. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  200. package/kits/templates/message-fragments/group-batch.md +1 -0
  201. package/kits/templates/message-fragments/item-group.md +4 -0
  202. package/kits/templates/message-fragments/item-private.md +4 -0
  203. package/kits/templates/message-fragments/thread-context.md +1 -1
  204. package/kits/templates/system-fragments/commands.md +5 -5
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +11 -7
  207. package/package.json +3 -2
  208. package/scripts/agent-template/index.mjs +9 -4
  209. package/scripts/agent-template/inspect.mjs +16 -9
  210. package/scripts/agent-template/shared/plan.mjs +3 -33
  211. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  212. package/scripts/agent-template/shared/template-package.mjs +119 -10
  213. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  214. package/scripts/agent-template/shared/template.mjs +5 -5
  215. package/scripts/agent-template/team-pack.mjs +245 -0
  216. package/scripts/agent-template/team-preview.mjs +111 -0
  217. package/scripts/aid-batch/identity-batch.mjs +143 -0
  218. package/dist/ability/versions.js +0 -32
  219. package/dist/aun/model-headers.js +0 -17
  220. package/dist/channels/builtin-plugins.js +0 -19
  221. package/dist/core/command/team-workspace-initializer.js +0 -2
  222. package/dist/core/command/team-workspace-job-store.js +0 -88
  223. package/dist/core/command/team-workspace-management-service.js +0 -2
  224. package/dist/core/contact-bind-registry.js +0 -27
  225. package/dist/event-center/ledger.js +0 -52
  226. package/dist/services/reply.js +0 -55
  227. package/kits/templates/message-fragments/item.md +0 -3
  228. package/scripts/agent-template/pack.mjs +0 -169
@@ -15,6 +15,8 @@ import { ownerResolver } from './ownership/owner-resolver.js';
15
15
  import { AgentInitializationService, InitializationStateError, initializationErrorCode, readInitialization } from '../cli/agent-create.js';
16
16
  import { getAidStore, loadClient } from '../aun/aid/store.js';
17
17
  import { isValidAid } from '../aun/aid/validation.js';
18
+ import { readPreparedTemplateIdentity } from '../agent-template/runtime.js';
19
+ import { readAgentCreationClaim } from './agent-creation-claim.js';
18
20
  export function loadStartupAgentRegistry(agentRegistry) {
19
21
  agentRegistry.loadAll();
20
22
  const agentInfos = agentRegistry.list();
@@ -233,18 +235,19 @@ export async function createStartupAgentRunners({ agentRegistry, agentLoader, se
233
235
  export async function completeStartupAgentRuntime(agentRegistry, current) {
234
236
  try {
235
237
  const { watchAgentSkills } = await import('./skill/startup.js');
236
- for (const info of agentRegistry.list()) {
237
- if (info.status === 'running')
238
- watchAgentSkills(info.aid);
238
+ for (const agent of agentRegistry.allAgents()) {
239
+ if (agent.status === 'running')
240
+ watchAgentSkills(agent.aid);
239
241
  }
240
242
  }
241
243
  catch (error) {
242
244
  logger.warn(`[skill] agent 监控注册失败: ${error instanceof Error ? error.message : String(error)}`);
243
245
  }
244
- if (agentRegistry.list().some(info => info.status === 'running')) {
246
+ const agents = agentRegistry.allAgents();
247
+ if (agents.some(agent => agent.status === 'running')) {
245
248
  return { state: 'running', error: undefined };
246
249
  }
247
- if (agentRegistry.runnableAgents().length === 0 && agentRegistry.list().length === 0) {
250
+ if (agents.length === 0) {
248
251
  return { ...current, state: 'empty' };
249
252
  }
250
253
  if (current.state === 'starting') {
@@ -343,11 +346,19 @@ export function createAgentReloadRuntime({ agentRegistry, agentLoader, sessionMa
343
346
  await new Promise(resolve => setTimeout(resolve, 25));
344
347
  }
345
348
  },
346
- acquireWorkGate: async (aid) => {
349
+ acquireWorkGate: async (aid, token) => {
347
350
  await awaitStartupAgent?.(aid);
348
351
  const agentName = agentRegistry.get(aid)?.name;
349
352
  if (!agentName)
350
353
  return;
354
+ if (token) {
355
+ const release = messageQueue.holdAgent(agentName, token);
356
+ return () => {
357
+ if (agentRegistry.get(aid)?.status === 'disabled')
358
+ messageQueue.muteAgent(agentName);
359
+ release();
360
+ };
361
+ }
351
362
  const inheritedReloadMute = reloadOwnedMutes.delete(agentName);
352
363
  const alreadyMuted = messageQueue.isAgentMuted(agentName);
353
364
  const ownsMute = inheritedReloadMute || !alreadyMuted;
@@ -401,14 +412,23 @@ export async function checkInitializationOwner(aid, expectedOwnerAid, expectedRe
401
412
  };
402
413
  return { status: 'pending', ...(checkedAt !== undefined ? { checkedAt } : {}), ...details };
403
414
  }
404
- export function createAgentInitializationRuntime({ agentRegistry, agentMap, channelInstances, hotLoad, activate, }) {
415
+ export function createAgentInitializationRuntime({ agentRegistry, agentMap, channelInstances, hotLoad, activate, activatePrepared, }) {
405
416
  const isConnected = (aid) => channelInstances.some(instance => instance.channelType === 'aun'
406
417
  && instance.channel.getAidState?.()?.aid === aid
407
418
  && instance.channel.getAidState?.()?.status === 'connected');
408
419
  return new AgentInitializationService({
420
+ preparedIdentity: (aid, ownerAid) => {
421
+ return readAgentCreationClaim(aid)?.teamJobId ? readPreparedTemplateIdentity(aid, ownerAid) : undefined;
422
+ },
409
423
  ownershipBeforePublication: true,
410
424
  register: async (aid, ownerAid, mode) => {
411
425
  assertAgentAidAvailable(aid);
426
+ const claim = (await import('./agent-creation-claim.js')).readAgentCreationClaim(aid);
427
+ if (claim?.teamJobId) {
428
+ const { readPreparedTemplateIdentity } = await import('../agent-template/runtime.js');
429
+ readPreparedTemplateIdentity(aid, ownerAid);
430
+ return;
431
+ }
412
432
  const { aidCreateIdentityOnly } = await import('../aun/aid/identity.js');
413
433
  const { assertAgentIdentityReusable } = await import('../aun/aid/agentmd.js');
414
434
  const created = await aidCreateIdentityOnly(aid, { type: 'agent' });
@@ -426,6 +446,11 @@ export function createAgentInitializationRuntime({ agentRegistry, agentMap, chan
426
446
  }
427
447
  },
428
448
  bindOwner: async (aid, ownerAid) => {
449
+ const claim = (await import('./agent-creation-claim.js')).readAgentCreationClaim(aid);
450
+ if (claim?.teamJobId) {
451
+ const { readPreparedTemplateIdentity } = await import('../agent-template/runtime.js');
452
+ return readPreparedTemplateIdentity(aid, ownerAid).bindingTask;
453
+ }
429
454
  // Initialization happens before the new Agent is hot-loaded. Use a
430
455
  // short-lived client for both modes; the long-lived resolver requires a
431
456
  // connected subject and therefore cannot bind a freshly registered AID.
@@ -468,6 +493,7 @@ export function createAgentInitializationRuntime({ agentRegistry, agentMap, chan
468
493
  throw Object.assign(new Error('AUN connection unavailable'), { code: 'INITIALIZE_CHANNEL_UNAVAILABLE' });
469
494
  },
470
495
  activate,
496
+ activatePrepared,
471
497
  usable: aid => {
472
498
  const agent = agentRegistry.get(aid);
473
499
  return !!agent && agent.config.enabled !== false && agentMap.has(`${aid}::${agent.baseagent}`) && isConnected(aid);
@@ -481,7 +507,7 @@ export function recoverIncompleteAgentInitializations(service, agentsDir = resol
481
507
  continue;
482
508
  try {
483
509
  const record = readInitialization(entry.name);
484
- if (record?.status === 'in_progress') {
510
+ if (record?.status === 'in_progress' && !record.teamJobId) {
485
511
  service.resume(entry.name, record.actor, record.mode === 'one_shot' ? record.clientRequestId : undefined);
486
512
  }
487
513
  }
@@ -563,6 +589,57 @@ export function createAgentRuntimeOperations({ agentRegistry, agentLoader, sessi
563
589
  handoffRuntime.resumeAgent(aid);
564
590
  }
565
591
  };
592
+ const unload = async (aid, options = {}) => {
593
+ if (!isValidAid(aid))
594
+ throw Object.assign(new Error('Invalid Agent AID'), { code: 'INVALID_ARGS' });
595
+ return reloadCoordinator.runExclusive(aid, async () => {
596
+ if (await options.prepare?.() === false)
597
+ return false;
598
+ const runtimeAgent = agentRegistry.get(aid);
599
+ if (!runtimeAgent)
600
+ return false;
601
+ let removed = false;
602
+ handoffRuntime.pauseAgent(aid);
603
+ try {
604
+ await handoffRuntime.drainAgent(aid);
605
+ await triggerSchedulers.remove(aid);
606
+ for (const channelName of runtimeAgent.channelInstanceNames()) {
607
+ const instance = channelInstances.find(candidate => candidate.adapter.channelName === channelName);
608
+ if (instance) {
609
+ await instance.disconnect();
610
+ const index = channelInstances.indexOf(instance);
611
+ if (index >= 0)
612
+ channelInstances.splice(index, 1);
613
+ }
614
+ unregisterRuntimeChannel(channelName);
615
+ }
616
+ runtimeAgent.channels?.clear();
617
+ for (const [key, runner] of agentMap) {
618
+ if (!key.startsWith(`${aid}::`))
619
+ continue;
620
+ await runner.dispose?.();
621
+ agentMap.delete(key);
622
+ }
623
+ const { globalSkillWatcher } = await import('./skill/global-watcher.js');
624
+ await globalSkillWatcher.unwatchAgent(aid);
625
+ agentRegistry.remove(aid);
626
+ messageQueue.clearByAgent(runtimeAgent.name);
627
+ removed = true;
628
+ return true;
629
+ }
630
+ catch (error) {
631
+ runtimeAgent.status = 'error';
632
+ runtimeAgent.error = `Unload failed: ${error instanceof Error ? error.message : String(error)}`;
633
+ agentRegistry.channelIndex.clear();
634
+ agentRegistry.buildChannelIndex();
635
+ throw error;
636
+ }
637
+ finally {
638
+ if (!removed)
639
+ handoffRuntime.resumeAgent(aid);
640
+ }
641
+ }, options);
642
+ };
566
643
  let resyncInFlight;
567
644
  const resync = async () => {
568
645
  if (resyncInFlight)
@@ -576,40 +653,11 @@ export function createAgentRuntimeOperations({ agentRegistry, agentLoader, sessi
576
653
  const diskCfg = diskAgents.find(agent => agent.aid === aid);
577
654
  if (!diskCfg || diskCfg.enabled === false) {
578
655
  try {
579
- const offlined = await reloadCoordinator.runExclusive(aid, async () => {
580
- const latestDiskCfg = readConfig(ConfigTarget.Agent, { self: aid }, { cache: false });
581
- if (latestDiskCfg && latestDiskCfg.enabled !== false)
582
- return false;
583
- const runtimeAgent = agentRegistry.get(aid);
584
- if (!runtimeAgent)
585
- return false;
586
- let removed = false;
587
- handoffRuntime.pauseAgent(aid);
588
- try {
589
- await handoffRuntime.drainAgent(aid);
590
- await triggerSchedulers.remove(aid);
591
- for (const channelName of runtimeAgent.channelInstanceNames()) {
592
- const instance = channelInstances.find(candidate => candidate.adapter.channelName === channelName);
593
- if (instance) {
594
- try {
595
- await instance.disconnect();
596
- }
597
- catch { }
598
- const index = channelInstances.indexOf(instance);
599
- if (index >= 0)
600
- channelInstances.splice(index, 1);
601
- }
602
- unregisterRuntimeChannel(channelName);
603
- }
604
- agentRegistry.agents.delete(aid);
605
- messageQueue.clearByAgent(runtimeAgent.name);
606
- removed = true;
607
- return true;
608
- }
609
- finally {
610
- if (!removed)
611
- handoffRuntime.resumeAgent(aid);
612
- }
656
+ const offlined = await unload(aid, {
657
+ prepare: () => {
658
+ const latestDiskCfg = readConfig(ConfigTarget.Agent, { self: aid }, { cache: false });
659
+ return !latestDiskCfg || latestDiskCfg.enabled === false;
660
+ },
613
661
  });
614
662
  if (offlined)
615
663
  results.push(`- ${aid} (offline)`);
@@ -668,7 +716,7 @@ export function createAgentRuntimeOperations({ agentRegistry, agentLoader, sessi
668
716
  resyncInFlight = undefined;
669
717
  }
670
718
  };
671
- return { hotLoad, resync };
719
+ return { hotLoad, unload, resync };
672
720
  }
673
721
  // Audited fastaun start()/capture() only read and verify documents. All writes
674
722
  // and notifications occur in execute(), which converts transport failures to
@@ -4,6 +4,7 @@ import crypto from 'crypto';
4
4
  import { authorizeOperation, buildAuthSubject } from './auth-gateway.js';
5
5
  import { refreshOwnershipForAuthorization } from '../ownership/owner-resolver.js';
6
6
  import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
7
+ import { prepareSameOwnerProof } from '../relation/same-owner-proof.js';
7
8
  import { logger } from '../../utils/logger.js';
8
9
  import { canonicalizeEvolcoreCommandArgv } from '../permission/ec-command-parser.js';
9
10
  import { MAIN_CLI_BIN } from '../../product.js';
@@ -26,7 +27,7 @@ export function readDelegationCredential(env = process.env) {
26
27
  return sessionToken || undefined;
27
28
  }
28
29
  export class AgentDelegationRegistry {
29
- runtimeEpoch = crypto.randomBytes(16).toString('hex');
30
+ runtimeEpoch;
30
31
  diagnostics;
31
32
  grantsByHash = new Map();
32
33
  activeHashBySession = new Map();
@@ -35,8 +36,13 @@ export class AgentDelegationRegistry {
35
36
  approvedCommandBindings = new Map();
36
37
  internalGrants = new Map();
37
38
  debugRegistry = new DebugDelegationRegistry();
38
- constructor() {
39
- this.diagnostics = new DelegationDiagnostics(this.runtimeEpoch);
39
+ constructor(runtimeEpoch = crypto.randomBytes(16).toString('hex'), diagnostics = new DelegationDiagnostics(runtimeEpoch)) {
40
+ this.runtimeEpoch = runtimeEpoch;
41
+ this.diagnostics = diagnostics;
42
+ }
43
+ static async createAsync() {
44
+ const runtimeEpoch = crypto.randomBytes(16).toString('hex');
45
+ return new AgentDelegationRegistry(runtimeEpoch, await DelegationDiagnostics.createAsync(runtimeEpoch));
40
46
  }
41
47
  getRuntimeEpoch() {
42
48
  return this.runtimeEpoch;
@@ -447,6 +453,10 @@ export async function authorizeDelegatedAunMsgSend(registry, input) {
447
453
  await refreshOwnershipForAuthorization(grant.selfAid, {
448
454
  allowTransient: true, includeDaemon: hasTrustedFullAccessDelegation(grant),
449
455
  });
456
+ if (grant.channelType === 'aun' && grant.chatType === 'private') {
457
+ // 审批到执行之间证明可能过期;按来源主体刷新,不能借发送目标改变角色。
458
+ await prepareSameOwnerProof(grant.selfAid, grant.actorId);
459
+ }
450
460
  const builtSubject = buildAuthSubject({
451
461
  selfAid: grant.selfAid,
452
462
  actorId: grant.actorId,
@@ -3,6 +3,8 @@ import crypto from 'node:crypto';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { StringDecoder } from 'node:string_decoder';
6
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
7
+ import { performance } from 'node:perf_hooks';
6
8
  import { isDelegationDiagnosticsEnabled } from '../../config-store.js';
7
9
  import { resolvePaths } from '../../paths.js';
8
10
  import { PRODUCT_DISPLAY_NAME } from '../../product.js';
@@ -106,15 +108,37 @@ export class DelegationDiagnostics {
106
108
  persistenceState;
107
109
  sequence = 0;
108
110
  lastWarnings = new Map();
109
- constructor(runtimeEpoch) {
111
+ constructor(runtimeEpoch, initialize = true) {
110
112
  this.runtimeEpoch = runtimeEpoch;
111
113
  const paths = resolvePaths();
112
114
  this.logDir = paths.logs;
113
115
  this.indexPath = path.join(paths.dataDir, 'delegation-diagnostics', 'index.json');
116
+ if (!initialize)
117
+ return;
114
118
  this.load();
115
119
  this.record('runtime.started');
116
120
  this.save();
117
121
  }
122
+ /** Hydrate fully before exposing the registry, yielding during history replay. */
123
+ static async createAsync(runtimeEpoch) {
124
+ const diagnostics = new DelegationDiagnostics(runtimeEpoch, false);
125
+ diagnostics.loadIndex();
126
+ let batchStarted = performance.now();
127
+ for (const state of diagnostics.scanHistory()) {
128
+ if (state !== null) {
129
+ diagnostics.restoreHistoryState(state);
130
+ continue;
131
+ }
132
+ // Each input chunk provides a checkpoint, even if it has no valid rows.
133
+ if (performance.now() - batchStarted >= 8) {
134
+ await yieldToIo();
135
+ batchStarted = performance.now();
136
+ }
137
+ }
138
+ diagnostics.record('runtime.started');
139
+ diagnostics.save();
140
+ return diagnostics;
141
+ }
118
142
  close() {
119
143
  this.writer?.close();
120
144
  }
@@ -284,6 +308,13 @@ export class DelegationDiagnostics {
284
308
  }
285
309
  }
286
310
  load() {
311
+ this.loadIndex();
312
+ for (const state of this.scanHistory()) {
313
+ if (state !== null)
314
+ this.restoreHistoryState(state);
315
+ }
316
+ }
317
+ loadIndex() {
287
318
  try {
288
319
  const index = JSON.parse(fs.readFileSync(this.indexPath, 'utf8'));
289
320
  if (index.version !== 1 || !Array.isArray(index.states))
@@ -298,16 +329,16 @@ export class DelegationDiagnostics {
298
329
  if (error.code !== 'ENOENT')
299
330
  this.warn('诊断索引读取失败,尝试从审计事件重建', error);
300
331
  }
301
- this.scanHistory(state => {
302
- if (!this.retained(state))
303
- return;
304
- const previous = this.states.get(stateKey(state));
305
- if (!previous || (state.sequence !== undefined && previous.sequence !== undefined
306
- ? state.sequence > previous.sequence : state.updatedAt > previous.updatedAt))
307
- this.store(state);
308
- });
309
332
  }
310
- scanHistory(visit) {
333
+ restoreHistoryState(state) {
334
+ if (!state || !this.retained(state))
335
+ return;
336
+ const previous = this.states.get(stateKey(state));
337
+ if (!previous || (state.sequence !== undefined && previous.sequence !== undefined
338
+ ? state.sequence > previous.sequence : state.updatedAt > previous.updatedAt))
339
+ this.store(state);
340
+ }
341
+ *scanHistory() {
311
342
  try {
312
343
  if (!fs.existsSync(this.logDir))
313
344
  return;
@@ -319,9 +350,18 @@ export class DelegationDiagnostics {
319
350
  return;
320
351
  try {
321
352
  const event = JSON.parse(line);
322
- const state = event.version === 1 ? readState(event.state) : undefined;
323
- if (state)
324
- visit(state);
353
+ const raw = event.version === 1 ? event.state : undefined;
354
+ if (!raw)
355
+ return;
356
+ // A covered revision cannot replace this key. Avoid sanitizing and
357
+ // checking retention for it again; legacy counters still use the
358
+ // timestamp comparison after normal validation.
359
+ const previous = this.states.get(stateKey(raw));
360
+ if (previous?.sequence !== undefined && typeof raw.sequence === 'number'
361
+ && Number.isSafeInteger(raw.sequence) && raw.sequence >= 0
362
+ && raw.sequence <= previous.sequence)
363
+ return;
364
+ return readState(raw);
325
365
  }
326
366
  catch (error) {
327
367
  this.warn(`忽略损坏的审计记录 ${name}`, error);
@@ -339,7 +379,7 @@ export class DelegationDiagnostics {
339
379
  let newline;
340
380
  while ((newline = pending.indexOf('\n')) >= 0) {
341
381
  if (!skipping && newline <= 64 * 1024)
342
- consume(pending.slice(0, newline));
382
+ yield consume(pending.slice(0, newline));
343
383
  pending = pending.slice(newline + 1);
344
384
  skipping = false;
345
385
  }
@@ -348,9 +388,10 @@ export class DelegationDiagnostics {
348
388
  skipping = true;
349
389
  this.warn(`忽略过长的审计记录 ${name}`, new Error('oversized record'));
350
390
  }
391
+ yield null; // End of this read, independent of record validity.
351
392
  }
352
393
  if (!skipping)
353
- consume(pending + decoder.end());
394
+ yield consume(pending + decoder.end());
354
395
  }
355
396
  catch (error) {
356
397
  this.warn(`历史审计读取失败 ${name}`, error);
@@ -5,10 +5,10 @@ import { isResolvedConfigMutation, } from '../../config/resolved-config-op.js';
5
5
  import { normalizePeer } from '../model/config-scope.js';
6
6
  import { getOperationMeta } from './operation-catalog.js';
7
7
  import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
8
- import { sameGroupAid } from '../../aun/group/index.js';
8
+ import { sameGroupAid } from '../../aun/group/identity.js';
9
9
  import { ownerResolver } from '../ownership/owner-resolver.js';
10
10
  const DAEMON_OWNER_PROCESS_OPERATIONS = new Set([
11
- ...['inspect', 'build', 'push', 'pull', 'deploy', 'query'].map(action => 'agent.template.' + action),
11
+ ...['inspect', 'build', 'push', 'pull', 'preview', 'deploy', 'status', 'resume', 'cancel', 'capabilities'].map(action => 'agent.template.' + action),
12
12
  'model.provider.catalog',
13
13
  'agent.list',
14
14
  'agent.create',
@@ -167,6 +167,7 @@ const OPERATIONS = [
167
167
  ['event.subscribers.list', 'List event subscribers'],
168
168
  ['event.stats.current', 'Read event publication statistics'],
169
169
  ['event.publishStats.current', 'Read per-pack event publication statistics'],
170
+ ['event.timeline.list', 'Read event publication timeline'],
170
171
  ['event.records.list', 'Read event delivery records'],
171
172
  ].map(([id, description]) => ({
172
173
  id,
@@ -228,10 +229,9 @@ const OPERATIONS = [
228
229
  description: '启动、停止、重载或守护本地服务',
229
230
  sources: ['agent-tool'],
230
231
  },
231
- // ── Model Operations ──
232
- ...['inspect', 'build', 'push', 'pull', 'deploy', 'query'].map(action => ({
232
+ ...['inspect', 'build', 'push', 'pull', 'preview', 'deploy', 'status', 'resume', 'cancel', 'capabilities'].map(action => ({
233
233
  id: 'agent.template.' + action, category: 'process',
234
- dangerous: !['inspect', 'query'].includes(action), defaultScopes: ['process'],
234
+ dangerous: !['status', 'capabilities'].includes(action), defaultScopes: ['process'],
235
235
  description: 'Agent template ' + action, sources: ['menu', 'control', 'agent-tool', 'ecweb'],
236
236
  })),
237
237
  { id: 'model.provider.catalog', category: 'process', dangerous: false, defaultScopes: ['process'],
@@ -1,4 +1,5 @@
1
1
  import { hasSuppliedInitialization } from '../cli/agent-create.js';
2
+ import { templateInstallationGate } from '../agent-template/jobs.js';
2
3
  import { ownerResolver, OWNERSHIP_AUTHORIZATION_MAX_AGE_MS } from './ownership/owner-resolver.js';
3
4
  import fs from 'fs';
4
5
  import path from 'path';
@@ -17,6 +18,8 @@ import * as outbox from '../aun/outbox.js';
17
18
  import { chatDirPath } from './session/session-fs-store.js';
18
19
  /** Coordinate the write-ahead completion welcome with the lifecycle commit. */
19
20
  export async function completeBootstrapWithWelcome(service, aid, welcome, sessions) {
21
+ if (templateInstallationGate(aid).blocked)
22
+ return { ok: false, code: 'TEAM_NOT_COMMITTED', error: 'Team creation has not committed', reloaded: false };
20
23
  const lifecycle = service.lifecycleOf(aid);
21
24
  const config = loadAgent(aid);
22
25
  const suppliedOwnerPending = lifecycle === 'ownerpending' && config?.initialization?.mode === 'supplied';
@@ -1,4 +1,5 @@
1
1
  import { ConfigTarget, read, write } from '../../config/config-manager.js';
2
+ import { resolveProjectDefaultPath } from '../../utils/project-path.js';
2
3
  import { ClaudeCapabilityProvider } from './providers/claude-capability-provider.js';
3
4
  import { CodexCapabilityProvider } from './providers/codex-capability-provider.js';
4
5
  import { GeminiCapabilityProvider } from './providers/gemini-capability-provider.js';
@@ -23,7 +24,8 @@ export function resolveCapabilityContext(input) {
23
24
  const aid = input.aid || input.config?.aid;
24
25
  if (!aid)
25
26
  return { error: '当前 channel 无绑定 agent', code: 'FORBIDDEN' };
26
- const projectPath = input.config?.projects?.defaultPath || input.projectPath || input.sessionProjectPath || null;
27
+ const projectPath = resolveProjectDefaultPath(input.config?.projects?.defaultPath)
28
+ || input.projectPath || input.sessionProjectPath || null;
27
29
  if (!projectPath)
28
30
  return { error: '无法解析当前 agent projectPath', code: 'NO_PROJECT' };
29
31
  const baseagent = resolveBaseagent(input);
@@ -8,7 +8,6 @@
8
8
  import { logger } from '../utils/logger.js';
9
9
  import { assertAgentAidAvailable } from '../config/config-manager.js';
10
10
  import { PluginHandle } from './plugin-lifecycle.js';
11
- import { ContactBindRegistry } from './contact-bind-registry.js';
12
11
  /**
13
12
  * 进程退出时给 AUN 渠道的 WebSocket 关闭握手留的时间。
14
13
  *
@@ -178,7 +177,7 @@ export class ChannelLoader {
178
177
  buildContext(agent) {
179
178
  return {
180
179
  agentName: agent.aid,
181
- defaultProjectPath: agent.config.projects?.defaultPath ?? process.cwd(),
180
+ defaultProjectPath: agent.projectPath,
182
181
  debug: this.processDebug,
183
182
  aunDefaultEncrypt: this.aunDefaultEncrypt,
184
183
  };
@@ -549,7 +548,7 @@ export function buildReloadHooks(deps) {
549
548
  }
550
549
  const ctx = {
551
550
  agentName: agent.aid ?? agent.config?.aid,
552
- defaultProjectPath: agent.config?.projects?.defaultPath ?? process.cwd(),
551
+ defaultProjectPath: agent.projectPath,
553
552
  debug: channelLoader.processDebug,
554
553
  aunDefaultEncrypt: channelLoader.aunDefaultEncrypt,
555
554
  };
@@ -593,3 +592,30 @@ export function buildReloadHooks(deps) {
593
592
  },
594
593
  };
595
594
  }
595
+ export class ContactBindRegistry {
596
+ providers = new Map();
597
+ register(channelType, provider) {
598
+ const normalizedType = channelType.trim().toLowerCase();
599
+ if (!normalizedType)
600
+ throw new Error('Contact-bind channel type must not be empty');
601
+ if (this.providers.has(normalizedType)) {
602
+ throw new Error(`Contact-bind provider '${normalizedType}' already registered`);
603
+ }
604
+ this.providers.set(normalizedType, provider);
605
+ }
606
+ get(channelType) {
607
+ return this.providers.get(channelType.trim().toLowerCase());
608
+ }
609
+ channelTypes() {
610
+ return [...this.providers.keys()];
611
+ }
612
+ handle(channelType, context) {
613
+ return this.get(channelType)?.handle(context) ?? { handled: false };
614
+ }
615
+ registerPending(channelType, request) {
616
+ const provider = this.get(channelType);
617
+ return provider
618
+ ? provider.register(request)
619
+ : { ok: false, error: `contact bind provider not configured for channel '${channelType}'` };
620
+ }
621
+ }
@@ -100,7 +100,7 @@ export function createChannelConnectionRuntime(dependencies) {
100
100
  const type = instance.channelType || name;
101
101
  dependencies.eventBus.publish({ type: 'channel:connected', channel: type.toLowerCase(), channelName: name, timestamp: Date.now() });
102
102
  const agent = dependencies.resolveOwningAgent(key, name);
103
- if (instance.channelType === 'aun' && agent && !dependencies.isStartupRecoveryPending()) {
103
+ if (instance.channelType === 'aun' && agent && !dependencies.isStartupRecoveryPending(agent.aid)) {
104
104
  void queuePendingObserverHints(agent.aid, key)
105
105
  .catch(error => logger.warn(`[ObserverHint] reconnect recovery failed for ${agent.aid}: ${error}`));
106
106
  }
@@ -14,7 +14,7 @@ import { uploadAvatar, uploadAvatarUrl } from '../../utils/avatar-upload.js';
14
14
  import { agentmdGet, agentmdPut, updateAgentMdFrontmatterName } from '../../aun/aid/agentmd.js';
15
15
  import { isValidAid } from '../../aun/aid/validation.js';
16
16
  import { isSupportedBaseagent } from '../../agents/baseagent.js';
17
- import { resolveProviderServiceForBaseagent } from '../../config/providers.js';
17
+ import { assertProviderModelAllowed, resolveProviderServiceForBaseagent } from '../../config/providers.js';
18
18
  import { claimAgentCreationAsync, removeAgentCreationClaim } from '../agent-creation-claim.js';
19
19
  /** Enabled by default; an explicit 0 retains the host-scoped rollback switch. */
20
20
  export function appOneShotCreateEnabled(env = process.env) {
@@ -858,8 +858,8 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
858
858
  if (provider) {
859
859
  try {
860
860
  const resolved = resolveProviderServiceForBaseagent(provider, a.baseagent);
861
- if (model && resolved.modelOverrides[model]?.enabled === false)
862
- throw new Error(`Model ${model} is disabled for provider ${provider}`);
861
+ if (model)
862
+ assertProviderModelAllowed(model, resolved);
863
863
  }
864
864
  catch (error) {
865
865
  return { error: error.message || String(error), code: 'INVALID_ARGS' };
@@ -938,7 +938,7 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
938
938
  ? await service.delete(a.aid, false)
939
939
  : await agentDelete(a.aid, false);
940
940
  if (!('ok' in res) || res.ok !== true)
941
- return { error: res.error, code: classifyError(res.error) };
941
+ return { error: res.error, code: res.code || classifyError(res.error) };
942
942
  eventBus?.publish({ type: 'agent:deleted', aid: res.aid, purged: res.purged, timestamp: Date.now() });
943
943
  return { data: { aid: res.aid, purged: res.purged } };
944
944
  }
@@ -961,7 +961,8 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
961
961
  reloaded: res.reloaded,
962
962
  timestamp: Date.now(),
963
963
  });
964
- return { data: { aid: res.aid, enabled: res.enabled, reloaded: res.reloaded } };
964
+ return { data: { aid: res.aid, enabled: res.enabled, reloaded: res.reloaded,
965
+ ...('configMissing' in res ? { configMissing: res.configMissing } : {}) } };
965
966
  }
966
967
  if (action === 'reload') {
967
968
  if (!a.aid)