evolcore 0.0.43-test.6 → 0.0.43-test.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +95 -0
- package/bin/ecmsg.js +188 -58
- package/dist/agent-template/jobs.js +62 -0
- package/dist/agent-template/runtime.js +214 -0
- package/dist/agent-template/service.js +465 -0
- package/dist/agent-template/tool-runner.js +45 -0
- package/dist/agent-template/types.js +5 -0
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/claude-runner.js +1 -1
- package/dist/agents/codex/app-server-client.js +22 -0
- package/dist/agents/codex-runner.js +69 -2
- package/dist/aun/aid/agentmd.js +56 -1
- package/dist/aun/aid/client.js +3 -1
- package/dist/aun/menu/client.js +3 -2
- package/dist/aun/msg/p2p.js +6 -1
- package/dist/channels/aun.js +277 -49
- package/dist/cli/agent-command.js +5 -0
- package/dist/cli/agent-create.js +7 -3
- package/dist/cli/agent-template.js +124 -0
- package/dist/cli/aun-commands.js +2 -2
- package/dist/cli/ctl-command.js +2 -1
- package/dist/cli/daemon-commands.js +11 -66
- package/dist/cli/daemon-lifecycle-client.js +61 -0
- package/dist/cli/ecmsg-gateway.js +35 -2
- package/dist/cli/events-command.js +109 -0
- package/dist/cli/index.js +60 -14
- package/dist/cli/invoke-command.js +182 -0
- package/dist/cli/managed-command-guard.js +6 -1
- package/dist/cli/net-check.js +1 -1
- package/dist/cli/restart-monitor.js +160 -83
- package/dist/cli/services-command.js +137 -0
- package/dist/cli/team-workspace-command.js +134 -0
- package/dist/cli/thread-command.js +103 -13
- package/dist/cli/watch-msg.js +1 -1
- package/dist/config/boot-log.js +8 -8
- package/dist/config/config-field-policy.js +2 -2
- package/dist/config/config-manager.js +0 -7
- package/dist/config/invoke-ipc-service.js +118 -0
- package/dist/config/schema-migration.js +45 -15
- package/dist/config-store.js +2 -1
- package/dist/core/agent-ipc-registration.js +25 -4
- package/dist/core/agent-reload-coordinator.js +6 -4
- package/dist/core/agent-runtime.js +106 -10
- package/dist/core/auth/delegation-authorization.js +66 -0
- package/dist/core/auth/operation-authorizer.js +2 -0
- package/dist/core/auth/operation-catalog.js +29 -0
- package/dist/core/baseagent-loader.js +60 -130
- package/dist/core/channel-loader.js +10 -1
- package/dist/core/channel-runtime.js +20 -12
- package/dist/core/command/agent-control.js +12 -2
- package/dist/core/command/agent-storage-menu.js +1 -1
- package/dist/core/command/agent-template-menu.js +147 -0
- package/dist/core/command/chatmode-config.js +2 -36
- package/dist/core/command/command-handler.js +80 -17
- package/dist/core/command/data-root-resolver.js +32 -23
- package/dist/core/command/eventcenter-menu.js +468 -0
- package/dist/core/command/menu-catalog.js +15 -0
- package/dist/core/command/menu-handler.js +216 -90
- package/dist/core/command/menu-protocol.js +71 -13
- package/dist/core/command/menu-query-batch.js +194 -0
- package/dist/core/command/slash-gate.js +1 -1
- package/dist/core/command/slash-handler.js +34 -42
- package/dist/core/command/team-workspace-bootstrap.js +350 -0
- package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
- package/dist/core/command/team-workspace-initializer.js +2 -0
- package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
- package/dist/core/command/team-workspace-job-store.js +88 -0
- package/dist/core/command/team-workspace-management-service.js +2 -0
- package/dist/core/command/team-workspace-management-store.js +96 -0
- package/dist/core/command/team-workspace-management.js +265 -0
- package/dist/core/command/team-workspace-members-menu.js +88 -0
- package/dist/core/command/team-workspace-store.js +612 -0
- package/dist/core/command/team-workspace-team.js +193 -0
- package/dist/core/daemon-control.js +22 -5
- package/dist/core/daemon-lifecycle.js +323 -191
- package/dist/core/handoff/runtime.js +45 -13
- package/dist/core/invoke/executors/index.js +13 -0
- package/dist/core/invoke/executors/media.js +283 -0
- package/dist/core/invoke/executors/text.js +198 -0
- package/dist/core/invoke/invoke-service.js +157 -0
- package/dist/core/invoke/style-router.js +48 -0
- package/dist/core/invoke/types.js +19 -0
- package/dist/core/ipc-registration.js +50 -7
- package/dist/core/legacy-rename.js +41 -0
- package/dist/core/memory/consolidation.js +7 -5
- package/dist/core/message/aun-ipc-sender.js +252 -17
- package/dist/core/message/im-renderer.js +116 -85
- package/dist/core/message/message-bridge.js +4 -0
- package/dist/core/message/message-queue.js +66 -15
- package/dist/core/message/message-utils.js +10 -2
- package/dist/core/message/peer-mode.js +7 -34
- package/dist/core/message/pending-hints.js +29 -5
- package/dist/core/message/response-engine.js +194 -61
- package/dist/core/message/send-options.js +7 -4
- package/dist/core/message/send-routing.js +50 -5
- package/dist/core/ownership/owner-resolver.js +7 -0
- package/dist/core/pack-auth.js +94 -0
- package/dist/core/pack-install.js +194 -0
- package/dist/core/permission/ec-command-parser.js +51 -17
- package/dist/core/permission/protected-paths.js +12 -2
- package/dist/core/permission/shell-environment.js +9 -0
- package/dist/core/rate-window.js +48 -0
- package/dist/core/relation/peer-identity.js +28 -0
- package/dist/core/session/session-file-health.js +243 -0
- package/dist/core/session/session-fs-store.js +67 -28
- package/dist/core/session/session-idle-monitor.js +59 -19
- package/dist/core/session/session-manager.js +13 -4
- package/dist/core/task/task-recovery-service.js +13 -2
- package/dist/core/thread/command-parser.js +9 -2
- package/dist/core/thread/thread-operation.js +21 -2
- package/dist/core/thread/thread-route.js +13 -2
- package/dist/core/thread/thread-service.js +52 -3
- package/dist/directory/owner-directory-admission.js +40 -53
- package/dist/directory/owner-directory-cache.js +89 -113
- package/dist/directory/owner-directory-query-operation.js +8 -10
- package/dist/eck/kit-renderer.js +7 -5
- package/dist/eck/message-renderer.js +2 -0
- package/dist/ecweb/basic-settings-service.js +1 -1
- package/dist/ecweb/message-context-service.js +0 -4
- package/dist/ecweb/runtime/lifecycle.js +6 -2
- package/dist/ecweb/runtime/supervisor.js +19 -4
- package/dist/event-center/admission-materializer.js +124 -0
- package/dist/event-center/bus-gate.js +154 -0
- package/dist/event-center/bus-host.js +307 -0
- package/dist/event-center/bus-resolver.js +120 -0
- package/dist/event-center/center-config.js +127 -0
- package/dist/event-center/daemon.js +44 -0
- package/dist/event-center/directory-source.js +55 -0
- package/dist/event-center/dispatcher.js +157 -0
- package/dist/event-center/event-log.js +110 -0
- package/dist/event-center/index-generator.js +73 -0
- package/dist/event-center/ipc-operation.js +423 -0
- package/dist/event-center/ledger.js +52 -0
- package/dist/event-center/pack-loader.js +207 -0
- package/dist/event-center/pack-manager.js +85 -0
- package/dist/event-center/registry.js +463 -0
- package/dist/event-center/runtime.js +837 -0
- package/dist/event-center/script-runner.js +356 -0
- package/dist/event-center/types.js +51 -0
- package/dist/event-center/validation.js +435 -0
- package/dist/index.js +424 -135
- package/dist/ipc.js +106 -12
- package/dist/paths.js +20 -0
- package/dist/product.js +14 -0
- package/dist/proxy/manager.js +5 -1
- package/dist/proxy/service-supervisor.js +13 -4
- package/dist/response-system/engines/v1/index.js +0 -1
- package/dist/response-system/engines/v1/proactive-flow.js +4 -2
- package/dist/response-system/modes/single-session/index.js +1 -1
- package/dist/services/dispatcher.js +100 -0
- package/dist/services/idempotency.js +90 -0
- package/dist/services/identity.js +52 -0
- package/dist/services/index-generator.js +70 -0
- package/dist/services/index.js +449 -0
- package/dist/services/ipc-operation.js +550 -0
- package/dist/services/ledger.js +52 -0
- package/dist/services/message-log.js +112 -0
- package/dist/services/pack-manager.js +215 -0
- package/dist/services/reply.js +55 -0
- package/dist/services/router.js +98 -0
- package/dist/services/script-runner.js +422 -0
- package/dist/services/service-payload.js +70 -0
- package/dist/services/types.js +18 -0
- package/dist/services/validation.js +297 -0
- package/dist/trigger/application-service.js +18 -0
- package/dist/trigger/event-source.js +1 -1
- package/dist/trigger/ipc-service.js +3 -1
- package/dist/trigger/scheduler.js +38 -0
- package/dist/trigger/script-sandbox.js +170 -24
- package/dist/utils/cross-platform.js +24 -10
- package/dist/utils/evolcore-version.js +69 -27
- package/dist/utils/instance-registry.js +19 -13
- package/dist/utils/npm-ops.js +2 -1
- package/dist/utils/package-version-info.js +6 -3
- package/dist/utils/process-introspect.js +45 -9
- package/dist/utils/startup-trace.js +74 -37
- package/dist/utils/windows-shell-trust.js +80 -6
- package/kits/docs/INDEX.md +2 -2
- package/kits/docs/aun/ABILITY_CALLING.md +9 -15
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +3 -1
- package/kits/docs/evolcore/ability.md +4 -0
- package/kits/docs/evolcore/agent.md +22 -1
- package/kits/docs/evolcore/aid.md +1 -1
- package/kits/docs/evolcore/event-center.md +227 -0
- package/kits/docs/evolcore/file-navigation.md +10 -264
- package/kits/docs/evolcore/fs.md +5 -3
- package/kits/docs/evolcore/group.md +1 -1
- package/kits/docs/evolcore/memory-architecture.md +2 -0
- package/kits/docs/evolcore/menu-protocol.md +28 -1
- package/kits/docs/evolcore/msg.md +21 -9
- package/kits/docs/evolcore/provider.md +3 -1
- package/kits/docs/evolcore/response.md +5 -5
- package/kits/docs/evolcore/services.md +294 -0
- package/kits/docs/evolcore/task.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +41 -0
- package/kits/docs/evolcore/thread-chain.md +15 -3
- package/kits/eck_manifest.json +26 -0
- package/kits/rules/02-navigation.md +10 -1
- package/kits/rules/06-channel.md +1 -0
- package/kits/schemas/_meta.json +17 -6
- package/kits/schemas/agent-config.schema.19.json +5 -7
- package/kits/schemas/agent-config.schema.20.json +936 -0
- package/kits/schemas/relation-config.schema.12.json +2 -3
- package/kits/schemas/role-config.schema.2.json +4 -4
- package/kits/skills/.switches.json +1 -5
- package/kits/skills/ability/SKILL.md +56 -0
- package/kits/skills/ability/references/calling.md +56 -0
- package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
- package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
- package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
- package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
- package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
- package/kits/skills/ec-agent-create/SKILL.md +0 -1
- package/kits/skills/ec-group/SKILL.md +5 -8
- package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
- package/kits/skills/ec-service-proxy/SKILL.md +34 -5
- package/kits/skills/ec-trigger/SKILL.md +4 -4
- package/kits/skills/personal-assistant/SKILL.md +6 -6
- package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
- package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
- package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
- package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
- package/kits/skills/thread-ops/SKILL.md +10 -10
- package/kits/templates/message-fragments/item.md +1 -1
- package/kits/templates/system-fragments/channel.md +3 -3
- package/kits/templates/system-fragments/commands.md +5 -3
- package/kits/templates/system-fragments/reply.md +1 -5
- package/kits/templates/system-fragments/thread.md +13 -10
- package/package.json +5 -6
- package/scripts/agent-template/index.mjs +40 -0
- package/scripts/agent-template/inspect.mjs +240 -0
- package/scripts/agent-template/overlay.mjs +71 -0
- package/scripts/agent-template/pack.mjs +169 -0
- package/scripts/agent-template/shared/common.mjs +235 -0
- package/scripts/agent-template/shared/evolcore.mjs +75 -0
- package/scripts/agent-template/shared/plan.mjs +129 -0
- package/scripts/agent-template/shared/team-schema.json +70 -0
- package/scripts/agent-template/shared/template-contract.mjs +154 -0
- package/scripts/agent-template/shared/template-package.mjs +265 -0
- package/scripts/agent-template/shared/template-runtime.mjs +80 -0
- package/scripts/agent-template/shared/template.mjs +142 -0
- package/dist/cli/pa-workspace-command.js +0 -225
- package/dist/core/command/pa-workspace-store.js +0 -468
- package/dist/core/relation/pa-team.js +0 -132
- package/kits/docs/evolcore/pa-workspace.md +0 -51
- package/kits/skills/aid-ability/SKILL.md +0 -244
- package/kits/skills/ec-ability/SKILL.md +0 -67
- package/kits/skills/ec-ability/references/workflows.md +0 -15
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|