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
@@ -1,5 +1,6 @@
1
1
  import { tryParseChannelKey } from './channel-loader.js';
2
2
  import { needsHandoffRecovery } from './handoff/types.js';
3
+ import { hasIndexedRecovery, parseQueueSnapshot } from './message/message-queue.js';
3
4
  import { replyContextFromSession } from './message/message-utils.js';
4
5
  import { logger } from '../utils/logger.js';
5
6
  import fs from 'fs';
@@ -10,6 +11,7 @@ import { OFFLINE_TOTAL_BUDGET_MS } from './lifecycle-notice.js';
10
11
  import { setImmediate as yieldToIo } from 'node:timers/promises';
11
12
  import { performance, monitorEventLoopDelay } from 'node:perf_hooks';
12
13
  import path from 'node:path';
14
+ import os from 'node:os';
13
15
  import { agentTriggersDir } from '../paths.js';
14
16
  import { readLastJsonlLineAsync, scanAgentChatDirsAsync } from './session/session-fs-store.js';
15
17
  import { pendingHintDirectoryVersion } from './message/pending-hints.js';
@@ -77,6 +79,7 @@ export async function discoverStartupWork(options) {
77
79
  priorityAids: new Set(), triggerAids: new Set(), requiredChannelKeys: new Set(),
78
80
  requiredExternalAids: new Set(), pendingSessions: [], staleSessions: [], sessionScanFailed: false,
79
81
  hintDirectories: new Map(),
82
+ recoveryIndexAids: new Set(options.agentAids),
80
83
  };
81
84
  const known = new Set(options.agentAids);
82
85
  const prioritized = new Set();
@@ -108,37 +111,37 @@ export async function discoverStartupWork(options) {
108
111
  else
109
112
  plan.requiredExternalAids.add(aid);
110
113
  };
111
- const queueStarted = Date.now();
112
- let queueItems = 0;
113
- let queueFiles = 0;
114
- try {
115
- const queue = await json(options.queuePath);
116
- if (queue !== undefined) {
117
- queueFiles = 1;
118
- if (!queue || ![1, 2].includes(queue.version) || !Array.isArray(queue.queues)
119
- || (queue.active !== undefined && !Array.isArray(queue.active)))
120
- throw new Error('invalid queue snapshot');
121
- for (const bucket of [...queue.queues, ...(queue.active ?? [])]) {
122
- if (!Array.isArray(bucket.items))
123
- throw new Error('invalid queue bucket');
124
- for (const item of bucket.items) {
125
- queueItems++;
126
- noteMessage(item.message, bucket.queueKey);
127
- for (const part of item.parts ?? [])
128
- noteMessage(part.message, bucket.queueKey);
114
+ let queueSnapshot;
115
+ const queueCapture = (async () => {
116
+ const queueStarted = Date.now();
117
+ let queueItems = 0;
118
+ let queueFiles = 0;
119
+ try {
120
+ const queue = await json(options.queuePath);
121
+ if (queue !== undefined) {
122
+ queueFiles = 1;
123
+ queueSnapshot = parseQueueSnapshot(queue);
124
+ for (const bucket of [...queueSnapshot.queues, ...(queueSnapshot.active ?? [])]) {
125
+ for (const item of bucket.items) {
126
+ queueItems++;
127
+ noteMessage(item.message, bucket.queueKey);
128
+ for (const part of item.parts ?? [])
129
+ noteMessage(part.message, bucket.queueKey);
130
+ }
129
131
  }
130
132
  }
131
133
  }
132
- }
133
- catch (error) {
134
- for (const aid of known)
135
- uncertain(aid, error);
136
- }
137
- finally {
138
- options.onScan?.({ phase: 'queue', durationMs: Date.now() - queueStarted, files: queueFiles, items: queueItems });
139
- options.onQueueCaptured?.();
140
- }
141
- const now = Date.now();
134
+ catch (error) {
135
+ plan.recoveryIndexAids.clear();
136
+ for (const aid of known)
137
+ uncertain(aid, error);
138
+ }
139
+ finally {
140
+ options.onScan?.({ phase: 'queue', durationMs: Date.now() - queueStarted, files: queueFiles, items: queueItems });
141
+ options.onQueueCaptured?.(queueSnapshot);
142
+ }
143
+ return Date.now();
144
+ })();
142
145
  const triggerDir = options.triggerDir ?? agentTriggersDir;
143
146
  const scanTriggers = async (aid) => {
144
147
  const started = Date.now();
@@ -189,108 +192,131 @@ export async function discoverStartupWork(options) {
189
192
  const loopStart = performance.eventLoopUtilization();
190
193
  loopDelay.enable();
191
194
  try {
192
- await Promise.all([daemonTriggerScan, ...Array.from({ length: Math.min(4, aids.length) }, async () => {
195
+ await Promise.all([queueCapture, daemonTriggerScan, ...Array.from({ length: Math.min(4, aids.length) }, async () => {
193
196
  while (next < aids.length) {
194
197
  const aid = aids[next++];
195
- const started = Date.now();
196
- let files = 0;
197
- let chats = 0;
198
- let directoryMs = 0;
199
- let threadDirectoryMs = 0;
200
- let metadataMs = 0;
201
- let readMaxMs = 0;
202
- const io = { openMs: 0, statMs: 0, readMs: 0, parseMs: 0, closeMs: 0, bytes: 0 };
203
- try {
204
- const hintVersion = pendingHintDirectoryVersion();
205
- let phaseStarted = performance.now();
206
- let chatDirs;
207
- try {
208
- chatDirs = await scanAgentChatDirsAsync(options.sessionsRoot, aid, undefined, { includeEntries: true });
209
- }
210
- finally {
211
- directoryMs = Math.round(performance.now() - phaseStarted);
212
- }
213
- chats = chatDirs.length;
214
- // Keep paths only; retries read current hint events. A new hint chat
215
- // invalidates this inventory even when created while discovery runs.
216
- if (hintVersion === pendingHintDirectoryVersion())
217
- plan.hintDirectories.set(aid, {
218
- sessionsDir: options.sessionsRoot, selfAID: aid, version: hintVersion,
219
- chats: chatDirs.map(({ entries: _entries, ...chat }) => chat),
220
- });
221
- const metadata = [];
222
- const collect = (dir, names, strict) => {
223
- for (const name of names)
224
- if (/^meta_.*\.jsonl$/.test(name)) {
225
- metadata.push({ file: path.join(dir, name), strict });
226
- files++;
227
- }
228
- };
229
- for (const chat of chatDirs)
230
- collect(chat.dirPath, chat.entries.map(entry => entry.name), false);
231
- phaseStarted = performance.now();
198
+ const scanSessions = async () => {
199
+ // Trigger evidence is independent of the queue. Session history and
200
+ // idle classification still require the captured recovery index.
201
+ const now = await queueCapture;
202
+ // A complete queue snapshot covers executions, including consumed hints.
203
+ // Do not enumerate historical chat/topic directories on the normal path.
204
+ if (hasIndexedRecovery(queueSnapshot, aid))
205
+ return;
206
+ const started = Date.now();
207
+ let files = 0;
208
+ let chats = 0;
209
+ let directoryMs = 0;
210
+ let threadDirectoryMs = 0;
211
+ let metadataMs = 0;
212
+ let readMaxMs = 0;
213
+ const io = { openMs: 0, statMs: 0, readMs: 0, parseMs: 0, closeMs: 0, bytes: 0 };
232
214
  try {
233
- await scanStartupItems(chatDirs.filter(chat => chat.entries.some(entry => entry.name === '_threads')), 8, async (chat) => {
234
- const dir = path.join(chat.dirPath, '_threads');
235
- try {
236
- collect(dir, await fs.promises.readdir(dir), true);
237
- }
238
- catch (error) {
239
- if (error.code !== 'ENOENT')
240
- throw error;
241
- }
242
- });
215
+ const hintVersion = pendingHintDirectoryVersion();
216
+ let phaseStarted = performance.now();
217
+ let chatDirs;
218
+ try {
219
+ chatDirs = await scanAgentChatDirsAsync(options.sessionsRoot, aid, undefined, { includeEntries: true });
220
+ }
221
+ finally {
222
+ directoryMs = Math.round(performance.now() - phaseStarted);
223
+ }
224
+ chats = chatDirs.length;
225
+ // Keep paths only; retries read current hint events. A new hint chat
226
+ // invalidates this inventory even when created while discovery runs.
227
+ if (hintVersion === pendingHintDirectoryVersion())
228
+ plan.hintDirectories.set(aid, {
229
+ sessionsDir: options.sessionsRoot, selfAID: aid, version: hintVersion,
230
+ chats: chatDirs.map(({ entries: _entries, ...chat }) => chat),
231
+ });
232
+ const metadata = [];
233
+ const collect = (dir, names, strict) => {
234
+ for (const name of names)
235
+ if (/^meta_.*\.jsonl$/.test(name)) {
236
+ metadata.push({ file: path.join(dir, name), strict });
237
+ files++;
238
+ }
239
+ };
240
+ for (const chat of chatDirs)
241
+ collect(chat.dirPath, chat.entries.map(entry => entry.name), false);
242
+ phaseStarted = performance.now();
243
+ try {
244
+ await scanStartupItems(chatDirs.filter(chat => chat.entries.some(entry => entry.name === '_threads')), 8, async (chat) => {
245
+ const dir = path.join(chat.dirPath, '_threads');
246
+ try {
247
+ collect(dir, await fs.promises.readdir(dir), true);
248
+ }
249
+ catch (error) {
250
+ if (error.code !== 'ENOENT')
251
+ throw error;
252
+ }
253
+ });
254
+ }
255
+ finally {
256
+ threadDirectoryMs = Math.round(performance.now() - phaseStarted);
257
+ }
258
+ // The eight-reader budget spans all chats of this Agent. A slow file
259
+ // must not serialize the next chat or a complete batch of eight files.
260
+ phaseStarted = performance.now();
261
+ try {
262
+ await scanStartupItems(metadata, 8, async ({ file, strict }) => {
263
+ const readStarted = performance.now();
264
+ let session;
265
+ try {
266
+ const record = await readLastJsonlLineAsync(file, strict, io);
267
+ if (!record) {
268
+ plan.recoveryIndexAids.delete(aid);
269
+ uncertain(aid, `no readable session record: ${file}`);
270
+ return;
271
+ }
272
+ session = fileToSession(record);
273
+ }
274
+ catch (error) {
275
+ // Match the compatibility recovery's per-file isolation;
276
+ // one corrupt record must not force a global blocking scan.
277
+ plan.recoveryIndexAids.delete(aid);
278
+ uncertain(aid, error);
279
+ logger.error(`[startup] Skipping unreadable session metadata during recovery: ${file}: ${error instanceof Error ? error.message : String(error)}`);
280
+ return;
281
+ }
282
+ finally {
283
+ readMaxMs = Math.max(readMaxMs, Math.round(performance.now() - readStarted));
284
+ }
285
+ if (!session.processingState)
286
+ return;
287
+ const startedAt = Number.parseInt(session.processingState.split(':', 1)[0], 10);
288
+ if (Number.isFinite(startedAt) && now - startedAt < 3_600_000) {
289
+ plan.pendingSessions.push(session);
290
+ prioritize(aid, 'sessions');
291
+ plan.requiredChannelKeys.add(session.channel);
292
+ }
293
+ else
294
+ plan.staleSessions.push(session);
295
+ });
296
+ }
297
+ finally {
298
+ metadataMs = Math.round(performance.now() - phaseStarted);
299
+ }
243
300
  }
244
- finally {
245
- threadDirectoryMs = Math.round(performance.now() - phaseStarted);
301
+ catch (error) {
302
+ plan.recoveryIndexAids.delete(aid);
303
+ plan.hintDirectories.delete(aid);
304
+ plan.sessionScanFailed = true;
305
+ uncertain(aid, error);
246
306
  }
247
- // The eight-reader budget spans all chats of this Agent. A slow file
248
- // must not serialize the next chat or a complete batch of eight files.
249
- phaseStarted = performance.now();
250
- try {
251
- await scanStartupItems(metadata, 8, async ({ file, strict }) => {
252
- const readStarted = performance.now();
253
- let record;
254
- try {
255
- record = await readLastJsonlLineAsync(file, strict, io);
256
- }
257
- finally {
258
- readMaxMs = Math.max(readMaxMs, Math.round(performance.now() - readStarted));
259
- }
260
- if (!record)
261
- return;
262
- const session = fileToSession(record);
263
- if (!session.processingState)
264
- return;
265
- const startedAt = Number.parseInt(session.processingState.split(':', 1)[0], 10);
266
- if (Number.isFinite(startedAt) && now - startedAt < 3_600_000) {
267
- plan.pendingSessions.push(session);
268
- prioritize(aid, 'sessions');
269
- plan.requiredChannelKeys.add(session.channel);
270
- }
271
- else
272
- plan.staleSessions.push(session);
273
- });
274
- }
275
- finally {
276
- metadataMs = Math.round(performance.now() - phaseStarted);
277
- }
278
- }
279
- catch (error) {
280
- plan.hintDirectories.delete(aid);
281
- plan.sessionScanFailed = true;
282
- uncertain(aid, error);
283
- }
284
- for (const key of Object.keys(io))
285
- io[key] = Math.round(io[key]);
286
- options.onScan?.({ phase: 'sessions', aid, durationMs: Date.now() - started, files, directories: chats,
287
- directoryMs, threadDirectoryMs, metadataMs, readMaxMs, io });
288
- if (aid === options.daemonTriggerAid)
289
- await daemonTriggerScan;
290
- else
291
- await scanTriggers(aid);
292
- if (aid === options.primaryAid)
293
- await daemonTriggerScan;
307
+ for (const key of Object.keys(io))
308
+ io[key] = Math.round(io[key]);
309
+ options.onScan?.({ phase: 'sessions', aid, durationMs: Date.now() - started, files, directories: chats,
310
+ directoryMs, threadDirectoryMs, metadataMs, readMaxMs, io });
311
+ };
312
+ // Start independent read-only evidence under the four-owner budget.
313
+ // Positive work can admit a busy owner early; idle classification
314
+ // still waits for both scans and the primary's daemon-owned Triggers.
315
+ await Promise.all([
316
+ scanSessions(),
317
+ aid === options.daemonTriggerAid ? daemonTriggerScan : scanTriggers(aid),
318
+ aid === options.primaryAid ? daemonTriggerScan : undefined,
319
+ ]);
294
320
  options.onAgentDiscovered?.(aid, plan);
295
321
  }
296
322
  })]);
@@ -303,6 +329,17 @@ export async function discoverStartupWork(options) {
303
329
  }
304
330
  return plan;
305
331
  }
332
+ /** One concurrent channel connection per available CPU, capped at eight. */
333
+ export function startupConnectionBudget() {
334
+ let cpuParallelism = 1;
335
+ try {
336
+ const available = os.availableParallelism();
337
+ if (Number.isInteger(available) && available > 0)
338
+ cpuParallelism = available;
339
+ }
340
+ catch { /* Retain the one-CPU budget when detection is unavailable. */ }
341
+ return { cpuParallelism, concurrency: Math.min(cpuParallelism, 8) };
342
+ }
306
343
  /** Bounded admission for startup side effects. Dependency waits belong outside this queue. */
307
344
  export class StartupTaskQueue {
308
345
  concurrency;
@@ -344,7 +381,7 @@ export class StartupTaskQueue {
344
381
  // Choose at admission time, so newly classified priority work can pass
345
382
  // queued idle channels. Never hold a free slot for unclassified work;
346
383
  // already-running connections finish within the existing concurrency cap.
347
- let index = this.pending.findIndex(task => task.priority === 'foreground');
384
+ let index = this.pending.findIndex(task => (typeof task.priority === 'function' ? task.priority() : task.priority) === 'foreground');
348
385
  if (index < 0)
349
386
  index = 0;
350
387
  const task = this.pending.splice(index, 1)[0];
@@ -411,6 +448,7 @@ export async function recoverStartupObserverHints(options) {
411
448
  await Promise.all(options.startupObserverRecoveries);
412
449
  await Promise.all(options.recoveryAids.map(async (aid) => {
413
450
  await options.beforeAgentRecovery?.(aid);
451
+ let attempts = 0;
414
452
  while (!options.isCancelled()) {
415
453
  const started = Date.now();
416
454
  try {
@@ -428,8 +466,9 @@ export async function recoverStartupObserverHints(options) {
428
466
  return;
429
467
  }
430
468
  catch (error) {
469
+ attempts++;
431
470
  options.trace?.addSpan('daemon.observerHints', started, Date.now(), `${aid}; retry pending`);
432
- logger.warn(`[startup] observer hint registration waits for ${aid}: ${error}`);
471
+ logger.warn(`[startup] observer hint registration waits for ${aid} (attempt ${attempts}): ${error}`);
433
472
  await recoveryRetryDelay();
434
473
  }
435
474
  }
@@ -547,7 +586,7 @@ export class StartupHandoffRecovery {
547
586
  finish?.(isCancelled() ? 'cancelled' : 'ok');
548
587
  }
549
588
  }
550
- export function resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap, pendingSessions = sessionManager.getPendingProcessingSessions(), }) {
589
+ export async function resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap, pendingSessions = sessionManager.getPendingProcessingSessions(), }) {
551
590
  if (pendingSessions.length === 0)
552
591
  return;
553
592
  logger.info(`[Resume] Found ${pendingSessions.length} pending session(s) from before restart`);
@@ -604,14 +643,16 @@ export function resumePendingSessions({ sessionManager, messageQueue, droppedTri
604
643
  peerId: '',
605
644
  threadId: sessionTopicThreadId(session),
606
645
  replyContext: replyContextFromSession(session),
646
+ boundSessionId: session.id,
647
+ baseagent: session.baseagent,
648
+ source: 'recovery',
607
649
  };
608
- sessionManager.clearProcessing(session.id);
609
- messageQueue.enqueue(session.id, resumeMessage, session.projectPath, {
650
+ // Persist before clearing the legacy marker: a crash must retain one recovery source.
651
+ await messageQueue.enqueuePersisted(session.id, resumeMessage, session.projectPath, {
610
652
  sessionKeyField: session.sessionKey,
611
653
  selfAID: resumeSelfAID,
612
- }).catch(error => {
613
- logger.error(`[Resume] Failed to resume session ${session.id}:`, error);
614
654
  });
655
+ sessionManager.clearProcessing(session.id);
615
656
  }
616
657
  }
617
658
  export function createDaemonShutdown({ disposePluginResources, lifecycleNotices, stopOwnership, ipcServer, readySignalPath, bindService, ecwebSupervisor, messageQueue, permissionGateway, removePermissionConfigListener, stopStatsPersistence, triggerSchedulers, agentMap, eventBus, removeGroupInviteConfigListener, groupInviteReviewService, channelLoader, channelInstances, startupRunners, waitForRunnerLoads, cancelStartup, controlChannel, sessionManager, removeAll, exit, }) {
@@ -621,6 +662,15 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
621
662
  if (shutdownInProgress)
622
663
  return;
623
664
  shutdownInProgress = true;
665
+ // Include pre-teardown notices and quiescing in the real stop boundary.
666
+ const trace = new StartupTracer('daemon', {
667
+ kind: 'stop',
668
+ traceId: traceId || undefined,
669
+ processStartMs: Date.now(),
670
+ });
671
+ trace.setMeta('signal', signal || shutdownSignal);
672
+ trace.setMeta('via', traceId ? 'ipc' : 'signal');
673
+ const preparationStartedAt = Date.now();
624
674
  cancelStartup?.();
625
675
  if (signal)
626
676
  shutdownSignal = signal;
@@ -636,6 +686,8 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
636
686
  // 异步的(发送前 await ownerResolver.refresh)。若不等它,stopOwnership 会在准入
637
687
  // 恢复执行前清空 resolver,snapshot() 重建空 subject 后一律判 unavailable,
638
688
  // 下线通知就会被 CONTACT_DENIED 拦下。
689
+ const offlineStartedAt = Date.now();
690
+ trace.addSpan('daemon.shutdown', preparationStartedAt, offlineStartedAt);
639
691
  try {
640
692
  await withDeadline(lifecycleNotices?.sendOffline(shutdownSignal), OFFLINE_TOTAL_BUDGET_MS);
641
693
  }
@@ -643,6 +695,10 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
643
695
  // A synchronous throw must not abort the exit; the notice is best-effort.
644
696
  logger.warn(`[Shutdown] offline notice failed: ${error instanceof Error ? error.message : String(error)}`);
645
697
  }
698
+ finally {
699
+ trace.addSpan('daemon.offlineNotices', offlineStartedAt, Date.now());
700
+ }
701
+ const quiesceStartedAt = Date.now();
646
702
  // Detaching ownership emits invalidations. Stop listeners first so those
647
703
  // invalidations cannot enqueue refreshes against a resolver being destroyed.
648
704
  for (const channel of [...channelInstances.map(instance => instance.channel), controlChannel]) {
@@ -661,17 +717,7 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
661
717
  const pid = process.pid;
662
718
  const ppid = process.ppid;
663
719
  logger.info(`\n\nShutting down gracefully... (signal=${shutdownSignal}, pid=${pid}, ppid=${ppid})`);
664
- // 停止甘特图埋点。基线是"收到停止请求的这一刻",不能回推进程启动时刻——
665
- // daemon 可能已经跑了几小时。traceId 由 `ec stop` 通过 IPC 带进来,
666
- // 没有的话(信号退出、超时兜底)自己生成一条独立的记录。
667
- const trace = new StartupTracer('daemon', {
668
- kind: 'stop',
669
- traceId: traceId || undefined,
670
- processStartMs: Date.now(),
671
- });
672
- trace.setMeta('signal', shutdownSignal);
673
- trace.setMeta('via', traceId ? 'ipc' : 'signal');
674
- trace.addSpan('daemon.shutdown', trace.startedAtMs, Date.now());
720
+ trace.addSpan('daemon.quiesceChannels', quiesceStartedAt, Date.now());
675
721
  const ipcStopStartedAt = Date.now();
676
722
  ipcServer.stopCpuTracking();
677
723
  ipcServer.stop();
@@ -96,7 +96,14 @@ export class EvolAgentRegistry {
96
96
  try {
97
97
  const raw = readConfig(ConfigTarget.Agent, { self: expandedRaw.aid }, { cache: true }) ?? expandedRaw;
98
98
  ownerResolver.setAgentConfiguredOwners(expandedRaw.aid, configuredOwnerList(raw));
99
- const merged = resolveEffective({ self: expandedRaw.aid }, {});
99
+ const precheck = precheckAgentConfig(expandedRaw.aid, raw);
100
+ if (precheck) {
101
+ this.registerErrorAgent(raw, `${precheck.code}: ${precheck.detail}`);
102
+ continue;
103
+ }
104
+ // Reuse the mtime-checked reads populated during enumeration; changes
105
+ // still reload through ConfigManager's normal atomic reader.
106
+ const merged = resolveEffective({ self: expandedRaw.aid }, { cache: true });
100
107
  const agent = new EvolAgent(raw, merged);
101
108
  ensureAgentDirSkeleton(expandedRaw.aid);
102
109
  ensureInitialRoleRegistry(expandedRaw.aid);
@@ -225,12 +232,16 @@ export class EvolAgentRegistry {
225
232
  list() {
226
233
  return [...this.agents.values()].map(a => this.toInfo(a));
227
234
  }
235
+ /** Current runtime instances, including disabled/error Agents, without display-file reads. */
236
+ allAgents() {
237
+ return [...this.agents.values()];
238
+ }
228
239
  invalidateAgentDisplayCache(aid) {
229
240
  invalidateAgentDisplayName(aid);
230
241
  this.personalNameCache.delete(aid);
231
242
  }
232
243
  runnableAgents() {
233
- return [...this.agents.values()].filter(a => a.status === 'stopped');
244
+ return this.allAgents().filter(a => a.status === 'stopped');
234
245
  }
235
246
  getSkipped() {
236
247
  return [...this.skipped];
@@ -270,6 +281,11 @@ export class EvolAgentRegistry {
270
281
  logger.warn(`[EvolAgentRegistry] loadNewAgent ${aid}: ${conflict}`);
271
282
  return this.registerErrorAgent(expandedRaw, `Channel conflict: ${conflict}`);
272
283
  }
284
+ const precheck = precheckAgentConfig(aid, expandedRaw);
285
+ if (precheck) {
286
+ logger.warn(`[EvolAgentRegistry] loadNewAgent ${aid}: ${precheck.detail}`);
287
+ return this.registerErrorAgent(expandedRaw, `${precheck.code}: ${precheck.detail}`);
288
+ }
273
289
  const raw = readConfig(ConfigTarget.Agent, { self: aid }, { cache: true }) ?? expandedRaw;
274
290
  ownerResolver.setAgentConfiguredOwners(aid, configuredOwnerList(raw));
275
291
  const merged = resolveEffective({ self: aid }, {});
@@ -294,6 +310,9 @@ export class EvolAgentRegistry {
294
310
  const errs = validateAgentConfig(expandedRaw);
295
311
  if (errs.length > 0)
296
312
  throw new Error(`Invalid config after edit: ${errs.join('; ')}`);
313
+ const precheck = precheckAgentConfig(oldAgent.aid, expandedRaw);
314
+ if (precheck)
315
+ throw new Error(`Precheck failed: ${precheck.detail}`);
297
316
  const raw = readConfig(ConfigTarget.Agent, { self: oldAgent.aid }, { cache: true }) ?? expandedRaw;
298
317
  ownerResolver.setAgentConfiguredOwners(oldAgent.aid, configuredOwnerList(raw));
299
318
  const merged = resolveEffective({ self: raw.aid }, {});
@@ -510,6 +529,16 @@ export class EvolAgentRegistry {
510
529
  throw err;
511
530
  }
512
531
  }
532
+ /** Remove an already-unloaded Agent and every registry index it owned. */
533
+ remove(aid) {
534
+ const removed = this.agents.delete(aid);
535
+ this.manuallyStopped.delete(aid);
536
+ this.personalNameCache.delete(aid);
537
+ invalidateAgentDisplayName(aid);
538
+ this.channelIndex.clear();
539
+ this.buildChannelIndex();
540
+ return removed;
541
+ }
513
542
  async stopAgent(aidOrName, hooks) {
514
543
  const agent = this.agents.get(aidOrName);
515
544
  if (!agent)
@@ -662,3 +691,22 @@ function safeInfoValue(fn, fallback) {
662
691
  function findInstanceByKey(raw, agent, channelKey) {
663
692
  return raw.channels.find(c => agent.effectiveChannelName(c.type, c.name) === channelKey) ?? null;
664
693
  }
694
+ /** active Agent 只有本地私钥和证书齐全,才参与启动编排。 */
695
+ function precheckAgentConfig(aid, config) {
696
+ if (resolveAgentLifecycle(config) !== 'active')
697
+ return null;
698
+ const directory = aidLocalDir(aid);
699
+ const missing = [];
700
+ for (const file of [path.join(directory, 'private', 'key.json'), path.join(directory, 'public', 'cert.pem')]) {
701
+ try {
702
+ if (fs.statSync(file).isFile())
703
+ continue;
704
+ }
705
+ catch { }
706
+ missing.push(file);
707
+ }
708
+ return missing.length ? {
709
+ code: 'AUN_IDENTITY_MISSING',
710
+ detail: `AUN identity incomplete for ${aid}; missing ${missing.join(', ')}`,
711
+ } : null;
712
+ }
@@ -1,3 +1,4 @@
1
+ import { resolveProjectDefaultPath } from '../utils/project-path.js';
1
2
  import { formatChannelKey, tryParseChannelKey } from './channel-loader.js';
2
3
  import { fileCache } from './daemon-file-cache.js';
3
4
  import { readSoulContent } from './soul.js';
@@ -78,7 +79,7 @@ export class EvolAgent {
78
79
  }
79
80
  }
80
81
  get projectPath() {
81
- return this.merged.projects?.defaultPath || process.cwd();
82
+ return resolveProjectDefaultPath(this.merged.projects?.defaultPath) || process.cwd();
82
83
  }
83
84
  // ── Channels ──────────────────────────────────────────────────────────
84
85
  /**
@@ -5,23 +5,9 @@
5
5
  // 所以这里校验的是**将要被使用的那份内容**(缓存里的或刚读到的),
6
6
  // 让读到的内容就是校验过的内容(TOCTOU)。
7
7
  import fs from 'fs';
8
- import path from 'path';
9
- import { kitsDir } from '../../paths.js';
10
8
  import { logger } from '../../utils/logger.js';
11
9
  import { verifyFile } from './store.js';
12
- /**
13
- * 判断一个路径是否属于随包发布的内容(`kits/`)。
14
- *
15
- * 只有随包发布的东西才该建立基线:它们在开发仓里由 agent 随手改、打包后应当冻结。
16
- * `$EVOLCORE_HOME` 下的运行时数据不能套用这套语义——那些文件本来就是给用户和
17
- * CLI 改的,一旦校验就会把合法修改回滚掉。
18
- */
19
- export function isShippedPath(filePath) {
20
- const kits = path.resolve(kitsDir());
21
- const target = path.resolve(filePath);
22
- const rel = path.relative(kits, target);
23
- return rel !== '' && !path.isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${path.sep}`);
24
- }
10
+ export { isShippedPath } from './store.js';
25
11
  /**
26
12
  * 返回可用于本次注入的文档内容。
27
13
  *
@@ -43,7 +29,14 @@ export function readVerifiedText(filePath, opts) {
43
29
  }
44
30
  }
45
31
  const restoreOnFail = opts.restoreOnFail ?? true;
46
- const result = verifyFile(filePath, { restoreOnFail });
32
+ let result;
33
+ try {
34
+ result = verifyFile(filePath, { restoreOnFail });
35
+ }
36
+ catch (err) {
37
+ logger.error(`[${tag}] verification-failed path=${filePath} ${err instanceof Error ? err.message : String(err)}`);
38
+ return null;
39
+ }
47
40
  if (result.status === 'missing') {
48
41
  logger.warn(`[${tag}] missing path=${filePath}`);
49
42
  return null;