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,235 @@
1
+ // Vendored from projects/pa-team/packages/pa-team-build/src/common.mjs (2026-11-09).
2
+ /**
3
+ * parseArgs, createRecorder, listFiles, readJson, writeJson, copyTree — 各子命令共用。
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { gzipSync, gunzipSync } from 'node:zlib';
9
+ import { isProcessRunning } from '../../../dist/utils/cross-platform.js';
10
+
11
+ const parentPid = process.ppid;
12
+
13
+ export const LIMITS = { file: 20 * 1024 * 1024, total: 200 * 1024 * 1024, entries: 20000 };
14
+ export const BASEAGENTS = ['claude', 'codex', 'gemini', 'ecagent'];
15
+ export const CONFIG_FIELDS = ['chatmode', 'memory'];
16
+ export const PROFILE_FIELDS = ['name', 'description', 'avatar', 'tags', 'exttype'];
17
+
18
+ export function assert(value, code, message, data) {
19
+ if (!value) throw Object.assign(new Error(message), { code, ...(data === undefined ? {} : { data }) });
20
+ }
21
+
22
+ export function sha256(bytes) { return createHash('sha256').update(bytes).digest('hex'); }
23
+ export function jsonBytes(value) { return Buffer.from(JSON.stringify(value, null, 2) + '\n'); }
24
+ export function posix(value) { return value.split(path.sep).join('/'); }
25
+ export function isRecord(value) { return !!value && typeof value === 'object' && !Array.isArray(value); }
26
+
27
+ export function inside(root, relative) {
28
+ assert(typeof relative === 'string' && relative.length && !path.isAbsolute(relative)
29
+ && !relative.includes('\\') && !relative.includes('\0') && !relative.includes(':')
30
+ && relative.split('/').every(p => p && p !== '.' && p !== '..'), 'INVALID_ARGUMENT', 'Invalid relative path: ' + relative);
31
+ const target = path.resolve(root, relative);
32
+ assert(target.startsWith(path.resolve(root) + path.sep), 'INVALID_ARGUMENT', 'Path leaves root');
33
+ return target;
34
+ }
35
+
36
+ /** Check ancestors as well: a missing file must not be created through a symlink. */
37
+ export function regularPath(target) {
38
+ let current = path.resolve(target);
39
+ while (true) {
40
+ try {
41
+ const stat = fs.lstatSync(current);
42
+ assert(!stat.isSymbolicLink(), 'INVALID_ARGUMENT', 'Symbolic links are not supported: ' + current);
43
+ if (current === path.resolve(target)) assert(stat.isFile() || stat.isDirectory(), 'INVALID_ARGUMENT', 'Regular path required');
44
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
45
+ const parent = path.dirname(current);
46
+ if (parent === current) break;
47
+ current = parent;
48
+ }
49
+ }
50
+
51
+ export function walkFiles(root, exclude = () => false) {
52
+ if (!fs.existsSync(root)) return [];
53
+ regularPath(root);
54
+ const files = [];
55
+ let total = 0;
56
+ const visit = (dir) => {
57
+ for (const e of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
58
+ const file = path.join(dir, e.name);
59
+ if (exclude(posix(path.relative(root, file)))) continue;
60
+ assert(!e.isSymbolicLink() && (e.isFile() || e.isDirectory()), 'INVALID_ARGUMENT', 'Only regular files/directories: ' + file);
61
+ assert(files.length < LIMITS.entries, 'PACKAGE_TOO_LARGE', 'Too many package files');
62
+ if (e.isDirectory()) visit(file);
63
+ else {
64
+ const stat = fs.statSync(file);
65
+ total += stat.size;
66
+ assert(stat.size <= LIMITS.file && total <= LIMITS.total, 'PACKAGE_TOO_LARGE', 'Package size limit exceeded: ' + file);
67
+ files.push(posix(path.relative(root, file)));
68
+ }
69
+ }
70
+ };
71
+ visit(root);
72
+ return files.sort();
73
+ }
74
+
75
+ export function atomicBytes(file, bytes, mode = 0o644) {
76
+ assert(isProcessRunning(parentPid), 'TASK_INTERRUPTED', 'Template coordinator exited');
77
+ regularPath(file);
78
+ fs.mkdirSync(path.dirname(file), { recursive: true });
79
+ const temporary = path.join(path.dirname(file), '.template-' + randomUUID());
80
+ try {
81
+ fs.writeFileSync(temporary, bytes, { flag: 'wx', mode });
82
+ fs.chmodSync(temporary, mode);
83
+ const descriptor = fs.openSync(temporary, 'r');
84
+ try { fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
85
+ fs.renameSync(temporary, file);
86
+ } finally { fs.rmSync(temporary, { force: true }); }
87
+ }
88
+
89
+ export function snapshot(file) {
90
+ regularPath(file);
91
+ try {
92
+ const stat = fs.statSync(file);
93
+ assert(stat.isFile(), 'CONFLICT', 'Expected file: ' + file);
94
+ return { sha256: sha256(fs.readFileSync(file)), mode: stat.mode & 0o777 };
95
+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
96
+ }
97
+
98
+ export function equalSnapshot(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
99
+
100
+ export function mergeObjects(existing, overlay) {
101
+ const out = structuredClone(existing);
102
+ for (const [key, value] of Object.entries(overlay)) {
103
+ assert(!['__proto__', 'constructor', 'prototype'].includes(key), 'INVALID_ARGUMENT', 'Invalid object key');
104
+ out[key] = isRecord(value) && isRecord(out[key]) ? mergeObjects(out[key], value) : structuredClone(value);
105
+ }
106
+ return out;
107
+ }
108
+
109
+ export function behaviorConfig(config) {
110
+ const out = {};
111
+ for (const field of CONFIG_FIELDS) if (config[field] !== undefined) out[field] = structuredClone(config[field]);
112
+ return out;
113
+ }
114
+
115
+ /** USTAR format, ordered entries, fixed owner/time; no system tar dependency. */
116
+ export function archive(root) {
117
+ const blocks = [];
118
+ for (const name of walkFiles(root)) {
119
+ const bytes = fs.readFileSync(inside(root, name));
120
+ const header = Buffer.alloc(512);
121
+ let short = name; let prefix = '';
122
+ if (Buffer.byteLength(name) > 100) {
123
+ const splits = [...name.matchAll(/\//g)].map(m => m.index).reverse();
124
+ const split = splits.find(i => Buffer.byteLength(name.slice(i + 1)) <= 100 && Buffer.byteLength(name.slice(0, i)) <= 155);
125
+ assert(split !== undefined, 'INVALID_ARGUMENT', 'Archive path too long: ' + name);
126
+ short = name.slice(split + 1); prefix = name.slice(0, split);
127
+ }
128
+ const octal = (n, offset, len) => header.write(n.toString(8).padStart(len - 1, '0') + '\0', offset, len, 'ascii');
129
+ header.write(short, 0, 100); octal(fs.statSync(inside(root, name)).mode & 0o111 ? 0o755 : 0o644, 100, 8);
130
+ octal(0, 108, 8); octal(0, 116, 8); octal(bytes.length, 124, 12); octal(0, 136, 12);
131
+ header.fill(32, 148, 156); header.write('0', 156); header.write('ustar\0', 257); header.write('00', 263);
132
+ header.write(prefix, 345, 155);
133
+ header.write(header.reduce((sum, b) => sum + b, 0).toString(8).padStart(6, '0') + '\0 ', 148, 8);
134
+ blocks.push(header, bytes, Buffer.alloc((512 - bytes.length % 512) % 512));
135
+ }
136
+ blocks.push(Buffer.alloc(1024));
137
+ return gzipSync(Buffer.concat(blocks), { level: 9 });
138
+ }
139
+
140
+ export function unpack(bytes, directory) {
141
+ assert(bytes.length <= LIMITS.total, 'PACKAGE_TOO_LARGE', 'Archive exceeds limit');
142
+ const tar = gunzipSync(bytes, { maxOutputLength: LIMITS.total + LIMITS.entries * 1024 });
143
+ const names = new Set(); let total = 0;
144
+ for (let offset = 0; offset + 512 <= tar.length;) {
145
+ const h = tar.subarray(offset, offset + 512); offset += 512;
146
+ if (h.every(b => b === 0)) break;
147
+ const text = (at, len) => h.subarray(at, at + len).toString('utf8').replace(/\0.*$/s, '');
148
+ const name = (text(345, 155) ? text(345, 155) + '/' : '') + text(0, 100);
149
+ const size = Number.parseInt(text(124, 12).trim() || '0', 8);
150
+ const checksum = h.reduce((n, b, i) => n + (i >= 148 && i < 156 ? 32 : b), 0);
151
+ assert(Number.parseInt(text(148, 8).trim(), 8) === checksum && ['', '0'].includes(text(156, 1))
152
+ && Number.isSafeInteger(size) && size >= 0 && size <= LIMITS.file && offset + size <= tar.length,
153
+ 'INTEGRITY_FAILED', 'Invalid archive entry');
154
+ total += size;
155
+ assert(!names.has(name.toLowerCase()) && names.size < LIMITS.entries && total <= LIMITS.total,
156
+ 'INTEGRITY_FAILED', 'Duplicate or excessive archive entries');
157
+ names.add(name.toLowerCase());
158
+ const dest = inside(directory, name);
159
+ regularPath(dest); fs.mkdirSync(path.dirname(dest), { recursive: true });
160
+ const mode = Number.parseInt(text(100, 8).trim(), 8) & 0o111 ? 0o755 : 0o644;
161
+ fs.writeFileSync(dest, tar.subarray(offset, offset + size), { flag: 'wx', mode });
162
+ offset += Math.ceil(size / 512) * 512;
163
+ }
164
+ assert(names.size > 0, 'INTEGRITY_FAILED', 'Empty archive');
165
+ }
166
+
167
+ export function readJson(file) {
168
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
169
+ }
170
+
171
+ /** 按 EvolCore 的规范排版写 JSON:JSON.stringify(value, null, 2) 加结尾换行。 */
172
+ export function writeJson(file, value) {
173
+ fs.mkdirSync(path.dirname(file), { recursive: true });
174
+ fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n');
175
+ }
176
+
177
+ /** 复制文件或目录;src 不存在时什么也不做。目标已有的同名文件被覆盖,其余保留。 */
178
+ export function copyTree(src, dst) {
179
+ if (!fs.existsSync(src)) return;
180
+ fs.cpSync(src, dst, { recursive: true, force: true, errorOnExist: false, verbatimSymlinks: true });
181
+ }
182
+
183
+ export class UsageError extends Error {
184
+ constructor(message) {
185
+ super(message);
186
+ this.name = 'UsageError';
187
+ }
188
+ }
189
+
190
+ export function parseArgs(argv, { values = [], booleans = [] }) {
191
+ const out = {};
192
+ for (let i = 0; i < argv.length; i++) {
193
+ const arg = argv[i];
194
+ if (arg === '--help') { out.help = true; continue; }
195
+ if (!arg.startsWith('--')) throw new UsageError(`unknown argument: ${arg}`);
196
+ const key = arg.slice(2);
197
+ if (booleans.includes(key)) { out[key] = true; continue; }
198
+ if (!values.includes(key)) throw new UsageError(`unknown option: ${arg}`);
199
+ if (i + 1 >= argv.length) throw new UsageError(`${arg} requires a value`);
200
+ out[key] = argv[++i];
201
+ }
202
+ return out;
203
+ }
204
+
205
+ export function createRecorder(logFile) {
206
+ const log = (entry) => fs.appendFileSync(logFile, JSON.stringify(entry) + '\n');
207
+ const checks = [];
208
+ return {
209
+ log,
210
+ check(name, ok, detail) {
211
+ const entry = { check: name, ok: !!ok };
212
+ if (detail !== undefined) entry.detail = detail;
213
+ checks.push(entry);
214
+ log(entry);
215
+ return ok;
216
+ },
217
+ summary() {
218
+ const failures = checks.filter(c => !c.ok).map(c => c.check);
219
+ return { total: checks.length, passed: checks.length - failures.length, failed: failures.length, failures };
220
+ },
221
+ };
222
+ }
223
+
224
+ export function listFiles(root) {
225
+ const out = [];
226
+ const walk = (dir) => {
227
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
228
+ const abs = path.join(dir, e.name);
229
+ if (e.isDirectory()) walk(abs);
230
+ else out.push(path.relative(root, abs));
231
+ }
232
+ };
233
+ walk(root);
234
+ return out.sort();
235
+ }
@@ -0,0 +1,75 @@
1
+ // Vendored from projects/pa-team/packages/pa-team-build/src/evolcore.mjs (2026-11-09).
2
+ /**
3
+ * 定位 EvolCore 包根并加载 pa-team-build 要复用的模块:配置校验、目录骨架、trigger 校验。
4
+ *
5
+ * 这些是 EvolCore 的内部构建产物(dist/),不是公开 API。路径或导出变化时,loadEvolcore() 会报出缺失项。
6
+ * EvolCore 的根目录由 EVOLCORE_HOME 决定且会被缓存;切换目标目录要调用 setHome()。
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ function isEvolcoreRoot(dir) {
13
+ try {
14
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
15
+ return pkg.name === 'evolcore' && fs.existsSync(path.join(dir, 'dist'));
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+
21
+ /** 查找顺序:--package-root → EVOLCORE_PACKAGE_ROOT → 当前 node 前缀下的全局安装。 */
22
+ export function resolvePackageRoot(explicit) {
23
+ const candidate = explicit
24
+ ? path.resolve(explicit)
25
+ : process.env.EVOLCORE_PACKAGE_ROOT
26
+ ? path.resolve(process.env.EVOLCORE_PACKAGE_ROOT)
27
+ : path.join(path.dirname(path.dirname(process.execPath)), 'lib', 'node_modules', 'evolcore');
28
+ if (!isEvolcoreRoot(candidate)) {
29
+ throw new Error(`EvolCore package root not found (tried ${candidate}); pass --package-root or set EVOLCORE_PACKAGE_ROOT`);
30
+ }
31
+ return fs.realpathSync(candidate);
32
+ }
33
+
34
+ /**
35
+ * @param {string} packageRoot
36
+ * @param {string} scratchHome 加载期间 EvolCore 写日志用的目录;不能是团队的 .evolcore/
37
+ */
38
+ export async function loadEvolcore(packageRoot, scratchHome) {
39
+ fs.mkdirSync(scratchHome, { recursive: true });
40
+ const { RUNTIME_HOME_ENV } = await import(pathToFileURL(path.join(packageRoot, 'dist', 'product.js')).href);
41
+ process.env[RUNTIME_HOME_ENV] = scratchHome;
42
+ const load = async (rel, names) => {
43
+ const file = path.join(packageRoot, 'dist', rel);
44
+ if (!fs.existsSync(file)) throw new Error(`EvolCore module missing: dist/${rel}`);
45
+ const mod = await import(pathToFileURL(file).href);
46
+ const missing = names.filter(n => typeof mod[n] === 'undefined');
47
+ if (missing.length) throw new Error(`EvolCore dist/${rel} lacks exports: ${missing.join(', ')}`);
48
+ return mod;
49
+ };
50
+ const paths = await load('paths.js', ['_resetRoot', 'resolveRoot']);
51
+ const store = await load('config-store.js', ['ensureAgentDirSkeleton']);
52
+ const cm = await load('config/config-manager.js', ['validateConfig', 'ConfigTarget']);
53
+ const schema = await load('config/schema-registry.js', ['currentVersion']);
54
+ const trigger = await load('trigger/validation.js', ['normalizeTriggerDefinition', 'assertExplicitAunDeliveryRoutes']);
55
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
56
+
57
+ return {
58
+ version: pkg.version,
59
+ /** 把 EvolCore 的根切到 dir;之后的目录骨架、配置校验都以它为准。 */
60
+ setHome(dir) {
61
+ process.env[RUNTIME_HOME_ENV] = dir;
62
+ paths._resetRoot();
63
+ },
64
+ ensureAgentDirSkeleton: store.ensureAgentDirSkeleton,
65
+ validate(target, value) {
66
+ return cm.validateConfig(cm.ConfigTarget[target], value);
67
+ },
68
+ schemaVersion: (name) => schema.currentVersion(name),
69
+ validateTrigger(raw) {
70
+ const def = trigger.normalizeTriggerDefinition(raw, { now: Date.now() });
71
+ trigger.assertExplicitAunDeliveryRoutes(def);
72
+ return def;
73
+ },
74
+ };
75
+ }
@@ -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
+ }