evolcore 0.0.43-test.8 → 0.0.46

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 (204) hide show
  1. package/CHANGELOG.md +75 -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 +13 -5
  12. package/dist/agents/codex/app-server-client.js +2 -4
  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/menu/client.js +142 -182
  18. package/dist/aun/rpc/client.js +33 -17
  19. package/dist/aun/service-proxy.js +6 -23
  20. package/dist/channels/aun.js +656 -112
  21. package/dist/cli/agent-create.js +37 -10
  22. package/dist/cli/agent-template.js +105 -84
  23. package/dist/cli/agent.js +31 -18
  24. package/dist/cli/daemon-commands.js +15 -17
  25. package/dist/cli/daemon-lifecycle-client.js +40 -18
  26. package/dist/cli/directory.js +12 -4
  27. package/dist/cli/ecmsg-gateway.js +5 -2
  28. package/dist/cli/events-command.js +2 -1
  29. package/dist/cli/init.js +50 -20
  30. package/dist/cli/integrity-command.js +2 -0
  31. package/dist/cli/managed-command-guard.js +20 -1
  32. package/dist/cli/menu-client.js +7 -5
  33. package/dist/cli/restart-monitor.js +33 -20
  34. package/dist/cli/services-command.js +28 -5
  35. package/dist/config/config-field-policy.js +24 -0
  36. package/dist/config/config-manager.js +20 -2
  37. package/dist/config/peer-book-store.js +152 -120
  38. package/dist/config/peer-role-resolver.js +24 -4
  39. package/dist/config/provider-identity-migration.js +1 -1
  40. package/dist/config/provider-identity.js +10 -4
  41. package/dist/config/provider-ipc-service.js +10 -2
  42. package/dist/config/provider-local-sync.js +2 -2
  43. package/dist/config/providers-config.js +95 -10
  44. package/dist/config/providers-import.js +4 -6
  45. package/dist/config/providers.js +14 -3
  46. package/dist/config/role-store.js +1 -1
  47. package/dist/config-store.js +9 -1
  48. package/dist/core/agent-application-service.js +56 -29
  49. package/dist/core/agent-create-status.js +3 -1
  50. package/dist/core/agent-creation-claim.js +1 -0
  51. package/dist/core/agent-ipc-registration.js +2 -2
  52. package/dist/core/agent-reload-coordinator.js +38 -1
  53. package/dist/core/agent-runtime.js +85 -38
  54. package/dist/core/auth/agent-delegation.js +5 -0
  55. package/dist/core/auth/operation-authorizer.js +1 -1
  56. package/dist/core/auth/operation-catalog.js +3 -3
  57. package/dist/core/bootstrap-service.js +3 -0
  58. package/dist/core/capability/capability-manager.js +3 -1
  59. package/dist/core/channel-loader.js +29 -3
  60. package/dist/core/channel-runtime.js +1 -1
  61. package/dist/core/command/agent-control.js +6 -5
  62. package/dist/core/command/agent-template-menu.js +32 -97
  63. package/dist/core/command/eventcenter-menu.js +61 -13
  64. package/dist/core/command/menu-catalog.js +11 -4
  65. package/dist/core/command/menu-handler.js +35 -8
  66. package/dist/core/command/menu-protocol.js +8 -16
  67. package/dist/core/command/skill-slash.js +6 -2
  68. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  69. package/dist/core/command/team-workspace-management-store.js +83 -0
  70. package/dist/core/command/team-workspace-management.js +1 -2
  71. package/dist/core/command/team-workspace-team.js +26 -3
  72. package/dist/core/daemon-control.js +3 -4
  73. package/dist/core/daemon-lifecycle.js +146 -110
  74. package/dist/core/evolagent-registry.js +42 -0
  75. package/dist/core/evolagent.js +2 -1
  76. package/dist/core/file-integrity/read.js +9 -16
  77. package/dist/core/file-integrity/store.js +94 -34
  78. package/dist/core/handoff/dispatcher.js +33 -7
  79. package/dist/core/handoff/runtime.js +8 -0
  80. package/dist/core/inference/text-inference.js +12 -2
  81. package/dist/core/invoke/invoke-service.js +24 -3
  82. package/dist/core/ipc-registration.js +3 -0
  83. package/dist/core/message/aun-ipc-sender.js +109 -7
  84. package/dist/core/message/contact-admission.js +6 -2
  85. package/dist/core/message/message-bridge.js +13 -0
  86. package/dist/core/message/message-queue.js +131 -30
  87. package/dist/core/message/pending-hints.js +8 -0
  88. package/dist/core/message/response-engine.js +48 -2
  89. package/dist/core/message/send-routing.js +3 -12
  90. package/dist/core/model/catalog-service.js +13 -0
  91. package/dist/core/model/model-catalog.js +57 -18
  92. package/dist/core/pack-auth.js +163 -31
  93. package/dist/core/pack-install.js +42 -1
  94. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  95. package/dist/core/permission/ec-command-parser.js +3 -1
  96. package/dist/core/permission/shell-environment.js +23 -0
  97. package/dist/core/rate-window.js +6 -1
  98. package/dist/core/session/session-idle-monitor.js +0 -1
  99. package/dist/core/session/session-manager.js +14 -0
  100. package/dist/core/session/session-title.js +26 -6
  101. package/dist/core/skill/index-generator.js +3 -4
  102. package/dist/core/thread/thread-service.js +0 -1
  103. package/dist/core/thread/topic-id.js +8 -0
  104. package/dist/directory/owner-directory-admission.js +17 -0
  105. package/dist/directory/owner-directory-cache.js +3 -1
  106. package/dist/directory/owner-directory-markdown.js +145 -23
  107. package/dist/directory/owner-directory-policy.js +23 -0
  108. package/dist/directory/owner-directory-query-operation.js +20 -6
  109. package/dist/directory/owner-directory-search.js +47 -0
  110. package/dist/eck/message-renderer.js +171 -32
  111. package/dist/ecweb/basic-settings-service.js +7 -3
  112. package/dist/ecweb/providers-service.js +17 -10
  113. package/dist/ecweb/runtime/lifecycle.js +1 -1
  114. package/dist/ecweb/runtime/supervisor.js +77 -35
  115. package/dist/event-center/admission-materializer.js +1 -1
  116. package/dist/event-center/bus-gate.js +48 -4
  117. package/dist/event-center/bus-host.js +3 -3
  118. package/dist/event-center/center-config.js +57 -28
  119. package/dist/event-center/dispatcher.js +8 -0
  120. package/dist/event-center/event-log.js +69 -27
  121. package/dist/event-center/index-generator.js +6 -1
  122. package/dist/event-center/ipc-operation.js +66 -25
  123. package/dist/event-center/pack-loader.js +12 -55
  124. package/dist/event-center/pack-manager.js +5 -3
  125. package/dist/event-center/registry.js +48 -52
  126. package/dist/event-center/runtime.js +219 -81
  127. package/dist/event-center/script-runner.js +18 -7
  128. package/dist/event-center/types.js +9 -1
  129. package/dist/event-center/validation.js +33 -4
  130. package/dist/index.js +96 -42
  131. package/dist/ipc.js +33 -7
  132. package/dist/product.js +1 -0
  133. package/dist/proxy/manager.js +52 -11
  134. package/dist/proxy/service-supervisor.js +265 -67
  135. package/dist/services/dispatcher.js +26 -3
  136. package/dist/services/idempotency.js +128 -0
  137. package/dist/services/identity.js +3 -27
  138. package/dist/services/index-generator.js +5 -1
  139. package/dist/services/index.js +244 -45
  140. package/dist/services/ipc-operation.js +164 -20
  141. package/dist/services/pack-manager.js +37 -9
  142. package/dist/services/router.js +100 -31
  143. package/dist/services/script-runner.js +15 -4
  144. package/dist/services/service-payload.js +50 -2
  145. package/dist/services/validation.js +107 -3
  146. package/dist/trigger/scheduler.js +14 -4
  147. package/dist/trigger/script-sandbox.js +39 -2
  148. package/dist/utils/cross-platform.js +35 -11
  149. package/dist/utils/error-utils.js +13 -1
  150. package/dist/utils/instance-registry.js +33 -35
  151. package/dist/utils/process-introspect.js +35 -20
  152. package/dist/utils/project-path.js +47 -3
  153. package/dist/utils/windows-shell-trust.js +174 -68
  154. package/kits/docs/context-assembly.md +3 -3
  155. package/kits/docs/evolcore/agent.md +28 -10
  156. package/kits/docs/evolcore/config.md +22 -0
  157. package/kits/docs/evolcore/directory.md +46 -12
  158. package/kits/docs/evolcore/event-center.md +6 -6
  159. package/kits/docs/evolcore/group-collaboration.md +1 -1
  160. package/kits/docs/evolcore/menu-client.md +7 -5
  161. package/kits/docs/evolcore/menu-protocol.md +5 -3
  162. package/kits/docs/evolcore/msg.md +10 -3
  163. package/kits/docs/evolcore/provider.md +7 -3
  164. package/kits/docs/evolcore/services.md +145 -12
  165. package/kits/docs/evolcore/thread-chain.md +17 -9
  166. package/kits/docs/prompt-loading-architecture.md +4 -4
  167. package/kits/eck_message_manifest.json +46 -3
  168. package/kits/rules/04-relation.md +10 -2
  169. package/kits/rules/06-channel.md +2 -1
  170. package/kits/schemas/providers.schema.2.json +1 -0
  171. package/kits/skills/ec-group/SKILL.md +4 -0
  172. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  173. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  174. package/kits/skills/thread-ops/SKILL.md +8 -5
  175. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  176. package/kits/templates/message-fragments/group-batch.md +1 -0
  177. package/kits/templates/message-fragments/item-group.md +4 -0
  178. package/kits/templates/message-fragments/item-private.md +4 -0
  179. package/kits/templates/message-fragments/thread-context.md +1 -1
  180. package/kits/templates/system-fragments/commands.md +5 -5
  181. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  182. package/kits/templates/system-fragments/relation.md +11 -7
  183. package/package.json +3 -2
  184. package/scripts/agent-template/index.mjs +9 -4
  185. package/scripts/agent-template/inspect.mjs +16 -9
  186. package/scripts/agent-template/shared/plan.mjs +3 -33
  187. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  188. package/scripts/agent-template/shared/template-package.mjs +119 -10
  189. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  190. package/scripts/agent-template/shared/template.mjs +5 -5
  191. package/scripts/agent-template/team-pack.mjs +245 -0
  192. package/scripts/agent-template/team-preview.mjs +111 -0
  193. package/scripts/aid-batch/identity-batch.mjs +143 -0
  194. package/dist/ability/versions.js +0 -32
  195. package/dist/aun/model-headers.js +0 -17
  196. package/dist/channels/builtin-plugins.js +0 -19
  197. package/dist/core/command/team-workspace-initializer.js +0 -2
  198. package/dist/core/command/team-workspace-job-store.js +0 -88
  199. package/dist/core/command/team-workspace-management-service.js +0 -2
  200. package/dist/core/contact-bind-registry.js +0 -27
  201. package/dist/event-center/ledger.js +0 -52
  202. package/dist/services/reply.js +0 -55
  203. package/kits/templates/message-fragments/item.md +0 -3
  204. 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();
@@ -111,16 +114,13 @@ export async function discoverStartupWork(options) {
111
114
  const queueStarted = Date.now();
112
115
  let queueItems = 0;
113
116
  let queueFiles = 0;
117
+ let queueSnapshot;
114
118
  try {
115
119
  const queue = await json(options.queuePath);
116
120
  if (queue !== undefined) {
117
121
  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');
122
+ queueSnapshot = parseQueueSnapshot(queue);
123
+ for (const bucket of [...queueSnapshot.queues, ...(queueSnapshot.active ?? [])]) {
124
124
  for (const item of bucket.items) {
125
125
  queueItems++;
126
126
  noteMessage(item.message, bucket.queueKey);
@@ -131,12 +131,13 @@ export async function discoverStartupWork(options) {
131
131
  }
132
132
  }
133
133
  catch (error) {
134
+ plan.recoveryIndexAids.clear();
134
135
  for (const aid of known)
135
136
  uncertain(aid, error);
136
137
  }
137
138
  finally {
138
139
  options.onScan?.({ phase: 'queue', durationMs: Date.now() - queueStarted, files: queueFiles, items: queueItems });
139
- options.onQueueCaptured?.();
140
+ options.onQueueCaptured?.(queueSnapshot);
140
141
  }
141
142
  const now = Date.now();
142
143
  const triggerDir = options.triggerDir ?? agentTriggersDir;
@@ -192,105 +193,125 @@ export async function discoverStartupWork(options) {
192
193
  await Promise.all([daemonTriggerScan, ...Array.from({ length: Math.min(4, aids.length) }, async () => {
193
194
  while (next < aids.length) {
194
195
  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;
196
+ const scanSessions = async () => {
197
+ // A complete queue snapshot covers executions, including consumed hints.
198
+ // Do not enumerate historical chat/topic directories on the normal path.
199
+ if (hasIndexedRecovery(queueSnapshot, aid))
200
+ return;
201
+ const started = Date.now();
202
+ let files = 0;
203
+ let chats = 0;
204
+ let directoryMs = 0;
205
+ let threadDirectoryMs = 0;
206
+ let metadataMs = 0;
207
+ let readMaxMs = 0;
208
+ const io = { openMs: 0, statMs: 0, readMs: 0, parseMs: 0, closeMs: 0, bytes: 0 };
207
209
  try {
208
- chatDirs = await scanAgentChatDirsAsync(options.sessionsRoot, aid, undefined, { includeEntries: true });
210
+ const hintVersion = pendingHintDirectoryVersion();
211
+ let phaseStarted = performance.now();
212
+ let chatDirs;
213
+ try {
214
+ chatDirs = await scanAgentChatDirsAsync(options.sessionsRoot, aid, undefined, { includeEntries: true });
215
+ }
216
+ finally {
217
+ directoryMs = Math.round(performance.now() - phaseStarted);
218
+ }
219
+ chats = chatDirs.length;
220
+ // Keep paths only; retries read current hint events. A new hint chat
221
+ // invalidates this inventory even when created while discovery runs.
222
+ if (hintVersion === pendingHintDirectoryVersion())
223
+ plan.hintDirectories.set(aid, {
224
+ sessionsDir: options.sessionsRoot, selfAID: aid, version: hintVersion,
225
+ chats: chatDirs.map(({ entries: _entries, ...chat }) => chat),
226
+ });
227
+ const metadata = [];
228
+ const collect = (dir, names, strict) => {
229
+ for (const name of names)
230
+ if (/^meta_.*\.jsonl$/.test(name)) {
231
+ metadata.push({ file: path.join(dir, name), strict });
232
+ files++;
233
+ }
234
+ };
235
+ for (const chat of chatDirs)
236
+ collect(chat.dirPath, chat.entries.map(entry => entry.name), false);
237
+ phaseStarted = performance.now();
238
+ try {
239
+ await scanStartupItems(chatDirs.filter(chat => chat.entries.some(entry => entry.name === '_threads')), 8, async (chat) => {
240
+ const dir = path.join(chat.dirPath, '_threads');
241
+ try {
242
+ collect(dir, await fs.promises.readdir(dir), true);
243
+ }
244
+ catch (error) {
245
+ if (error.code !== 'ENOENT')
246
+ throw error;
247
+ }
248
+ });
249
+ }
250
+ finally {
251
+ threadDirectoryMs = Math.round(performance.now() - phaseStarted);
252
+ }
253
+ // The eight-reader budget spans all chats of this Agent. A slow file
254
+ // must not serialize the next chat or a complete batch of eight files.
255
+ phaseStarted = performance.now();
256
+ try {
257
+ await scanStartupItems(metadata, 8, async ({ file, strict }) => {
258
+ const readStarted = performance.now();
259
+ let session;
260
+ try {
261
+ const record = await readLastJsonlLineAsync(file, strict, io);
262
+ if (!record) {
263
+ plan.recoveryIndexAids.delete(aid);
264
+ uncertain(aid, `no readable session record: ${file}`);
265
+ return;
266
+ }
267
+ session = fileToSession(record);
268
+ }
269
+ catch (error) {
270
+ // Match the compatibility recovery's per-file isolation;
271
+ // one corrupt record must not force a global blocking scan.
272
+ plan.recoveryIndexAids.delete(aid);
273
+ uncertain(aid, error);
274
+ logger.error(`[startup] Skipping unreadable session metadata during recovery: ${file}: ${error instanceof Error ? error.message : String(error)}`);
275
+ return;
276
+ }
277
+ finally {
278
+ readMaxMs = Math.max(readMaxMs, Math.round(performance.now() - readStarted));
279
+ }
280
+ if (!session.processingState)
281
+ return;
282
+ const startedAt = Number.parseInt(session.processingState.split(':', 1)[0], 10);
283
+ if (Number.isFinite(startedAt) && now - startedAt < 3_600_000) {
284
+ plan.pendingSessions.push(session);
285
+ prioritize(aid, 'sessions');
286
+ plan.requiredChannelKeys.add(session.channel);
287
+ }
288
+ else
289
+ plan.staleSessions.push(session);
290
+ });
291
+ }
292
+ finally {
293
+ metadataMs = Math.round(performance.now() - phaseStarted);
294
+ }
209
295
  }
210
- finally {
211
- directoryMs = Math.round(performance.now() - phaseStarted);
296
+ catch (error) {
297
+ plan.recoveryIndexAids.delete(aid);
298
+ plan.hintDirectories.delete(aid);
299
+ plan.sessionScanFailed = true;
300
+ uncertain(aid, error);
212
301
  }
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();
232
- 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
- });
243
- }
244
- finally {
245
- threadDirectoryMs = Math.round(performance.now() - phaseStarted);
246
- }
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;
302
+ for (const key of Object.keys(io))
303
+ io[key] = Math.round(io[key]);
304
+ options.onScan?.({ phase: 'sessions', aid, durationMs: Date.now() - started, files, directories: chats,
305
+ directoryMs, threadDirectoryMs, metadataMs, readMaxMs, io });
306
+ };
307
+ // Independent evidence sources share the existing four-owner budget.
308
+ // Positive work can admit a busy owner early; idle classification
309
+ // still waits for both scans and the primary's daemon-owned Triggers.
310
+ await Promise.all([
311
+ scanSessions(),
312
+ aid === options.daemonTriggerAid ? daemonTriggerScan : scanTriggers(aid),
313
+ aid === options.primaryAid ? daemonTriggerScan : undefined,
314
+ ]);
294
315
  options.onAgentDiscovered?.(aid, plan);
295
316
  }
296
317
  })]);
@@ -303,6 +324,17 @@ export async function discoverStartupWork(options) {
303
324
  }
304
325
  return plan;
305
326
  }
327
+ /** One concurrent channel connection per CPU available to this process. */
328
+ export function startupConnectionBudget() {
329
+ let cpuParallelism = 1;
330
+ try {
331
+ const available = os.availableParallelism();
332
+ if (Number.isInteger(available) && available > 0)
333
+ cpuParallelism = available;
334
+ }
335
+ catch { /* Retain the one-CPU budget when detection is unavailable. */ }
336
+ return { cpuParallelism, concurrency: cpuParallelism };
337
+ }
306
338
  /** Bounded admission for startup side effects. Dependency waits belong outside this queue. */
307
339
  export class StartupTaskQueue {
308
340
  concurrency;
@@ -344,7 +376,7 @@ export class StartupTaskQueue {
344
376
  // Choose at admission time, so newly classified priority work can pass
345
377
  // queued idle channels. Never hold a free slot for unclassified work;
346
378
  // already-running connections finish within the existing concurrency cap.
347
- let index = this.pending.findIndex(task => task.priority === 'foreground');
379
+ let index = this.pending.findIndex(task => (typeof task.priority === 'function' ? task.priority() : task.priority) === 'foreground');
348
380
  if (index < 0)
349
381
  index = 0;
350
382
  const task = this.pending.splice(index, 1)[0];
@@ -411,6 +443,7 @@ export async function recoverStartupObserverHints(options) {
411
443
  await Promise.all(options.startupObserverRecoveries);
412
444
  await Promise.all(options.recoveryAids.map(async (aid) => {
413
445
  await options.beforeAgentRecovery?.(aid);
446
+ let attempts = 0;
414
447
  while (!options.isCancelled()) {
415
448
  const started = Date.now();
416
449
  try {
@@ -428,8 +461,9 @@ export async function recoverStartupObserverHints(options) {
428
461
  return;
429
462
  }
430
463
  catch (error) {
464
+ attempts++;
431
465
  options.trace?.addSpan('daemon.observerHints', started, Date.now(), `${aid}; retry pending`);
432
- logger.warn(`[startup] observer hint registration waits for ${aid}: ${error}`);
466
+ logger.warn(`[startup] observer hint registration waits for ${aid} (attempt ${attempts}): ${error}`);
433
467
  await recoveryRetryDelay();
434
468
  }
435
469
  }
@@ -547,7 +581,7 @@ export class StartupHandoffRecovery {
547
581
  finish?.(isCancelled() ? 'cancelled' : 'ok');
548
582
  }
549
583
  }
550
- export function resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap, pendingSessions = sessionManager.getPendingProcessingSessions(), }) {
584
+ export async function resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap, pendingSessions = sessionManager.getPendingProcessingSessions(), }) {
551
585
  if (pendingSessions.length === 0)
552
586
  return;
553
587
  logger.info(`[Resume] Found ${pendingSessions.length} pending session(s) from before restart`);
@@ -604,14 +638,16 @@ export function resumePendingSessions({ sessionManager, messageQueue, droppedTri
604
638
  peerId: '',
605
639
  threadId: sessionTopicThreadId(session),
606
640
  replyContext: replyContextFromSession(session),
641
+ boundSessionId: session.id,
642
+ baseagent: session.baseagent,
643
+ source: 'recovery',
607
644
  };
608
- sessionManager.clearProcessing(session.id);
609
- messageQueue.enqueue(session.id, resumeMessage, session.projectPath, {
645
+ // Persist before clearing the legacy marker: a crash must retain one recovery source.
646
+ await messageQueue.enqueuePersisted(session.id, resumeMessage, session.projectPath, {
610
647
  sessionKeyField: session.sessionKey,
611
648
  selfAID: resumeSelfAID,
612
- }).catch(error => {
613
- logger.error(`[Resume] Failed to resume session ${session.id}:`, error);
614
649
  });
650
+ sessionManager.clearProcessing(session.id);
615
651
  }
616
652
  }
617
653
  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, }) {
@@ -96,6 +96,11 @@ 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 precheck = precheckAgentConfig(expandedRaw.aid, raw);
100
+ if (precheck) {
101
+ this.registerErrorAgent(raw, `${precheck.code}: ${precheck.detail}`);
102
+ continue;
103
+ }
99
104
  const merged = resolveEffective({ self: expandedRaw.aid }, {});
100
105
  const agent = new EvolAgent(raw, merged);
101
106
  ensureAgentDirSkeleton(expandedRaw.aid);
@@ -270,6 +275,11 @@ export class EvolAgentRegistry {
270
275
  logger.warn(`[EvolAgentRegistry] loadNewAgent ${aid}: ${conflict}`);
271
276
  return this.registerErrorAgent(expandedRaw, `Channel conflict: ${conflict}`);
272
277
  }
278
+ const precheck = precheckAgentConfig(aid, expandedRaw);
279
+ if (precheck) {
280
+ logger.warn(`[EvolAgentRegistry] loadNewAgent ${aid}: ${precheck.detail}`);
281
+ return this.registerErrorAgent(expandedRaw, `${precheck.code}: ${precheck.detail}`);
282
+ }
273
283
  const raw = readConfig(ConfigTarget.Agent, { self: aid }, { cache: true }) ?? expandedRaw;
274
284
  ownerResolver.setAgentConfiguredOwners(aid, configuredOwnerList(raw));
275
285
  const merged = resolveEffective({ self: aid }, {});
@@ -294,6 +304,9 @@ export class EvolAgentRegistry {
294
304
  const errs = validateAgentConfig(expandedRaw);
295
305
  if (errs.length > 0)
296
306
  throw new Error(`Invalid config after edit: ${errs.join('; ')}`);
307
+ const precheck = precheckAgentConfig(oldAgent.aid, expandedRaw);
308
+ if (precheck)
309
+ throw new Error(`Precheck failed: ${precheck.detail}`);
297
310
  const raw = readConfig(ConfigTarget.Agent, { self: oldAgent.aid }, { cache: true }) ?? expandedRaw;
298
311
  ownerResolver.setAgentConfiguredOwners(oldAgent.aid, configuredOwnerList(raw));
299
312
  const merged = resolveEffective({ self: raw.aid }, {});
@@ -510,6 +523,16 @@ export class EvolAgentRegistry {
510
523
  throw err;
511
524
  }
512
525
  }
526
+ /** Remove an already-unloaded Agent and every registry index it owned. */
527
+ remove(aid) {
528
+ const removed = this.agents.delete(aid);
529
+ this.manuallyStopped.delete(aid);
530
+ this.personalNameCache.delete(aid);
531
+ invalidateAgentDisplayName(aid);
532
+ this.channelIndex.clear();
533
+ this.buildChannelIndex();
534
+ return removed;
535
+ }
513
536
  async stopAgent(aidOrName, hooks) {
514
537
  const agent = this.agents.get(aidOrName);
515
538
  if (!agent)
@@ -662,3 +685,22 @@ function safeInfoValue(fn, fallback) {
662
685
  function findInstanceByKey(raw, agent, channelKey) {
663
686
  return raw.channels.find(c => agent.effectiveChannelName(c.type, c.name) === channelKey) ?? null;
664
687
  }
688
+ /** active Agent 只有本地私钥和证书齐全,才参与启动编排。 */
689
+ function precheckAgentConfig(aid, config) {
690
+ if (resolveAgentLifecycle(config) !== 'active')
691
+ return null;
692
+ const directory = aidLocalDir(aid);
693
+ const missing = [];
694
+ for (const file of [path.join(directory, 'private', 'key.json'), path.join(directory, 'public', 'cert.pem')]) {
695
+ try {
696
+ if (fs.statSync(file).isFile())
697
+ continue;
698
+ }
699
+ catch { }
700
+ missing.push(file);
701
+ }
702
+ return missing.length ? {
703
+ code: 'AUN_IDENTITY_MISSING',
704
+ detail: `AUN identity incomplete for ${aid}; missing ${missing.join(', ')}`,
705
+ } : null;
706
+ }
@@ -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;