evolcore 0.0.46 → 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 (54) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/agents/claude-runner.js +9 -1
  3. package/dist/agents/codex/app-server-client.js +32 -23
  4. package/dist/aun/group/fs-download.js +1 -1
  5. package/dist/channels/aun.js +19 -8
  6. package/dist/channels/daemon.js +1 -1
  7. package/dist/cli/daemon-commands.js +27 -39
  8. package/dist/cli/daemon-lifecycle-client.js +17 -3
  9. package/dist/cli/init-channel.js +2 -2
  10. package/dist/cli/init.js +7 -1
  11. package/dist/cli/restart-monitor.js +104 -28
  12. package/dist/cli/task-context.js +83 -15
  13. package/dist/cli/upgrade-command.js +4 -2
  14. package/dist/config/config-manager.js +29 -17
  15. package/dist/config/peer-book-store.js +18 -10
  16. package/dist/config/provider-identity-migration.js +157 -5
  17. package/dist/config/schema-migration.js +123 -16
  18. package/dist/config/schema-registry.js +6 -2
  19. package/dist/core/agent-runtime.js +6 -5
  20. package/dist/core/auth/agent-delegation.js +8 -3
  21. package/dist/core/auth/delegation-diagnostics.js +56 -15
  22. package/dist/core/auth/operation-authorizer.js +1 -1
  23. package/dist/core/command/menu-handler.js +4 -4
  24. package/dist/core/command/slash-handler.js +4 -6
  25. package/dist/core/daemon-bootstrap.js +11 -9
  26. package/dist/core/daemon-control.js +1 -3
  27. package/dist/core/daemon-lifecycle.js +50 -40
  28. package/dist/core/evolagent-registry.js +8 -2
  29. package/dist/core/host-snapshot.js +9 -4
  30. package/dist/core/initialization/service.js +22 -4
  31. package/dist/core/ipc-registration.js +4 -3
  32. package/dist/core/memory/consolidation.js +6 -6
  33. package/dist/core/ownership/owner-resolver.js +27 -10
  34. package/dist/core/relation/peer-identity.js +5 -1
  35. package/dist/core/relation/same-owner-proof.js +2 -1
  36. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  37. package/dist/core/session/session-file-health.js +36 -7
  38. package/dist/core/task/task-image-resources.js +1 -1
  39. package/dist/ecweb/runtime/lifecycle.js +64 -15
  40. package/dist/ecweb/runtime/supervisor.js +2 -15
  41. package/dist/index.js +37 -34
  42. package/dist/ipc.js +2 -1
  43. package/dist/trigger/scheduler.js +4 -0
  44. package/dist/trigger/state.js +7 -0
  45. package/dist/utils/aid-bind.js +155 -18
  46. package/dist/utils/atomic-write.js +3 -3
  47. package/dist/utils/cross-platform.js +24 -5
  48. package/dist/utils/error-utils.js +13 -0
  49. package/dist/utils/instance-registry.js +61 -0
  50. package/dist/utils/process-introspect.js +152 -7
  51. package/dist/utils/upgrade-jobs.js +4 -4
  52. package/kits/docs/evolcore/aid.md +3 -1
  53. package/kits/docs/evolcore/provider.md +10 -2
  54. package/package.json +2 -2
@@ -2,8 +2,144 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
4
  import { providerIdentity } from './provider-identity.js';
5
- import { initializationRuntimePlan, providerEnvironmentVariable } from './providers-config.js';
5
+ import { initializationRuntimePlan, providerEnvironmentVariable, providerServiceTypeForBaseagent, providerServiceTypeForPurpose, resolveProviderId, } from './providers-config.js';
6
6
  import { validateProvidersFile } from './providers-config.js';
7
+ import { loadSchema } from './schema-registry.js';
8
+ /** Validate the complete in-memory result before snapshots, journals or configuration writes. */
9
+ export function validateProviderIdentityMigrationPlan(plan) {
10
+ const invalid = (detail) => {
11
+ throw Object.assign(new Error(`Provider migration validation failed: ${detail}; no configuration was changed`), {
12
+ code: 'PROVIDER_MIGRATION_INVALID',
13
+ });
14
+ };
15
+ const registry = validateProvidersFile(plan.registry);
16
+ const endpoint = (provider, serviceType) => {
17
+ const base = provider.common.baseUrl;
18
+ const servicePath = provider.services?.[serviceType]?.path || '.';
19
+ if (providerEnvironmentVariable(base))
20
+ return JSON.stringify([base, servicePath]);
21
+ const url = new URL(servicePath, base.endsWith('/') ? base : `${base}/`);
22
+ if (url.origin !== new URL(base).origin)
23
+ invalid(`service ${serviceType} leaves its Provider origin`);
24
+ return url.href.replace(/\/+$/u, '');
25
+ };
26
+ for (const [id, source] of Object.entries(plan.sourceRegistry.providers)) {
27
+ const targetId = resolveProviderId(plan.providerMapping[id] ?? id, registry);
28
+ const target = registry.providers[targetId];
29
+ if (!target)
30
+ invalid(`Provider ${id} has no migration target`);
31
+ for (const field of ['apiKey', 'headers', 'queryParams']) {
32
+ if (!isDeepStrictEqual(source.common[field], target.common[field]))
33
+ invalid(`Provider ${id} common.${field} changed`);
34
+ }
35
+ for (const [serviceType, service] of Object.entries(source.services ?? {})) {
36
+ const migrated = target.services?.[serviceType];
37
+ if (!migrated || endpoint(source, serviceType) !== endpoint(target, serviceType)
38
+ || !isDeepStrictEqual({ ...service, path: undefined }, { ...migrated, path: undefined })) {
39
+ invalid(`Provider ${id} service ${serviceType} changed its endpoint or settings`);
40
+ }
41
+ }
42
+ }
43
+ const after = new Map(plan.changes.map(change => [change.file, change.after]));
44
+ const parse = (text, file) => {
45
+ try {
46
+ const value = JSON.parse(text.replace(/^\uFEFF/u, ''));
47
+ if (value && typeof value === 'object' && !Array.isArray(value))
48
+ return value;
49
+ }
50
+ catch { /* Report the location without exposing JSON fragments containing credentials. */ }
51
+ return invalid(`invalid configuration object in ${file}`);
52
+ };
53
+ const checkReferences = (value, location, serviceType, baseagent, previous) => {
54
+ if (!value || typeof value !== 'object')
55
+ return;
56
+ const selection = value;
57
+ if (typeof selection.provider === 'string') {
58
+ const id = resolveProviderId(selection.provider, registry);
59
+ const provider = registry.providers[id];
60
+ if (!provider)
61
+ invalid(`missing Provider at ${location}.provider`);
62
+ const service = baseagent ? providerServiceTypeForBaseagent(baseagent, provider) : serviceType;
63
+ if (service && !Object.hasOwn(provider.services ?? {}, service))
64
+ invalid(`missing service at ${location}.provider`);
65
+ const oldId = previous && typeof previous === 'object'
66
+ ? previous.provider : undefined;
67
+ if (typeof oldId === 'string') {
68
+ const sourceId = resolveProviderId(oldId, plan.sourceRegistry);
69
+ const source = plan.sourceRegistry.providers[sourceId];
70
+ if (source && resolveProviderId(plan.providerMapping[sourceId] ?? sourceId, registry) === id) {
71
+ const sourceService = baseagent ? providerServiceTypeForBaseagent(baseagent, source) : serviceType;
72
+ if (sourceService && service && source.services?.[sourceService]
73
+ && (endpoint(source, sourceService) !== endpoint(provider, service)
74
+ || !isDeepStrictEqual({ ...source.services[sourceService], path: undefined }, { ...provider.services?.[service], path: undefined }))) {
75
+ invalid(`service selection changed at ${location}.provider`);
76
+ }
77
+ }
78
+ }
79
+ }
80
+ for (const [key, child] of Object.entries(value)) {
81
+ const oldChild = previous && typeof previous === 'object' ? previous[key] : undefined;
82
+ checkReferences(child, `${location}.${key}`, serviceType, baseagent, oldChild);
83
+ }
84
+ };
85
+ const files = new Map(plan.expected.map(item => [item.file, item.before]));
86
+ for (const change of plan.changes)
87
+ files.set(change.file, change.before);
88
+ for (const [file, before] of files) {
89
+ const text = after.get(file) ?? before;
90
+ if (text === null)
91
+ continue;
92
+ const value = parse(text, file);
93
+ const original = before === null ? undefined : parse(before, file);
94
+ const parts = path.relative(plan.home, file).split(path.sep);
95
+ if (parts.length === 1 && parts[0] === 'providers.json') {
96
+ if (!isDeepStrictEqual(validateProvidersFile(value), registry))
97
+ invalid('planned Provider registry differs from its file');
98
+ continue;
99
+ }
100
+ let schemaName;
101
+ if (parts[0] === 'agents' && parts[1] === 'defaults.json')
102
+ schemaName = 'defaults';
103
+ else if (parts[0] === 'agents' && parts.at(-1) === 'config.json') {
104
+ schemaName = parts[2] === 'relations' ? 'relation-config' : 'agent-config';
105
+ }
106
+ if (schemaName) {
107
+ const version = typeof value.$schema_version === 'number' ? value.$schema_version : undefined;
108
+ const schema = loadSchema(schemaName, version);
109
+ if (!schema.validate(value)) {
110
+ const issues = (schema.validate.errors ?? []).map(error => `${error.instancePath || '/'} ${error.keyword}`);
111
+ invalid(`${file} does not match ${schemaName} schema: ${issues.join('; ')}`);
112
+ }
113
+ }
114
+ for (const key of ['baseagents', 'agents', 'Services']) {
115
+ const selections = value[key];
116
+ if (!selections || typeof selections !== 'object')
117
+ continue;
118
+ for (const [name, selection] of Object.entries(selections)) {
119
+ const previous = original?.[key];
120
+ checkReferences(selection, `${file}:${key}.${name}`, key === 'Services' ? providerServiceTypeForPurpose(name) : undefined, key === 'Services' ? undefined : name, previous?.[name]);
121
+ }
122
+ }
123
+ checkReferences(value.decision_model, `${file}:decision_model`, 'decision', undefined, original?.decision_model);
124
+ const record = parts.at(-1) === 'initialization.json' ? value
125
+ : value.creation && typeof value.creation === 'object' ? value.creation : undefined;
126
+ if (record?.plan && typeof record.plan === 'object' && !Array.isArray(record.plan)) {
127
+ const originalRecord = parts.at(-1) === 'initialization.json' ? original
128
+ : original?.creation;
129
+ if (!isDeepStrictEqual(record.plan, originalRecord?.plan))
130
+ invalid(`frozen initialization plan changed in ${file}`);
131
+ const runtime = initializationRuntimePlan(record);
132
+ const previous = originalRecord?.plan
133
+ ? initializationRuntimePlan(originalRecord) : undefined;
134
+ checkReferences(runtime, `${file}:plan`, undefined, runtime.baseagent, previous);
135
+ }
136
+ else {
137
+ checkReferences(value.plan, `${file}:plan`);
138
+ }
139
+ checkReferences(value.providerIds && typeof value.providerIds === 'object'
140
+ ? Object.values(value.providerIds).map(provider => ({ provider })) : undefined, `${file}:providerIds`);
141
+ }
142
+ }
7
143
  export function planProviderIdentityMigration(home, registry, options = {}) {
8
144
  home = path.resolve(home);
9
145
  const changes = [];
@@ -16,13 +152,24 @@ export function planProviderIdentityMigration(home, registry, options = {}) {
16
152
  throw new Error('Provider migration does not follow configuration symlinks');
17
153
  const text = fs.readFileSync(file, 'utf8');
18
154
  expected.push({ file, before: text });
19
- const value = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
155
+ let value;
156
+ try {
157
+ value = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
158
+ }
159
+ catch (error) {
160
+ throw Object.assign(new Error(`Provider migration could not parse configuration JSON: ${file}`, { cause: error }), {
161
+ code: 'PROVIDER_CONFIG_INVALID',
162
+ });
163
+ }
20
164
  if (!value || typeof value !== 'object' || Array.isArray(value))
21
165
  throw new Error('Provider migration requires object configurations');
22
166
  return { text, value: value };
23
167
  };
24
168
  if (!fs.existsSync(providerFile) && !registry)
25
- return { home, changes, summary, pending, expected, registry: { providers: {} } };
169
+ return {
170
+ home, changes, summary, pending, expected, registry: { providers: {} },
171
+ sourceRegistry: { providers: {} }, providerMapping: {},
172
+ };
26
173
  const original = fs.existsSync(providerFile) ? readJson(providerFile) : { text: null, value: { providers: {} } };
27
174
  if (original.text === null)
28
175
  expected.push({ file: providerFile, before: null });
@@ -72,7 +219,9 @@ export function planProviderIdentityMigration(home, registry, options = {}) {
72
219
  services[serviceType] = service;
73
220
  }
74
221
  if (conflicts.length) {
75
- throw Object.assign(new Error('Provider migration conflicts; no configuration was changed'), {
222
+ const message = `Provider migration conflict between ${providerIds.join(', ')} (${target.domain}): `
223
+ + `${conflicts.join(', ')} differ; no configuration was changed`;
224
+ throw Object.assign(new Error(message), {
76
225
  code: 'PROVIDER_CONFLICT',
77
226
  data: { kind: 'provider_migration_conflict', providerIds, domain: target.domain, fields: conflicts },
78
227
  });
@@ -139,7 +288,10 @@ export function planProviderIdentityMigration(home, registry, options = {}) {
139
288
  const finish = () => {
140
289
  if (!isDeepStrictEqual(original.value, normalizedRegistry))
141
290
  queue(providerFile, original.text, normalizedRegistry);
142
- return { home, changes, summary, pending, expected, registry: normalizedRegistry };
291
+ const plan = { home, changes, summary, pending, expected, registry: normalizedRegistry,
292
+ sourceRegistry: source, providerMapping: aliases };
293
+ validateProviderIdentityMigrationPlan(plan);
294
+ return plan;
143
295
  };
144
296
  if (!Object.keys(aliases).length)
145
297
  return finish();
@@ -6,9 +6,11 @@ import { resolvePaths } from '../paths.js';
6
6
  import { acquireConfigMutationLock, ConfigError } from './config-manager.js';
7
7
  import { firstConfiguredOwner } from './owner-config.js';
8
8
  import { currentVersion, loadSchema } from './schema-registry.js';
9
- import { planProviderIdentityMigration } from './provider-identity-migration.js';
9
+ import { planProviderIdentityMigration, validateProviderIdentityMigrationPlan } from './provider-identity-migration.js';
10
10
  import { providerIdentity } from './provider-identity.js';
11
11
  import { snapshot } from './snapshot.js';
12
+ import { logger } from '../utils/logger.js';
13
+ import { atomicReplaceFile } from '../utils/atomic-write.js';
12
14
  const MIGRATION_KIND = {
13
15
  'auxiliary-model-v1': 'auxiliary-model',
14
16
  'agent-only-model-v1': 'agent-only-model',
@@ -42,20 +44,24 @@ function hasOwn(value, field) {
42
44
  return Object.prototype.hasOwnProperty.call(value, field);
43
45
  }
44
46
  let startupReadCache = null;
47
+ let startupRelationFiles = null;
45
48
  /**
46
49
  * 在这个作用域内共享配置读取结果。
47
50
  *
48
51
  * 只能包住「只读规划」阶段:一旦有迁移落盘,缓存里的内容就过期了。
49
- * 每次启动在三份迁移之间开一次,结束后自动失效。
52
+ * 配置文本与关系文件列表共用作用域,结束后自动失效。
50
53
  */
51
54
  export async function withMigrationReadCache(run) {
52
55
  const previous = startupReadCache;
56
+ const previousRelations = startupRelationFiles;
53
57
  startupReadCache = new Map();
58
+ startupRelationFiles = new Map();
54
59
  try {
55
60
  return await run();
56
61
  }
57
62
  finally {
58
63
  startupReadCache = previous;
64
+ startupRelationFiles = previousRelations;
59
65
  }
60
66
  }
61
67
  /**
@@ -68,6 +74,7 @@ export async function withMigrationReadCache(run) {
68
74
  */
69
75
  export function invalidateMigrationReadCache() {
70
76
  startupReadCache?.clear();
77
+ startupRelationFiles?.clear();
71
78
  }
72
79
  function readJson(file) {
73
80
  if (startupReadCache) {
@@ -374,6 +381,9 @@ function migrateConfig(input, file, parentContext) {
374
381
  };
375
382
  }
376
383
  function walkRelationConfigs(dir) {
384
+ const cached = startupRelationFiles?.get(dir);
385
+ if (cached)
386
+ return cached;
377
387
  if (!fs.existsSync(dir))
378
388
  return [];
379
389
  const files = [];
@@ -386,6 +396,7 @@ function walkRelationConfigs(dir) {
386
396
  else if (entry.isFile() && entry.name === 'config.json')
387
397
  files.push(full);
388
398
  }
399
+ startupRelationFiles?.set(dir, files);
389
400
  return files;
390
401
  }
391
402
  function planConfigFile(file, parentContext, changes, summary) {
@@ -525,10 +536,55 @@ function acquireLock(home, id) {
525
536
  }
526
537
  function atomicWrite(file, content) {
527
538
  fs.mkdirSync(path.dirname(file), { recursive: true });
528
- const mode = fs.existsSync(file) ? fs.statSync(file).mode & 0o777 : 0o600;
539
+ const exists = fs.existsSync(file);
540
+ const mode = exists ? fs.statSync(file).mode & 0o777 : 0o600;
541
+ const windows = process.platform === 'win32';
542
+ const readonly = windows && exists && (mode & 0o200) === 0;
529
543
  const temp = `${file}.schema-migration-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`;
530
- fs.writeFileSync(temp, content, { mode });
531
- fs.renameSync(temp, file);
544
+ let restoreReadonly = false;
545
+ let failure;
546
+ let failed = false;
547
+ try {
548
+ // A Windows readonly temporary file cannot be safely cleaned up on failure.
549
+ fs.writeFileSync(temp, content, { mode: windows ? mode | 0o200 : mode, flag: 'wx' });
550
+ if (readonly) {
551
+ fs.chmodSync(file, mode | 0o200);
552
+ restoreReadonly = true;
553
+ }
554
+ // Migration journals restore complete files; never truncate the live file
555
+ // as a fallback when Windows refuses to replace its directory entry.
556
+ atomicReplaceFile(temp, file, { allowInPlaceFallback: false });
557
+ }
558
+ catch (error) {
559
+ failed = true;
560
+ failure = error;
561
+ }
562
+ finally {
563
+ if (restoreReadonly) {
564
+ try {
565
+ fs.chmodSync(file, mode);
566
+ }
567
+ catch (error) {
568
+ failure = failed ? migrationRecoveryFailure(failure, error, 'Restoring readonly attribute failed') : error;
569
+ failed = true;
570
+ }
571
+ }
572
+ try {
573
+ fs.rmSync(temp, { force: true });
574
+ }
575
+ catch (error) {
576
+ logger.warn(`[config] Could not remove migration temporary file ${temp}: ${error}`);
577
+ }
578
+ }
579
+ if (failed)
580
+ throw failure;
581
+ }
582
+ function migrationRecoveryFailure(original, recovery, step) {
583
+ const detail = (error) => error instanceof Error ? error.message : String(error);
584
+ const error = new AggregateError([original, recovery], `${detail(original)}; ${step}: ${detail(recovery)}`, {
585
+ cause: original,
586
+ });
587
+ return Object.assign(error, isRecord(original) && typeof original.code === 'string' ? { code: original.code } : {});
532
588
  }
533
589
  function journalPath(home, id) {
534
590
  return path.join(home, 'data', `${id}-migration.json`);
@@ -538,7 +594,11 @@ function writeJournal(plan, state, id) {
538
594
  schemaVersion: 1,
539
595
  state,
540
596
  home: plan.home,
541
- changes: plan.changes,
597
+ changes: plan.changes.map(item => ({
598
+ ...item,
599
+ ...(process.platform === 'win32' && item.before !== null
600
+ ? { mode: fs.statSync(item.file).mode & 0o777 } : {}),
601
+ })),
542
602
  };
543
603
  atomicWrite(journalPath(plan.home, id), jsonText(journal));
544
604
  }
@@ -563,7 +623,8 @@ function readJournal(home, id) {
563
623
  const changes = [];
564
624
  for (const item of raw.changes) {
565
625
  if (!isRecord(item) || typeof item.file !== 'string' || typeof item.after !== 'string'
566
- || (item.before !== null && typeof item.before !== 'string')) {
626
+ || (item.before !== null && typeof item.before !== 'string')
627
+ || (item.mode !== undefined && (!Number.isInteger(item.mode) || Number(item.mode) < 0 || Number(item.mode) > 0o777))) {
567
628
  throw new Error(`Migration journal contains an unsafe change: ${file}`);
568
629
  }
569
630
  const target = path.resolve(item.file);
@@ -575,6 +636,7 @@ function readJournal(home, id) {
575
636
  kind: MIGRATION_KIND[id],
576
637
  before: item.before,
577
638
  after: item.after,
639
+ ...(typeof item.mode === 'number' ? { mode: item.mode } : {}),
578
640
  });
579
641
  }
580
642
  return {
@@ -592,8 +654,27 @@ function recoverJournal(home, id) {
592
654
  for (const item of [...journal.changes].reverse()) {
593
655
  if (item.before === null)
594
656
  fs.rmSync(item.file, { force: true });
595
- else
596
- atomicWrite(item.file, item.before);
657
+ else {
658
+ // A failed first replacement may leave the original already intact.
659
+ // Replacing it again can repeat the same Windows access error forever.
660
+ let current;
661
+ try {
662
+ current = fs.readFileSync(item.file, 'utf8');
663
+ }
664
+ catch (error) {
665
+ if (!isRecord(error) || error.code !== 'ENOENT')
666
+ throw error;
667
+ current = null;
668
+ }
669
+ if (current !== item.before)
670
+ atomicWrite(item.file, item.before);
671
+ // Also restore readonly after a crash between chmod and replacement,
672
+ // including when the original bytes were never changed.
673
+ if (process.platform === 'win32' && item.mode !== undefined
674
+ && (fs.statSync(item.file).mode & 0o200) !== (item.mode & 0o200)) {
675
+ fs.chmodSync(item.file, item.mode);
676
+ }
677
+ }
597
678
  }
598
679
  }
599
680
  fs.rmSync(journalPath(home, id), { force: true });
@@ -633,7 +714,12 @@ function applyMigration(plan, id) {
633
714
  fs.rmSync(journalPath(plan.home, id), { force: true });
634
715
  }
635
716
  catch (error) {
636
- recoverJournal(plan.home, id);
717
+ try {
718
+ recoverJournal(plan.home, id);
719
+ }
720
+ catch (recovery) {
721
+ throw migrationRecoveryFailure(error, recovery, 'Migration rollback failed');
722
+ }
637
723
  throw error;
638
724
  }
639
725
  return backup;
@@ -1303,16 +1389,17 @@ function planAgentModelProviderMigration(home) {
1303
1389
  value.$schema_version = AGENT_CONFIG_RESTAMP.to;
1304
1390
  }
1305
1391
  summary.gatewayFieldsRemoved += removed.length;
1306
- const nextText = jsonText(value);
1307
- if (nextText === entry.text)
1392
+ if (isDeepStrictEqual(value, entry.value))
1308
1393
  continue;
1394
+ const nextText = jsonText(value);
1309
1395
  changes.push({ file, kind: 'agent-only-model', before: entry.text, after: nextText });
1310
1396
  details.push({ file: path.relative(home, file), removed });
1311
1397
  summary.filesChanged += 1;
1312
1398
  }
1313
1399
  if (Object.keys(providers).length > 0) {
1314
- const nextText = jsonText({ $schema_version: 1, ...providerRegistry, providers });
1315
- if (nextText !== providersBefore) {
1400
+ const nextRegistry = { $schema_version: 1, ...providerRegistry, providers };
1401
+ if (!isDeepStrictEqual(nextRegistry, providerRegistry)) {
1402
+ const nextText = jsonText(nextRegistry);
1316
1403
  changes.push({ file: providersFile, kind: 'agent-only-model', before: providersBefore, after: nextText });
1317
1404
  details.push({ file: 'providers.json', removed: [] });
1318
1405
  summary.filesChanged += 1;
@@ -1420,7 +1507,14 @@ export function runProviderIdentitySchemaMigration(options = {}) {
1420
1507
  try {
1421
1508
  assertDaemonStopped(home);
1422
1509
  recoverJournal(home, id);
1423
- const plan = planProviderIdentityMigration(home, undefined, { cleanupAliases: true });
1510
+ let plan;
1511
+ try {
1512
+ plan = planProviderIdentityMigration(home, undefined, { cleanupAliases: true });
1513
+ }
1514
+ catch (error) {
1515
+ const detail = error instanceof Error ? error.message : String(error);
1516
+ throw new ConfigError('PROVIDER_IDENTITY_PLAN_FAILED', `Provider identity migration planning failed: ${detail}`, { cause: error });
1517
+ }
1424
1518
  const backup = options.apply ? commitProviderSyncMigration(plan, true) : null;
1425
1519
  return { ok: true, mode: options.apply ? 'applied' : 'dry-run',
1426
1520
  home, changedFiles: plan.changes.length, backup, summary: plan.summary, pending: plan.pending };
@@ -1435,7 +1529,19 @@ export async function ensureProviderIdentityMigrationOnStartup() {
1435
1529
  return result.changedFiles === 0 && result.pending.length === 0 ? null : result;
1436
1530
  }
1437
1531
  catch (error) {
1438
- throw new ConfigError('PROVIDER_IDENTITY_MIGRATION_FAILED', 'Automatic Provider identity migration failed; resolve conflicting domains or connection settings before restarting', { cause: error });
1532
+ if (!(error instanceof ConfigError) || error.code !== 'PROVIDER_IDENTITY_PLAN_FAILED') {
1533
+ const detail = error instanceof Error ? error.message : String(error);
1534
+ throw new ConfigError('PROVIDER_IDENTITY_MIGRATION_FAILED', `Automatic Provider identity migration failed: ${detail}`, { cause: error });
1535
+ }
1536
+ const cause = isRecord(error.data) ? error.data.cause : error;
1537
+ const code = isRecord(cause) && typeof cause.code === 'string'
1538
+ ? cause.code : 'PROVIDER_IDENTITY_PLAN_FAILED';
1539
+ const detail = cause instanceof Error ? cause.message : String(cause);
1540
+ const message = `[config] Automatic Provider identity migration skipped [${code}]: ${detail}; `
1541
+ + 'continuing startup with existing configuration';
1542
+ logger.warn(message);
1543
+ console.error(`⚠ ${message}`);
1544
+ return null;
1439
1545
  }
1440
1546
  }
1441
1547
  export function commitProviderSyncMigration(plan, migrationLocked = false) {
@@ -1464,6 +1570,7 @@ export function commitProviderSyncMigration(plan, migrationLocked = false) {
1464
1570
  throw Object.assign(new Error('Configuration changed during Provider sync; retry after reviewing the current configuration'), { code: 'CONFLICT' });
1465
1571
  }
1466
1572
  }
1573
+ validateProviderIdentityMigrationPlan(plan);
1467
1574
  return applyMigration(plan, id);
1468
1575
  }
1469
1576
  finally {
@@ -12,13 +12,17 @@
12
12
  */
13
13
  import fs from 'fs';
14
14
  import path from 'path';
15
- import Ajv from 'ajv';
15
+ import { createRequire } from 'node:module';
16
16
  import { kitsSchemasDir } from '../paths.js';
17
17
  import { createErrorCapturingReader, fileCache } from '../core/daemon-file-cache.js';
18
18
  let _ajv = null;
19
+ const requireSchemaDependency = createRequire(import.meta.url);
19
20
  function ajv() {
20
21
  if (!_ajv) {
21
- _ajv = new Ajv({ allErrors: true, strict: false, useDefaults: false });
22
+ // Version/metadata readers do not compile schemas. Keep the synchronous
23
+ // validator contract without loading Ajv into every lifecycle client.
24
+ const AjvConstructor = requireSchemaDependency('ajv');
25
+ _ajv = new AjvConstructor({ allErrors: true, strict: false, useDefaults: false });
22
26
  }
23
27
  return _ajv;
24
28
  }
@@ -235,18 +235,19 @@ export async function createStartupAgentRunners({ agentRegistry, agentLoader, se
235
235
  export async function completeStartupAgentRuntime(agentRegistry, current) {
236
236
  try {
237
237
  const { watchAgentSkills } = await import('./skill/startup.js');
238
- for (const info of agentRegistry.list()) {
239
- if (info.status === 'running')
240
- watchAgentSkills(info.aid);
238
+ for (const agent of agentRegistry.allAgents()) {
239
+ if (agent.status === 'running')
240
+ watchAgentSkills(agent.aid);
241
241
  }
242
242
  }
243
243
  catch (error) {
244
244
  logger.warn(`[skill] agent 监控注册失败: ${error instanceof Error ? error.message : String(error)}`);
245
245
  }
246
- if (agentRegistry.list().some(info => info.status === 'running')) {
246
+ const agents = agentRegistry.allAgents();
247
+ if (agents.some(agent => agent.status === 'running')) {
247
248
  return { state: 'running', error: undefined };
248
249
  }
249
- if (agentRegistry.runnableAgents().length === 0 && agentRegistry.list().length === 0) {
250
+ if (agents.length === 0) {
250
251
  return { ...current, state: 'empty' };
251
252
  }
252
253
  if (current.state === 'starting') {
@@ -27,7 +27,7 @@ export function readDelegationCredential(env = process.env) {
27
27
  return sessionToken || undefined;
28
28
  }
29
29
  export class AgentDelegationRegistry {
30
- runtimeEpoch = crypto.randomBytes(16).toString('hex');
30
+ runtimeEpoch;
31
31
  diagnostics;
32
32
  grantsByHash = new Map();
33
33
  activeHashBySession = new Map();
@@ -36,8 +36,13 @@ export class AgentDelegationRegistry {
36
36
  approvedCommandBindings = new Map();
37
37
  internalGrants = new Map();
38
38
  debugRegistry = new DebugDelegationRegistry();
39
- constructor() {
40
- 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));
41
46
  }
42
47
  getRuntimeEpoch() {
43
48
  return this.runtimeEpoch;
@@ -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,7 +5,7 @@ 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
11
  ...['inspect', 'build', 'push', 'pull', 'preview', 'deploy', 'status', 'resume', 'cancel', 'capabilities'].map(action => 'agent.template.' + action),