evolcore 0.0.43-test.7 → 0.0.45

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 (127) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +22 -9
  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/claude-runner.js +1 -1
  9. package/dist/aun/aid/agentmd.js +56 -1
  10. package/dist/aun/aid/client.js +3 -1
  11. package/dist/aun/menu/client.js +3 -2
  12. package/dist/aun/msg/p2p.js +1 -1
  13. package/dist/channels/aun.js +47 -32
  14. package/dist/cli/agent-command.js +5 -0
  15. package/dist/cli/agent-create.js +5 -1
  16. package/dist/cli/agent-template.js +124 -0
  17. package/dist/cli/aun-commands.js +2 -2
  18. package/dist/cli/ctl-command.js +2 -1
  19. package/dist/cli/daemon-commands.js +5 -0
  20. package/dist/cli/ecmsg-gateway.js +2 -2
  21. package/dist/cli/events-command.js +45 -9
  22. package/dist/cli/index.js +29 -0
  23. package/dist/cli/net-check.js +1 -1
  24. package/dist/cli/restart-monitor.js +115 -36
  25. package/dist/cli/services-command.js +29 -3
  26. package/dist/cli/thread-command.js +97 -11
  27. package/dist/config/boot-log.js +8 -8
  28. package/dist/config/schema-migration.js +41 -16
  29. package/dist/core/agent-ipc-registration.js +25 -4
  30. package/dist/core/agent-runtime.js +2 -0
  31. package/dist/core/auth/operation-authorizer.js +2 -0
  32. package/dist/core/auth/operation-catalog.js +11 -2
  33. package/dist/core/channel-runtime.js +16 -9
  34. package/dist/core/command/agent-control.js +11 -1
  35. package/dist/core/command/agent-template-menu.js +147 -0
  36. package/dist/core/command/command-handler.js +27 -6
  37. package/dist/core/command/eventcenter-menu.js +158 -28
  38. package/dist/core/command/menu-catalog.js +8 -1
  39. package/dist/core/command/menu-handler.js +18 -6
  40. package/dist/core/command/menu-protocol.js +11 -2
  41. package/dist/core/daemon-control.js +14 -0
  42. package/dist/core/daemon-lifecycle.js +262 -189
  43. package/dist/core/handoff/runtime.js +42 -10
  44. package/dist/core/ipc-registration.js +5 -1
  45. package/dist/core/legacy-rename.js +41 -0
  46. package/dist/core/message/aun-ipc-sender.js +118 -13
  47. package/dist/core/message/im-renderer.js +88 -1
  48. package/dist/core/message/message-queue.js +66 -15
  49. package/dist/core/message/pending-hints.js +29 -5
  50. package/dist/core/message/response-engine.js +37 -7
  51. package/dist/core/message/send-routing.js +13 -6
  52. package/dist/core/pack-auth.js +94 -0
  53. package/dist/core/pack-install.js +194 -0
  54. package/dist/core/permission/ec-command-parser.js +49 -16
  55. package/dist/core/rate-window.js +48 -0
  56. package/dist/core/relation/peer-identity.js +28 -0
  57. package/dist/core/session/session-fs-store.js +66 -26
  58. package/dist/core/session/session-idle-monitor.js +59 -19
  59. package/dist/core/session/session-manager.js +13 -4
  60. package/dist/core/thread/thread-route.js +2 -2
  61. package/dist/core/thread/thread-service.js +52 -3
  62. package/dist/eck/kit-renderer.js +1 -1
  63. package/dist/eck/message-renderer.js +2 -0
  64. package/dist/event-center/admission-materializer.js +22 -12
  65. package/dist/event-center/bus-gate.js +20 -2
  66. package/dist/event-center/bus-host.js +46 -29
  67. package/dist/event-center/bus-resolver.js +1 -1
  68. package/dist/event-center/center-config.js +41 -14
  69. package/dist/event-center/daemon.js +1 -2
  70. package/dist/event-center/directory-source.js +3 -1
  71. package/dist/event-center/index-generator.js +12 -2
  72. package/dist/event-center/ipc-operation.js +140 -25
  73. package/dist/event-center/pack-loader.js +61 -56
  74. package/dist/event-center/pack-manager.js +2 -2
  75. package/dist/event-center/registry.js +242 -17
  76. package/dist/event-center/runtime.js +271 -75
  77. package/dist/event-center/types.js +20 -4
  78. package/dist/event-center/validation.js +34 -12
  79. package/dist/index.js +147 -44
  80. package/dist/ipc.js +44 -4
  81. package/dist/paths.js +2 -2
  82. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  83. package/dist/services/index.js +3 -3
  84. package/dist/services/ipc-operation.js +99 -7
  85. package/dist/services/pack-manager.js +17 -6
  86. package/dist/services/router.js +8 -5
  87. package/dist/services/validation.js +5 -5
  88. package/dist/trigger/scheduler.js +38 -0
  89. package/dist/trigger/script-sandbox.js +52 -2
  90. package/dist/utils/npm-ops.js +2 -1
  91. package/dist/utils/package-version-info.js +6 -3
  92. package/kits/docs/aun/ABILITY_CALLING.md +4 -3
  93. package/kits/docs/context-assembly.md +1 -1
  94. package/kits/docs/evolcore/INDEX.md +3 -3
  95. package/kits/docs/evolcore/agent.md +22 -1
  96. package/kits/docs/evolcore/event-center.md +30 -10
  97. package/kits/docs/evolcore/fs.md +4 -3
  98. package/kits/docs/evolcore/menu-protocol.md +7 -1
  99. package/kits/docs/evolcore/msg.md +8 -8
  100. package/kits/docs/evolcore/response.md +2 -2
  101. package/kits/docs/evolcore/services.md +27 -10
  102. package/kits/docs/evolcore/thread-chain.md +15 -3
  103. package/kits/rules/06-channel.md +1 -0
  104. package/kits/skills/ability/references/calling.md +2 -2
  105. package/kits/skills/ec-group/SKILL.md +5 -8
  106. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  107. package/kits/skills/ec-trigger/SKILL.md +4 -4
  108. package/kits/skills/thread-ops/SKILL.md +10 -10
  109. package/kits/templates/message-fragments/item.md +1 -1
  110. package/kits/templates/system-fragments/channel.md +1 -1
  111. package/kits/templates/system-fragments/commands.md +1 -1
  112. package/kits/templates/system-fragments/reply.md +1 -0
  113. package/kits/templates/system-fragments/thread.md +3 -2
  114. package/package.json +4 -3
  115. package/scripts/agent-template/index.mjs +40 -0
  116. package/scripts/agent-template/inspect.mjs +240 -0
  117. package/scripts/agent-template/overlay.mjs +71 -0
  118. package/scripts/agent-template/pack.mjs +169 -0
  119. package/scripts/agent-template/shared/common.mjs +235 -0
  120. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  121. package/scripts/agent-template/shared/plan.mjs +129 -0
  122. package/scripts/agent-template/shared/team-schema.json +70 -0
  123. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  124. package/scripts/agent-template/shared/template-package.mjs +265 -0
  125. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  126. package/scripts/agent-template/shared/template.mjs +142 -0
  127. package/dist/event-center/client-factory.js +0 -50
@@ -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
+ }
@@ -0,0 +1,80 @@
1
+ /** Shared, pure template binding/rendering. No home discovery or runtime writes. */
2
+ export const BASEAGENTS = ['claude', 'codex', 'gemini', 'ecagent'];
3
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const fail = message => { throw Object.assign(new Error(message), { code: 'INVALID_ARGUMENT' }); };
5
+
6
+ export function renderText(text, vars = {}, externalAids = {}) {
7
+ let out = text.replace(/\{\{\s*([a-z]+\.[a-z]+)\s*\}\}/g,
8
+ (token, key) => Object.hasOwn(vars, key) ? String(vars[key]) : token);
9
+ // One pass avoids cascading A -> B -> C substitutions.
10
+ const keys = Object.keys(externalAids).sort((a, b) => b.length - a.length);
11
+ if (keys.length) {
12
+ const pattern = keys.map(key => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
13
+ out = out.replace(new RegExp(pattern, 'g'), match => String(externalAids[match]));
14
+ }
15
+ return out;
16
+ }
17
+
18
+ /** Parse JSON first, then render string values so quotes/newlines cannot change types or structure. */
19
+ export function renderValue(value, vars = {}, externalAids = {}) {
20
+ if (typeof value === 'string') return renderText(value, vars, externalAids);
21
+ if (Array.isArray(value)) return value.map(item => renderValue(item, vars, externalAids));
22
+ if (record(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, renderValue(item, vars, externalAids)]));
23
+ return value;
24
+ }
25
+
26
+ /** Binary and non-UTF8 files are byte-preserved. JSON resources keep their data structure. */
27
+ export function renderResource(bytes, vars = {}, externalAids = {}, { json = false } = {}) {
28
+ if (bytes.includes(0) || !Buffer.from(bytes.toString('utf8')).equals(bytes)) return bytes;
29
+ const text = bytes.toString('utf8');
30
+ return Buffer.from(json ? JSON.stringify(renderValue(JSON.parse(text), vars, externalAids), null, 2) + '\n'
31
+ : renderText(text, vars, externalAids));
32
+ }
33
+
34
+ export function providerUsable(providers, id, baseagent) {
35
+ if (typeof id !== 'string' || !Object.hasOwn(providers, id)) return false;
36
+ const services = providers[id]?.services;
37
+ return record(services) && (baseagent === 'ecagent' ? ['ecagent', 'text'] : [baseagent])
38
+ .some(name => Object.hasOwn(services, name));
39
+ }
40
+
41
+ /** Match by exact stable ID, never by display name. Missing matches can be previewed, not installed. */
42
+ export function bindTemplateProviders(config, { providers = {}, defaults = {}, selections = {}, allowMissing = false } = {}) {
43
+ if (!record(config) || !record(providers) || !record(defaults) || !record(selections)) fail('Invalid Provider binding input');
44
+ const out = structuredClone(config);
45
+ const blocks = out.baseagents ?? {};
46
+ if (!record(blocks)) fail('baseagents must be an object');
47
+ const active = out.active_baseagent ?? defaults.active_baseagent ?? 'claude';
48
+ const names = [...new Set([...Object.keys(blocks), active])];
49
+ if (Object.keys(selections).some(name => !names.includes(name))) fail('Unknown baseagent selection');
50
+ const refs = [];
51
+ for (const name of names) {
52
+ if (!BASEAGENTS.includes(name)) fail('Invalid baseagent: ' + name);
53
+ const block = blocks[name] ?? defaults.baseagents?.[name] ?? {};
54
+ const select = selections[name] ?? {};
55
+ if (!record(block) || !record(select) || Object.keys(select).some(key => !['provider', 'model', 'effort'].includes(key))) fail('Invalid baseagent selection: ' + name);
56
+ const reference = block.provider ?? defaults.baseagents?.[name]?.provider;
57
+ const ref = typeof reference === 'string' ? { id: reference } : reference;
58
+ if (ref !== undefined && (!record(ref) || typeof ref.id !== 'string')) fail('Provider identity required: ' + name);
59
+ if (select.provider !== undefined && (typeof select.provider !== 'string' || !select.provider)) fail('Invalid selected Provider: ' + name);
60
+ if (select.model !== undefined && (typeof select.model !== 'string' || !select.model.trim())) fail('Invalid model: ' + name);
61
+ if (select.effort !== undefined && select.effort !== null && !['low', 'medium', 'high', 'xhigh', 'max'].includes(select.effort)) fail('Invalid effort: ' + name);
62
+ const selected = select.provider ?? ref?.id;
63
+ const usable = providerUsable(providers, selected, name);
64
+ refs.push({ baseagent: name, template: { ...(ref ?? {}), model: block.model, effort: block.effort },
65
+ match: usable ? 'reused' : 'select', provider: usable ? selected : null });
66
+ if (!usable && (!allowMissing || select.provider !== undefined)) {
67
+ throw Object.assign(new Error('Provider binding required or unsupported service: ' + name), { code: 'PROVIDER_NOT_FOUND', refs });
68
+ }
69
+ if (Object.hasOwn(blocks, name) || Object.hasOwn(selections, name)) {
70
+ out.baseagents ??= {};
71
+ const bound = { ...structuredClone(block) };
72
+ if (selected !== undefined) bound.provider = selected;
73
+ if (select.model !== undefined) bound.model = select.model;
74
+ if (select.effort === null) delete bound.effort;
75
+ else if (select.effort !== undefined) bound.effort = select.effort;
76
+ out.baseagents[name] = bound;
77
+ }
78
+ }
79
+ return { config: out, refs };
80
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * 模板目录的读取与校验。
3
+ *
4
+ * <模板>/
5
+ * ├── team.json 团队声明(值的来源)
6
+ * ├── team.schema.json 模板 schema:允许写哪些字段、什么类型
7
+ * ├── .evolcore/ 只放「原样放进容器」的资源
8
+ * │ ├── providers.json 模型服务凭证(可用 ${VAR} 引用环境变量)
9
+ * │ ├── agents/defaults.json 全局默认配置
10
+ * │ └── skills/<技能名>/ 本机技能,所有 agent 共用
11
+ * ├── agents/<key>/ 每个 agent 的资源(不含配置)
12
+ * │ ├── personal/soul/*.md
13
+ * │ └── triggers/<id>/trigger.json 可用 {{agent.aid}} {{owner.aid}} {{host.aid}}
14
+ * └── workspace/<key>/ 可选:该项目目录的初始内容
15
+ *
16
+ * 配置不进模板文件:agent config.json 与 daemon.json 由 pa-team-build 按 team.json 的
17
+ * config 段 + 工具管理的字段生成,避免「改模板配置」和「工具写配置」两处打架。
18
+ */
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { createHash } from 'node:crypto';
22
+ import { normalizeTeam, normalizeTeamSchema, validateContractSchema } from './template-contract.mjs';
23
+
24
+ /** 由工具写入,模板里出现即视为错误。 */
25
+ export const MANAGED_AGENT_FIELDS = ['aid', 'enabled', 'lifecycle', 'owner', 'owners', 'channels', 'projects'];
26
+ export const MANAGED_DAEMON_FIELDS = ['aid', 'owner', 'owners'];
27
+
28
+ /** 允许放进模板 .evolcore/ 的条目。AIDs/、agents/<aid>/ 等运行时目录不能出现。 */
29
+ export const HOME_ALLOWED = ['providers.json', 'agents', 'skills', '.env'];
30
+ const HOME_AGENTS_ALLOWED = ['defaults.json'];
31
+
32
+ /** 每个 agent 目录里允许出现的条目。配置文件不在其中——它由工具生成。 */
33
+ const AGENT_DIR_ALLOWED = ['personal', 'triggers'];
34
+
35
+ const KEY_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
36
+ const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
37
+
38
+ function readJson(file) {
39
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
40
+ }
41
+
42
+ function listRel(root) {
43
+ const out = [];
44
+ const walk = (dir) => {
45
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
46
+ const abs = path.join(dir, e.name);
47
+ if (e.isSymbolicLink()) throw new Error(`symlinks are not allowed in templates: ${path.relative(root, abs)}`);
48
+ if (e.isDirectory()) walk(abs);
49
+ else out.push(path.relative(root, abs));
50
+ }
51
+ };
52
+ if (fs.existsSync(root)) walk(root);
53
+ return out.sort();
54
+ }
55
+
56
+ /** 模板内容摘要:文件路径 + 内容。用于记录「这支团队套的是哪一版模板」。 */
57
+ export function templateDigest(dir) {
58
+ const h = createHash('sha256');
59
+ for (const rel of listRel(dir)) {
60
+ h.update(rel).update('\0').update(fs.readFileSync(path.join(dir, rel))).update('\0');
61
+ }
62
+ return h.digest('hex').slice(0, 12);
63
+ }
64
+
65
+ /**
66
+ * 读取并做结构校验(不依赖 EvolCore)。返回 { tpl, errors }。
67
+ * schema 是否与 EvolCore 一致由 prepare 阶段用 validateConfig 复核。
68
+ */
69
+ export function loadTemplate(dir) {
70
+ const root = path.resolve(dir);
71
+ const errors = [];
72
+ for (const f of ['team.json', 'team.schema.json']) {
73
+ if (!fs.existsSync(path.join(root, f))) return { errors: [`${f} not found in ${root}`] };
74
+ }
75
+
76
+ let team; let schema;
77
+ try { team = readJson(path.join(root, 'team.json')); } catch (err) { return { errors: [`team.json: ${err.message}`] }; }
78
+ try { schema = readJson(path.join(root, 'team.schema.json')); } catch (err) { return { errors: [`team.schema.json: ${err.message}`] }; }
79
+ const normalized = normalizeTeam(team, { fallbackName: path.basename(root) });
80
+ if (normalized.errors.length) return { errors: normalized.errors };
81
+ team = normalized.team;
82
+ try { schema = normalizeTeamSchema(schema); } catch (err) { return { errors: [err.message] }; }
83
+ errors.push(...validateContractSchema(team, schema, 'team.json'));
84
+
85
+ const name = team.name ?? path.basename(root);
86
+ const version = team.version !== undefined ? String(team.version) : '';
87
+ if (typeof name !== 'string' || !NAME_RE.test(name)) errors.push(`team.json name must match ${NAME_RE}`);
88
+ const keys = Array.isArray(team.agents) ? team.agents.map(a => a?.key) : [];
89
+ if (keys.length === 0 || !keys.every(k => typeof k === 'string' && KEY_RE.test(k))) {
90
+ errors.push('team.json agents[].key are required and must be path-safe');
91
+ }
92
+ if (!schema || schema.type !== 'object') errors.push('team.schema.json must be a JSON Schema object');
93
+
94
+ let files;
95
+ try { files = listRel(root); } catch (err) { return { errors: [err.message] }; }
96
+
97
+ // .evolcore/ 只允许白名单内的条目
98
+ const homeFiles = files.filter(f => f.startsWith('.evolcore/')).map(f => f.slice('.evolcore/'.length));
99
+ for (const f of homeFiles) {
100
+ const top = f.split('/')[0];
101
+ if (!HOME_ALLOWED.includes(top)) errors.push(`.evolcore/${top} is not allowed in templates`);
102
+ else if (top === 'agents' && !HOME_AGENTS_ALLOWED.includes(f.slice('agents/'.length))) {
103
+ errors.push(`.evolcore/${f} is not allowed; per-agent files go under agents/<key>/`);
104
+ }
105
+ }
106
+
107
+ // daemon.json 不再来自模板;模板若还留着就明确报错,避免以为它生效
108
+ for (const stale of ['daemon.json']) {
109
+ if (fs.existsSync(path.join(root, '.evolcore', stale))) {
110
+ errors.push(`.evolcore/${stale} is no longer read; put daemon fields under host.config in team.json`);
111
+ }
112
+ }
113
+
114
+ // agents/<key>/ 必须和 team.json 对上,且不能自带 config.json
115
+ const agentDirs = fs.existsSync(path.join(root, 'agents'))
116
+ ? fs.readdirSync(path.join(root, 'agents'), { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name)
117
+ : [];
118
+ for (const d of agentDirs) if (!keys.includes(d)) errors.push(`agents/${d} has no matching key in team.json`);
119
+ for (const key of keys) {
120
+ const agentRoot = path.join(root, 'agents', key);
121
+ if (!fs.existsSync(agentRoot)) continue;
122
+ for (const e of fs.readdirSync(agentRoot, { withFileTypes: true })) {
123
+ if (!AGENT_DIR_ALLOWED.includes(e.name)) errors.push(`agents/${key}/${e.name} is not allowed; configuration is generated from team.json`);
124
+ }
125
+ const cfg = path.join(agentRoot, 'config.json');
126
+ if (fs.existsSync(cfg)) errors.push(`agents/${key}/config.json is not read; put agent fields under agents[].config in team.json`);
127
+ }
128
+
129
+ const wsDirs = fs.existsSync(path.join(root, 'workspace'))
130
+ ? fs.readdirSync(path.join(root, 'workspace'), { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name)
131
+ : [];
132
+ for (const d of wsDirs) if (!keys.includes(d)) errors.push(`workspace/${d} has no matching key in team.json`);
133
+
134
+ if (errors.length) return { errors };
135
+ return {
136
+ errors,
137
+ tpl: {
138
+ root, name, version, keys, files, team, schema, changes: normalized.changes,
139
+ label: `${name}@${version || templateDigest(root)}`,
140
+ },
141
+ };
142
+ }