evolcore 0.0.49 → 0.0.50

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 (250) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/bin/ecmsg.js +9 -4
  3. package/dist/ability/caller/authorization.js +21 -0
  4. package/dist/ability/caller/command.js +164 -0
  5. package/dist/ability/caller/contract.js +102 -0
  6. package/dist/ability/caller/daemon.js +158 -0
  7. package/dist/ability/caller/service.js +380 -0
  8. package/dist/ability/command-contract.js +5 -0
  9. package/dist/ability/daemon.js +5 -1
  10. package/dist/ability/interop-v1.js +10 -3
  11. package/dist/ability/management.js +1 -0
  12. package/dist/agent-template/jobs.js +173 -1
  13. package/dist/agent-template/runtime.js +280 -6
  14. package/dist/agent-template/service.js +1159 -40
  15. package/dist/agent-template/types.js +2 -1
  16. package/dist/agents/baseagent-availability.js +27 -3
  17. package/dist/agents/baseagent-capability-adapter.js +102 -0
  18. package/dist/agents/baseagent-plugin-descriptor.js +274 -0
  19. package/dist/agents/baseagent-plugin-loader.js +145 -0
  20. package/dist/agents/baseagent.js +68 -2
  21. package/dist/agents/claude-gateway/agent-registration.js +389 -0
  22. package/dist/agents/claude-gateway/binding.js +96 -0
  23. package/dist/agents/claude-gateway/inbox.js +138 -0
  24. package/dist/agents/claude-gateway/index.js +125 -0
  25. package/dist/agents/claude-gateway/listing.js +330 -0
  26. package/dist/agents/claude-gateway/router.js +328 -0
  27. package/dist/agents/claude-gateway/sessions.js +128 -0
  28. package/dist/agents/claude-gateway/terminal.js +250 -0
  29. package/dist/agents/claude-gateway/transcript.js +272 -0
  30. package/dist/agents/claude-gateway/types.js +14 -0
  31. package/dist/agents/claude-runner.js +6 -10
  32. package/dist/agents/codex-runner.js +4 -1
  33. package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
  34. package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
  35. package/dist/agents/gemini/index.js +51 -0
  36. package/dist/aun/aid/control-aid.js +52 -32
  37. package/dist/aun/group/invite-service.js +6 -36
  38. package/dist/aun/group/operations.js +6 -0
  39. package/dist/aun/msg/mention-schema.js +1 -1
  40. package/dist/aun/msg/p2p.js +29 -1
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +537 -189
  44. package/dist/cli/ability-command.js +42 -0
  45. package/dist/cli/agent-command.js +20 -1
  46. package/dist/cli/agent-create.js +78 -18
  47. package/dist/cli/agent-template.js +5 -3
  48. package/dist/cli/agent.js +91 -0
  49. package/dist/cli/aun-commands.js +92 -34
  50. package/dist/cli/bench.js +5 -2
  51. package/dist/cli/config.js +22 -6
  52. package/dist/cli/daemon-commands.js +245 -101
  53. package/dist/cli/ecmsg-gateway.js +11 -9
  54. package/dist/cli/index.js +23 -4
  55. package/dist/cli/init.js +39 -63
  56. package/dist/cli/managed-command-guard.js +1 -0
  57. package/dist/cli/menu-client.js +32 -7
  58. package/dist/cli/pay-command.js +30 -0
  59. package/dist/cli/provider-command.js +6 -2
  60. package/dist/cli/restart-monitor.js +2 -2
  61. package/dist/cli/services-command.js +11 -9
  62. package/dist/cli/thread-command.js +78 -12
  63. package/dist/config/access-policy.js +16 -3
  64. package/dist/config/config-field-policy.js +17 -8
  65. package/dist/config/config-manager.js +86 -46
  66. package/dist/config/config-operation-service.js +22 -1
  67. package/dist/config/gateway-config.js +9 -8
  68. package/dist/config/owner-config.js +0 -16
  69. package/dist/config/peer-role-resolver.js +1 -7
  70. package/dist/config/providers-config.js +99 -16
  71. package/dist/config/providers-management.js +35 -19
  72. package/dist/config/resolved-config-op.js +1 -42
  73. package/dist/config/schema-migration.js +78 -5
  74. package/dist/config/schema-registry.js +52 -7
  75. package/dist/config-store.js +1309 -17
  76. package/dist/core/agent-application-service.js +220 -1
  77. package/dist/core/agent-ipc-registration.js +19 -2
  78. package/dist/core/agent-reload-coordinator.js +5 -0
  79. package/dist/core/agent-runtime.js +198 -54
  80. package/dist/core/auth/agent-delegation.js +14 -0
  81. package/dist/core/auth/operation-authorizer.js +16 -1
  82. package/dist/core/auth/operation-catalog.js +50 -7
  83. package/dist/core/baseagent-loader.js +30 -3
  84. package/dist/core/capability/capability-manager.js +16 -7
  85. package/dist/core/channel-runtime.js +4 -2
  86. package/dist/core/command/agent-control.js +20 -2
  87. package/dist/core/command/agent-template-menu.js +4 -3
  88. package/dist/core/command/cli-intent-parser.js +15 -0
  89. package/dist/core/command/menu-catalog.js +20 -4
  90. package/dist/core/command/menu-file-path.js +70 -0
  91. package/dist/core/command/menu-handler.js +91 -72
  92. package/dist/core/command/menu-protocol.js +5 -0
  93. package/dist/core/command/menu-query-batch.js +2 -2
  94. package/dist/core/command/private-mention-menu.js +71 -0
  95. package/dist/core/command/slash-handler.js +17 -26
  96. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  97. package/dist/core/command/topic-slash.js +7 -1
  98. package/dist/core/daemon-bootstrap.js +0 -4
  99. package/dist/core/daemon-control.js +2 -1
  100. package/dist/core/daemon-lifecycle.js +13 -5
  101. package/dist/core/evolagent-registry.js +12 -7
  102. package/dist/core/handoff/runtime.js +1 -1
  103. package/dist/core/host-snapshot.js +8 -3
  104. package/dist/core/initialization/service.js +3 -0
  105. package/dist/core/interaction-router.js +130 -0
  106. package/dist/core/ipc-registration.js +4 -0
  107. package/dist/core/memory/consolidation-context.js +2 -1
  108. package/dist/core/memory/consolidation.js +35 -64
  109. package/dist/core/message/aun-ipc-sender.js +98 -21
  110. package/dist/core/message/aun-request-registry.js +31 -0
  111. package/dist/core/message/message-bridge.js +105 -6
  112. package/dist/core/message/message-log.js +8 -0
  113. package/dist/core/message/message-queue.js +5 -3
  114. package/dist/core/message/peer-mode.js +15 -4
  115. package/dist/core/message/response-engine.js +23 -8
  116. package/dist/core/message/send-options.js +37 -3
  117. package/dist/core/message/send-routing.js +11 -7
  118. package/dist/core/model/model-catalog.js +5 -5
  119. package/dist/core/ownership/owner-resolver.js +12 -86
  120. package/dist/core/pack-auth.js +4 -0
  121. package/dist/core/permission/ec-command-parser.js +182 -58
  122. package/dist/core/permission/protected-paths.js +64 -9
  123. package/dist/core/permission/services-path-acl.js +9 -2
  124. package/dist/core/permission/tool-policy.js +21 -9
  125. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  126. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  127. package/dist/core/session/session-manager.js +47 -10
  128. package/dist/core/session/session-mapper.js +16 -0
  129. package/dist/core/skill/index-generator.js +2 -3
  130. package/dist/core/skill/switch-resolver.js +3 -0
  131. package/dist/core/thread/command-parser.js +4 -1
  132. package/dist/core/thread/ipc-operation.js +4 -2
  133. package/dist/core/thread/thread-operation.js +25 -10
  134. package/dist/core/thread/thread-service.js +294 -55
  135. package/dist/core/thread/topic-id.js +52 -2
  136. package/dist/core/thread/types.js +15 -1
  137. package/dist/eck/kit-renderer.js +2 -1
  138. package/dist/ecweb/basic-settings-service.js +5 -9
  139. package/dist/ecweb/providers-service.js +4 -2
  140. package/dist/index.js +116 -41
  141. package/dist/ipc.js +58 -2
  142. package/dist/paths.js +48 -1
  143. package/dist/pay/command.js +38 -0
  144. package/dist/pay/protocol.js +136 -0
  145. package/dist/pay/runtime.js +188 -0
  146. package/dist/pay/service.js +384 -0
  147. package/dist/pay/store.js +81 -0
  148. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  149. package/dist/services/dispatcher.js +23 -5
  150. package/dist/services/host/main.js +388 -0
  151. package/dist/services/host/protocol.js +118 -0
  152. package/dist/services/host/resident.js +310 -0
  153. package/dist/services/host-client.js +386 -0
  154. package/dist/services/host-deploy.js +180 -0
  155. package/dist/services/host-launch.js +117 -0
  156. package/dist/services/host-recycle.js +203 -0
  157. package/dist/services/host-runtime.js +802 -0
  158. package/dist/services/idempotency.js +44 -86
  159. package/dist/services/index-generator.js +4 -3
  160. package/dist/services/index.js +176 -18
  161. package/dist/services/ipc-operation.js +204 -44
  162. package/dist/services/script-runner.js +515 -83
  163. package/dist/services/validation.js +109 -4
  164. package/dist/trigger/application-service.js +6 -4
  165. package/dist/trigger/local-files.js +19 -9
  166. package/dist/trigger/scheduler.js +22 -12
  167. package/dist/trigger/script-sandbox.js +51 -20
  168. package/dist/utils/aid-bind.js +3 -0
  169. package/dist/utils/evolcore-version.js +2 -2
  170. package/dist/utils/host-info.js +73 -0
  171. package/dist/utils/logger.js +2 -2
  172. package/dist/utils/media-cache.js +190 -43
  173. package/dist/utils/restart-safety.js +14 -1
  174. package/dist/utils/system-memory.js +113 -25
  175. package/dist/utils/systemd-lifecycle.js +154 -0
  176. package/dist/utils/windows-shell-trust.js +7 -3
  177. package/kits/docs/INDEX.md +3 -2
  178. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
  179. package/kits/docs/channels/aun.md +1 -1
  180. package/kits/docs/evolcore/INDEX.md +7 -6
  181. package/kits/docs/evolcore/agent.md +36 -1
  182. package/kits/docs/evolcore/aid.md +20 -3
  183. package/kits/docs/evolcore/config.md +1 -1
  184. package/kits/docs/evolcore/group.md +2 -1
  185. package/kits/docs/evolcore/memory-tags.md +2 -0
  186. package/kits/docs/evolcore/menu-client.md +3 -3
  187. package/kits/docs/evolcore/menu-protocol.md +7 -0
  188. package/kits/docs/evolcore/model.md +3 -0
  189. package/kits/docs/evolcore/msg.md +68 -10
  190. package/kits/docs/evolcore/pay.md +34 -0
  191. package/kits/docs/evolcore/provider.md +21 -0
  192. package/kits/docs/evolcore/services.md +46 -18
  193. package/kits/docs/evolcore/thread-chain.md +2 -0
  194. package/kits/docs/evolcore/tool-authorization.md +10 -0
  195. package/kits/rules/01-overview.md +11 -32
  196. package/kits/rules/02-navigation.md +7 -0
  197. package/kits/rules/06-channel.md +3 -3
  198. package/kits/schemas/_meta.json +38 -5
  199. package/kits/schemas/agent-config.schema.21.json +974 -0
  200. package/kits/schemas/agent-config.schema.22.json +977 -0
  201. package/kits/schemas/agent-config.schema.23.json +958 -0
  202. package/kits/schemas/daemon.schema.10.json +373 -0
  203. package/kits/schemas/daemon.schema.9.json +12 -0
  204. package/kits/schemas/defaults.schema.7.json +472 -0
  205. package/kits/schemas/providers.schema.3.json +18 -2
  206. package/kits/schemas/relation-config.schema.13.json +289 -0
  207. package/kits/skills/.switches.json +13 -1
  208. package/kits/skills/ability/SKILL.md +229 -34
  209. package/kits/skills/ability/STRUCTURE.md +333 -0
  210. package/kits/skills/ability/references/cli.md +208 -0
  211. package/kits/skills/ability/references/development.md +107 -37
  212. package/kits/skills/ability/references/management.md +106 -46
  213. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  214. package/kits/skills/agent-output-cards/SKILL.md +12 -5
  215. package/kits/skills/ec-group/SKILL.md +8 -6
  216. package/kits/skills/ec-group/TASK.md +186 -0
  217. package/kits/skills/ec-group/WORKLOG.md +180 -0
  218. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  219. package/kits/skills/ec-pay/SKILL.md +101 -0
  220. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  221. package/kits/skills/ec-provider/SKILL.md +1 -1
  222. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  223. package/kits/skills/ec-service-call/SKILL.md +135 -0
  224. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  225. package/kits/skills/ec-trigger/SKILL.md +1 -1
  226. package/kits/templates/memory-consolidation/notes.md +2 -2
  227. package/kits/templates/memory-consolidation/workflow.md +46 -0
  228. package/kits/templates/system-fragments/channel.md +13 -4
  229. package/kits/templates/system-fragments/commands.md +4 -3
  230. package/kits/templates/system-fragments/reply.md +1 -0
  231. package/kits/templates/system-fragments/session.md +1 -1
  232. package/kits/templates/system-fragments/thread.md +27 -129
  233. package/kits/templates/system-fragments/venue.md +16 -0
  234. package/package.json +4 -5
  235. package/scripts/agent-template/inspect.mjs +37 -23
  236. package/scripts/agent-template/overlay.mjs +20 -2
  237. package/scripts/agent-template/shared/common.mjs +16 -4
  238. package/scripts/agent-template/shared/team-schema.json +20 -4
  239. package/scripts/agent-template/shared/template-contract.mjs +53 -13
  240. package/scripts/agent-template/shared/template-package.mjs +90 -26
  241. package/scripts/agent-template/shared/template-runtime.mjs +111 -1
  242. package/scripts/agent-template/shared/template.mjs +65 -7
  243. package/scripts/agent-template/team-pack.mjs +89 -33
  244. package/scripts/agent-template/team-preview.mjs +249 -5
  245. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  246. package/kits/docs/evolcore/ability.md +0 -185
  247. package/kits/skills/ability/references/calling.md +0 -56
  248. package/kits/skills/ability/references/contract-checklist.md +0 -37
  249. package/kits/skills/ability/references/recovery.md +0 -27
  250. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -1,5 +1,6 @@
1
1
  export const TEMPLATE_ACTIONS = ['inspect', 'build', 'push', 'pull', 'preview', 'deploy',
2
- 'status', 'resume', 'cancel', 'capabilities'];
2
+ 'status', 'resume', 'cancel', 'capabilities', 'register-team', 'team-members', 'prepare-member-install', 'resume-member-join',
3
+ 'update-status', 'check-update', 'bind-update-source', 'confirm-update-source', 'preview-update', 'read-update-notice'];
3
4
  export function templateJobAids(job) {
4
5
  return Object.values(job.members).flatMap(member => member.aid ? [member.aid] : []);
5
6
  }
@@ -1,4 +1,6 @@
1
- import { normalizeBaseagent } from './baseagent.js';
1
+ import { HARDCODED_BASEAGENT_NAMES, listSupportedBaseagents, normalizeBaseagent } from './baseagent.js';
2
+ import { loadDefaults } from '../config-store.js';
3
+ import { getBaseagentPluginDescriptor } from './baseagent-plugin-descriptor.js';
2
4
  import { commandExists, commandExistsAsync } from '../utils/cross-platform.js';
3
5
  import { getCodexAppServerAvailability, getCodexAppServerAvailabilityAsync } from './codex-runner.js';
4
6
  import { probeBundledClaudeVersion, probeBundledClaudeVersionAsync, resolveBundledClaudeExecutable } from './claude-runner.js';
@@ -21,14 +23,26 @@ export const AUTO_BASEAGENT_CANDIDATES = ['claude', 'codex', 'gemini'];
21
23
  * CLI with app-server; ecagent is bundled with EvolCore.
22
24
  */
23
25
  export function detectAvailableBaseagents(codexAvailability = getCodexAppServerAvailability()) {
24
- return BASEAGENT_CANDIDATES.filter((baseagent) => {
26
+ const flags = loadDefaults()?.baseagents;
27
+ return listSupportedBaseagents().filter((baseagent) => {
28
+ const enabled = flags?.[baseagent]?.enabled;
29
+ if (!HARDCODED_BASEAGENT_NAMES.has(baseagent)
30
+ && enabled !== undefined && enabled !== true)
31
+ return false;
25
32
  if (baseagent === 'ecagent')
26
33
  return true;
27
34
  if (baseagent === 'codex')
28
35
  return codexAvailability.available;
29
36
  if (baseagent === 'claude')
30
37
  return claudeExecutable() !== undefined;
31
- return commandExists(baseagent);
38
+ if (baseagent === 'gemini')
39
+ return commandExists(baseagent);
40
+ try {
41
+ return getBaseagentPluginDescriptor(baseagent)?.probe?.().available === true;
42
+ }
43
+ catch {
44
+ return false;
45
+ }
32
46
  });
33
47
  }
34
48
  export function detectBaseagentDetails(codexAvailability = getCodexAppServerAvailability()) {
@@ -80,6 +94,16 @@ function baseagentDetails(codexAvailability, claude, claudeVersion, gemini) {
80
94
  detected: true,
81
95
  detectionSource: ['内置'],
82
96
  },
97
+ ...listSupportedBaseagents().filter(id => !BASEAGENT_CANDIDATES.includes(id)).map(id => {
98
+ try {
99
+ const probe = getBaseagentPluginDescriptor(id)?.probe?.();
100
+ return { id, detected: probe?.available === true, detectionSource: probe?.available ? ['plugin probe'] : [],
101
+ version: probe?.version, reason: probe?.reason ?? (probe ? undefined : 'Plugin has no dependency probe') };
102
+ }
103
+ catch (error) {
104
+ return { id, detected: false, detectionSource: [], reason: String(error) };
105
+ }
106
+ }),
83
107
  ];
84
108
  }
85
109
  /** Currently loaded runners only; configured on-demand choices are provided separately. */
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Baseagent 能力适配器
3
+ *
4
+ * 提供运行时能力查询接口,用于:
5
+ * - Host 判断某个能力是否可用(如决定是否降级、拦截工具)
6
+ * - 不做运行时探测,只读声明 + 环境匹配
7
+ */
8
+ /**
9
+ * Baseagent 能力适配器
10
+ *
11
+ * 根据插件的能力声明和当前运行环境,提供能力查询接口
12
+ */
13
+ export class BaseagentCapabilityAdapter {
14
+ descriptor;
15
+ envKey;
16
+ capabilityMap;
17
+ /**
18
+ * @param descriptor 插件描述符
19
+ * @param envKey 环境键(默认为 process.platform)
20
+ */
21
+ constructor(descriptor, envKey) {
22
+ this.descriptor = descriptor;
23
+ this.envKey = envKey ?? process.platform;
24
+ // 构建能力 ID → 声明的映射
25
+ this.capabilityMap = new Map();
26
+ for (const cap of descriptor.declaredCapabilities) {
27
+ this.capabilityMap.set(cap.id, cap);
28
+ }
29
+ }
30
+ /**
31
+ * 查询能力是否可用
32
+ *
33
+ * @param id 能力 ID(如 B01、C03)
34
+ * @returns 当前环境下该能力是否可用
35
+ */
36
+ isAvailable(id) {
37
+ const cap = this.capabilityMap.get(id);
38
+ if (!cap) {
39
+ // 未声明的能力视为不支持
40
+ return false;
41
+ }
42
+ // 解析当前环境的实际可用性
43
+ const envOverride = cap.environments?.[this.envKey];
44
+ const actualAvailability = envOverride?.availability ?? cap.availability;
45
+ const verification = envOverride?.verification ?? cap.verification;
46
+ return this.descriptor.environments.some(environment => environment.os === this.envKey)
47
+ && actualAvailability === 'available' && verification === 'verified'
48
+ && cap.implementation !== 'unsupported';
49
+ }
50
+ /**
51
+ * 获取能力的实现方式
52
+ *
53
+ * @param id 能力 ID
54
+ * @returns 实现方式(native/adapted/host-only/unsupported),未声明返回 null
55
+ */
56
+ getImplementation(id) {
57
+ const cap = this.capabilityMap.get(id);
58
+ return cap?.implementation ?? null;
59
+ }
60
+ /**
61
+ * 获取能力的完整信息
62
+ *
63
+ * @param id 能力 ID
64
+ * @returns 能力信息对象,未声明返回 null
65
+ */
66
+ getCapability(id) {
67
+ const cap = this.capabilityMap.get(id);
68
+ if (!cap) {
69
+ return null;
70
+ }
71
+ // 解析当前环境的实际值
72
+ const envOverride = cap.environments?.[this.envKey];
73
+ const actualAvailability = envOverride?.availability ?? cap.availability;
74
+ const actualVerification = envOverride?.verification ?? cap.verification;
75
+ const actualNotes = envOverride?.notes ?? cap.notes;
76
+ const supportedEnvironment = this.descriptor.environments.some(environment => environment.os === this.envKey);
77
+ return {
78
+ id: cap.id,
79
+ level: cap.level,
80
+ implementation: cap.implementation,
81
+ availability: supportedEnvironment ? actualAvailability : 'unavailable',
82
+ verification: supportedEnvironment ? actualVerification : 'unverified',
83
+ notes: supportedEnvironment ? actualNotes : 'Plugin environment has not been verified: ' + this.envKey,
84
+ };
85
+ }
86
+ /**
87
+ * 列举所有已声明的能力 ID
88
+ *
89
+ * @returns 能力 ID 列表
90
+ */
91
+ listCapabilities() {
92
+ return Array.from(this.capabilityMap.keys());
93
+ }
94
+ /**
95
+ * 获取当前环境键
96
+ *
97
+ * @returns 环境键(如 'linux', 'darwin', 'win32')
98
+ */
99
+ getCurrentEnvironment() {
100
+ return this.envKey;
101
+ }
102
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Baseagent 插件描述符类型定义与校验函数
3
+ *
4
+ * 插件接入协议:
5
+ * - 一个目录即一个插件(src/agents/<name>/index.ts 存在即被发现)
6
+ * - 自描述:通过 descriptor 声明身份、能力、环境支持
7
+ * - 无中央清单:启动期扫描,自动发现与注册
8
+ * - 环境匹配:未实测环境不启用
9
+ * - 失败隔离:单个插件失败不影响其他插件和 daemon 启动
10
+ */
11
+ import { createRequire } from 'node:module';
12
+ // ============================================================================
13
+ // 常量
14
+ // ============================================================================
15
+ /** B 类能力 ID 列表(B01–B14,必须全部声明) */
16
+ export const REQUIRED_B_CAPABILITIES = [
17
+ 'B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07',
18
+ 'B08', 'B09', 'B10', 'B11', 'B12', 'B13', 'B14',
19
+ ];
20
+ /** 插件名称格式正则(小写字母开头,可含数字和连字符,1-32 字符) */
21
+ export const PLUGIN_NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
22
+ /**
23
+ * 校验插件描述符
24
+ *
25
+ * @param descriptor 插件描述符
26
+ * @param dirname 插件目录名
27
+ * @param builtinNames 内置 baseagent 名称集合
28
+ * @param builtinAliases 内置 baseagent 别名集合
29
+ * @returns 校验结果
30
+ */
31
+ export function validatePluginDescriptor(descriptor, dirname, builtinNames, builtinAliases, currentOS = process.platform) {
32
+ const errors = [];
33
+ if (!isRecord(descriptor)) {
34
+ return { valid: false, errors: ['Descriptor must be an object'] };
35
+ }
36
+ const d = descriptor;
37
+ // === 1. 基础字段校验 ===
38
+ if (!d.name || typeof d.name !== 'string') {
39
+ errors.push('Missing or invalid field: name');
40
+ }
41
+ else {
42
+ // 名称格式
43
+ if (!PLUGIN_NAME_PATTERN.test(d.name)) {
44
+ errors.push(`Invalid name format: ${d.name} (must match ${PLUGIN_NAME_PATTERN})`);
45
+ }
46
+ // 名称与目录名一致
47
+ if (d.name !== dirname) {
48
+ errors.push(`Name mismatch: descriptor.name="${d.name}" but directory="${dirname}"`);
49
+ }
50
+ // 与内置冲突
51
+ if (builtinNames.has(d.name)) {
52
+ errors.push(`Name conflicts with builtin baseagent: ${d.name}`);
53
+ }
54
+ }
55
+ if (typeof d.displayName !== 'string' || !d.displayName.trim()) {
56
+ errors.push('Missing or invalid field: displayName');
57
+ }
58
+ if (!Array.isArray(d.aliases)) {
59
+ errors.push('Missing or invalid field: aliases (must be array)');
60
+ }
61
+ else {
62
+ // 别名冲突检查
63
+ for (const alias of d.aliases) {
64
+ if (typeof alias !== 'string') {
65
+ errors.push(`Invalid alias: ${alias} (must be string)`);
66
+ continue;
67
+ }
68
+ const normalized = normalizeAlias(alias);
69
+ if (!normalized)
70
+ errors.push('Aliases must not be empty');
71
+ if (builtinNames.has(normalized) || builtinAliases.has(normalized)) {
72
+ errors.push(`Alias conflicts with builtin: ${alias}`);
73
+ }
74
+ }
75
+ }
76
+ if (!isRecord(d.configSchema)) {
77
+ errors.push('Missing or invalid field: configSchema');
78
+ }
79
+ else {
80
+ try {
81
+ compileConfigSchema(d.configSchema);
82
+ }
83
+ catch (error) {
84
+ errors.push(`Invalid configSchema: ${String(error)}`);
85
+ }
86
+ for (const field of ['apiKey', 'baseUrl', 'headers', 'queryParams']) {
87
+ if (isRecord(d.configSchema.properties) && Object.hasOwn(d.configSchema.properties, field)) {
88
+ errors.push(`configSchema.${field}: connection settings belong in providers.json`);
89
+ }
90
+ }
91
+ }
92
+ if (d.defaultModel !== undefined && (typeof d.defaultModel !== 'string' || !d.defaultModel.trim())) {
93
+ errors.push('defaultModel must be a non-empty string');
94
+ }
95
+ if (d.probe !== undefined && typeof d.probe !== 'function')
96
+ errors.push('probe must be a function');
97
+ // === 2. 环境声明校验 ===
98
+ if (!Array.isArray(d.environments) || d.environments.length === 0) {
99
+ errors.push('environments must be non-empty array');
100
+ }
101
+ else {
102
+ for (const env of d.environments) {
103
+ if (!isRecord(env)) {
104
+ errors.push('Environment must be an object');
105
+ continue;
106
+ }
107
+ if (!env.os || !['linux', 'darwin', 'win32'].includes(env.os)) {
108
+ errors.push(`Invalid environment.os: ${env.os}`);
109
+ }
110
+ if (!isRecord(env.probedWith)) {
111
+ errors.push('environment.probedWith is required');
112
+ }
113
+ else if (typeof env.probedWith.at !== 'string'
114
+ || !/^\d{4}-\d\d-\d\dT/.test(env.probedWith.at) || !Number.isFinite(Date.parse(env.probedWith.at))) {
115
+ errors.push('environment.probedWith.at must be an ISO timestamp');
116
+ }
117
+ }
118
+ }
119
+ // === 3. 能力声明校验 ===
120
+ if (!Array.isArray(d.declaredCapabilities)) {
121
+ errors.push('declaredCapabilities must be array');
122
+ }
123
+ else {
124
+ const declaredIds = new Set();
125
+ for (const card of d.declaredCapabilities) {
126
+ if (!isRecord(card)) {
127
+ errors.push('Capability must be an object');
128
+ continue;
129
+ }
130
+ if (typeof card.id !== 'string' || !/^(?:[BCX]\d{2}|EXT-[a-z][a-z0-9-]*)$/.test(card.id)) {
131
+ errors.push('Invalid capability ID');
132
+ continue;
133
+ }
134
+ if (declaredIds.has(card.id))
135
+ errors.push(`Duplicate capability ID: ${card.id}`);
136
+ declaredIds.add(card.id);
137
+ if (!['B', 'C', 'X'].includes(card.level)
138
+ || (!card.id.startsWith('EXT-') && card.level !== card.id[0])) {
139
+ errors.push(`Capability ${card.id}: level does not match ID`);
140
+ }
141
+ if (!['native', 'adapted', 'host-only', 'unsupported'].includes(card.implementation)) {
142
+ errors.push(`Capability ${card.id}: invalid implementation`);
143
+ }
144
+ for (const [environment, values] of Object.entries({ default: card, ...(card.environments ?? {}) })) {
145
+ if (!isRecord(values)) {
146
+ errors.push(`Capability ${card.id}: invalid environment override`);
147
+ continue;
148
+ }
149
+ if (values.availability !== undefined
150
+ && !['available', 'unavailable', 'unknown'].includes(values.availability)) {
151
+ errors.push(`Capability ${card.id}: invalid availability on ${environment}`);
152
+ }
153
+ if (values.verification !== undefined && !['verified', 'unverified'].includes(values.verification)) {
154
+ errors.push(`Capability ${card.id}: invalid verification on ${environment}`);
155
+ }
156
+ }
157
+ if (!['available', 'unavailable', 'unknown'].includes(card.availability)
158
+ || !['verified', 'unverified'].includes(card.verification)) {
159
+ errors.push(`Capability ${card.id}: availability and verification are required`);
160
+ }
161
+ }
162
+ // B 类能力完整性检查
163
+ const missingBCapabilities = REQUIRED_B_CAPABILITIES.filter((id) => !declaredIds.has(id));
164
+ if (missingBCapabilities.length > 0) {
165
+ errors.push(`Missing required B capabilities: ${missingBCapabilities.join(', ')}`);
166
+ }
167
+ // 能力一致性检查:当前环境下 B 类能力不能有 unknown + available + unverified 组合
168
+ for (const cap of d.declaredCapabilities) {
169
+ if (!isRecord(cap))
170
+ continue;
171
+ // 解析当前环境的实际值
172
+ const envOverride = cap.environments?.[currentOS];
173
+ const actualAvailability = envOverride?.availability ?? cap.availability;
174
+ const actualVerification = envOverride?.verification ?? cap.verification;
175
+ if (cap.implementation === 'unsupported' && actualAvailability === 'available') {
176
+ errors.push(`Capability ${cap.id}: unsupported implementation cannot be available`);
177
+ }
178
+ // 不允许:available + unverified
179
+ if (actualAvailability === 'available' && actualVerification === 'unverified') {
180
+ errors.push(`Capability ${cap.id}: available but unverified on ${currentOS} ` +
181
+ `(must run probe script first)`);
182
+ }
183
+ // 不允许:unknown availability for B capabilities
184
+ if (cap.id?.startsWith('B') && actualAvailability === 'unknown') {
185
+ errors.push(`Capability ${cap.id}: unknown availability on ${currentOS}`);
186
+ }
187
+ }
188
+ }
189
+ // === 4. 工厂函数校验 ===
190
+ if (typeof d.createRunner !== 'function') {
191
+ errors.push('createRunner must be a function');
192
+ }
193
+ if (d.createSessionAdapter !== undefined && typeof d.createSessionAdapter !== 'function') {
194
+ errors.push('createSessionAdapter must be a function or undefined');
195
+ }
196
+ if (d.createCapabilityProvider !== undefined && typeof d.createCapabilityProvider !== 'function') {
197
+ errors.push('createCapabilityProvider must be a function or undefined');
198
+ }
199
+ return {
200
+ valid: errors.length === 0,
201
+ errors,
202
+ };
203
+ }
204
+ /**
205
+ * 检查当前环境是否在插件的支持列表中
206
+ *
207
+ * @param descriptor 插件描述符
208
+ * @returns 是否支持当前环境
209
+ */
210
+ export function isCurrentEnvironmentSupported(descriptor) {
211
+ const currentOS = process.platform;
212
+ return descriptor.environments.some((env) => env.os === currentOS);
213
+ }
214
+ /**
215
+ * 获取已实测的操作系统列表(用于日志)
216
+ *
217
+ * @param descriptor 插件描述符
218
+ * @returns 操作系统列表字符串
219
+ */
220
+ export function getTestedEnvironments(descriptor) {
221
+ return descriptor.environments.map((env) => env.os).join(', ');
222
+ }
223
+ function isRecord(value) {
224
+ return !!value && typeof value === 'object' && !Array.isArray(value);
225
+ }
226
+ function normalizeAlias(value) {
227
+ return value.trim().toLowerCase().replace(/_/g, '-');
228
+ }
229
+ const requireDependency = createRequire(import.meta.url);
230
+ let schemaCompiler;
231
+ function compileConfigSchema(schema) {
232
+ const Constructor = requireDependency('ajv');
233
+ schemaCompiler ??= new Constructor({ strict: false, allErrors: true, useDefaults: false });
234
+ return schemaCompiler.compile(schema);
235
+ }
236
+ const descriptors = new Map();
237
+ /** Metadata is available before Agent configs are loaded; registration does not start a runner. */
238
+ export function registerBaseagentPluginDescriptor(descriptor) {
239
+ const previous = descriptors.get(descriptor.name);
240
+ const entry = { descriptor, validate: compileConfigSchema(descriptor.configSchema) };
241
+ descriptors.set(descriptor.name, entry);
242
+ return () => {
243
+ if (descriptors.get(descriptor.name) !== entry)
244
+ return;
245
+ if (previous)
246
+ descriptors.set(descriptor.name, previous);
247
+ else
248
+ descriptors.delete(descriptor.name);
249
+ };
250
+ }
251
+ export function getBaseagentPluginDescriptor(name) {
252
+ return descriptors.get(name)?.descriptor;
253
+ }
254
+ export function validateBaseagentPluginConfigs(blocks, defaults = false) {
255
+ if (!isRecord(blocks))
256
+ return [];
257
+ const errors = [];
258
+ for (const [name, raw] of Object.entries(blocks)) {
259
+ const entry = descriptors.get(name);
260
+ if (!entry)
261
+ continue;
262
+ if (isRecord(raw)) {
263
+ for (const field of ['apiKey', 'baseUrl', 'headers', 'queryParams']) {
264
+ if (Object.hasOwn(raw, field))
265
+ errors.push(`/baseagents/${name}/${field}: use providers.json`);
266
+ }
267
+ }
268
+ const value = defaults && isRecord(raw) ? Object.fromEntries(Object.entries(raw).filter(([k]) => k !== 'enabled')) : raw;
269
+ if (!entry.validate(value)) {
270
+ errors.push(...(entry.validate.errors ?? []).map(error => `/baseagents/${name}${error.instancePath} ${error.message}`));
271
+ }
272
+ }
273
+ return errors;
274
+ }
@@ -0,0 +1,145 @@
1
+ /** Package-owned metadata discovery, followed by atomic runtime component registration. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { registerCapabilityProvider } from '../core/capability/capability-manager.js';
6
+ import { loadDefaults } from '../config-store.js';
7
+ import { getPackageRoot } from '../paths.js';
8
+ import { logger } from '../utils/logger.js';
9
+ import { HARDCODED_BASEAGENT_NAMES, registerExternalBaseagentAliases, reservedBaseagentAliases, } from './baseagent.js';
10
+ import { PLUGIN_NAME_PATTERN, validatePluginDescriptor, isCurrentEnvironmentSupported, getTestedEnvironments, registerBaseagentPluginDescriptor, } from './baseagent-plugin-descriptor.js';
11
+ /** Discover metadata before loading Agent configs. This never calls component factories. */
12
+ export async function discoverBaseagentPlugins(options = {}) {
13
+ const packageRoot = getPackageRoot();
14
+ // Follow the executing tree, including a dev checkout containing stale dist output.
15
+ const source = path.extname(fileURLToPath(import.meta.url)) === '.ts';
16
+ const preferred = path.join(packageRoot, source ? 'src' : 'dist', 'agents');
17
+ const fallback = path.join(packageRoot, 'dist', 'agents');
18
+ const scanRoot = fs.existsSync(preferred) ? preferred : fallback;
19
+ const descriptors = [];
20
+ let entries;
21
+ let flags;
22
+ try {
23
+ if (!fs.existsSync(scanRoot))
24
+ return descriptors;
25
+ entries = fs.readdirSync(scanRoot, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
26
+ flags = (loadDefaults()?.baseagents ?? {});
27
+ }
28
+ catch (error) {
29
+ logger.error('[BaseagentPlugins] Cannot discover package plugins:', error);
30
+ return descriptors;
31
+ }
32
+ for (const entry of entries) {
33
+ if (!entry.isDirectory() || !PLUGIN_NAME_PATTERN.test(entry.name)
34
+ || HARDCODED_BASEAGENT_NAMES.has(entry.name))
35
+ continue;
36
+ const enabled = flags[entry.name]?.enabled;
37
+ if (enabled !== undefined && typeof enabled !== 'boolean') {
38
+ try {
39
+ registerExternalBaseagentAliases(entry.name, entry.name, []);
40
+ }
41
+ catch (error) {
42
+ logger.warn('[BaseagentPlugins] Cannot reserve disabled plugin identity:', error);
43
+ }
44
+ logger.warn('[BaseagentPlugins] Invalid enabled flag: ' + entry.name);
45
+ continue;
46
+ }
47
+ if (enabled === false) {
48
+ try {
49
+ registerExternalBaseagentAliases(entry.name, entry.name, []);
50
+ }
51
+ catch (error) {
52
+ logger.warn('[BaseagentPlugins] Cannot reserve disabled plugin identity:', error);
53
+ }
54
+ if (!options.quiet)
55
+ logger.info('Skipping disabled plugin: ' + entry.name);
56
+ continue;
57
+ }
58
+ const tsPath = path.join(scanRoot, entry.name, 'index.ts');
59
+ const indexPath = source && fs.existsSync(tsPath) ? tsPath : path.join(scanRoot, entry.name, 'index.js');
60
+ try {
61
+ if (!fs.existsSync(indexPath) || !fs.lstatSync(indexPath).isFile())
62
+ continue;
63
+ }
64
+ catch (error) {
65
+ logger.warn('[BaseagentPlugins] Cannot inspect ' + indexPath + ':', error);
66
+ continue;
67
+ }
68
+ let undoAliases;
69
+ try {
70
+ const descriptor = (await import(pathToFileURL(indexPath).href)).default;
71
+ const validation = validatePluginDescriptor(descriptor, entry.name, HARDCODED_BASEAGENT_NAMES, reservedBaseagentAliases());
72
+ if (!validation.valid) {
73
+ logger.warn('[BaseagentPlugins] ' + entry.name + ': validation failed', validation.errors);
74
+ continue;
75
+ }
76
+ if (!isCurrentEnvironmentSupported(descriptor)) {
77
+ if (!options.quiet)
78
+ logger.info('Plugin ' + entry.name + ': environment not supported '
79
+ + '(current: ' + process.platform + ', tested: ' + getTestedEnvironments(descriptor) + ')');
80
+ continue;
81
+ }
82
+ undoAliases = registerExternalBaseagentAliases(descriptor.name, descriptor.displayName, descriptor.aliases);
83
+ registerBaseagentPluginDescriptor(descriptor);
84
+ descriptors.push(descriptor);
85
+ }
86
+ catch (error) {
87
+ undoAliases?.();
88
+ logger.error('[BaseagentPlugins] Cannot discover ' + entry.name + ':', error);
89
+ }
90
+ }
91
+ return descriptors;
92
+ }
93
+ /** All factories finish before anything is published. Metadata remains known if a runtime factory fails. */
94
+ export async function loadExternalBaseagentPlugins(agentLoader, sessionManager, descriptors) {
95
+ let loaded = 0;
96
+ for (const descriptor of descriptors ?? await discoverBaseagentPlugins()) {
97
+ const undo = [];
98
+ let sessionAdapter;
99
+ try {
100
+ const runner = descriptor.createRunner();
101
+ if (!runner || runner.name !== descriptor.name
102
+ || typeof runner.isEnabled !== 'function' || typeof runner.createAgent !== 'function') {
103
+ throw new Error('Runner factory returned an invalid identity or interface');
104
+ }
105
+ sessionAdapter = descriptor.createSessionAdapter?.();
106
+ if (descriptor.createSessionAdapter)
107
+ validateComponent(sessionAdapter, descriptor.name, ['checkExists', 'getFileInfo', 'readFirstMessage', 'readLastUserMessage', 'scanCliSessions']);
108
+ const provider = descriptor.createCapabilityProvider?.();
109
+ if (descriptor.createCapabilityProvider)
110
+ validateComponent(provider, descriptor.name, ['getSupport', 'discover']);
111
+ const keepUndo = (value) => { if (typeof value === 'function')
112
+ undo.push(value); };
113
+ keepUndo(agentLoader.register(runner));
114
+ if (sessionAdapter)
115
+ keepUndo(sessionManager.registerFileAdapter(sessionAdapter));
116
+ if (provider)
117
+ keepUndo(registerCapabilityProvider(provider));
118
+ loaded++;
119
+ logger.info('Loaded baseagent plugin: ' + descriptor.name + ' (' + descriptor.displayName + ')');
120
+ }
121
+ catch (error) {
122
+ for (const rollback of undo.reverse()) {
123
+ try {
124
+ rollback();
125
+ }
126
+ catch (failure) {
127
+ logger.error('[BaseagentPlugins] Rollback failed:', failure);
128
+ }
129
+ }
130
+ try {
131
+ sessionAdapter?.close?.();
132
+ }
133
+ catch (failure) {
134
+ logger.warn('[BaseagentPlugins] Cleanup failed:', failure);
135
+ }
136
+ logger.error('[BaseagentPlugins] Cannot register ' + descriptor.name + ':', error);
137
+ }
138
+ }
139
+ return loaded;
140
+ }
141
+ function validateComponent(value, name, methods) {
142
+ if (!value || value.baseagent !== name || methods.some(method => typeof value[method] !== 'function')) {
143
+ throw new Error('Component factory returned an invalid identity or interface: ' + name);
144
+ }
145
+ }