evolcore 0.0.41-test.0 → 0.0.41-test.2

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 (235) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +88 -49
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +146 -71
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/aid/agentmd.js +98 -11
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +26 -2
  11. package/dist/aun/aid/identity.js +91 -0
  12. package/dist/aun/aid/index.js +1 -1
  13. package/dist/aun/aid/managed-operation.js +1 -1
  14. package/dist/aun/aid/ownership-operation.js +23 -22
  15. package/dist/aun/group/fs-download.js +39 -0
  16. package/dist/aun/group/identity.js +36 -21
  17. package/dist/aun/group/operations.js +5 -0
  18. package/dist/aun/menu/client.js +27 -0
  19. package/dist/aun/msg/managed-operation.js +68 -7
  20. package/dist/aun/msg/p2p.js +8 -8
  21. package/dist/aun/service-proxy.js +53 -12
  22. package/dist/channels/aun.js +633 -32
  23. package/dist/channels/daemon.js +15 -1
  24. package/dist/cli/agent-command.js +5 -2
  25. package/dist/cli/agent-create.js +991 -233
  26. package/dist/cli/agent.js +49 -10
  27. package/dist/cli/aid-bind-command.js +48 -19
  28. package/dist/cli/aun-commands.js +48 -36
  29. package/dist/cli/daemon-commands.js +679 -697
  30. package/dist/cli/fs-command.js +64 -2
  31. package/dist/cli/index.js +72 -5
  32. package/dist/cli/init-channel.js +1 -1
  33. package/dist/cli/init.js +75 -1
  34. package/dist/cli/managed-command-guard.js +17 -1
  35. package/dist/cli/model.js +40 -40
  36. package/dist/cli/provider-command.js +57 -0
  37. package/dist/cli/proxy-command.js +92 -0
  38. package/dist/cli/restart-monitor.js +4 -2
  39. package/dist/cli/role.js +85 -0
  40. package/dist/cli/stats.js +10 -3
  41. package/dist/cli/task-context.js +19 -0
  42. package/dist/config/access-policy.js +7 -2
  43. package/dist/config/boot-log.js +39 -1
  44. package/dist/config/config-field-policy.js +17 -39
  45. package/dist/config/config-manager.js +183 -44
  46. package/dist/config/config-operation-service.js +5 -19
  47. package/dist/config/contact-book-store.js +47 -21
  48. package/dist/config/contact-book.js +18 -12
  49. package/dist/config/contact-operation-service.js +3 -4
  50. package/dist/config/contact-request-service.js +11 -0
  51. package/dist/config/daemon-services.js +11 -0
  52. package/dist/config/gateway-config.js +88 -594
  53. package/dist/config/owner-config.js +2 -2
  54. package/dist/config/peer-role-resolver.js +15 -12
  55. package/dist/config/provider-ipc-service.js +132 -0
  56. package/dist/config/provider-menu-request.js +58 -0
  57. package/dist/config/providers-config.js +12 -7
  58. package/dist/config/providers-import.js +3 -21
  59. package/dist/config/providers-management.js +78 -5
  60. package/dist/config/resolved-config-op.js +11 -1
  61. package/dist/config/role-command-service.js +166 -0
  62. package/dist/config/role-request-service.js +193 -0
  63. package/dist/config/schema-migration.js +1000 -25
  64. package/dist/config-store.js +89 -4
  65. package/dist/contracts/ecweb-instance.js +41 -0
  66. package/dist/contracts/ecweb-service-protocol.js +4 -1
  67. package/dist/core/agent-application-service.js +60 -11
  68. package/dist/core/agent-create-status.js +203 -0
  69. package/dist/core/agent-creation-claim.js +177 -0
  70. package/dist/core/agent-ipc-registration.js +39 -18
  71. package/dist/core/agent-runtime.js +194 -24
  72. package/dist/core/auth/agent-delegation.js +6 -3
  73. package/dist/core/auth/auth-gateway.js +67 -2
  74. package/dist/core/auth/authorization-audit.js +58 -11
  75. package/dist/core/auth/delegation-authorization.js +5 -2
  76. package/dist/core/auth/operation-authorizer.js +43 -6
  77. package/dist/core/auth/operation-catalog.js +45 -7
  78. package/dist/core/channel-loader.js +2 -0
  79. package/dist/core/command/agent-control.js +260 -21
  80. package/dist/core/command/agent-storage-menu.js +5 -3
  81. package/dist/core/command/cli-intent-parser.js +8 -3
  82. package/dist/core/command/command-handler.js +112 -154
  83. package/dist/core/command/connect-menu.js +11 -3
  84. package/dist/core/command/data-root-resolver.js +5 -4
  85. package/dist/core/command/memory-slash.js +16 -8
  86. package/dist/core/command/menu-catalog.js +10 -6
  87. package/dist/core/command/menu-handler.js +106 -73
  88. package/dist/core/command/menu-protocol.js +15 -1
  89. package/dist/core/command/provider-menu.js +46 -0
  90. package/dist/core/command/role-menu.js +147 -30
  91. package/dist/core/command/slash-handler.js +125 -255
  92. package/dist/core/daemon-control.js +26 -27
  93. package/dist/core/event-catalog.js +10 -0
  94. package/dist/core/evolagent-registry.js +7 -5
  95. package/dist/core/evolagent.js +10 -8
  96. package/dist/core/file-integrity/store.js +11 -0
  97. package/dist/core/handoff/ipc-registration.js +3 -0
  98. package/dist/core/inference/text-inference.js +31 -40
  99. package/dist/core/initialization/service.js +491 -0
  100. package/dist/core/ipc-registration.js +40 -24
  101. package/dist/core/memory/consolidation-context.js +51 -5
  102. package/dist/core/memory/consolidation-ops-records.js +96 -1
  103. package/dist/core/memory/consolidation-trigger.js +208 -191
  104. package/dist/core/memory/consolidation.js +333 -35
  105. package/dist/core/memory/index-manager.js +27 -5
  106. package/dist/core/memory/memory-admin.js +45 -5
  107. package/dist/core/memory/memory-writer.js +163 -18
  108. package/dist/core/memory/relation-idle-monitor.js +119 -58
  109. package/dist/core/memory/relation-sweep.js +55 -45
  110. package/dist/core/message/aun-ipc-sender.js +81 -69
  111. package/dist/core/message/im-renderer.js +25 -4
  112. package/dist/core/message/message-admission.js +89 -4
  113. package/dist/core/message/message-bridge.js +66 -21
  114. package/dist/core/message/response-engine.js +108 -35
  115. package/dist/core/model/catalog-service.js +5 -3
  116. package/dist/core/model/config-scope.js +29 -71
  117. package/dist/core/model/field-scope.js +1 -1
  118. package/dist/core/model/model-catalog.js +30 -41
  119. package/dist/core/model/model-diagnostics.js +4 -3
  120. package/dist/core/model/model-fallback.js +10 -7
  121. package/dist/core/model/model-permission.js +3 -2
  122. package/dist/core/ownership/owner-resolver.js +772 -158
  123. package/dist/core/permission/approval-gateway.js +103 -403
  124. package/dist/core/permission/ec-command-parser.js +62 -6
  125. package/dist/core/permission/index.js +1 -0
  126. package/dist/core/permission/permission-result.js +78 -0
  127. package/dist/core/permission/sandbox-runtime.js +18 -1
  128. package/dist/core/permission/tool-policy.js +21 -46
  129. package/dist/core/relation/peer-identity.js +64 -1
  130. package/dist/core/role/runtime-policy.js +72 -13
  131. package/dist/core/session/session-capsule.js +1 -1
  132. package/dist/core/session/session-idle-monitor.js +1 -1
  133. package/dist/core/session/session-manager.js +20 -0
  134. package/dist/core/session/session-renew.js +3 -3
  135. package/dist/core/skill/index-generator.js +15 -5
  136. package/dist/core/system-session/memory.js +43 -8
  137. package/dist/core/thread/thread-service.js +19 -6
  138. package/dist/directory/owner-directory-admission.js +95 -0
  139. package/dist/directory/owner-directory-authorization.js +309 -0
  140. package/dist/directory/owner-directory-cache.js +635 -0
  141. package/dist/eck/kit-renderer.js +2 -2
  142. package/dist/ecweb/basic-settings-service.js +33 -40
  143. package/dist/ecweb/init-menu.js +32 -0
  144. package/dist/ecweb/message-context-service.js +110 -0
  145. package/dist/index.js +93 -19
  146. package/dist/ipc.js +247 -29
  147. package/dist/paths.js +7 -0
  148. package/dist/proxy/command.js +122 -0
  149. package/dist/proxy/ipc-service.js +68 -0
  150. package/dist/proxy/manager.js +484 -0
  151. package/dist/proxy/service-supervisor.js +603 -0
  152. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  153. package/dist/trigger/authorization.js +27 -17
  154. package/dist/trigger/feedback.js +2 -3
  155. package/dist/trigger/ipc-service.js +105 -78
  156. package/dist/trigger/local-files.js +2 -1
  157. package/dist/trigger/manager.js +5 -3
  158. package/dist/trigger/scheduler.js +88 -6
  159. package/dist/utils/atomic-write.js +28 -0
  160. package/dist/utils/cross-platform.js +14 -0
  161. package/dist/utils/ecweb-supervisor.js +258 -83
  162. package/dist/utils/error-utils.js +26 -2
  163. package/dist/utils/logger.js +92 -6
  164. package/dist/utils/package-version-info.js +4 -2
  165. package/dist/utils/welcome.js +1 -1
  166. package/kits/docs/INDEX.md +1 -0
  167. package/kits/docs/aun/SDK.md +4 -1
  168. package/kits/docs/channels/aun.md +9 -0
  169. package/kits/docs/evolcore/INDEX.md +1 -0
  170. package/kits/docs/evolcore/agent.md +8 -1
  171. package/kits/docs/evolcore/aid.md +67 -17
  172. package/kits/docs/evolcore/config.md +28 -7
  173. package/kits/docs/evolcore/contact.md +3 -0
  174. package/kits/docs/evolcore/fs.md +11 -0
  175. package/kits/docs/evolcore/group.md +1 -1
  176. package/kits/docs/evolcore/memory-architecture.md +2 -2
  177. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  178. package/kits/docs/evolcore/memory.md +1 -1
  179. package/kits/docs/evolcore/menu-protocol.md +4 -0
  180. package/kits/docs/evolcore/model.md +23 -20
  181. package/kits/docs/evolcore/msg.md +4 -7
  182. package/kits/docs/evolcore/provider.md +50 -0
  183. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  184. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  185. package/kits/rules/01-overview.md +3 -0
  186. package/kits/rules/04-relation.md +1 -1
  187. package/kits/schemas/_meta.json +37 -4
  188. package/kits/schemas/agent-config.schema.13.json +8 -3
  189. package/kits/schemas/agent-config.schema.16.json +891 -0
  190. package/kits/schemas/daemon.schema.9.json +366 -0
  191. package/kits/schemas/defaults.schema.5.json +406 -127
  192. package/kits/schemas/relation-config.schema.11.json +277 -0
  193. package/kits/schemas/role-config.schema.1.json +7 -7
  194. package/kits/skills/.switches.json +4 -0
  195. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  196. package/kits/skills/ec-identity/SKILL.md +2 -2
  197. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  198. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  199. package/kits/skills/personal-assistant/SKILL.md +176 -0
  200. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  201. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  202. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  203. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  204. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  205. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  206. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  207. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  208. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  209. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  210. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  211. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  212. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  213. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  214. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  215. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  216. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  217. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  218. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  219. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  220. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  221. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  222. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  223. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  224. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  225. package/kits/skills/thread-ops/SKILL.md +5 -0
  226. package/kits/templates/memory-consolidation/forget.md +19 -6
  227. package/kits/templates/memory-consolidation/notes.md +1 -1
  228. package/kits/templates/memory-consolidation/profile.md +2 -2
  229. package/kits/templates/memory-consolidation/promote.md +20 -3
  230. package/kits/templates/roles/member.json +8 -1
  231. package/kits/templates/system-fragments/baseagent.md +2 -2
  232. package/kits/templates/system-fragments/memory.md +4 -4
  233. package/kits/templates/system-fragments/venue.md +1 -1
  234. package/package.json +7 -3
  235. package/dist/core/message/create-status.js +0 -96
@@ -3,6 +3,16 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { resolvePaths } from '../paths.js';
5
5
  import { ConfigError } from './config-manager.js';
6
+ import { firstConfiguredOwner } from './owner-config.js';
7
+ import { resolveLegacyBaseagentModelSelection } from '../agents/baseagent.js';
8
+ const MIGRATION_KIND = {
9
+ 'auxiliary-model-v1': 'auxiliary-model',
10
+ 'agent-only-model-v1': 'agent-only-model',
11
+ 'agent-model-provider-v1': 'agent-only-model',
12
+ 'provider-service-type-v1': 'provider-service-type',
13
+ 'relation-config-v11-v1': 'agent-only-model',
14
+ 'legacy-model-selection-v1': 'agent-only-model',
15
+ };
6
16
  const SUPPORTED_BASEAGENTS = new Set(['claude', 'codex', 'gemini', 'ecagent']);
7
17
  const BASEAGENT_ALIASES = new Map([
8
18
  ['cc', 'claude'],
@@ -47,6 +57,65 @@ function baseagentSource(value) {
47
57
  ? value.agents
48
58
  : undefined;
49
59
  }
60
+ function firstOwnerAid(agent) {
61
+ const owner = firstConfiguredOwner(agent);
62
+ if (owner && validAid(owner))
63
+ return owner;
64
+ return undefined;
65
+ }
66
+ /**
67
+ * Read only the configured owner's legacy relation selections. Relation
68
+ * values from every other peer are deliberately ignored: after this
69
+ * migration model/effort are Agent-owned and there is no deterministic
70
+ * precedence among ordinary relations.
71
+ */
72
+ function ownerRelationSelections(relationsDir, ownerAid, fallbackBaseagent) {
73
+ const selections = new Map();
74
+ if (!ownerAid)
75
+ return selections;
76
+ const ownerDirNames = new Set([`aun#${ownerAid}`, `aun#${encodeURIComponent(ownerAid)}`]);
77
+ for (const relationFile of walkRelationConfigs(relationsDir)) {
78
+ if (!ownerDirNames.has(path.basename(path.dirname(relationFile))))
79
+ continue;
80
+ let relation;
81
+ try {
82
+ relation = readJson(relationFile).value;
83
+ }
84
+ catch {
85
+ continue;
86
+ }
87
+ if (!isRecord(relation))
88
+ continue;
89
+ const active = canonicalBaseagent(relation.active_baseagent) || fallbackBaseagent;
90
+ // Older relation files could hold a flat model/effort pair. Attribute it
91
+ // to that relation's active backend, while still ignoring non-owner peers.
92
+ if (active && (typeof relation.model === 'string' || typeof relation.effort === 'string' || typeof relation.reasoning === 'string')) {
93
+ const selection = {};
94
+ if (typeof relation.model === 'string' && relation.model.trim())
95
+ selection.model = relation.model.trim();
96
+ const effort = typeof relation.effort === 'string' ? relation.effort : relation.reasoning;
97
+ if (typeof effort === 'string' && effort.trim())
98
+ selection.effort = effort.trim();
99
+ if (selection.model !== undefined || selection.effort !== undefined)
100
+ selections.set(active, selection);
101
+ }
102
+ const source = baseagentSource(relation) ?? {};
103
+ for (const [rawName, rawBlock] of Object.entries(source)) {
104
+ const name = canonicalBaseagent(rawName);
105
+ if (!name || !isRecord(rawBlock))
106
+ continue;
107
+ const selection = {};
108
+ if (typeof rawBlock.model === 'string' && rawBlock.model.trim())
109
+ selection.model = rawBlock.model.trim();
110
+ const effort = typeof rawBlock.effort === 'string' ? rawBlock.effort : rawBlock.reasoning;
111
+ if (typeof effort === 'string' && effort.trim())
112
+ selection.effort = effort.trim();
113
+ if (selection.model !== undefined || selection.effort !== undefined)
114
+ selections.set(name, selection);
115
+ }
116
+ }
117
+ return selections;
118
+ }
50
119
  function baseagentNames(value) {
51
120
  const source = baseagentSource(value);
52
121
  if (!source)
@@ -379,11 +448,11 @@ function assertDaemonStopped(home) {
379
448
  }
380
449
  }
381
450
  }
382
- function lockPath(home) {
383
- return path.join(home, 'data', 'auxiliary-model-v1-migration.lock');
451
+ function lockPath(home, id) {
452
+ return path.join(home, 'data', `${id}-migration.lock`);
384
453
  }
385
- function acquireLock(home) {
386
- const dir = lockPath(home);
454
+ function acquireLock(home, id) {
455
+ const dir = lockPath(home, id);
387
456
  const ownerFile = path.join(dir, 'owner.json');
388
457
  fs.mkdirSync(path.dirname(dir), { recursive: true });
389
458
  try {
@@ -401,7 +470,7 @@ function acquireLock(home) {
401
470
  }
402
471
  const pid = isRecord(owner) ? Number(owner.pid) : NaN;
403
472
  if (Number.isInteger(pid) && pid > 0 && processIsAlive(pid)) {
404
- throw new Error(`Another auxiliary model migration is already running (pid=${pid})`);
473
+ throw new Error(`Another ${id} migration is already running (pid=${pid})`);
405
474
  }
406
475
  fs.rmSync(dir, { recursive: true, force: true });
407
476
  fs.mkdirSync(dir);
@@ -412,24 +481,24 @@ function acquireLock(home) {
412
481
  function atomicWrite(file, content) {
413
482
  fs.mkdirSync(path.dirname(file), { recursive: true });
414
483
  const mode = fs.existsSync(file) ? fs.statSync(file).mode & 0o777 : 0o600;
415
- const temp = `${file}.auxiliary-model-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`;
484
+ const temp = `${file}.schema-migration-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`;
416
485
  fs.writeFileSync(temp, content, { mode });
417
486
  fs.renameSync(temp, file);
418
487
  }
419
- function journalPath(home) {
420
- return path.join(home, 'data', 'auxiliary-model-v1-migration.json');
488
+ function journalPath(home, id) {
489
+ return path.join(home, 'data', `${id}-migration.json`);
421
490
  }
422
- function writeJournal(plan, state) {
491
+ function writeJournal(plan, state, id) {
423
492
  const journal = {
424
493
  schemaVersion: 1,
425
494
  state,
426
495
  home: plan.home,
427
496
  changes: plan.changes,
428
497
  };
429
- atomicWrite(journalPath(plan.home), jsonText(journal));
498
+ atomicWrite(journalPath(plan.home, id), jsonText(journal));
430
499
  }
431
- function readJournal(home) {
432
- const file = journalPath(home);
500
+ function readJournal(home, id) {
501
+ const file = journalPath(home, id);
433
502
  if (!fs.existsSync(file))
434
503
  return undefined;
435
504
  let raw;
@@ -458,7 +527,7 @@ function readJournal(home) {
458
527
  }
459
528
  changes.push({
460
529
  file: item.file,
461
- kind: 'auxiliary-model',
530
+ kind: MIGRATION_KIND[id],
462
531
  before: item.before,
463
532
  after: item.after,
464
533
  });
@@ -470,8 +539,8 @@ function readJournal(home) {
470
539
  changes,
471
540
  };
472
541
  }
473
- function recoverJournal(home) {
474
- const journal = readJournal(home);
542
+ function recoverJournal(home, id) {
543
+ const journal = readJournal(home, id);
475
544
  if (!journal)
476
545
  return;
477
546
  if (journal.state === 'prepared') {
@@ -482,13 +551,13 @@ function recoverJournal(home) {
482
551
  atomicWrite(item.file, item.before);
483
552
  }
484
553
  }
485
- fs.rmSync(journalPath(home), { force: true });
554
+ fs.rmSync(journalPath(home, id), { force: true });
486
555
  }
487
- function applyMigration(plan) {
556
+ function applyMigration(plan, id) {
488
557
  if (plan.changes.length === 0)
489
558
  return null;
490
559
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
491
- const backup = path.join(plan.home, 'backups', 'auxiliary-model-v1-migration', stamp);
560
+ const backup = path.join(plan.home, 'backups', `${id}-migration`, stamp);
492
561
  fs.mkdirSync(path.join(backup, 'files'), { recursive: true });
493
562
  for (const item of plan.changes) {
494
563
  if (item.before === null)
@@ -506,28 +575,29 @@ function applyMigration(plan) {
506
575
  kind: item.kind,
507
576
  })),
508
577
  }));
509
- writeJournal(plan, 'prepared');
578
+ writeJournal(plan, 'prepared', id);
510
579
  try {
511
580
  for (const item of plan.changes)
512
581
  atomicWrite(item.file, item.after);
513
- writeJournal(plan, 'committed');
514
- fs.rmSync(journalPath(plan.home), { force: true });
582
+ writeJournal(plan, 'committed', id);
583
+ fs.rmSync(journalPath(plan.home, id), { force: true });
515
584
  }
516
585
  catch (error) {
517
- recoverJournal(plan.home);
586
+ recoverJournal(plan.home, id);
518
587
  throw error;
519
588
  }
520
589
  return backup;
521
590
  }
522
591
  /** Plan or apply the legacy response-mode bucket to baseagent schema migration. */
523
592
  export function runAuxiliaryModelSchemaMigration(options = {}) {
593
+ const id = 'auxiliary-model-v1';
524
594
  const home = path.resolve(options.home || resolvePaths().root);
525
- const release = acquireLock(home);
595
+ const release = acquireLock(home, id);
526
596
  try {
527
597
  assertDaemonStopped(home);
528
- recoverJournal(home);
598
+ recoverJournal(home, id);
529
599
  const plan = planAuxiliaryModelMigration(home);
530
- const backup = options.apply ? applyMigration(plan) : null;
600
+ const backup = options.apply ? applyMigration(plan, id) : null;
531
601
  return {
532
602
  ok: true,
533
603
  mode: options.apply ? 'applied' : 'dry-run',
@@ -560,3 +630,908 @@ export async function ensureAuxiliaryModelMigrationOnStartup() {
560
630
  throw new ConfigError('AUXILIARY_MODEL_MIGRATION_FAILED', `Automatic Session Renew auxiliary-model schema migration failed: ${detail}`, { cause: error });
561
631
  }
562
632
  }
633
+ // ── Preserve pre-upgrade runner selections once, before removing legacy relation settings. ──
634
+ export function runLegacyModelSelectionMigration(options = {}) {
635
+ const home = path.resolve(options.home || resolvePaths().root);
636
+ const id = 'legacy-model-selection-v1';
637
+ const release = acquireLock(home, id);
638
+ try {
639
+ assertDaemonStopped(home);
640
+ recoverJournal(home, id);
641
+ const markerFile = path.join(home, 'data', `${id}-completed.json`);
642
+ if (fs.existsSync(markerFile)) {
643
+ const marker = readJson(markerFile).value;
644
+ if (!isRecord(marker) || marker.schemaVersion !== 1)
645
+ throw new Error(`Invalid model migration marker: ${markerFile}`);
646
+ return { mode: options.apply ? 'applied' : 'dry-run', changedFiles: 0, restoredModels: 0, backup: null };
647
+ }
648
+ const changes = [];
649
+ const selections = [];
650
+ let restoredModels = 0;
651
+ const agentsRoot = path.join(home, 'agents');
652
+ const defaultsFile = path.join(agentsRoot, 'defaults.json');
653
+ const defaults = fs.existsSync(defaultsFile) ? readJson(defaultsFile).value : {};
654
+ if (!isRecord(defaults))
655
+ throw new Error(`${defaultsFile}: defaults configuration must be an object`);
656
+ const inheritedBlocks = baseagentSource(defaults) ?? {};
657
+ const entries = fs.existsSync(agentsRoot) ? fs.readdirSync(agentsRoot, { withFileTypes: true }) : [];
658
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
659
+ if (!entry.isDirectory() || !validAid(entry.name))
660
+ continue;
661
+ const file = path.join(agentsRoot, entry.name, 'config.json');
662
+ if (!fs.existsSync(file))
663
+ continue;
664
+ let parsed;
665
+ try {
666
+ parsed = readJson(file);
667
+ }
668
+ catch {
669
+ continue;
670
+ }
671
+ if (!isRecord(parsed.value))
672
+ continue;
673
+ const agent = parsed.value;
674
+ const baseagent = canonicalBaseagent(agent.active_baseagent) || canonicalBaseagent(defaults.active_baseagent);
675
+ if (!baseagent)
676
+ continue;
677
+ const blocks = baseagentSource(agent) ?? {};
678
+ const ownerSelections = ownerRelationSelections(path.join(agentsRoot, entry.name, 'relations'), firstOwnerAid(agent), baseagent);
679
+ // Process every configured backend, not only the currently active one.
680
+ // This preserves an Owner's explicit override even when the Agent later
681
+ // switches active_baseagent.
682
+ const backends = new Set([baseagent]);
683
+ for (const rawName of Object.keys(blocks)) {
684
+ const name = canonicalBaseagent(rawName);
685
+ if (name)
686
+ backends.add(name);
687
+ }
688
+ for (const name of ownerSelections.keys())
689
+ backends.add(name);
690
+ let nextBlocks = { ...blocks };
691
+ for (const backend of backends) {
692
+ const block = isRecord(blocks[backend]) ? blocks[backend] : {};
693
+ const inherited = isRecord(inheritedBlocks[backend]) ? inheritedBlocks[backend] : {};
694
+ const ownerSelection = ownerSelections.get(backend);
695
+ const nextBlock = { ...block };
696
+ const migrated = { aid: entry.name, baseagent: backend };
697
+ // Owner relation values win field-by-field over an existing Agent
698
+ // value. A missing Owner field leaves the Agent value untouched.
699
+ if (ownerSelection?.model !== undefined && ownerSelection.model !== block.model) {
700
+ nextBlock.model = ownerSelection.model;
701
+ migrated.model = ownerSelection.model;
702
+ migrated.modelSource = 'owner-relation';
703
+ }
704
+ if (ownerSelection?.effort !== undefined && ownerSelection.effort !== block.effort) {
705
+ nextBlock.effort = ownerSelection.effort;
706
+ migrated.effort = ownerSelection.effort;
707
+ migrated.effortSource = 'owner-relation';
708
+ }
709
+ // Preserve the runner's historical selection when no Agent/defaults
710
+ // model exists and the Owner relation did not provide one. This is a
711
+ // one-time compatibility fallback; other relation values are ignored.
712
+ const hasAgentModel = typeof block.model === 'string' && block.model.trim().length > 0;
713
+ const hasDefaultModel = typeof inherited.model === 'string' && inherited.model.trim().length > 0;
714
+ if (backend === baseagent && !hasAgentModel && !hasDefaultModel && ownerSelection?.model === undefined) {
715
+ const legacy = resolveLegacyBaseagentModelSelection(backend);
716
+ if (legacy) {
717
+ nextBlock.model = legacy.model;
718
+ migrated.model = legacy.model;
719
+ migrated.modelSource = legacy.source;
720
+ if (!block.effort && ownerSelection?.effort === undefined && legacy.effort) {
721
+ nextBlock.effort = legacy.effort;
722
+ migrated.effort = legacy.effort;
723
+ migrated.effortSource = legacy.source;
724
+ }
725
+ }
726
+ }
727
+ if (Object.keys(migrated).length > 2) {
728
+ nextBlocks = { ...nextBlocks, [backend]: nextBlock };
729
+ selections.push(migrated);
730
+ if (migrated.model !== undefined)
731
+ restoredModels += 1;
732
+ }
733
+ }
734
+ if (JSON.stringify(nextBlocks) !== JSON.stringify(blocks)) {
735
+ const next = { ...agent, baseagents: nextBlocks };
736
+ changes.push({ file, kind: 'agent-only-model', before: parsed.text, after: jsonText(next) });
737
+ }
738
+ }
739
+ changes.push({ file: markerFile, kind: 'agent-only-model', before: null,
740
+ after: jsonText({ schemaVersion: 1, completedAt: new Date().toISOString(), selections }) });
741
+ const backup = options.apply ? applyMigration({ home, changes, summary: { restoredModels } }, id) : null;
742
+ return { mode: options.apply ? 'applied' : 'dry-run', changedFiles: changes.length, restoredModels, backup };
743
+ }
744
+ finally {
745
+ release();
746
+ }
747
+ }
748
+ // ── Remove relation model fields while preserving defaults and Agent selections. ──
749
+ /** 关系层不再承载的模型字段(与 config-manager 合并时的剥离规则一致)。 */
750
+ const RELATION_MODEL_FIELDS = ['active_baseagent', 'model', 'models'];
751
+ /** 剥离后内容与新版本 schema 等价的直接前驱版本(relation v10 已撤销、从未发布)。 */
752
+ const RELATION_RESTAMP = { from: 9, to: 11 };
753
+ const DEFAULTS_RESTAMP = { from: 6, to: 5 };
754
+ function stripOwnFields(value, fields) {
755
+ const removed = [];
756
+ for (const field of fields) {
757
+ if (!hasOwn(value, field))
758
+ continue;
759
+ delete value[field];
760
+ removed.push(field);
761
+ }
762
+ return removed;
763
+ }
764
+ function stripRelationModelFields(input) {
765
+ const value = { ...input };
766
+ const removed = stripOwnFields(value, RELATION_MODEL_FIELDS);
767
+ if (isRecord(value.baseagents)) {
768
+ const baseagents = {};
769
+ for (const [baseagent, rawBlock] of Object.entries(value.baseagents)) {
770
+ if (!isRecord(rawBlock)) {
771
+ baseagents[baseagent] = rawBlock;
772
+ continue;
773
+ }
774
+ const block = { ...rawBlock };
775
+ for (const field of ['model', 'effort', 'reasoning']) {
776
+ if (!hasOwn(block, field))
777
+ continue;
778
+ delete block[field];
779
+ removed.push(`baseagents.${baseagent}.${field}`);
780
+ }
781
+ if (Object.keys(block).length > 0)
782
+ baseagents[baseagent] = block;
783
+ }
784
+ if (Object.keys(baseagents).length > 0)
785
+ value.baseagents = baseagents;
786
+ else
787
+ delete value.baseagents;
788
+ }
789
+ if (removed.length > 0 && value.$schema_version === RELATION_RESTAMP.from)
790
+ value.$schema_version = RELATION_RESTAMP.to;
791
+ return { value, removed };
792
+ }
793
+ function stripDefaultsModelFields(input) {
794
+ const value = { ...input };
795
+ const removed = stripOwnFields(value, ['models']);
796
+ if (isRecord(value.baseagents)) {
797
+ const baseagents = {};
798
+ for (const [name, block] of Object.entries(value.baseagents)) {
799
+ if (!isRecord(block)) {
800
+ baseagents[name] = block;
801
+ continue;
802
+ }
803
+ const next = { ...block };
804
+ if (hasOwn(next, 'reasoning')) {
805
+ if (!hasOwn(next, 'effort'))
806
+ next.effort = next.reasoning;
807
+ delete next.reasoning;
808
+ removed.push(`baseagents.${name}.reasoning`);
809
+ }
810
+ baseagents[name] = next;
811
+ }
812
+ value.baseagents = baseagents;
813
+ }
814
+ // v6 never shipped as a public defaults schema; restore the unpublished
815
+ // restamp to the released v5 schema while preserving model defaults.
816
+ if (value.$schema_version === DEFAULTS_RESTAMP.from)
817
+ value.$schema_version = DEFAULTS_RESTAMP.to;
818
+ return { value, removed };
819
+ }
820
+ function planAgentOnlyModelMigration(home) {
821
+ const changes = [];
822
+ const details = [];
823
+ const summary = {
824
+ configsScanned: 0,
825
+ filesChanged: 0,
826
+ relationFilesChanged: 0,
827
+ defaultsFieldsRemoved: 0,
828
+ defaultsBaseagentsAdded: 0,
829
+ ownerModelsPromoted: 0,
830
+ ownerEffortsPromoted: 0,
831
+ legacyModelsRestored: 0,
832
+ };
833
+ const agentsRoot = path.join(home, 'agents');
834
+ if (!fs.existsSync(agentsRoot))
835
+ return { home, changes, summary, details };
836
+ // 损坏的 JSON 不在此处理:保持原样,由各自的读取路径报告。
837
+ const plan = (file, strip) => {
838
+ summary.configsScanned += 1;
839
+ let parsed;
840
+ try {
841
+ parsed = readJson(file);
842
+ }
843
+ catch {
844
+ return [];
845
+ }
846
+ if (!isRecord(parsed.value))
847
+ return [];
848
+ const result = strip(parsed.value);
849
+ if (result.value.$schema_version === parsed.value.$schema_version && result.removed.length === 0)
850
+ return [];
851
+ changes.push({ file, kind: 'agent-only-model', before: parsed.text, after: jsonText(result.value) });
852
+ details.push({ file: path.relative(home, file), removed: result.removed });
853
+ summary.filesChanged += 1;
854
+ return result.removed;
855
+ };
856
+ const defaultsFile = path.join(agentsRoot, 'defaults.json');
857
+ if (fs.existsSync(defaultsFile))
858
+ summary.defaultsFieldsRemoved += plan(defaultsFile, stripDefaultsModelFields).length;
859
+ const pendingDefaults = changes.find(change => change.file === defaultsFile);
860
+ const defaultsRaw = pendingDefaults
861
+ ? JSON.parse(pendingDefaults.after)
862
+ : fs.existsSync(defaultsFile) ? readJson(defaultsFile).value : {};
863
+ if (!isRecord(defaultsRaw))
864
+ throw new Error(`${defaultsFile}: defaults configuration must be an object`);
865
+ const inheritedBlocks = baseagentSource(defaultsRaw) ?? {};
866
+ const agentEntries = fs.readdirSync(agentsRoot, { withFileTypes: true })
867
+ .sort((left, right) => left.name.localeCompare(right.name));
868
+ const declaredBaseagents = new Set();
869
+ for (const entry of agentEntries) {
870
+ if (!entry.isDirectory() || !validAid(entry.name))
871
+ continue;
872
+ const agentFile = path.join(agentsRoot, entry.name, 'config.json');
873
+ if (fs.existsSync(agentFile)) {
874
+ summary.configsScanned += 1;
875
+ try {
876
+ const parsed = readJson(agentFile);
877
+ const agent = parsed.value;
878
+ if (isRecord(agent)) {
879
+ const active = canonicalBaseagent(agent.active_baseagent);
880
+ if (active)
881
+ declaredBaseagents.add(active);
882
+ for (const name of baseagentNames(agent)) {
883
+ const canonical = canonicalBaseagent(name);
884
+ if (canonical)
885
+ declaredBaseagents.add(canonical);
886
+ }
887
+ const selected = active || canonicalBaseagent(defaultsRaw.active_baseagent);
888
+ if (selected) {
889
+ const ownerSelections = ownerRelationSelections(path.join(agentsRoot, entry.name, 'relations'), firstOwnerAid(agent), selected);
890
+ const sourceBlocks = baseagentSource(agent) ?? {};
891
+ const nextBlocks = { ...sourceBlocks };
892
+ const backends = new Set([selected]);
893
+ for (const rawName of Object.keys(sourceBlocks)) {
894
+ const name = canonicalBaseagent(rawName);
895
+ if (name)
896
+ backends.add(name);
897
+ }
898
+ for (const name of ownerSelections.keys())
899
+ backends.add(name);
900
+ const migrated = [];
901
+ for (const backend of backends) {
902
+ const block = isRecord(sourceBlocks[backend]) ? sourceBlocks[backend] : {};
903
+ const inherited = isRecord(inheritedBlocks[backend]) ? inheritedBlocks[backend] : {};
904
+ const owner = ownerSelections.get(backend);
905
+ const next = { ...block };
906
+ if (owner?.model !== undefined && owner.model !== block.model) {
907
+ next.model = owner.model;
908
+ migrated.push(`baseagents.${backend}.model from owner relation`);
909
+ summary.ownerModelsPromoted += 1;
910
+ }
911
+ if (owner?.effort !== undefined && owner.effort !== block.effort) {
912
+ next.effort = owner.effort;
913
+ migrated.push(`baseagents.${backend}.effort from owner relation`);
914
+ summary.ownerEffortsPromoted += 1;
915
+ }
916
+ const hasAgentModel = typeof block.model === 'string' && block.model.trim().length > 0;
917
+ const hasDefaultModel = typeof inherited.model === 'string' && inherited.model.trim().length > 0;
918
+ if (backend === selected && !hasAgentModel && !hasDefaultModel && owner?.model === undefined) {
919
+ const legacy = resolveLegacyBaseagentModelSelection(backend);
920
+ if (legacy) {
921
+ next.model = legacy.model;
922
+ migrated.push(`baseagents.${backend}.model from ${legacy.source}`);
923
+ summary.legacyModelsRestored += 1;
924
+ if (!block.effort && owner?.effort === undefined && legacy.effort) {
925
+ next.effort = legacy.effort;
926
+ migrated.push(`baseagents.${backend}.effort from ${legacy.source}`);
927
+ }
928
+ }
929
+ }
930
+ if (Object.keys(next).length > 0)
931
+ nextBlocks[backend] = next;
932
+ }
933
+ if (migrated.length > 0) {
934
+ changes.push({ file: agentFile, kind: 'agent-only-model', before: parsed.text,
935
+ after: jsonText({ ...agent, baseagents: nextBlocks }) });
936
+ details.push({ file: path.relative(home, agentFile), removed: [], migrated });
937
+ summary.filesChanged += 1;
938
+ }
939
+ }
940
+ }
941
+ }
942
+ catch {
943
+ // Do not replace unreadable Agent configuration with invented defaults.
944
+ }
945
+ }
946
+ for (const relationFile of walkRelationConfigs(path.join(agentsRoot, entry.name, 'relations'))) {
947
+ if (plan(relationFile, stripRelationModelFields).length > 0)
948
+ summary.relationFilesChanged += 1;
949
+ }
950
+ }
951
+ if (declaredBaseagents.size > 0) {
952
+ const pendingDefaults = changes.find(change => change.file === defaultsFile);
953
+ const original = fs.existsSync(defaultsFile) ? readJson(defaultsFile) : undefined;
954
+ const defaults = pendingDefaults ? JSON.parse(pendingDefaults.after) : original?.value;
955
+ if (defaults !== undefined && !isRecord(defaults)) {
956
+ throw new Error(`${defaultsFile}: defaults configuration must be an object`);
957
+ }
958
+ const value = defaults ? { ...defaults } : { $schema_version: 5 };
959
+ if (value.baseagents !== undefined && !isRecord(value.baseagents)) {
960
+ throw new Error(`${defaultsFile}: baseagents must be an object`);
961
+ }
962
+ const blocks = { ...(isRecord(value.baseagents) ? value.baseagents : {}) };
963
+ for (const name of [...declaredBaseagents].sort()) {
964
+ if (hasOwn(blocks, name))
965
+ continue;
966
+ blocks[name] = {};
967
+ summary.defaultsBaseagentsAdded += 1;
968
+ }
969
+ if (summary.defaultsBaseagentsAdded > 0) {
970
+ value.baseagents = blocks;
971
+ if (pendingDefaults)
972
+ pendingDefaults.after = jsonText(value);
973
+ else {
974
+ changes.push({ file: defaultsFile, kind: 'agent-only-model', before: original?.text ?? null, after: jsonText(value) });
975
+ details.push({ file: path.relative(home, defaultsFile), removed: [] });
976
+ summary.filesChanged += 1;
977
+ }
978
+ }
979
+ }
980
+ return { home, changes, summary, details };
981
+ }
982
+ /** Remove relation model parameters and register missing backend names in defaults. */
983
+ export function runAgentOnlyModelSchemaMigration(options = {}) {
984
+ const id = 'agent-only-model-v1';
985
+ const home = path.resolve(options.home || resolvePaths().root);
986
+ const release = acquireLock(home, id);
987
+ try {
988
+ assertDaemonStopped(home);
989
+ recoverJournal(home, id);
990
+ const plan = planAgentOnlyModelMigration(home);
991
+ const backup = options.apply ? applyMigration(plan, id) : null;
992
+ return {
993
+ ok: true,
994
+ mode: options.apply ? 'applied' : 'dry-run',
995
+ home,
996
+ changedFiles: plan.changes.length,
997
+ backup,
998
+ summary: plan.summary,
999
+ details: plan.details,
1000
+ };
1001
+ }
1002
+ finally {
1003
+ release();
1004
+ }
1005
+ }
1006
+ /** Apply the agent-only model migration before daemon registration. */
1007
+ export async function ensureAgentOnlyModelMigrationOnStartup() {
1008
+ const home = resolvePaths().root;
1009
+ try {
1010
+ const result = runAgentOnlyModelSchemaMigration({ home, apply: true });
1011
+ if (result.changedFiles === 0)
1012
+ return null;
1013
+ return {
1014
+ mode: 'applied',
1015
+ changedFiles: result.changedFiles,
1016
+ backup: result.backup,
1017
+ summary: result.summary,
1018
+ details: result.details,
1019
+ };
1020
+ }
1021
+ catch (error) {
1022
+ const detail = error instanceof Error ? error.message : String(error);
1023
+ throw new ConfigError('AGENT_ONLY_MODEL_MIGRATION_FAILED', `Automatic agent-only model schema migration failed: ${detail}`, { cause: error });
1024
+ }
1025
+ }
1026
+ // ── 网关信息迁入 providers.json,模型默认保留在 defaults ───────────────────────
1027
+ /** Agent/defaults baseagents.<ba> 中只允许由 providers.json 承载的连接字段。 */
1028
+ const AGENT_BASEAGENT_REMOVED_FIELDS = [
1029
+ 'apiKey', 'baseUrl', 'headers', 'queryParams',
1030
+ 'auxiliaryModel', 'auxiliaryEffort', 'approvalsReviewer',
1031
+ 'mode', 'useVertex', 'project', 'location',
1032
+ ];
1033
+ /**
1034
+ * Agent 级 config.json 顶层已迁走或早已废除、代码无读取点的字段。
1035
+ * response_modes(旧响应模式块)与 dispatch(旧广播开关)在现行实现里都没有消费者。
1036
+ */
1037
+ const AGENT_TOP_REMOVED_FIELDS = ['model', 'models', 'decision_model', 'response_modes', 'dispatch'];
1038
+ /** 剥离后内容与新版本 schema 等价的直接前驱版本。 */
1039
+ const AGENT_CONFIG_RESTAMP = { from: 13, to: 16 };
1040
+ const DEFAULTS_SCHEMA_TARGET = 5;
1041
+ /** 指认 provider 时各 baseagent 使用的服务类型。 */
1042
+ const BASEAGENT_SERVICE_TYPES = {
1043
+ claude: 'claude',
1044
+ codex: 'codex',
1045
+ gemini: 'gemini',
1046
+ ecagent: 'text',
1047
+ };
1048
+ /**
1049
+ * providers.json 中已存在同 baseUrl 且同凭证的服务时复用该条目,避免重复登记。
1050
+ * 端点相同但凭证不同必须单独建条目:否则显式 apiKey 会在迁移中丢失。
1051
+ */
1052
+ function findProviderForConnection(providers, connection) {
1053
+ for (const [providerId, provider] of Object.entries(providers)) {
1054
+ if (!isRecord(provider) || !isRecord(provider.common))
1055
+ continue;
1056
+ const baseUrl = typeof provider.common.baseUrl === 'string' ? provider.common.baseUrl.trim() : '';
1057
+ if (baseUrl !== connection.baseUrl)
1058
+ continue;
1059
+ const existingKey = typeof provider.common.apiKey === 'string' ? provider.common.apiKey.trim() : '';
1060
+ if (connection.apiKey && existingKey !== connection.apiKey)
1061
+ continue;
1062
+ const services = isRecord(provider.services) ? provider.services : {};
1063
+ if (Object.keys(services).length === 0 || hasOwn(services, connection.serviceType))
1064
+ return providerId;
1065
+ }
1066
+ return undefined;
1067
+ }
1068
+ function createProviderId(providers) {
1069
+ let sequence = 1;
1070
+ for (const providerId of Object.keys(providers)) {
1071
+ const match = /^provider-(\d+)$/u.exec(providerId);
1072
+ if (match)
1073
+ sequence = Math.max(sequence, Number(match[1]) + 1);
1074
+ }
1075
+ while (hasOwn(providers, `provider-${sequence}`))
1076
+ sequence += 1;
1077
+ return `provider-${sequence}`;
1078
+ }
1079
+ /** 旧写法 $ENV:NAME 统一成 providers 认识的整体引用 ${NAME};明文原样保留。 */
1080
+ function normalizeProviderSecret(value) {
1081
+ if (typeof value !== 'string')
1082
+ return undefined;
1083
+ const trimmed = value.trim();
1084
+ if (!trimmed)
1085
+ return undefined;
1086
+ const legacy = /^\$ENV:([A-Za-z_][A-Za-z0-9_]*)$/u.exec(trimmed);
1087
+ return legacy ? '${' + legacy[1] + '}' : trimmed;
1088
+ }
1089
+ function connectionFromBlock(block, serviceType) {
1090
+ const baseUrl = typeof block.baseUrl === 'string' ? block.baseUrl.trim() : '';
1091
+ if (!baseUrl || baseUrl.includes('placeholder'))
1092
+ return undefined;
1093
+ try {
1094
+ new URL(baseUrl);
1095
+ }
1096
+ catch {
1097
+ return undefined;
1098
+ }
1099
+ const headers = isRecord(block.headers) ? block.headers : undefined;
1100
+ const queryParams = isRecord(block.queryParams) ? block.queryParams : undefined;
1101
+ const apiKey = normalizeProviderSecret(block.apiKey);
1102
+ return {
1103
+ baseUrl,
1104
+ ...(apiKey ? { apiKey } : {}),
1105
+ ...(headers && Object.keys(headers).length > 0 ? { headers } : {}),
1106
+ ...(queryParams && Object.keys(queryParams).length > 0 ? { queryParams } : {}),
1107
+ serviceType,
1108
+ };
1109
+ }
1110
+ /** decision_model 的 base_url 是完整请求地址:拆成 provider 的 origin+目录 与 service path。 */
1111
+ function connectionFromDecisionModel(block) {
1112
+ const rawUrl = typeof block.base_url === 'string' ? block.base_url.trim() : '';
1113
+ if (!rawUrl)
1114
+ return undefined;
1115
+ let parsed;
1116
+ try {
1117
+ parsed = new URL(rawUrl);
1118
+ }
1119
+ catch {
1120
+ return undefined;
1121
+ }
1122
+ const trimmedPath = parsed.pathname.replace(/\/+$/u, '');
1123
+ const slash = trimmedPath.lastIndexOf('/');
1124
+ const basePath = slash > 0 ? trimmedPath.slice(0, slash) : '';
1125
+ const servicePath = slash > 0 ? trimmedPath.slice(slash + 1) : trimmedPath.replace(/^\//u, '');
1126
+ const headers = isRecord(block.headers) ? block.headers : undefined;
1127
+ const queryParams = isRecord(block.queryParams) ? block.queryParams : undefined;
1128
+ const apiKey = normalizeProviderSecret(block.apikey ?? block.apiKey);
1129
+ return {
1130
+ connection: {
1131
+ baseUrl: `${parsed.origin}${basePath}`,
1132
+ ...(apiKey ? { apiKey } : {}),
1133
+ ...(headers && Object.keys(headers).length > 0 ? { headers } : {}),
1134
+ ...(queryParams && Object.keys(queryParams).length > 0 ? { queryParams } : {}),
1135
+ serviceType: 'decision',
1136
+ },
1137
+ path: servicePath,
1138
+ };
1139
+ }
1140
+ function registerConnection(providers, connection, servicePath, summary) {
1141
+ const existing = findProviderForConnection(providers, connection);
1142
+ const providerId = existing ?? createProviderId(providers);
1143
+ const current = existing && isRecord(providers[existing]) ? providers[existing] : undefined;
1144
+ const common = current && isRecord(current.common) ? { ...current.common } : {};
1145
+ const services = current && isRecord(current.services) ? { ...current.services } : {};
1146
+ const nextCommon = {
1147
+ ...common,
1148
+ baseUrl: connection.baseUrl,
1149
+ ...(connection.apiKey && !common.apiKey ? { apiKey: connection.apiKey } : {}),
1150
+ ...(connection.headers ? { headers: connection.headers } : {}),
1151
+ ...(connection.queryParams ? { queryParams: connection.queryParams } : {}),
1152
+ };
1153
+ const nextServices = {
1154
+ ...services,
1155
+ [connection.serviceType]: {
1156
+ ...(isRecord(services[connection.serviceType]) ? services[connection.serviceType] : {}),
1157
+ ...(servicePath ? { path: servicePath } : {}),
1158
+ ...(connection.serviceType === 'decision' ? { style: 'systemone' } : {}),
1159
+ },
1160
+ };
1161
+ const nextProvider = { ...(current ?? {}), common: nextCommon, services: nextServices };
1162
+ if (!hasOwn(nextProvider, 'name'))
1163
+ nextProvider.name = providerId;
1164
+ providers[providerId] = nextProvider;
1165
+ if (existing)
1166
+ summary.providersUpdated += 1;
1167
+ else
1168
+ summary.providersCreated += 1;
1169
+ return providerId;
1170
+ }
1171
+ function planAgentModelProviderMigration(home) {
1172
+ const changes = [];
1173
+ const details = [];
1174
+ const summary = {
1175
+ configsScanned: 0,
1176
+ filesChanged: 0,
1177
+ providersCreated: 0,
1178
+ providersUpdated: 0,
1179
+ gatewayFieldsRemoved: 0,
1180
+ decisionModelsMigrated: 0,
1181
+ };
1182
+ const agentsRoot = path.join(home, 'agents');
1183
+ if (!fs.existsSync(agentsRoot))
1184
+ return { home, changes, summary, details };
1185
+ const defaultsFile = path.join(agentsRoot, 'defaults.json');
1186
+ const agentFiles = fs.readdirSync(agentsRoot, { withFileTypes: true })
1187
+ .filter(entry => entry.isDirectory() && validAid(entry.name))
1188
+ .sort((left, right) => left.name.localeCompare(right.name))
1189
+ .map(entry => path.join(agentsRoot, entry.name, 'config.json'))
1190
+ .filter(file => fs.existsSync(file));
1191
+ const parsed = new Map();
1192
+ for (const file of [defaultsFile, ...agentFiles]) {
1193
+ if (!fs.existsSync(file))
1194
+ continue;
1195
+ summary.configsScanned += 1;
1196
+ try {
1197
+ const loaded = readJson(file);
1198
+ if (isRecord(loaded.value))
1199
+ parsed.set(file, { value: loaded.value, text: loaded.text });
1200
+ }
1201
+ catch {
1202
+ // 损坏的 JSON 保持原样,由各自的读取路径报告。
1203
+ }
1204
+ }
1205
+ const providersFile = path.join(home, 'providers.json');
1206
+ let providers = {};
1207
+ if (fs.existsSync(providersFile)) {
1208
+ try {
1209
+ const raw = readJson(providersFile).value;
1210
+ if (isRecord(raw) && isRecord(raw.providers))
1211
+ providers = { ...raw.providers };
1212
+ }
1213
+ catch {
1214
+ providers = {};
1215
+ }
1216
+ }
1217
+ const providersBefore = fs.existsSync(providersFile) ? fs.readFileSync(providersFile, 'utf8') : null;
1218
+ const defaultConnections = new Map();
1219
+ const defaultBlocks = new Map();
1220
+ const defaultsEntry = parsed.get(defaultsFile);
1221
+ if (defaultsEntry && isRecord(defaultsEntry.value.baseagents)) {
1222
+ for (const [name, block] of Object.entries(defaultsEntry.value.baseagents)) {
1223
+ if (!isRecord(block))
1224
+ continue;
1225
+ defaultBlocks.set(name, block);
1226
+ const serviceType = BASEAGENT_SERVICE_TYPES[name];
1227
+ const connection = serviceType ? connectionFromBlock(block, serviceType) : undefined;
1228
+ if (connection)
1229
+ defaultConnections.set(name, registerConnection(providers, connection, '', summary));
1230
+ }
1231
+ }
1232
+ for (const [file, entry] of parsed) {
1233
+ const value = { ...entry.value };
1234
+ const removed = [];
1235
+ const isDefaults = file === defaultsFile;
1236
+ removed.push(...stripOwnFields(value, isDefaults
1237
+ ? ['models', 'decision_model']
1238
+ : AGENT_TOP_REMOVED_FIELDS));
1239
+ const baseagents = isRecord(entry.value.baseagents) ? entry.value.baseagents : undefined;
1240
+ if (baseagents) {
1241
+ const nextBaseagents = {};
1242
+ for (const [name, rawBlock] of Object.entries(baseagents)) {
1243
+ if (!isRecord(rawBlock)) {
1244
+ nextBaseagents[name] = rawBlock;
1245
+ continue;
1246
+ }
1247
+ const block = { ...rawBlock };
1248
+ const serviceType = BASEAGENT_SERVICE_TYPES[name];
1249
+ // Agent 级块常常只写 apiKey(端点沿用 defaults),这种情况下也要单独建 provider,
1250
+ // 否则显式凭证会在迁移里丢失。defaults 自身同样迁移旧连接字段,
1251
+ // 但保留 model/effort/fallback 与 runner 参数。
1252
+ const inheritedBaseUrl = typeof defaultBlocks.get(name)?.baseUrl === 'string'
1253
+ ? defaultBlocks.get(name).baseUrl
1254
+ : undefined;
1255
+ const own = serviceType
1256
+ ? connectionFromBlock(block, serviceType)
1257
+ ?? (normalizeProviderSecret(block.apiKey) && inheritedBaseUrl
1258
+ ? connectionFromBlock({ ...block, baseUrl: inheritedBaseUrl }, serviceType)
1259
+ : undefined)
1260
+ : undefined;
1261
+ removed.push(...stripOwnFields(block, AGENT_BASEAGENT_REMOVED_FIELDS)
1262
+ .map(field => `baseagents.${name}.${field}`));
1263
+ if (serviceType && block.provider === undefined) {
1264
+ const providerId = own
1265
+ ? registerConnection(providers, own, '', summary)
1266
+ : defaultConnections.get(name);
1267
+ if (providerId)
1268
+ block.provider = providerId;
1269
+ }
1270
+ nextBaseagents[name] = block;
1271
+ }
1272
+ value.baseagents = nextBaseagents;
1273
+ }
1274
+ // decision_model migrates into Services.decision at the same scope; do not
1275
+ // copy defaults into every Agent because the config merge already inherits it.
1276
+ const ownDecision = isRecord(entry.value.decision_model) ? entry.value.decision_model : undefined;
1277
+ const decisionMigrated = ownDecision ? connectionFromDecisionModel(ownDecision) : undefined;
1278
+ let decisionSelection;
1279
+ if (decisionMigrated) {
1280
+ const providerId = registerConnection(providers, decisionMigrated.connection, decisionMigrated.path, summary);
1281
+ const model = typeof ownDecision.model === 'string' ? ownDecision.model.trim() : '';
1282
+ decisionSelection = { provider: providerId, ...(model ? { model } : {}) };
1283
+ summary.decisionModelsMigrated += 1;
1284
+ }
1285
+ if (decisionSelection) {
1286
+ const services = isRecord(value.Services) ? { ...value.Services } : {};
1287
+ if (!isRecord(services.decision)) {
1288
+ value.Services = { ...services, decision: decisionSelection };
1289
+ }
1290
+ }
1291
+ if (isDefaults) {
1292
+ value.$schema_version = DEFAULTS_SCHEMA_TARGET;
1293
+ }
1294
+ else if (typeof value.$schema_version === 'number' && value.$schema_version < AGENT_CONFIG_RESTAMP.to) {
1295
+ // Model/provider migration preserves the v16 admission fields unchanged.
1296
+ value.$schema_version = AGENT_CONFIG_RESTAMP.to;
1297
+ }
1298
+ summary.gatewayFieldsRemoved += removed.length;
1299
+ const nextText = jsonText(value);
1300
+ if (nextText === entry.text)
1301
+ continue;
1302
+ changes.push({ file, kind: 'agent-only-model', before: entry.text, after: nextText });
1303
+ details.push({ file: path.relative(home, file), removed });
1304
+ summary.filesChanged += 1;
1305
+ }
1306
+ if (Object.keys(providers).length > 0) {
1307
+ const nextText = jsonText({ $schema_version: 1, providers });
1308
+ if (nextText !== providersBefore) {
1309
+ changes.push({ file: providersFile, kind: 'agent-only-model', before: providersBefore, after: nextText });
1310
+ details.push({ file: 'providers.json', removed: [] });
1311
+ summary.filesChanged += 1;
1312
+ }
1313
+ }
1314
+ return { home, changes, summary, details };
1315
+ }
1316
+ /** Plan or apply the migration that moves gateway credentials into providers.json. */
1317
+ export function runAgentModelProviderSchemaMigration(options = {}) {
1318
+ const id = 'agent-model-provider-v1';
1319
+ const home = path.resolve(options.home || resolvePaths().root);
1320
+ const release = acquireLock(home, id);
1321
+ try {
1322
+ assertDaemonStopped(home);
1323
+ recoverJournal(home, id);
1324
+ const plan = planAgentModelProviderMigration(home);
1325
+ const backup = options.apply ? applyMigration(plan, id) : null;
1326
+ return {
1327
+ ok: true,
1328
+ mode: options.apply ? 'applied' : 'dry-run',
1329
+ home,
1330
+ changedFiles: plan.changes.length,
1331
+ backup,
1332
+ summary: plan.summary,
1333
+ details: plan.details,
1334
+ };
1335
+ }
1336
+ finally {
1337
+ release();
1338
+ }
1339
+ }
1340
+ /** Apply the model-provider migration before daemon registration. */
1341
+ export async function ensureAgentModelProviderMigrationOnStartup() {
1342
+ const home = resolvePaths().root;
1343
+ try {
1344
+ const result = runAgentModelProviderSchemaMigration({ home, apply: true });
1345
+ if (result.changedFiles === 0)
1346
+ return null;
1347
+ return {
1348
+ mode: 'applied',
1349
+ changedFiles: result.changedFiles,
1350
+ backup: result.backup,
1351
+ summary: result.summary,
1352
+ details: result.details,
1353
+ };
1354
+ }
1355
+ catch (error) {
1356
+ const detail = error instanceof Error ? error.message : String(error);
1357
+ throw new ConfigError('AGENT_MODEL_PROVIDER_MIGRATION_FAILED', `Automatic agent model provider migration failed: ${detail}`, { cause: error });
1358
+ }
1359
+ }
1360
+ function planProviderServiceTypeMigration(home) {
1361
+ const changes = [];
1362
+ const details = [];
1363
+ const summary = { configsScanned: 0, filesChanged: 0, fieldsRemoved: 0 };
1364
+ const agentsRoot = path.join(home, 'agents');
1365
+ if (!fs.existsSync(agentsRoot))
1366
+ return { home, changes, summary, details };
1367
+ const defaultsFile = path.join(agentsRoot, 'defaults.json');
1368
+ const agentFiles = fs.readdirSync(agentsRoot, { withFileTypes: true })
1369
+ .filter(entry => entry.isDirectory() && validAid(entry.name))
1370
+ .sort((left, right) => left.name.localeCompare(right.name))
1371
+ .map(entry => path.join(agentsRoot, entry.name, 'config.json'))
1372
+ .filter(file => fs.existsSync(file));
1373
+ for (const file of [defaultsFile, ...agentFiles]) {
1374
+ if (!fs.existsSync(file))
1375
+ continue;
1376
+ summary.configsScanned += 1;
1377
+ let parsed;
1378
+ try {
1379
+ parsed = readJson(file);
1380
+ }
1381
+ catch {
1382
+ continue;
1383
+ }
1384
+ if (!isRecord(parsed.value) || !isRecord(parsed.value.baseagents))
1385
+ continue;
1386
+ const value = { ...parsed.value };
1387
+ const baseagents = {};
1388
+ const removed = [];
1389
+ for (const [baseagent, rawBlock] of Object.entries(parsed.value.baseagents)) {
1390
+ if (!isRecord(rawBlock) || !hasOwn(rawBlock, 'providerServiceType')) {
1391
+ baseagents[baseagent] = rawBlock;
1392
+ continue;
1393
+ }
1394
+ const block = { ...rawBlock };
1395
+ delete block.providerServiceType;
1396
+ baseagents[baseagent] = block;
1397
+ removed.push(`baseagents.${baseagent}.providerServiceType`);
1398
+ }
1399
+ if (removed.length === 0)
1400
+ continue;
1401
+ value.baseagents = baseagents;
1402
+ changes.push({ file, kind: 'provider-service-type', before: parsed.text, after: jsonText(value) });
1403
+ details.push({ file: path.relative(home, file), removed });
1404
+ summary.filesChanged += 1;
1405
+ summary.fieldsRemoved += removed.length;
1406
+ }
1407
+ return { home, changes, summary, details };
1408
+ }
1409
+ export function runProviderServiceTypeSchemaMigration(options = {}) {
1410
+ const id = 'provider-service-type-v1';
1411
+ const home = path.resolve(options.home || resolvePaths().root);
1412
+ const release = acquireLock(home, id);
1413
+ try {
1414
+ assertDaemonStopped(home);
1415
+ recoverJournal(home, id);
1416
+ const plan = planProviderServiceTypeMigration(home);
1417
+ const backup = options.apply ? applyMigration(plan, id) : null;
1418
+ return {
1419
+ ok: true,
1420
+ mode: options.apply ? 'applied' : 'dry-run',
1421
+ home,
1422
+ changedFiles: plan.changes.length,
1423
+ backup,
1424
+ summary: plan.summary,
1425
+ details: plan.details,
1426
+ };
1427
+ }
1428
+ finally {
1429
+ release();
1430
+ }
1431
+ }
1432
+ export async function ensureProviderServiceTypeMigrationOnStartup() {
1433
+ const home = resolvePaths().root;
1434
+ try {
1435
+ const result = runProviderServiceTypeSchemaMigration({ home, apply: true });
1436
+ return result.changedFiles === 0 ? null : result;
1437
+ }
1438
+ catch (error) {
1439
+ const detail = error instanceof Error ? error.message : String(error);
1440
+ throw new ConfigError('PROVIDER_SERVICE_TYPE_MIGRATION_FAILED', `Automatic provider service type migration failed: ${detail}`, { cause: error });
1441
+ }
1442
+ }
1443
+ // ── 关系配置版本重打:v8/v9 → v11 ────────────────────────────────────────────
1444
+ /**
1445
+ * 关系配置在 v10/v11 只删了可选字段,schema 始终 `additionalProperties: true` 且无必填项,
1446
+ * 所以旧版本文件的内容本来就是合法 v11;这一步只把版本号重打到当前值,
1447
+ * 顺带清掉早已无人读取的 `sessionIdleSec`。
1448
+ */
1449
+ const RELATION_CONFIG_TARGET_VERSION = 11;
1450
+ /** 关系配置里已无运行时读取方的遗留字段(v8 的会话闲置周期,v9 起由 sessionLoop 取代)。 */
1451
+ const RELATION_RETIRED_FIELDS = ['sessionIdleSec'];
1452
+ function restampRelationConfig(input) {
1453
+ const value = { ...input };
1454
+ const removed = stripOwnFields(value, RELATION_RETIRED_FIELDS);
1455
+ if (typeof value.$schema_version === 'number' && value.$schema_version < RELATION_CONFIG_TARGET_VERSION) {
1456
+ value.$schema_version = RELATION_CONFIG_TARGET_VERSION;
1457
+ }
1458
+ return { value, removed };
1459
+ }
1460
+ function planRelationConfigVersionMigration(home) {
1461
+ const changes = [];
1462
+ const details = [];
1463
+ const summary = { configsScanned: 0, filesChanged: 0, fieldsRemoved: 0 };
1464
+ const agentsRoot = path.join(home, 'agents');
1465
+ if (!fs.existsSync(agentsRoot))
1466
+ return { home, changes, summary, details };
1467
+ for (const entry of fs.readdirSync(agentsRoot, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
1468
+ if (!entry.isDirectory() || !validAid(entry.name))
1469
+ continue;
1470
+ for (const file of walkRelationConfigs(path.join(agentsRoot, entry.name, 'relations'))) {
1471
+ summary.configsScanned += 1;
1472
+ // 损坏的 JSON 保持原样,由各自的读取路径报告。
1473
+ let parsed;
1474
+ try {
1475
+ parsed = readJson(file);
1476
+ }
1477
+ catch {
1478
+ continue;
1479
+ }
1480
+ if (!isRecord(parsed.value))
1481
+ continue;
1482
+ const result = restampRelationConfig(parsed.value);
1483
+ const nextText = jsonText(result.value);
1484
+ if (nextText === parsed.text)
1485
+ continue;
1486
+ changes.push({ file, kind: 'agent-only-model', before: parsed.text, after: nextText });
1487
+ details.push({ file: path.relative(home, file), removed: result.removed });
1488
+ summary.filesChanged += 1;
1489
+ summary.fieldsRemoved += result.removed.length;
1490
+ }
1491
+ }
1492
+ return { home, changes, summary, details };
1493
+ }
1494
+ /** Plan or apply the relation-config version restamp (v8/v9 → v11). */
1495
+ export function runRelationConfigVersionSchemaMigration(options = {}) {
1496
+ const id = 'relation-config-v11-v1';
1497
+ const home = path.resolve(options.home || resolvePaths().root);
1498
+ const release = acquireLock(home, id);
1499
+ try {
1500
+ assertDaemonStopped(home);
1501
+ recoverJournal(home, id);
1502
+ const plan = planRelationConfigVersionMigration(home);
1503
+ const backup = options.apply ? applyMigration(plan, id) : null;
1504
+ return {
1505
+ ok: true,
1506
+ mode: options.apply ? 'applied' : 'dry-run',
1507
+ home,
1508
+ changedFiles: plan.changes.length,
1509
+ backup,
1510
+ summary: plan.summary,
1511
+ details: plan.details,
1512
+ };
1513
+ }
1514
+ finally {
1515
+ release();
1516
+ }
1517
+ }
1518
+ /** Apply the relation-config version migration before daemon registration. */
1519
+ export async function ensureRelationConfigVersionMigrationOnStartup() {
1520
+ const home = resolvePaths().root;
1521
+ try {
1522
+ const result = runRelationConfigVersionSchemaMigration({ home, apply: true });
1523
+ if (result.changedFiles === 0)
1524
+ return null;
1525
+ return {
1526
+ mode: 'applied',
1527
+ changedFiles: result.changedFiles,
1528
+ backup: result.backup,
1529
+ summary: result.summary,
1530
+ details: result.details,
1531
+ };
1532
+ }
1533
+ catch (error) {
1534
+ const detail = error instanceof Error ? error.message : String(error);
1535
+ throw new ConfigError('RELATION_CONFIG_VERSION_MIGRATION_FAILED', `Automatic relation-config version migration failed: ${detail}`, { cause: error });
1536
+ }
1537
+ }