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,40 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { isMainScript } from '../../dist/utils/cross-platform.js';
4
+ import { parseArgs, readJson } from './shared/common.mjs';
5
+
6
+ export async function cli(argv) {
7
+ const command = argv[0];
8
+ if (!command || argv.includes('--help')) {
9
+ console.log('Agent template: inspect-agent | pack | inspect-package | overlay --options-file <JSON>');
10
+ return 0;
11
+ }
12
+ const args = parseArgs(argv.slice(1), { values: ['options-file', 'agent-dir', 'template', 'out', 'aid', 'owner', 'host', 'providers', 'workspace', 'backup'] });
13
+ const options = { ...(args['options-file'] ? readJson(args['options-file']) : {}) };
14
+ const mapping = { 'agent-dir': 'agentDir', template: 'templateDir', out: 'out', aid: 'targetAid', owner: 'ownerAid', host: 'hostAid', workspace: 'projectPath', backup: 'backupDir' };
15
+ for (const [from, to] of Object.entries(mapping)) if (args[from]) options[to] = args[from];
16
+ if (args.providers) options.selections = JSON.parse(args.providers);
17
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
18
+ options.packageRoot ??= packageRoot;
19
+ const commands = {
20
+ 'inspect-agent': ['./inspect.mjs', 'inspectAgent'],
21
+ pack: ['./pack.mjs', 'pack'],
22
+ 'inspect-package': ['./inspect.mjs', 'inspectPackage'],
23
+ overlay: ['./overlay.mjs', 'overlay'],
24
+ };
25
+ const entry = commands[command];
26
+ if (!entry) throw Object.assign(new Error('Unknown template command: ' + command), { code: 'INVALID_ARGUMENT' });
27
+ const mod = await import(new URL(entry[0], import.meta.url).href);
28
+ const result = await mod[entry[1]](options);
29
+ console.log(JSON.stringify({ type: 'result', ok: true, data: result }));
30
+ return 0;
31
+ }
32
+
33
+ if (isMainScript(import.meta.url)) {
34
+ try { process.exitCode = await cli(process.argv.slice(2)); }
35
+ catch (error) {
36
+ console.log(JSON.stringify({ type: 'result', ok: false, code: error.code || 'TOOL_FAILED', message: error.message,
37
+ ...(error.data === undefined ? {} : { data: error.data }) }));
38
+ process.exitCode = error.code === 'INVALID_ARGUMENT' || error.name === 'UsageError' ? 2 : 1;
39
+ }
40
+ }
@@ -0,0 +1,240 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { createHash } from 'node:crypto';
5
+ import { readJson, jsonBytes, assert, sha256, walkFiles, inside, unpack, behaviorConfig, mergeObjects,
6
+ snapshot, BASEAGENTS, PROFILE_FIELDS, isRecord, regularPath, atomicBytes } from './shared/common.mjs';
7
+ import { loadTemplate, MANAGED_AGENT_FIELDS, templateDigest } from './shared/template.mjs';
8
+ import { loadEvolcore } from './shared/evolcore.mjs';
9
+ import { validateAgainstSchema, buildAgentTriggers, resolveProviderRefs } from './shared/plan.mjs';
10
+ import { excluded } from './pack.mjs';
11
+ import { normalizeTeam } from './shared/template-contract.mjs';
12
+ import { renderValue as renderTemplateValue, renderResource, bindTemplateProviders } from './shared/template-runtime.mjs';
13
+
14
+ export async function inspectAgent(options) {
15
+ const config = options.effectiveConfig ?? readJson(path.join(options.agentDir, 'config.json'));
16
+ const soul = path.join(options.agentDir, 'personal', 'soul');
17
+ const triggerRoot = path.join(options.agentDir, 'triggers');
18
+ const project = options.projectPath ?? config.projects?.defaultPath;
19
+ assert(typeof project === 'string' && path.isAbsolute(project), 'INVALID_ARGUMENT', 'Agent default project is required');
20
+ const triggers = fs.existsSync(triggerRoot) ? fs.readdirSync(triggerRoot, { withFileTypes: true }).filter(e => e.isDirectory()).map(e => {
21
+ const def = readJson(path.join(triggerRoot, e.name, 'trigger.json'));
22
+ return { id: def.id, name: def.name, enabled: def.enabled !== false };
23
+ }) : [];
24
+ return { aid: options.agentAid, name: options.profile?.name ?? '', description: options.profile?.description ?? '',
25
+ profile: { soul: fs.existsSync(soul) ? fs.readdirSync(soul).filter(f => f.endsWith('.md') && f !== '00-GUIDE.md').sort() : [],
26
+ welcome: fs.existsSync(path.join(options.agentDir, 'personal', 'welcome.md')), config: behaviorConfig(config) },
27
+ activeBaseagent: config.active_baseagent,
28
+ baseagents: BASEAGENTS.filter(name => config.baseagents?.[name]).map(name => ({ name, currentModel: config.baseagents[name].model ?? null,
29
+ currentEffort: config.baseagents[name].effort ?? null, provider: config.baseagents[name].provider ?? null })),
30
+ triggers, skills: options.skills ?? [],
31
+ project: { path: project, files: fs.existsSync(project) ? fs.readdirSync(project).filter(f => !excluded(f)).sort() : [] } };
32
+ }
33
+
34
+ export async function inspectPackage(options) {
35
+ let root = options.packageDir;
36
+ if (options.archivePath) {
37
+ root = path.join(options.out, 'unpacked');
38
+ assert(!fs.existsSync(root), 'CONFLICT', 'Package is already unpacked');
39
+ fs.mkdirSync(root, { recursive: true });
40
+ const bytes = fs.readFileSync(options.archivePath);
41
+ assert('sha256:' + sha256(bytes) === options.digest, 'INTEGRITY_FAILED', 'Package digest mismatch');
42
+ unpack(bytes, root);
43
+ }
44
+ assert(root && path.isAbsolute(root), 'INVALID_ARGUMENT', 'Package directory required');
45
+ const pkg = readJson(path.join(root, 'PACKAGE.json'));
46
+ assert(pkg.$schema_version === 1 && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(pkg.id)
47
+ && /^\d+\.\d+\.\d+$/.test(pkg.version), 'INTEGRITY_FAILED', 'Invalid package metadata');
48
+ const manifest = readJson(path.join(root, 'MANIFEST.json'));
49
+ assert(Array.isArray(manifest), 'INTEGRITY_FAILED', 'Invalid manifest');
50
+ const templateDir = path.join(root, 'template');
51
+ const files = walkFiles(templateDir);
52
+ assert(manifest.length === files.length && new Set(manifest.map(f => f.path)).size === files.length,
53
+ 'INTEGRITY_FAILED', 'Manifest file set mismatch');
54
+ for (const entry of manifest) {
55
+ assert(files.includes(entry.path), 'INTEGRITY_FAILED', 'Unexpected manifest entry');
56
+ const bytes = fs.readFileSync(inside(templateDir, entry.path));
57
+ assert(bytes.length === entry.size && sha256(bytes) === entry.sha256, 'INTEGRITY_FAILED', 'Manifest checksum mismatch: ' + entry.path);
58
+ }
59
+ assert(walkFiles(root).length === files.length + 2, 'INTEGRITY_FAILED', 'Unexpected package entries');
60
+ const { tpl, errors } = loadTemplate(templateDir);
61
+ assert(!errors.length, 'INVALID_ARGUMENT', errors.join('; '));
62
+ const contract = normalizeTeam(tpl.team, { packageInfo: pkg });
63
+ assert(!contract.errors.length, 'INTEGRITY_FAILED', contract.errors.join('; '));
64
+ assert(tpl.keys.length > 0 && new Set(tpl.keys).size === tpl.keys.length && tpl.name === pkg.id && tpl.version === pkg.version,
65
+ 'INVALID_ARGUMENT', 'Matching template metadata and unique member keys required');
66
+ const schemaErrors = validateAgainstSchema(tpl.team, tpl.schema);
67
+ assert(!schemaErrors.length, 'INVALID_ARGUMENT', schemaErrors.join('; '));
68
+ // Check the complete package before selecting member resources. No member may hide unsupported files.
69
+ for (const file of files) assert(file === 'team.json' || file === 'team.schema.json'
70
+ || file.startsWith('.evolcore/skills/') || tpl.keys.some(key => file.startsWith('workspace/' + key + '/')
71
+ || file.startsWith('agents/' + key + '/personal/soul/') && file.endsWith('.md') && !file.endsWith('/00-GUIDE.md')
72
+ || file === 'agents/' + key + '/personal/welcome.md' || file.startsWith('agents/' + key + '/triggers/')),
73
+ 'INVALID_ARGUMENT', 'Unsupported template resource: ' + file);
74
+ const platforms = tpl.team.host?.platform;
75
+ if (platforms !== undefined) assert(Array.isArray(platforms) && platforms.length
76
+ && platforms.every(p => ['linux', 'darwin', 'win32'].includes(p)) && platforms.includes(process.platform),
77
+ 'INCOMPATIBLE', 'Template host.platform must support this host');
78
+ if (!options.targets) {
79
+ assert(tpl.keys.length === 1, 'INVALID_ARGUMENT', 'Provide targets mapping for every template member');
80
+ return inspectMember(options, { pkg, tpl, templateDir, files, key: tpl.keys[0] });
81
+ }
82
+ assert(isRecord(options.targets) && tpl.keys.length === Object.keys(options.targets).length
83
+ && tpl.keys.every(key => Object.hasOwn(options.targets, key)), 'INVALID_ARGUMENT', 'Map every template member exactly once');
84
+ const contexts = tpl.keys.map(key => options.targets[key]);
85
+ assert(contexts.every(c => isRecord(c) && typeof c.targetAid === 'string' && c.home === contexts[0].home)
86
+ && new Set(contexts.map(c => c.targetAid)).size === contexts.length,
87
+ 'INVALID_ARGUMENT', 'Members must map to distinct Agents on the same host');
88
+ assert(Object.keys(options.members ?? {}).every(key => tpl.keys.includes(key)), 'INVALID_ARGUMENT', 'Unknown member selection');
89
+ const writes = new Map(); const members = []; const plans = [];
90
+ for (const key of tpl.keys) {
91
+ const selection = options.members?.[key] ?? {};
92
+ const out = inside(options.out ?? path.dirname(root), 'members/' + key);
93
+ const data = await inspectMember({ ...options.targets[key], out, packageRoot: options.packageRoot, digest: options.digest,
94
+ pullId: options.pullId, selections: selection.providers ?? {}, externalAids: selection.externalAids ?? {} },
95
+ { pkg, tpl, templateDir, key, files: files.filter(f => !f.startsWith('agents/') && !f.startsWith('workspace/')
96
+ || f.startsWith('agents/' + key + '/') || f.startsWith('workspace/' + key + '/')) });
97
+ const plan = readJson(data.planFile);
98
+ for (const write of plan.writes) {
99
+ const previous = writes.get(write.path);
100
+ assert(!previous || JSON.stringify(previous) === JSON.stringify(write), 'CONFLICT', 'Members write different shared content: ' + write.path);
101
+ writes.set(write.path, write);
102
+ }
103
+ const { planFile: _planFile, ...preview } = data;
104
+ members.push({ key, targetAid: plan.targetAid, ...preview });
105
+ plans.push({ key, targetAid: plan.targetAid, projectPath: plan.projectPath, profile: plan.profile,
106
+ originalProfile: plan.originalProfile, profileVersion: plan.profileVersion, providers: plan.providers });
107
+ }
108
+ const planFile = path.join(options.out ?? path.dirname(root), 'plan.json');
109
+ atomicBytes(planFile, jsonBytes({ version: 1, home: contexts[0].home, templateDir,
110
+ templateDigest: templateDigest(templateDir), package: pkg, writes: [...writes.values()], members: plans }));
111
+ return { pullId: options.pullId, template: members[0].template, compatible: true, incompatible: [],
112
+ members, externalAids: pkg.externalAids ?? [], planFile };
113
+ }
114
+
115
+ async function inspectMember(options, { pkg, tpl, templateDir, files, key }) {
116
+ const root = path.dirname(templateDir);
117
+ const targets = options.targetConfig;
118
+ assert(targets?.aid === options.targetAid, 'INVALID_ARGUMENT', 'Target configuration required');
119
+ const project = options.projectPath ?? targets.projects?.defaultPath;
120
+ assert(typeof project === 'string' && path.isAbsolute(project), 'INVALID_ARGUMENT', 'Target default project required');
121
+ const vars = { 'agent.aid': options.targetAid, 'owner.aid': options.ownerAid, 'host.aid': options.hostAid, 'project.path': project };
122
+ const renderValue = value => renderTemplateValue(value, vars, options.externalAids ?? {});
123
+ const spec = renderValue(tpl.team.agents.find(agent => agent.key === key));
124
+ for (const file of files) assert(file === 'team.json' || file === 'team.schema.json'
125
+ || file.startsWith('.evolcore/skills/') || file.startsWith('workspace/' + key + '/')
126
+ || file.startsWith('agents/' + key + '/personal/soul/') && file.endsWith('.md') && !file.endsWith('/00-GUIDE.md')
127
+ || file === 'agents/' + key + '/personal/welcome.md' || file.startsWith('agents/' + key + '/triggers/'),
128
+ 'INVALID_ARGUMENT', 'Unsupported template resource: ' + file);
129
+ assert(isRecord(spec.config) && !MANAGED_AGENT_FIELDS.some(f => f in spec.config)
130
+ && Object.keys(spec.config).every(f => ['chatmode', 'memory', 'active_baseagent', 'baseagents'].includes(f)),
131
+ 'INVALID_ARGUMENT', 'Unsupported template configuration');
132
+ const packageRoot = options.packageRoot ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
133
+ const temp = process.env.TMPDIR;
134
+ assert(temp && path.isAbsolute(temp), 'TEMP_UNAVAILABLE', 'Absolute TMPDIR required');
135
+ const scratch = fs.mkdtempSync(path.join(temp, 'template-validator-'));
136
+ let ec;
137
+ try { ec = await loadEvolcore(packageRoot, scratch); }
138
+ finally { /* Modules remain loaded; scratch is cleaned after validation below. */ }
139
+ try {
140
+ const { default: semver } = await import('semver');
141
+ assert(Array.isArray(pkg.compat?.platforms) && pkg.compat.platforms.includes(process.platform)
142
+ && semver.validRange(pkg.compat.evolcore) && semver.satisfies(ec.version.replace(/-test\.\d+$/, ''), pkg.compat.evolcore, { includePrerelease: true }),
143
+ 'INCOMPATIBLE', 'Platform or EvolCore version is incompatible', { incompatible: ['platform/version'] });
144
+ const selections = options.selections ?? {};
145
+ for (const [name, block] of Object.entries(spec.config.baseagents ?? {})) {
146
+ assert(BASEAGENTS.includes(name) && isRecord(block) && Object.keys(block).every(f => ['provider', 'model', 'effort', 'params'].includes(f)),
147
+ 'INVALID_ARGUMENT', 'Invalid baseagent block');
148
+ }
149
+ const { config: resolved, refs } = bindTemplateProviders(spec.config,
150
+ { providers: options.providers ?? {}, selections, allowMissing: true });
151
+ assert(resolved.baseagents?.[resolved.active_baseagent], 'INVALID_ARGUMENT', 'Default baseagent must be selected');
152
+ assert(Object.keys(selections).every(name => resolved.baseagents?.[name]), 'INVALID_ARGUMENT', 'Unknown baseagent selection');
153
+ const config = mergeObjects(targets, resolveProviderRefs(resolved));
154
+ for (const [name, select] of Object.entries(selections)) if (select.effort === null) delete config.baseagents[name].effort;
155
+ const configErrors = ec.validate('Agent', config);
156
+ assert(!configErrors.length, 'INVALID_ARGUMENT', configErrors.join('; '));
157
+ const agentDir = path.join(options.home, 'agents', options.targetAid);
158
+ const writes = [];
159
+ const add = (target, bytes, mode) => writes.push({ path: target, content: bytes.toString('base64'),
160
+ mode: mode ?? snapshot(target)?.mode ?? 0o644, expected: snapshot(target) });
161
+ add(path.join(agentDir, 'config.json'), jsonBytes(config));
162
+ add(path.join(agentDir, 'template.lock.json'), jsonBytes({ id: pkg.id, version: pkg.version,
163
+ publisherAid: pkg.publisher?.aid, digest: options.digest, installedAt: Date.now() }));
164
+ const render = (bytes, relative = '') => renderResource(bytes, vars, options.externalAids ?? {}, { json: relative.endsWith('.json') });
165
+ const preview = { profile: { fields: PROFILE_FIELDS.filter(f => spec.profile?.[f] !== undefined), preserve: ['aid', 'type', 'owner'] },
166
+ soul: { add: [], overwrite: [] }, triggers: { add: [], overwrite: [] }, skills: [], files: { add: 0, overwrite: 0 },
167
+ project: { path: project, changeDefault: false }, config: Object.keys(resolved) };
168
+ const skillMapping = {};
169
+ const localNames = [...new Set(files.filter(f => f.startsWith('.evolcore/skills/')).map(f => f.split('/')[2]))];
170
+ for (const name of localNames) {
171
+ const source = inside(path.join(templateDir, '.evolcore', 'skills'), name);
172
+ const hash = createHash('sha256');
173
+ for (const p of walkFiles(source)) hash.update(p).update('\0').update(render(fs.readFileSync(inside(source, p)), p)).update('\0');
174
+ const desiredDigest = hash.digest('hex').slice(0, 12);
175
+ let destName = name;
176
+ const original = inside(path.join(options.home, 'skills'), name);
177
+ if (fs.existsSync(original) && templateDigest(original) !== desiredDigest) destName += '--' + pkg.id;
178
+ const dest = inside(path.join(options.home, 'skills'), destName);
179
+ if (fs.existsSync(dest)) assert(templateDigest(dest) === desiredDigest, 'CONFLICT', 'Skill name conflicts: ' + destName);
180
+ skillMapping[name] = destName;
181
+ preview.skills.push({ name, installAs: destName });
182
+ for (const p of walkFiles(source)) add(inside(dest, p), render(fs.readFileSync(inside(source, p)), p),
183
+ fs.statSync(inside(source, p)).mode & 0o111 ? 0o755 : 0o644);
184
+ }
185
+ const switchesFile = path.join(agentDir, 'skills', '.switches.json');
186
+ const switches = fs.existsSync(switchesFile) ? readJson(switchesFile) : {};
187
+ for (const [name, value] of Object.entries(spec.skills ?? {})) switches[skillMapping[name] ?? name] = { enabled: value.enabled === true };
188
+ add(switchesFile, jsonBytes(switches));
189
+ const failures = []; const allowedTriggerFiles = new Set();
190
+ const triggers = buildAgentTriggers({ templateRoot: templateDir, key, aid: options.targetAid, vars, ec,
191
+ rec: { check: (name, ok, detail) => { if (!ok) failures.push(name + ': ' + String(detail)); } } });
192
+ assert(!failures.length, 'INVALID_ARGUMENT', failures.join('; '));
193
+ const triggerNames = new Set();
194
+ for (const { id, definition } of triggers) {
195
+ const dir = inside(path.join(agentDir, 'triggers'), id); triggerNames.add(id);
196
+ allowedTriggerFiles.add('agents/' + key + '/triggers/' + id + '/trigger.json');
197
+ const def = renderValue(definition);
198
+ def.enabled = false; delete def.authorizedBy; delete def.operatorPeers;
199
+ const normalized = ec.validateTrigger(def);
200
+ add(path.join(dir, 'trigger.json'), jsonBytes(normalized));
201
+ preview.triggers[fs.existsSync(path.join(dir, 'trigger.json')) ? 'overwrite' : 'add'].push(id);
202
+ if (def.execution.type === 'script') {
203
+ const rel = def.execution.script.path;
204
+ allowedTriggerFiles.add('agents/' + key + '/triggers/' + id + '/' + rel);
205
+ const source = inside(path.join(templateDir, 'agents', key, 'triggers', id), rel);
206
+ regularPath(source); add(inside(dir, rel), render(fs.readFileSync(source)), fs.statSync(source).mode & 0o111 ? 0o755 : 0o644);
207
+ }
208
+ const active = path.join(dir, 'active.json');
209
+ if (fs.existsSync(active)) writes.push({ path: active, remove: true, expected: snapshot(active) });
210
+ }
211
+ for (const file of files.filter(f => f.startsWith('agents/' + key + '/triggers/'))) {
212
+ assert(allowedTriggerFiles.has(file), 'INVALID_ARGUMENT', 'Unexpected Trigger file: ' + file);
213
+ }
214
+ for (const file of files) {
215
+ const prefix = 'agents/' + key + '/personal/';
216
+ if (file.startsWith(prefix)) {
217
+ const rel = file.slice(prefix.length); const target = inside(path.join(agentDir, 'personal'), rel);
218
+ add(target, render(fs.readFileSync(inside(templateDir, file)), file));
219
+ if (rel.startsWith('soul/')) preview.soul[fs.existsSync(target) ? 'overwrite' : 'add'].push(rel.slice(5));
220
+ } else if (file.startsWith('workspace/' + key + '/')) {
221
+ const rel = file.slice(('workspace/' + key + '/').length);
222
+ assert(!excluded(rel), 'INVALID_ARGUMENT', 'Excluded project file');
223
+ const target = inside(project, rel); add(target, render(fs.readFileSync(inside(templateDir, file)), file),
224
+ fs.statSync(inside(templateDir, file)).mode & 0o111 ? 0o755 : 0o644);
225
+ preview.files[fs.existsSync(target) ? 'overwrite' : 'add']++;
226
+ }
227
+ }
228
+ const plan = { version: 1, targetAid: options.targetAid, home: options.home, projectPath: project,
229
+ templateDir, templateDigest: templateDigest(templateDir), package: pkg, writes,
230
+ profile: spec.profile,
231
+ originalProfile: options.profile, profileVersion: options.profileVersion, providers: refs };
232
+ const planFile = path.join(options.out ?? path.dirname(root), 'plan.json');
233
+ atomicBytes(planFile, jsonBytes(plan));
234
+ return { pullId: options.pullId, template: { id: pkg.id, version: pkg.version, name: pkg.name, publisherAid: pkg.publisher?.aid },
235
+ compatible: true, incompatible: [], currentConfig: { baseagents: Object.entries((options.effectiveConfig ?? targets).baseagents ?? {}).map(([name, b]) => ({ name, ...b })),
236
+ soul: fs.existsSync(path.join(agentDir, 'personal', 'soul')) ? fs.readdirSync(path.join(agentDir, 'personal', 'soul')) : [],
237
+ triggers: fs.existsSync(path.join(agentDir, 'triggers')) ? fs.readdirSync(path.join(agentDir, 'triggers')) : [] },
238
+ providers: refs, preview, externalAids: pkg.externalAids ?? [], planFile };
239
+ } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
240
+ }
@@ -0,0 +1,71 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { assert, snapshot, equalSnapshot, readJson, jsonBytes, atomicBytes, regularPath } from './shared/common.mjs';
4
+ import { templateDigest } from './shared/template.mjs';
5
+
6
+ export function verifyPlan(plan) {
7
+ assert(templateDigest(plan.templateDir) === plan.templateDigest, 'CONFLICT', 'Cached template changed');
8
+ for (const write of plan.writes) assert(equalSnapshot(snapshot(write.path), write.expected), 'CONFLICT', 'Target changed: ' + write.path);
9
+ }
10
+
11
+ export function restore(backupDir) {
12
+ const file = path.join(backupDir, 'journal.json');
13
+ const journal = readJson(file);
14
+ assert(journal.version === 1 && Array.isArray(journal.entries), 'INSTALL_BROKEN', 'Invalid restore journal');
15
+ for (const entry of [...journal.entries].reverse()) {
16
+ regularPath(entry.path);
17
+ if (entry.existed) atomicBytes(entry.path, fs.readFileSync(path.join(backupDir, entry.backup)), entry.mode);
18
+ else fs.rmSync(entry.path, { force: true });
19
+ }
20
+ for (const dir of [...journal.createdDirs].reverse()) {
21
+ try { fs.rmdirSync(dir); } catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; }
22
+ }
23
+ atomicBytes(file, jsonBytes({ ...journal, restored: true }));
24
+ return { rolledBack: true };
25
+ }
26
+
27
+ export async function overlay(options) {
28
+ if (options.operation === 'restore') return restore(options.backupDir);
29
+ const plan = options.plan ?? readJson(options.planFile);
30
+ verifyPlan(plan);
31
+ if (options.operation === 'verify') return { valid: true };
32
+ const backupDir = options.backupDir;
33
+ const file = path.join(backupDir, 'journal.json');
34
+ const journal = { version: 1, targetAid: plan.targetAid,
35
+ ...(plan.members ? { targetAids: plan.members.map(member => member.targetAid) } : {}),
36
+ entries: [], createdDirs: [], applied: false };
37
+ const dirs = new Set();
38
+ // All originals are durable before the first target mutation. Recovery is idempotent.
39
+ try {
40
+ fs.mkdirSync(backupDir, { recursive: true });
41
+ assert(!fs.existsSync(file), 'CONFLICT', 'Overlay was already started');
42
+ for (const [i, write] of plan.writes.entries()) {
43
+ regularPath(write.path);
44
+ const existing = snapshot(write.path);
45
+ const entry = { path: write.path, existed: existing !== null, mode: existing?.mode ?? write.mode, backup: i + '.bin' };
46
+ if (existing) atomicBytes(path.join(backupDir, entry.backup), fs.readFileSync(write.path), 0o600);
47
+ journal.entries.push(entry);
48
+ let dir = path.dirname(write.path); const missing = [];
49
+ while (!fs.existsSync(dir)) { missing.unshift(dir); dir = path.dirname(dir); }
50
+ for (const d of missing) if (!dirs.has(d)) { dirs.add(d); journal.createdDirs.push(d); }
51
+ }
52
+ atomicBytes(file, jsonBytes(journal), 0o600);
53
+ } catch (error) {
54
+ if (error.code === 'CONFLICT') throw error;
55
+ throw Object.assign(new Error('Backup failed: ' + error.message), { code: 'BACKUP_FAILED' });
56
+ }
57
+ try {
58
+ verifyPlan(plan);
59
+ for (const write of plan.writes) {
60
+ if (write.remove) fs.rmSync(write.path, { force: true });
61
+ else atomicBytes(write.path, Buffer.from(write.content, 'base64'), write.mode);
62
+ }
63
+ atomicBytes(file, jsonBytes({ ...journal, applied: true }), 0o600);
64
+ return { applied: true, backupDir };
65
+ } catch (error) {
66
+ try { restore(backupDir); }
67
+ catch (restoreError) { throw Object.assign(new Error(error.message + '; restore: ' + restoreError.message),
68
+ { code: 'INSTALL_BROKEN', data: { rolledBack: false } }); }
69
+ throw Object.assign(error, { data: { rolledBack: true } });
70
+ }
71
+ }
@@ -0,0 +1,169 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { readJson, jsonBytes, assert, sha256, walkFiles, inside, archive, behaviorConfig,
4
+ BASEAGENTS, PROFILE_FIELDS, regularPath, atomicBytes, isRecord } from './shared/common.mjs';
5
+ import { normalizeTeam, readTeamSchema } from './shared/template-contract.mjs';
6
+
7
+ export function excluded(relative) {
8
+ return relative.split('/').some(p => ['.git', 'node_modules', '.claude'].includes(p)
9
+ || /^\.env/.test(p) || /\.(?:pem|key|db(?:[-.].*)?)$/i.test(p));
10
+ }
11
+
12
+ export function identityText(text, options, reverse = false) {
13
+ const pairs = [[options.agentAid, '{{agent.aid}}'], [options.ownerAid, '{{owner.aid}}'], [options.hostAid, '{{host.aid}}']];
14
+ if (options.projectPath) pairs.push([options.projectPath, '{{project.path}}']);
15
+ for (const [value, token] of pairs) if (value) text = text.split(reverse ? token : value).join(reverse ? value : token);
16
+ return text;
17
+ }
18
+
19
+ function identityValue(value, options) {
20
+ if (typeof value === 'string') return identityText(value, options);
21
+ if (Array.isArray(value)) return value.map(v => identityValue(v, options));
22
+ if (isRecord(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, identityValue(v, options)]));
23
+ return value;
24
+ }
25
+
26
+ export function normalizeId(aid) {
27
+ let id = aid.split('.')[0].toLowerCase().replace(/[^a-z0-9_-]/g, '-').replace(/^[^a-z0-9]+/, '');
28
+ if (id.length < 3) id = (id || 'a') + '-tpl';
29
+ return id.slice(0, 64);
30
+ }
31
+
32
+ export async function pack(options) {
33
+ const { inspectAgent } = await import('./inspect.mjs');
34
+ const inventory = await inspectAgent(options);
35
+ const include = options.include;
36
+ assert(isRecord(include), 'INVALID_ARGUMENT', 'include is required');
37
+ const info = { ...options.template, id: options.template?.id ?? normalizeId(options.agentAid) };
38
+ assert(/^[a-z0-9][a-z0-9._-]{0,63}$/.test(info.id) && /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(info.version || '')
39
+ && typeof info.name === 'string' && info.name.trim().length && info.name.length <= 64
40
+ && (info.description === undefined || typeof info.description === 'string' && info.description.length <= 500),
41
+ 'INVALID_ARGUMENT', 'Invalid template id, version, name or description');
42
+ const platforms = include.platforms ?? [process.platform];
43
+ assert(Array.isArray(platforms) && platforms.length && platforms.every(p => ['linux', 'darwin', 'win32'].includes(p)),
44
+ 'INVALID_ARGUMENT', 'Invalid platforms');
45
+ const selected = include.baseagents ?? inventory.baseagents.map(b => ({ name: b.name,
46
+ model: b.currentModel ?? undefined, effort: b.currentEffort ?? undefined, default: b.name === inventory.activeBaseagent }));
47
+ assert(Array.isArray(selected) && selected.length && selected.filter(b => b.default === true).length === 1
48
+ && new Set(selected.map(b => b.name)).size === selected.length, 'INVALID_ARGUMENT', 'Select baseagents and exactly one default');
49
+ const sourceConfig = options.effectiveConfig ?? readJson(path.join(options.agentDir, 'config.json'));
50
+ const config = behaviorConfig(sourceConfig);
51
+ config.active_baseagent = selected.find(b => b.default).name;
52
+ config.baseagents = {};
53
+ for (const b of selected) {
54
+ assert(BASEAGENTS.includes(b.name) && inventory.baseagents.some(x => x.name === b.name), 'INVALID_ARGUMENT', 'Unknown baseagent');
55
+ const source = sourceConfig.baseagents?.[b.name] ?? {};
56
+ const providerId = options.providerRefs?.[b.name]?.id ?? source.provider;
57
+ assert(typeof providerId === 'string' && options.providers?.[providerId], 'PROVIDER_NOT_FOUND', 'Configure a Provider for ' + b.name);
58
+ const provider = options.providers[providerId];
59
+ const block = { provider: { id: providerId, name: provider.name || providerId } };
60
+ if (b.model !== undefined) { assert(typeof b.model === 'string' && b.model.trim(), 'INVALID_ARGUMENT', 'Invalid model'); block.model = b.model; }
61
+ if (b.effort !== undefined) { assert(typeof b.effort === 'string' && ['low', 'medium', 'high', 'xhigh', 'max'].includes(b.effort), 'INVALID_ARGUMENT', 'Invalid effort'); block.effort = b.effort; }
62
+ if (source.params !== undefined) block.params = structuredClone(source.params);
63
+ config.baseagents[b.name] = block;
64
+ }
65
+ const root = path.join(options.out, 'package');
66
+ assert(!fs.existsSync(root), 'CONFLICT', 'Build output already exists');
67
+ fs.mkdirSync(root, { recursive: true });
68
+ const put = (relative, bytes, mode) => {
69
+ const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
70
+ let content = buffer;
71
+ if (!buffer.includes(0) && Buffer.from(buffer.toString('utf8')).equals(buffer)) {
72
+ content = Buffer.from(identityText(buffer.toString('utf8'), options));
73
+ }
74
+ atomicBytes(inside(root, 'template/' + relative), content, mode);
75
+ };
76
+ const agentPrefix = 'agents/agent';
77
+ for (const name of inventory.profile.soul) put(agentPrefix + '/personal/soul/' + name,
78
+ fs.readFileSync(inside(path.join(options.agentDir, 'personal', 'soul'), name)));
79
+ if (inventory.profile.welcome) put(agentPrefix + '/personal/welcome.md', fs.readFileSync(path.join(options.agentDir, 'personal', 'welcome.md')));
80
+ const triggers = include.triggers ?? [];
81
+ assert(Array.isArray(triggers) && triggers.every(id => inventory.triggers.some(t => t.id === id)), 'INVALID_ARGUMENT', 'Unknown Trigger selection');
82
+ for (const id of triggers) {
83
+ const dir = inside(path.join(options.agentDir, 'triggers'), id);
84
+ const def = readJson(path.join(dir, 'trigger.json'));
85
+ // Approval/runtime provenance belongs to the target environment, never to a template.
86
+ delete def.authorizedBy; delete def.operatorPeers;
87
+ put(agentPrefix + '/triggers/' + id + '/trigger.json', jsonBytes(identityValue(def, options)));
88
+ if (def.execution?.type === 'script') {
89
+ const script = def.execution.script.path;
90
+ const source = inside(dir, script); regularPath(source);
91
+ put(agentPrefix + '/triggers/' + id + '/' + script, fs.readFileSync(source), fs.statSync(source).mode & 0o777);
92
+ }
93
+ }
94
+ const skillNames = include.skills === true ? inventory.skills.filter(s => s.type === 'local' && s.enabled).map(s => s.name)
95
+ : include.skills || [];
96
+ assert(Array.isArray(skillNames) && skillNames.every(name => inventory.skills.some(s => s.name === name && s.type === 'local' && s.enabled)),
97
+ 'INVALID_ARGUMENT', 'Unknown or disabled local skill');
98
+ const switches = {};
99
+ for (const s of inventory.skills.filter(s => s.type === 'builtin')) switches[s.name] = { enabled: s.enabled };
100
+ for (const name of skillNames) {
101
+ switches[name] = { enabled: true };
102
+ const dir = inside(path.join(options.home, 'skills'), name);
103
+ for (const file of walkFiles(dir)) put('.evolcore/skills/' + name + '/' + file, fs.readFileSync(inside(dir, file)), fs.statSync(inside(dir, file)).mode & 0o777);
104
+ }
105
+ const files = include.files ?? [];
106
+ assert(Array.isArray(files), 'INVALID_ARGUMENT', 'Invalid files selection');
107
+ const copied = new Set();
108
+ for (const relative of files) {
109
+ const absolute = path.resolve(inventory.project.path, relative);
110
+ const homeRelative = path.relative(options.home, absolute).split(path.sep);
111
+ assert(homeRelative[0] === '..' || !['AIDs', 'agents', 'data', 'logs', 'backups', 'eck', 'directory'].includes(homeRelative[0]),
112
+ 'INVALID_ARGUMENT', 'Runtime data is not a project artifact');
113
+ const file = inside(inventory.project.path, relative); regularPath(file);
114
+ assert(!excluded(relative) && fs.existsSync(file), 'INVALID_ARGUMENT', 'Excluded or missing selection: ' + relative);
115
+ const paths = fs.statSync(file).isDirectory() ? walkFiles(file, p => excluded(relative + '/' + p)).map(p => relative + '/' + p) : [relative];
116
+ for (const p of paths) if (!excluded(p) && !copied.has(p)) {
117
+ copied.add(p); const source = inside(inventory.project.path, p);
118
+ put('workspace/agent/' + p, fs.readFileSync(source), fs.statSync(source).mode & 0o777);
119
+ }
120
+ }
121
+ const profile = Object.fromEntries([...PROFILE_FIELDS, 'type'].filter(k => options.profile?.[k] !== undefined).map(k => [k, options.profile[k]]));
122
+ const normalized = normalizeTeam({ $schema_version: 1, name: info.id, title: info.name,
123
+ ...(info.description !== undefined ? { description: info.description } : {}),
124
+ version: info.version, host: { platform: platforms }, agents: [{ key: 'agent',
125
+ profile: { ...profile, name: profile.name ?? info.name }, config, skills: switches }] });
126
+ assert(!normalized.errors.length, 'INVALID_ARGUMENT', normalized.errors.join('; '));
127
+ const team = normalized.team;
128
+ put('team.json', jsonBytes(identityValue(team, options)));
129
+ put('team.schema.json', jsonBytes(readTeamSchema()));
130
+ const findings = []; const external = new Set();
131
+ for (const relative of walkFiles(path.join(root, 'template'))) {
132
+ const bytes = fs.readFileSync(inside(path.join(root, 'template'), relative));
133
+ if (bytes.includes(0)) continue;
134
+ bytes.toString('utf8').split('\n').forEach((line, i) => {
135
+ for (const aid of line.match(/[a-z0-9][a-z0-9_-]*\.(?:[a-z0-9-]+\.)+[a-z]{2,}/gi) ?? []) {
136
+ if (!line.includes('://' + aid) && !aid.startsWith('www.')) external.add(aid);
137
+ }
138
+ const entropy = (token) => [...new Set(token)].reduce((sum, character) => {
139
+ const probability = token.split(character).length / token.length - 1 / token.length;
140
+ return sum - probability * Math.log2(probability);
141
+ }, 0);
142
+ if (/(?: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)
143
+ || (line.match(/[A-Za-z0-9_+/=-]{40,}/g) ?? []).some(token => entropy(token) > 4.5)) {
144
+ findings.push({ findingId: 'f' + (findings.length + 1), file: 'template/' + relative, line: i + 1, rule: 'credential' });
145
+ }
146
+ });
147
+ }
148
+ const manifest = walkFiles(path.join(root, 'template')).map(p => {
149
+ const bytes = fs.readFileSync(inside(path.join(root, 'template'), p));
150
+ return { path: p, size: bytes.length, sha256: sha256(bytes) };
151
+ });
152
+ const pkg = { $schema_version: 1, ...info, publisher: options.publisher, createdAt: options.createdAt ?? Date.now(),
153
+ compat: { platforms, evolcore: options.evolcoreRange ?? '>=0.0.43', baseagents: selected.map(b => b.name) }, externalAids: [...external].sort() };
154
+ atomicBytes(path.join(root, 'PACKAGE.json'), jsonBytes(pkg));
155
+ atomicBytes(path.join(root, 'MANIFEST.json'), jsonBytes(manifest));
156
+ const bytes = archive(root);
157
+ const filename = info.id + '-' + info.version + '.ectpl';
158
+ const file = path.join(options.out, filename); atomicBytes(file, bytes);
159
+ const warnings = [];
160
+ if (platforms.includes('win32') && manifest.some(f => /\.(?:sh|bash)$/.test(f.path))) {
161
+ warnings.push({ code: 'PLATFORM_MISMATCH', message: 'Package contains shell scripts; verify their Windows runtime before use' });
162
+ }
163
+ const result = { template: info, file, digest: 'sha256:' + sha256(bytes), size: bytes.length,
164
+ summary: { soul: inventory.profile.soul.length, triggers: triggers.length, skills: skillNames.length, files: copied.size },
165
+ compat: pkg.compat, providers: selected.map(b => ({ baseagent: b.name, ...config.baseagents[b.name].provider })),
166
+ externalAids: pkg.externalAids, scan: { status: findings.length ? 'blocked' : 'clean', findings }, warnings };
167
+ atomicBytes(path.join(options.out, 'build.json'), jsonBytes(result));
168
+ return result;
169
+ }