evolcore 0.0.43-test.6 → 0.0.43-test.8

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 (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -0,0 +1,129 @@
1
+ /**
2
+ * 共享函数:create 与 overlay 都要用到的逻辑。
3
+ * 从 prepare.mjs 抽出,不包含破坏性操作(删除、整份替换)。
4
+ * 接口说明见 docs/template-share-interface.md 第三节;改签名或行为需要双方同意。
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { renderText, renderValue } from './template-runtime.mjs';
9
+
10
+ /**
11
+ * 替换 {{x.y}} 占位符;vars 里没有的保留原文。
12
+ * @param {string} text
13
+ * @param {Record<string, string>} vars
14
+ * @returns {string}
15
+ */
16
+ export function renderPlaceholders(text, vars) {
17
+ return renderText(text, vars);
18
+ }
19
+
20
+ /**
21
+ * 最小 JSON Schema 校验:只覆盖模板 schema 用到的关键字。
22
+ * 完整规则仍由 EvolCore 的 validate() 在生成后复核,这里先给出「模板作者写错了哪一行」。
23
+ * @param {unknown} value
24
+ * @param {object} schema
25
+ * @param {string} at
26
+ * @returns {string[]}
27
+ */
28
+ export function validateAgainstSchema(value, schema, at = '$') {
29
+ const errors = [];
30
+ if (!schema || typeof schema !== 'object') return [`${at}: schema missing`];
31
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
32
+ if (types.length) {
33
+ const actual = Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;
34
+ const matches = types.some(t => t === actual || (t === 'integer' && Number.isInteger(value)) || (t === 'number' && typeof value === 'number'));
35
+ if (!matches) return [`${at}: expected ${types.join('|')}, got ${actual}`];
36
+ }
37
+ if (schema.enum && !schema.enum.includes(value)) errors.push(`${at}: must be one of ${schema.enum.join(', ')}`);
38
+ if (typeof value === 'string') {
39
+ if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${at}: shorter than ${schema.minLength}`);
40
+ if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(`${at}: does not match ${schema.pattern}`);
41
+ }
42
+ if (typeof value === 'number' && schema.minimum !== undefined && value < schema.minimum) errors.push(`${at}: below ${schema.minimum}`);
43
+ if (Array.isArray(value)) {
44
+ if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${at}: needs at least ${schema.minItems} items`);
45
+ if (schema.items) value.forEach((v, i) => errors.push(...validateAgainstSchema(v, schema.items, `${at}[${i}]`)));
46
+ }
47
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
48
+ for (const req of schema.required ?? []) if (!Object.hasOwn(value, req)) errors.push(`${at}: missing "${req}"`);
49
+ const props = schema.properties ?? {};
50
+ for (const [k, v] of Object.entries(value)) {
51
+ if (Object.hasOwn(props, k)) errors.push(...validateAgainstSchema(v, props[k], `${at}.${k}`));
52
+ else if (schema.additionalProperties === false) errors.push(`${at}.${k}: not allowed`);
53
+ else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
54
+ errors.push(...validateAgainstSchema(v, schema.additionalProperties, `${at}.${k}`));
55
+ }
56
+ }
57
+ }
58
+ return errors;
59
+ }
60
+
61
+ /**
62
+ * 把 baseagents.<x>.provider 的 { id, name } 换成 mapping[id] ?? id;字符串原样保留。
63
+ * 返回新对象,不改入参。mapping 形如 { "<模板里的 provider ID>": "<本机 providers.json 的 key>" }。
64
+ * @param {object} config
65
+ * @param {Record<string, string>} mapping
66
+ * @returns {object}
67
+ */
68
+ export function resolveProviderRefs(config, mapping = {}) {
69
+ if (!config.baseagents || typeof config.baseagents !== 'object') return config;
70
+ const out = { ...config, baseagents: {} };
71
+ for (const [ba, def] of Object.entries(config.baseagents)) {
72
+ if (!def || typeof def !== 'object') { out.baseagents[ba] = def; continue; }
73
+ const provider = def.provider;
74
+ if (typeof provider === 'string' || !provider || typeof provider !== 'object') {
75
+ out.baseagents[ba] = def;
76
+ } else {
77
+ const id = typeof provider.id === 'string' ? provider.id : '';
78
+ out.baseagents[ba] = { ...def, provider: mapping[id] ?? id };
79
+ }
80
+ }
81
+ return out;
82
+ }
83
+
84
+ /**
85
+ * agent 选用的 provider 是否可用:是字符串、在 providers 里有定义、带有该基座能用的服务类型
86
+ * (ecagent 为 ecagent 或 text,其余基座为同名服务)。
87
+ * baseagent 缺省取 config.active_baseagent ?? defaults.active_baseagent ?? 'claude';
88
+ * provider 取 config.baseagents[b].provider ?? defaults.baseagents[b].provider。
89
+ * providers 是 providers.json 的 .providers 对象,defaults 是 agents/defaults.json。
90
+ * @param {{ config: object, defaults?: object, providers?: object, baseagent?: string }} opts
91
+ * @returns {{ ok: boolean, detail: { baseagent: string, provider: string|null, defined: string[], services: string[], need: string[] } }}
92
+ */
93
+ export function checkAgentProvider({ config, defaults = {}, providers = {}, baseagent }) {
94
+ const ba = baseagent ?? config.active_baseagent ?? defaults.active_baseagent ?? 'claude';
95
+ const provider = config.baseagents?.[ba]?.provider ?? defaults.baseagents?.[ba]?.provider;
96
+ const providerIds = Object.keys(providers);
97
+ const services = Object.keys((typeof provider === 'string' && providers[provider]?.services) || {});
98
+ const need = ba === 'ecagent' ? ['ecagent', 'text'] : [ba];
99
+ const ok = typeof provider === 'string' && providerIds.includes(provider) && need.some(t => services.includes(t));
100
+ return { ok, detail: { baseagent: ba, provider: provider ?? null, defined: providerIds, services, need } };
101
+ }
102
+
103
+ /**
104
+ * 读 <templateRoot>/agents/<key>/triggers/<id>/trigger.json,用 vars + { 'agent.aid': aid } 渲染,
105
+ * 经 ec.validateTrigger 校验,并核对 agentAid、id。不落盘。
106
+ * 每个 trigger 记一条 rec.check(`trigger[<key>/<id>]`, …),名称与现在相同。
107
+ * @param {{ templateRoot: string, key: string, aid: string, vars: Record<string, string>, ec: any, rec: any }} opts
108
+ * @returns {Array<{ id: string, definition: object }>}
109
+ */
110
+ export function buildAgentTriggers({ templateRoot, key, aid, vars, ec, rec }) {
111
+ const triggersDir = path.join(templateRoot, 'agents', key, 'triggers');
112
+ if (!fs.existsSync(triggersDir)) return [];
113
+ const agentVars = { ...vars, 'agent.aid': aid };
114
+ const triggers = [];
115
+ for (const id of fs.readdirSync(triggersDir, { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name)) {
116
+ const file = path.join(triggersDir, id, 'trigger.json');
117
+ if (!fs.existsSync(file)) { rec.check(`trigger[${key}/${id}]`, false, 'trigger.json missing'); continue; }
118
+ let rendered;
119
+ try { rendered = renderValue(JSON.parse(fs.readFileSync(file, 'utf8')), agentVars); } catch (err) { rec.check(`trigger[${key}/${id}]`, false, err.message); continue; }
120
+ try {
121
+ const def = ec.validateTrigger(rendered);
122
+ rec.check(`trigger[${key}/${id}]`, def.agentAid === aid && def.id === id, { agentAid: def.agentAid, id: def.id });
123
+ triggers.push({ id, definition: rendered });
124
+ } catch (err) {
125
+ rec.check(`trigger[${key}/${id}]`, false, err.message);
126
+ }
127
+ }
128
+ return triggers;
129
+ }
@@ -0,0 +1,70 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "urn:evolcore:agent-template:team:v1",
4
+ "title": "Agent 团队模板 v1",
5
+ "type": "object",
6
+ "required": ["$schema_version", "name", "version", "host", "agents"],
7
+ "additionalProperties": true,
8
+ "properties": {
9
+ "$schema_version": { "type": "integer", "const": 1, "default": 1, "title": "格式版本" },
10
+ "name": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]{0,63}$", "title": "模板标识", "description": "稳定标识,对应 PACKAGE.id;兼容既有 PA Team 标识" },
11
+ "version": { "type": "string", "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$", "default": "1.0.0", "title": "模板版本" },
12
+ "title": { "type": "string", "minLength": 1, "maxLength": 64, "title": "模板显示名", "description": "发布时对应 PACKAGE.name;省略时使用模板标识" },
13
+ "description": { "type": "string", "maxLength": 500, "title": "模板说明" },
14
+ "issuer": { "type": "string", "pattern": "^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$", "title": "签发域", "description": "创建身份时使用,覆盖安装不改变身份" },
15
+ "owner": { "type": "object", "title": "创建时的 Owner", "additionalProperties": false, "properties": { "name": { "type": "string", "minLength": 1, "title": "显示名" } } },
16
+ "host": {
17
+ "type": "object", "title": "主机", "required": ["platform"], "additionalProperties": false,
18
+ "properties": {
19
+ "platform": { "type": "array", "title": "支持平台", "minItems": 1, "uniqueItems": true, "default": ["linux"], "items": { "type": "string", "enum": ["linux", "darwin", "win32"] } },
20
+ "config": { "type": "object", "title": "创建时的主机配置", "description": "仅创建流程使用,运行时继续由 EvolCore 配置 schema 校验", "additionalProperties": true, "properties": { "aun": { "type": "object", "title": "AUN 配置" }, "services": { "type": "array", "title": "本地服务", "items": { "type": "object" } } } }
21
+ }
22
+ },
23
+ "agents": {
24
+ "type": "array", "title": "团队成员", "minItems": 1,
25
+ "items": {
26
+ "type": "object", "required": ["key", "profile"], "additionalProperties": true,
27
+ "properties": {
28
+ "key": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]{0,31}$", "title": "成员标识", "description": "对应资源目录与目标映射中的 key" },
29
+ "profile": {
30
+ "type": "object", "title": "公开名片", "required": ["name"], "additionalProperties": false,
31
+ "properties": {
32
+ "name": { "type": "string", "minLength": 1, "maxLength": 64, "title": "显示名" },
33
+ "description": { "type": "string", "title": "简介" },
34
+ "avatar": { "type": "string", "title": "头像地址" },
35
+ "tags": { "type": "array", "title": "标签", "items": { "type": "string", "minLength": 1 } },
36
+ "exttype": { "type": "string", "title": "扩展类型" },
37
+ "type": { "type": "string", "title": "来源类型", "readOnly": true, "description": "仅为旧包来源信息,不能覆盖目标身份类型" }
38
+ }
39
+ },
40
+ "config": {
41
+ "type": "object", "title": "Agent 配置", "additionalProperties": true,
42
+ "description": "保留扩展配置;创建与覆盖分别执行本模式的能力边界和完整运行时校验",
43
+ "properties": {
44
+ "active_baseagent": { "type": "string", "title": "默认基座", "enum": ["claude", "codex", "gemini", "ecagent"] },
45
+ "baseagents": {
46
+ "type": "object", "title": "基座配置", "additionalProperties": {
47
+ "type": "object", "additionalProperties": true,
48
+ "properties": {
49
+ "provider": { "type": ["string", "object"], "title": "Provider 引用", "required": ["id"], "additionalProperties": false, "properties": { "id": { "type": "string", "pattern": "^provider-[0-9]{8}$" }, "name": { "type": "string" } } },
50
+ "model": { "type": "string", "minLength": 1, "title": "模型" },
51
+ "effort": { "type": "string", "title": "推理强度", "enum": ["low", "medium", "high", "xhigh", "max"] },
52
+ "params": { "type": "object", "title": "模型参数" }
53
+ }
54
+ }
55
+ },
56
+ "chatmode": { "type": "object", "title": "对话模式", "additionalProperties": true },
57
+ "memory": { "type": "object", "title": "记忆配置" },
58
+ "aun": { "type": "object", "title": "AUN 配置" },
59
+ "Services": { "type": "object", "title": "服务配置" },
60
+ "params": { "type": "object", "title": "其他参数" }
61
+ }
62
+ },
63
+ "skills": { "type": "object", "title": "技能开关", "additionalProperties": { "type": "object", "required": ["enabled"], "additionalProperties": false, "properties": { "enabled": { "type": "boolean", "title": "启用" } } } }
64
+ }
65
+ }
66
+ },
67
+ "personal_assistant": { "type": "integer", "minimum": 0, "title": "个人助理下标", "description": "创建团队时的个人助理成员下标,必须在成员范围内" },
68
+ "tags": { "type": "array", "title": "创建时的公共标签", "minItems": 1, "items": { "type": "string", "minLength": 1 } }
69
+ }
70
+ }
@@ -0,0 +1,154 @@
1
+ import fs from 'node:fs';
2
+
3
+ export const TEAM_SCHEMA_VERSION = 1;
4
+ export const TEAM_SCHEMA_ID = 'urn:evolcore:agent-template:team:v1';
5
+ const schema = JSON.parse(fs.readFileSync(new URL('./team-schema.json', import.meta.url), 'utf8'));
6
+ export const readTeamSchema = () => structuredClone(schema);
7
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
8
+ const own = (value, key) => Object.hasOwn(value, key);
9
+ const versionPattern = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
10
+
11
+ /** Upgrade field locations while retaining a template author's extra fields and restrictions. */
12
+ export function normalizeTeamSchema(local = {}) {
13
+ if (!record(local) || local.type !== 'object') throw new Error('team.schema.json must be a JSON Schema object');
14
+ const merge = (base, custom) => {
15
+ const out = { ...structuredClone(base), ...structuredClone(custom) };
16
+ for (const group of ['properties']) if (base[group] || custom[group]) {
17
+ out[group] = structuredClone({ ...base[group], ...custom[group] });
18
+ for (const key of Object.keys(base[group] ?? {})) if (record(custom[group]?.[key])) {
19
+ out[group][key] = merge(base[group][key], custom[group][key]);
20
+ }
21
+ }
22
+ if (record(base.items) && record(custom.items)) out.items = merge(base.items, custom.items);
23
+ if (base.required || custom.required) out.required = [...new Set([...(base.required ?? []), ...(custom.required ?? [])])];
24
+ return out;
25
+ };
26
+ const out = merge(schema, local);
27
+ out.$id = TEAM_SCHEMA_ID;
28
+ out.$schema = schema.$schema;
29
+ out.properties.$schema_version = structuredClone(schema.properties.$schema_version);
30
+ out.properties.version = structuredClone(schema.properties.version);
31
+ out.properties.host.properties.platform = structuredClone(schema.properties.host.properties.platform);
32
+ const member = out.properties.agents.items;
33
+ const original = local.properties?.agents?.items?.properties ?? {};
34
+ for (const key of ['name', 'description']) {
35
+ if (record(original[key])) member.properties.profile.properties[key] = merge(schema.properties.agents.items.properties.profile.properties[key], original[key]);
36
+ delete member.properties[key];
37
+ }
38
+ const legacyRequired = member.required ?? [];
39
+ member.required = [...new Set(legacyRequired.map(key => ['name', 'description'].includes(key) ? 'profile' : key))];
40
+ for (const key of ['name', 'description']) if (legacyRequired.includes(key)) {
41
+ member.properties.profile.required = [...new Set([...(member.properties.profile.required ?? []), key])];
42
+ }
43
+ return out;
44
+ }
45
+
46
+ /** JSON Schema subset used by the shared declaration; full runtime validation remains mode-specific. */
47
+ export function validateContractSchema(value, rule, at = '$') {
48
+ const errors = [];
49
+ if (!record(rule)) return [`${at}: schema must be an object`];
50
+ const types = Array.isArray(rule.type) ? rule.type : rule.type ? [rule.type] : [];
51
+ const actual = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
52
+ if (types.length && !types.some(t => t === actual || t === 'integer' && Number.isInteger(value))) {
53
+ return [`${at}: expected ${types.join('|')}, got ${actual}`];
54
+ }
55
+ if (own(rule, 'const') && !Object.is(value, rule.const)) errors.push(`${at}: must equal ${JSON.stringify(rule.const)}`);
56
+ if (rule.enum && !rule.enum.some(item => Object.is(item, value))) errors.push(`${at}: must be one of ${rule.enum.join(', ')}`);
57
+ if (typeof value === 'string') {
58
+ if (rule.minLength !== undefined && value.length < rule.minLength) errors.push(`${at}: shorter than ${rule.minLength}`);
59
+ if (rule.maxLength !== undefined && value.length > rule.maxLength) errors.push(`${at}: longer than ${rule.maxLength}`);
60
+ if (rule.pattern && !new RegExp(rule.pattern).test(value)) errors.push(`${at}: does not match ${rule.pattern}`);
61
+ }
62
+ if (typeof value === 'number') {
63
+ if (!Number.isFinite(value)) errors.push(`${at}: finite number required`);
64
+ if (rule.minimum !== undefined && value < rule.minimum) errors.push(`${at}: below ${rule.minimum}`);
65
+ if (rule.maximum !== undefined && value > rule.maximum) errors.push(`${at}: above ${rule.maximum}`);
66
+ }
67
+ if (Array.isArray(value)) {
68
+ if (rule.minItems !== undefined && value.length < rule.minItems) errors.push(`${at}: needs at least ${rule.minItems} items`);
69
+ if (rule.maxItems !== undefined && value.length > rule.maxItems) errors.push(`${at}: too many items`);
70
+ if (rule.uniqueItems && new Set(value.map(item => JSON.stringify(item))).size !== value.length) errors.push(`${at}: duplicate items`);
71
+ if (record(rule.items)) value.forEach((item, i) => errors.push(...validateContractSchema(item, rule.items, `${at}[${i}]`)));
72
+ }
73
+ if (record(value)) {
74
+ for (const key of rule.required ?? []) if (!own(value, key)) errors.push(`${at}: missing "${key}"`);
75
+ for (const [key, item] of Object.entries(value)) {
76
+ const child = own(rule.properties ?? {}, key) ? rule.properties[key] : rule.additionalProperties;
77
+ if (child === false) errors.push(`${at}.${key}: not allowed`);
78
+ else if (record(child)) errors.push(...validateContractSchema(item, child, `${at}.${key}`));
79
+ }
80
+ }
81
+ return errors;
82
+ }
83
+
84
+ /** Pure read normalization; does not mutate input or write files. Conversions are returned as changes. */
85
+ export function normalizeTeam(input, { fallbackName, packageInfo } = {}) {
86
+ const errors = []; const changes = [];
87
+ if (!record(input)) return { errors: ['team: object required'], changes };
88
+ if (input.$schema_version !== undefined && input.$schema_version !== TEAM_SCHEMA_VERSION) {
89
+ return { errors: ['team.$schema_version: unsupported template format version'], changes };
90
+ }
91
+ const legacy = input.$schema_version === undefined;
92
+ const team = structuredClone(input);
93
+ const change = (field, message) => changes.push({ field, message });
94
+ if (legacy) { team.$schema_version = TEAM_SCHEMA_VERSION; change('$schema_version', 'Legacy declaration normalized to v1'); }
95
+ if (team.name === undefined && fallbackName) { team.name = fallbackName; change('name', 'Use template directory identifier'); }
96
+ if (typeof team.name === 'string' && team.name !== team.name.trim()) {
97
+ team.name = team.name.trim(); change('name', 'Trimmed identifier whitespace');
98
+ }
99
+ if (legacy) {
100
+ const oldVersion = team.version;
101
+ if (oldVersion === undefined) team.version = '1.0.0';
102
+ else if (typeof oldVersion === 'number' && Number.isSafeInteger(oldVersion) && oldVersion >= 0) team.version = `${oldVersion}.0.0`;
103
+ else if (typeof oldVersion === 'string' && /^(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))?$/.test(oldVersion)) {
104
+ team.version = oldVersion.split('.').concat(['0', '0']).slice(0, 3).join('.');
105
+ }
106
+ if (team.version !== oldVersion) change('version', `Converted ${JSON.stringify(oldVersion) ?? 'missing'} to ${team.version}`);
107
+ if (team.host === undefined) team.host = {};
108
+ if (record(team.host)) {
109
+ if (team.host.platform === undefined) { team.host.platform = ['linux']; change('host.platform', 'Use legacy linux default'); }
110
+ else if (typeof team.host.platform === 'string') { team.host.platform = [team.host.platform]; change('host.platform', 'Converted legacy platform string to list'); }
111
+ }
112
+ }
113
+ if (Array.isArray(team.agents)) team.agents.forEach((agent, i) => {
114
+ if (!record(agent)) return;
115
+ const prefix = `agents[${i}]`;
116
+ if (agent.profile !== undefined && !record(agent.profile)) { errors.push(`${prefix}.profile: object required`); return; }
117
+ if (legacy && agent.profile === undefined) agent.profile = {};
118
+ if (!record(agent.profile)) return;
119
+ for (const key of ['name', 'description']) if (own(agent, key)) {
120
+ if (!legacy) { errors.push(`${prefix}.${key}: use profile.${key} in v1`); continue; }
121
+ if (own(agent.profile, key) && agent.profile[key] !== agent[key]) errors.push(`${prefix}.${key}: conflicts with profile.${key}`);
122
+ else if (!own(agent.profile, key)) agent.profile[key] = agent[key];
123
+ delete agent[key]; change(`${prefix}.${key}`, `Moved to profile.${key}`);
124
+ }
125
+ if (typeof agent.profile.name === 'string' && agent.profile.name !== agent.profile.name.trim()) {
126
+ agent.profile.name = agent.profile.name.trim(); change(`${prefix}.profile.name`, 'Trimmed display name whitespace');
127
+ }
128
+ if (legacy && agent.profile.tags === undefined && team.tags !== undefined) {
129
+ agent.profile.tags = structuredClone(team.tags); change(`${prefix}.profile.tags`, 'Inherited legacy team tags');
130
+ }
131
+ });
132
+ errors.push(...validateContractSchema(team, schema));
133
+ if (Array.isArray(team.agents)) {
134
+ const keys = new Set(); const names = new Set();
135
+ for (const [i, agent] of team.agents.entries()) {
136
+ if (!record(agent)) continue;
137
+ if (keys.has(agent.key)) errors.push(`agents[${i}].key: duplicated`);
138
+ keys.add(agent.key);
139
+ if (record(agent.profile) && typeof agent.profile.name === 'string') {
140
+ if (names.has(agent.profile.name)) errors.push(`agents[${i}].profile.name is duplicated`);
141
+ names.add(agent.profile.name);
142
+ }
143
+ }
144
+ if (Number.isInteger(team.personal_assistant) && team.personal_assistant >= team.agents.length) errors.push('personal_assistant: index outside agents');
145
+ }
146
+ if (packageInfo) {
147
+ if (team.name !== packageInfo.id) errors.push('team.name: differs from PACKAGE.id');
148
+ if (team.version !== packageInfo.version || !versionPattern.test(packageInfo.version)) errors.push('team.version: differs from PACKAGE.version');
149
+ if (team.title !== undefined && team.title !== packageInfo.name) errors.push('team.title: differs from PACKAGE.name');
150
+ if (team.description !== undefined && team.description !== packageInfo.description) errors.push('team.description: differs from PACKAGE.description');
151
+ }
152
+ return { ...(errors.length ? {} : { team }), errors, changes,
153
+ metadata: { id: team.name, name: team.title ?? packageInfo?.name ?? team.name, version: team.version } };
154
+ }
@@ -0,0 +1,265 @@
1
+ /** Portable .ectpl transport, shared with EvolCore. Only reads explicit template directories. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { gzipSync, gunzipSync } from 'node:zlib';
6
+ import { loadTemplate } from './template.mjs';
7
+ import { normalizeTeam, normalizeTeamSchema, validateContractSchema, readTeamSchema } from './template-contract.mjs';
8
+ import { BASEAGENTS } from './template-runtime.mjs';
9
+
10
+ export const PACKAGE_LIMITS = { file: 20 * 1024 * 1024, total: 200 * 1024 * 1024, entries: 20000 };
11
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
12
+ const json = value => Buffer.from(JSON.stringify(value, null, 2) + '\n');
13
+ export const packageDigest = bytes => 'sha256:' + createHash('sha256').update(bytes).digest('hex');
14
+ function check(value, message, code = 'INVALID_ARGUMENT') {
15
+ if (!value) throw Object.assign(new Error(message), { code });
16
+ }
17
+ export function packagePath(name) {
18
+ check(typeof name === 'string' && name.length && !/[\\\0:]/.test(name)
19
+ && name.split('/').every(part => part && part !== '.' && part !== '..'), 'Invalid package path');
20
+ return name;
21
+ }
22
+ export function regularAncestors(file) {
23
+ let current = path.resolve(file);
24
+ while (true) {
25
+ const stat = fs.lstatSync(current, { throwIfNoEntry: false });
26
+ check(!stat?.isSymbolicLink(), 'Symbolic links are not supported');
27
+ const parent = path.dirname(current);
28
+ if (parent === current) break;
29
+ current = parent;
30
+ }
31
+ }
32
+ export function excludedResource(name) {
33
+ return name.split('/').some(part => ['.git', 'node_modules', '.claude'].includes(part)
34
+ || /^\.env/.test(part) || /\.(?:pem|key|db(?:[-.].*)?)$/i.test(part));
35
+ }
36
+
37
+ /** Ordered USTAR+gzip, compatible with EvolCore archive(). */
38
+ export function encodePackageEntries(entries) {
39
+ check(entries instanceof Map && entries.size && entries.size <= PACKAGE_LIMITS.entries, 'Invalid package entries');
40
+ const blocks = []; let total = 0;
41
+ for (const [name, entry] of [...entries].sort(([a], [b]) => a.localeCompare(b))) {
42
+ packagePath(name);
43
+ const bytes = Buffer.from(entry.bytes); total += bytes.length;
44
+ check(bytes.length <= PACKAGE_LIMITS.file && total <= PACKAGE_LIMITS.total, 'Package size limit exceeded', 'PACKAGE_TOO_LARGE');
45
+ const header = Buffer.alloc(512); let short = name; let prefix = '';
46
+ if (Buffer.byteLength(name) > 100) {
47
+ const splits = [...name.matchAll(/\//g)].map(match => match.index).reverse();
48
+ const split = splits.find(i => Buffer.byteLength(name.slice(i + 1)) <= 100 && Buffer.byteLength(name.slice(0, i)) <= 155);
49
+ check(split !== undefined, 'Archive path too long'); short = name.slice(split + 1); prefix = name.slice(0, split);
50
+ }
51
+ const octal = (n, offset, len) => header.write(n.toString(8).padStart(len - 1, '0') + '\0', offset, len, 'ascii');
52
+ header.write(short, 0, 100); octal(entry.mode & 0o111 ? 0o755 : 0o644, 100, 8);
53
+ octal(0, 108, 8); octal(0, 116, 8); octal(bytes.length, 124, 12); octal(0, 136, 12);
54
+ header.fill(32, 148, 156); header.write('0', 156); header.write('ustar\0', 257); header.write('00', 263); header.write(prefix, 345, 155);
55
+ header.write(header.reduce((sum, byte) => sum + byte, 0).toString(8).padStart(6, '0') + '\0 ', 148, 8);
56
+ blocks.push(header, bytes, Buffer.alloc((512 - bytes.length % 512) % 512));
57
+ }
58
+ blocks.push(Buffer.alloc(1024));
59
+ return gzipSync(Buffer.concat(blocks), { level: 9 });
60
+ }
61
+
62
+ export function decodePackageEntries(bytes) {
63
+ check(Buffer.isBuffer(bytes) && bytes.length <= PACKAGE_LIMITS.total, 'Archive exceeds limit', 'PACKAGE_TOO_LARGE');
64
+ const tar = gunzipSync(bytes, { maxOutputLength: PACKAGE_LIMITS.total + PACKAGE_LIMITS.entries * 1024 });
65
+ const entries = new Map(); const names = new Set(); let total = 0; let ended = false;
66
+ for (let offset = 0; offset + 512 <= tar.length;) {
67
+ const header = tar.subarray(offset, offset + 512); offset += 512;
68
+ if (header.every(byte => byte === 0)) {
69
+ check(tar.subarray(offset).every(byte => byte === 0), 'Unexpected archive trailer', 'INTEGRITY_FAILED'); ended = true; break;
70
+ }
71
+ const text = (at, len) => header.subarray(at, at + len).toString('utf8').replace(/\0.*$/s, '');
72
+ const name = (text(345, 155) ? text(345, 155) + '/' : '') + text(0, 100);
73
+ packagePath(name);
74
+ const sizeText = text(124, 12).trim();
75
+ const size = /^[0-7]+$/.test(sizeText) ? Number.parseInt(sizeText, 8) : NaN;
76
+ const checksum = header.reduce((sum, byte, i) => sum + (i >= 148 && i < 156 ? 32 : byte), 0);
77
+ check(Number.parseInt(text(148, 8).trim(), 8) === checksum && ['', '0'].includes(text(156, 1))
78
+ && Number.isSafeInteger(size) && size >= 0 && size <= PACKAGE_LIMITS.file && offset + Math.ceil(size / 512) * 512 <= tar.length,
79
+ 'Invalid archive entry', 'INTEGRITY_FAILED');
80
+ total += size;
81
+ check(!names.has(name.toLowerCase()) && entries.size < PACKAGE_LIMITS.entries && total <= PACKAGE_LIMITS.total,
82
+ 'Duplicate or excessive archive entries', 'INTEGRITY_FAILED');
83
+ names.add(name.toLowerCase());
84
+ entries.set(name, { bytes: Buffer.from(tar.subarray(offset, offset + size)),
85
+ mode: Number.parseInt(text(100, 8).trim(), 8) & 0o111 ? 0o755 : 0o644 });
86
+ offset += Math.ceil(size / 512) * 512;
87
+ }
88
+ check(entries.size && ended, 'Empty or truncated archive', 'INTEGRITY_FAILED');
89
+ return entries;
90
+ }
91
+
92
+ function portableFile(name, keys) {
93
+ if (['team.json', 'team.schema.json'].includes(name)) return true;
94
+ if (name.startsWith('.evolcore/skills/')) return !excludedResource(name);
95
+ const [group, key, ...rest] = name.split('/');
96
+ if (!keys.includes(key)) return false;
97
+ const relative = rest.join('/');
98
+ return group === 'workspace' && !excludedResource(relative)
99
+ || group === 'agents' && (relative.startsWith('personal/soul/') && relative.endsWith('.md') && !relative.endsWith('/00-GUIDE.md')
100
+ || relative === 'personal/welcome.md' || relative.startsWith('triggers/') && !excludedResource(relative));
101
+ }
102
+
103
+ /** Validate all bytes before extracting; never trusts a MANIFEST path for filesystem access. */
104
+ export function inspectTemplatePackage(bytes, { digest } = {}) {
105
+ const actual = packageDigest(bytes);
106
+ check(digest === undefined || /^sha256:[a-f0-9]{64}$/.test(digest) && digest === actual, 'Package digest mismatch', 'INTEGRITY_FAILED');
107
+ const entries = decodePackageEntries(bytes);
108
+ const read = name => { check(entries.has(name), 'Missing package entry: ' + name, 'INTEGRITY_FAILED'); return JSON.parse(entries.get(name).bytes.toString('utf8')); };
109
+ const metadata = read('PACKAGE.json'); const manifest = read('MANIFEST.json');
110
+ check(record(metadata) && metadata.$schema_version === 1 && typeof metadata.name === 'string' && metadata.name.trim()
111
+ && metadata.name.length <= 64 && record(metadata.compat) && typeof metadata.compat.evolcore === 'string'
112
+ && metadata.compat.evolcore.length > 0, 'Invalid package metadata', 'INTEGRITY_FAILED');
113
+ check(Array.isArray(manifest) && manifest.length && entries.size === manifest.length + 2, 'Invalid manifest', 'INTEGRITY_FAILED');
114
+ const seen = new Set();
115
+ for (const entry of manifest) {
116
+ check(record(entry), 'Invalid manifest entry', 'INTEGRITY_FAILED'); packagePath(entry.path);
117
+ check(!seen.has(entry.path.toLowerCase()) && entries.has('template/' + entry.path), 'Duplicate or missing manifest entry', 'INTEGRITY_FAILED');
118
+ seen.add(entry.path.toLowerCase());
119
+ const file = entries.get('template/' + entry.path).bytes;
120
+ check(entry.size === file.length && entry.sha256 === packageDigest(file).slice(7), 'Manifest content mismatch', 'INTEGRITY_FAILED');
121
+ }
122
+ const normalized = normalizeTeam(read('template/team.json'), { packageInfo: metadata });
123
+ check(!normalized.errors.length, normalized.errors.join('; '), 'INTEGRITY_FAILED');
124
+ const team = normalized.team; const schema = normalizeTeamSchema(read('template/team.schema.json'));
125
+ const errors = validateContractSchema(team, schema);
126
+ check(!errors.length, errors.join('; '));
127
+ const platforms = metadata.compat.platforms;
128
+ check(Array.isArray(platforms) && platforms.length === team.host.platform.length
129
+ && new Set(platforms).size === platforms.length && platforms.every(p => team.host.platform.includes(p)), 'Conflicting platform metadata', 'INTEGRITY_FAILED');
130
+ const keys = team.agents.map(agent => agent.key);
131
+ for (const { path: name } of manifest) check(portableFile(name, keys), 'Unsupported portable resource: ' + name);
132
+ return { metadata, team, schema, entries, digest: actual, changes: normalized.changes,
133
+ resources: manifest.map(({ path: name, size }) => ({ path: name, size })) };
134
+ }
135
+
136
+ /** Export behavior/resources only; credentials and host infrastructure never enter the share package. */
137
+ export function exportTemplatePackage(templateDir, { publisher, createdAt = Date.now(), evolcoreRange = '>=0.0.43' } = {}) {
138
+ regularAncestors(templateDir);
139
+ const { tpl, errors } = loadTemplate(templateDir);
140
+ check(!errors.length, errors.join('; '));
141
+ const excluded = []; const team = structuredClone(tpl.team);
142
+ const readOptional = relative => {
143
+ const file = path.join(tpl.root, ...relative.split('/'));
144
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
145
+ };
146
+ const defaults = readOptional('.evolcore/agents/defaults.json');
147
+ const providers = readOptional('.evolcore/providers.json').providers ?? {};
148
+ if (team.host.config !== undefined) { delete team.host.config; excluded.push('host.config'); }
149
+ for (const agent of team.agents) {
150
+ const source = { ...structuredClone(defaults), ...agent.config,
151
+ baseagents: { ...defaults.baseagents, ...agent.config?.baseagents } };
152
+ const config = {};
153
+ for (const name of ['chatmode', 'memory']) if (source[name] !== undefined) config[name] = source[name];
154
+ config.active_baseagent = source.active_baseagent ?? 'claude'; config.baseagents = {};
155
+ for (const [name, sourceBlock] of Object.entries(source.baseagents)) {
156
+ const block = { ...defaults.baseagents?.[name], ...sourceBlock };
157
+ check(BASEAGENTS.includes(name) && record(block), 'Invalid baseagent block');
158
+ const ref = typeof block.provider === 'string' ? { id: block.provider, name: providers[block.provider]?.name ?? block.provider } : block.provider;
159
+ check(record(ref) && /^provider-[0-9]{8}$/.test(ref.id), 'Provider identity required: ' + agent.key + '/' + name);
160
+ config.baseagents[name] = { provider: { id: ref.id, ...(ref.name !== undefined ? { name: ref.name } : {}) } };
161
+ for (const field of ['model', 'effort', 'params']) if (block[field] !== undefined) config.baseagents[name][field] = structuredClone(block[field]);
162
+ }
163
+ check(config.baseagents[config.active_baseagent], 'Default baseagent must have a binding: ' + agent.key);
164
+ for (const field of Object.keys(agent.config ?? {})) if (!Object.hasOwn(config, field)) excluded.push('agents/' + agent.key + '/config/' + field);
165
+ agent.config = config;
166
+ }
167
+ // The directory's custom constraints belong to its authoring form. Portable fields use the common schema.
168
+ const normalized = normalizeTeam(team);
169
+ check(!normalized.errors.length, normalized.errors.join('; '));
170
+ const entries = new Map();
171
+ for (const relative of tpl.files) {
172
+ const name = relative.split(path.sep).join('/');
173
+ if (['team.json', 'team.schema.json'].includes(name)) continue;
174
+ if (!portableFile(name, tpl.keys)) { excluded.push(name); continue; }
175
+ const file = path.join(tpl.root, relative);
176
+ entries.set('template/' + name, { bytes: fs.readFileSync(file), mode: fs.statSync(file).mode & 0o777 });
177
+ }
178
+ entries.set('template/team.json', { bytes: json(team), mode: 0o644 });
179
+ entries.set('template/team.schema.json', { bytes: json(readTeamSchema()), mode: 0o644 });
180
+ const external = new Set();
181
+ for (const [name, entry] of entries) {
182
+ if (entry.bytes.includes(0) || !Buffer.from(entry.bytes.toString('utf8')).equals(entry.bytes)) continue;
183
+ for (const line of entry.bytes.toString('utf8').split('\n')) {
184
+ check(!/(?:sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|AKIA[A-Z0-9]{16}|-----BEGIN .*PRIVATE KEY|(?:API_KEY|TOKEN|SECRET|PASSWORD)\s*=\s*(?!\$\{)\S{8,})/i.test(line),
185
+ 'Credential content in portable resource: ' + name, 'SENSITIVE_CONTENT');
186
+ for (const aid of line.match(/[a-z0-9][a-z0-9_-]*\.(?:[a-z0-9-]+\.)+[a-z]{2,}/gi) ?? []) {
187
+ if (!line.includes('://' + aid) && !aid.startsWith('www.')) external.add(aid);
188
+ }
189
+ }
190
+ }
191
+ const metadata = { $schema_version: 1, id: team.name, name: team.title ?? team.name, version: team.version,
192
+ ...(team.description !== undefined ? { description: team.description } : {}), ...(publisher ? { publisher } : {}), createdAt,
193
+ compat: { platforms: team.host.platform, evolcore: evolcoreRange, baseagents: [...new Set(team.agents.flatMap(agent => Object.keys(agent.config.baseagents)))] }, externalAids: [...external].sort() };
194
+ const manifest = [...entries].map(([name, entry]) => ({ path: name.slice('template/'.length), size: entry.bytes.length, sha256: packageDigest(entry.bytes).slice(7) }));
195
+ entries.set('PACKAGE.json', { bytes: json(metadata), mode: 0o644 });
196
+ entries.set('MANIFEST.json', { bytes: json(manifest), mode: 0o644 });
197
+ const bytes = encodePackageEntries(entries);
198
+ inspectTemplatePackage(bytes);
199
+ return { bytes, metadata, digest: packageDigest(bytes), excluded, filename: metadata.id + '-' + metadata.version + '.ectpl' };
200
+ }
201
+
202
+ /** Atomic new-directory publication. Existing templates are never overwritten. */
203
+ export function importTemplatePackage(bytes, destination, options = {}) {
204
+ const checked = inspectTemplatePackage(bytes, options);
205
+ const target = path.resolve(destination); regularAncestors(target);
206
+ check(!fs.existsSync(target), 'Template directory already exists', 'CONFLICT');
207
+ fs.mkdirSync(path.dirname(target), { recursive: true });
208
+ const temp = process.env.TMPDIR;
209
+ check(temp && path.isAbsolute(temp), 'Absolute TMPDIR required');
210
+ fs.mkdirSync(temp, { recursive: true });
211
+ const stage = fs.mkdtempSync(path.join(temp, 'template-import-'));
212
+ try {
213
+ for (const [name, entry] of checked.entries) if (name.startsWith('template/')) {
214
+ const file = path.join(stage, ...name.slice('template/'.length).split('/'));
215
+ fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, entry.bytes, { flag: 'wx', mode: entry.mode });
216
+ }
217
+ fs.writeFileSync(path.join(stage, 'team.json'), json(checked.team));
218
+ fs.writeFileSync(path.join(stage, 'team.schema.json'), json(checked.schema));
219
+ if (options.buildEnvironment) attachBuildEnvironment(stage, options.buildEnvironment);
220
+ const { errors } = loadTemplate(stage); check(!errors.length, errors.join('; '));
221
+ check(!fs.existsSync(target), 'Template directory already exists', 'CONFLICT');
222
+ fs.chmodSync(stage, 0o755);
223
+ // Reserve the destination before publication so concurrent imports cannot overwrite it.
224
+ fs.mkdirSync(target);
225
+ try {
226
+ if (fs.statSync(stage).dev === fs.statSync(path.dirname(target)).dev) fs.renameSync(stage, target);
227
+ else {
228
+ // Cross-device copy publishes team.json last; template lists only see complete templates.
229
+ for (const entry of fs.readdirSync(stage)) if (!['team.json', 'team.schema.json'].includes(entry)) {
230
+ fs.cpSync(path.join(stage, entry), path.join(target, entry), { recursive: true, errorOnExist: true, force: false });
231
+ }
232
+ fs.copyFileSync(path.join(stage, 'team.schema.json'), path.join(target, 'team.schema.json'), fs.constants.COPYFILE_EXCL);
233
+ fs.copyFileSync(path.join(stage, 'team.json'), path.join(target, 'team.json'), fs.constants.COPYFILE_EXCL);
234
+ }
235
+ } catch (error) { fs.rmSync(target, { recursive: true, force: true }); throw error; }
236
+ } finally { fs.rmSync(stage, { recursive: true, force: true }); }
237
+ return { directory: target, metadata: checked.metadata, digest: checked.digest, changes: checked.changes };
238
+ }
239
+
240
+ /** Explicit local infrastructure for create; portable Agent configuration stays unchanged. */
241
+ export function attachBuildEnvironment(templateDir, sourceDir) {
242
+ regularAncestors(sourceDir);
243
+ const base = loadTemplate(sourceDir);
244
+ check(!base.errors.length, 'Invalid build environment: ' + base.errors.join('; '));
245
+ const teamFile = path.join(templateDir, 'team.json');
246
+ const team = JSON.parse(fs.readFileSync(teamFile, 'utf8'));
247
+ if (base.tpl.team.host.config !== undefined) team.host.config = structuredClone(base.tpl.team.host.config);
248
+ if (base.tpl.team.issuer !== undefined) team.issuer = base.tpl.team.issuer;
249
+ for (const name of ['providers.json', 'agents/defaults.json', '.env']) {
250
+ const source = path.join(base.tpl.root, '.evolcore', ...name.split('/'));
251
+ if (!fs.existsSync(source)) continue;
252
+ const target = path.join(templateDir, '.evolcore', ...name.split('/'));
253
+ fs.mkdirSync(path.dirname(target), { recursive: true });
254
+ fs.copyFileSync(source, target); fs.chmodSync(target, 0o600);
255
+ }
256
+ fs.writeFileSync(teamFile, json(team));
257
+ }
258
+
259
+ export function templateProviderSummary(templateDir) {
260
+ const file = path.join(templateDir, '.evolcore', 'providers.json');
261
+ regularAncestors(file);
262
+ if (!fs.existsSync(file)) return [];
263
+ const providers = JSON.parse(fs.readFileSync(file, 'utf8')).providers ?? {};
264
+ return Object.entries(providers).map(([id, value]) => ({ id, name: value.name ?? id, services: Object.keys(value.services ?? {}) }));
265
+ }