evolcore 0.0.43-test.8 → 0.0.46
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 +75 -0
- package/bin/ecmsg.js +33 -23
- package/dist/ability/application-service.js +1 -2
- package/dist/ability/package.js +28 -0
- package/dist/agent-template/jobs.js +158 -36
- package/dist/agent-template/runtime.js +401 -34
- package/dist/agent-template/service.js +764 -369
- package/dist/agent-template/tool-runner.js +35 -17
- package/dist/agent-template/types.js +7 -4
- package/dist/agents/baseagent.js +10 -9
- package/dist/agents/claude-runner.js +13 -5
- package/dist/agents/codex/app-server-client.js +2 -4
- package/dist/agents/codex/diagnostics.js +18 -1
- package/dist/agents/codex-runner.js +3 -1
- package/dist/agents/ecagent-runner.js +3 -1
- package/dist/agents/gemini-runner.js +2 -1
- package/dist/aun/menu/client.js +142 -182
- package/dist/aun/rpc/client.js +33 -17
- package/dist/aun/service-proxy.js +6 -23
- package/dist/channels/aun.js +656 -112
- package/dist/cli/agent-create.js +37 -10
- package/dist/cli/agent-template.js +105 -84
- package/dist/cli/agent.js +31 -18
- package/dist/cli/daemon-commands.js +15 -17
- package/dist/cli/daemon-lifecycle-client.js +40 -18
- package/dist/cli/directory.js +12 -4
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/events-command.js +2 -1
- package/dist/cli/init.js +50 -20
- package/dist/cli/integrity-command.js +2 -0
- package/dist/cli/managed-command-guard.js +20 -1
- package/dist/cli/menu-client.js +7 -5
- package/dist/cli/restart-monitor.js +33 -20
- package/dist/cli/services-command.js +28 -5
- package/dist/config/config-field-policy.js +24 -0
- package/dist/config/config-manager.js +20 -2
- package/dist/config/peer-book-store.js +152 -120
- package/dist/config/peer-role-resolver.js +24 -4
- package/dist/config/provider-identity-migration.js +1 -1
- package/dist/config/provider-identity.js +10 -4
- package/dist/config/provider-ipc-service.js +10 -2
- package/dist/config/provider-local-sync.js +2 -2
- package/dist/config/providers-config.js +95 -10
- package/dist/config/providers-import.js +4 -6
- package/dist/config/providers.js +14 -3
- package/dist/config/role-store.js +1 -1
- package/dist/config-store.js +9 -1
- package/dist/core/agent-application-service.js +56 -29
- package/dist/core/agent-create-status.js +3 -1
- package/dist/core/agent-creation-claim.js +1 -0
- package/dist/core/agent-ipc-registration.js +2 -2
- package/dist/core/agent-reload-coordinator.js +38 -1
- package/dist/core/agent-runtime.js +85 -38
- package/dist/core/auth/agent-delegation.js +5 -0
- package/dist/core/auth/operation-authorizer.js +1 -1
- package/dist/core/auth/operation-catalog.js +3 -3
- package/dist/core/bootstrap-service.js +3 -0
- package/dist/core/capability/capability-manager.js +3 -1
- package/dist/core/channel-loader.js +29 -3
- package/dist/core/channel-runtime.js +1 -1
- package/dist/core/command/agent-control.js +6 -5
- package/dist/core/command/agent-template-menu.js +32 -97
- package/dist/core/command/eventcenter-menu.js +61 -13
- package/dist/core/command/menu-catalog.js +11 -4
- package/dist/core/command/menu-handler.js +35 -8
- package/dist/core/command/menu-protocol.js +8 -16
- package/dist/core/command/skill-slash.js +6 -2
- package/dist/core/command/team-workspace-bootstrap.js +1 -2
- package/dist/core/command/team-workspace-management-store.js +83 -0
- package/dist/core/command/team-workspace-management.js +1 -2
- package/dist/core/command/team-workspace-team.js +26 -3
- package/dist/core/daemon-control.js +3 -4
- package/dist/core/daemon-lifecycle.js +146 -110
- package/dist/core/evolagent-registry.js +42 -0
- package/dist/core/evolagent.js +2 -1
- package/dist/core/file-integrity/read.js +9 -16
- package/dist/core/file-integrity/store.js +94 -34
- package/dist/core/handoff/dispatcher.js +33 -7
- package/dist/core/handoff/runtime.js +8 -0
- package/dist/core/inference/text-inference.js +12 -2
- package/dist/core/invoke/invoke-service.js +24 -3
- package/dist/core/ipc-registration.js +3 -0
- package/dist/core/message/aun-ipc-sender.js +109 -7
- package/dist/core/message/contact-admission.js +6 -2
- package/dist/core/message/message-bridge.js +13 -0
- package/dist/core/message/message-queue.js +131 -30
- package/dist/core/message/pending-hints.js +8 -0
- package/dist/core/message/response-engine.js +48 -2
- package/dist/core/message/send-routing.js +3 -12
- package/dist/core/model/catalog-service.js +13 -0
- package/dist/core/model/model-catalog.js +57 -18
- package/dist/core/pack-auth.js +163 -31
- package/dist/core/pack-install.js +42 -1
- package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
- package/dist/core/permission/ec-command-parser.js +3 -1
- package/dist/core/permission/shell-environment.js +23 -0
- package/dist/core/rate-window.js +6 -1
- package/dist/core/session/session-idle-monitor.js +0 -1
- package/dist/core/session/session-manager.js +14 -0
- package/dist/core/session/session-title.js +26 -6
- package/dist/core/skill/index-generator.js +3 -4
- package/dist/core/thread/thread-service.js +0 -1
- package/dist/core/thread/topic-id.js +8 -0
- package/dist/directory/owner-directory-admission.js +17 -0
- package/dist/directory/owner-directory-cache.js +3 -1
- package/dist/directory/owner-directory-markdown.js +145 -23
- package/dist/directory/owner-directory-policy.js +23 -0
- package/dist/directory/owner-directory-query-operation.js +20 -6
- package/dist/directory/owner-directory-search.js +47 -0
- package/dist/eck/message-renderer.js +171 -32
- package/dist/ecweb/basic-settings-service.js +7 -3
- package/dist/ecweb/providers-service.js +17 -10
- package/dist/ecweb/runtime/lifecycle.js +1 -1
- package/dist/ecweb/runtime/supervisor.js +77 -35
- package/dist/event-center/admission-materializer.js +1 -1
- package/dist/event-center/bus-gate.js +48 -4
- package/dist/event-center/bus-host.js +3 -3
- package/dist/event-center/center-config.js +57 -28
- package/dist/event-center/dispatcher.js +8 -0
- package/dist/event-center/event-log.js +69 -27
- package/dist/event-center/index-generator.js +6 -1
- package/dist/event-center/ipc-operation.js +66 -25
- package/dist/event-center/pack-loader.js +12 -55
- package/dist/event-center/pack-manager.js +5 -3
- package/dist/event-center/registry.js +48 -52
- package/dist/event-center/runtime.js +219 -81
- package/dist/event-center/script-runner.js +18 -7
- package/dist/event-center/types.js +9 -1
- package/dist/event-center/validation.js +33 -4
- package/dist/index.js +96 -42
- package/dist/ipc.js +33 -7
- package/dist/product.js +1 -0
- package/dist/proxy/manager.js +52 -11
- package/dist/proxy/service-supervisor.js +265 -67
- package/dist/services/dispatcher.js +26 -3
- package/dist/services/idempotency.js +128 -0
- package/dist/services/identity.js +3 -27
- package/dist/services/index-generator.js +5 -1
- package/dist/services/index.js +244 -45
- package/dist/services/ipc-operation.js +164 -20
- package/dist/services/pack-manager.js +37 -9
- package/dist/services/router.js +100 -31
- package/dist/services/script-runner.js +15 -4
- package/dist/services/service-payload.js +50 -2
- package/dist/services/validation.js +107 -3
- package/dist/trigger/scheduler.js +14 -4
- package/dist/trigger/script-sandbox.js +39 -2
- package/dist/utils/cross-platform.js +35 -11
- package/dist/utils/error-utils.js +13 -1
- package/dist/utils/instance-registry.js +33 -35
- package/dist/utils/process-introspect.js +35 -20
- package/dist/utils/project-path.js +47 -3
- package/dist/utils/windows-shell-trust.js +174 -68
- package/kits/docs/context-assembly.md +3 -3
- package/kits/docs/evolcore/agent.md +28 -10
- package/kits/docs/evolcore/config.md +22 -0
- package/kits/docs/evolcore/directory.md +46 -12
- package/kits/docs/evolcore/event-center.md +6 -6
- package/kits/docs/evolcore/group-collaboration.md +1 -1
- package/kits/docs/evolcore/menu-client.md +7 -5
- package/kits/docs/evolcore/menu-protocol.md +5 -3
- package/kits/docs/evolcore/msg.md +10 -3
- package/kits/docs/evolcore/provider.md +7 -3
- package/kits/docs/evolcore/services.md +145 -12
- package/kits/docs/evolcore/thread-chain.md +17 -9
- package/kits/docs/prompt-loading-architecture.md +4 -4
- package/kits/eck_message_manifest.json +46 -3
- package/kits/rules/04-relation.md +10 -2
- package/kits/rules/06-channel.md +2 -1
- package/kits/schemas/providers.schema.2.json +1 -0
- package/kits/skills/ec-group/SKILL.md +4 -0
- package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
- package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
- package/kits/skills/thread-ops/SKILL.md +8 -5
- package/kits/templates/message-fragments/group-batch-item.md +3 -0
- package/kits/templates/message-fragments/group-batch.md +1 -0
- package/kits/templates/message-fragments/item-group.md +4 -0
- package/kits/templates/message-fragments/item-private.md +4 -0
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/system-fragments/commands.md +5 -5
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +11 -7
- package/package.json +3 -2
- package/scripts/agent-template/index.mjs +9 -4
- package/scripts/agent-template/inspect.mjs +16 -9
- package/scripts/agent-template/shared/plan.mjs +3 -33
- package/scripts/agent-template/shared/template-contract.mjs +186 -3
- package/scripts/agent-template/shared/template-package.mjs +119 -10
- package/scripts/agent-template/shared/template-runtime.mjs +49 -6
- package/scripts/agent-template/shared/template.mjs +5 -5
- package/scripts/agent-template/team-pack.mjs +245 -0
- package/scripts/agent-template/team-preview.mjs +111 -0
- package/scripts/aid-batch/identity-batch.mjs +143 -0
- package/dist/ability/versions.js +0 -32
- package/dist/aun/model-headers.js +0 -17
- package/dist/channels/builtin-plugins.js +0 -19
- package/dist/core/command/team-workspace-initializer.js +0 -2
- package/dist/core/command/team-workspace-job-store.js +0 -88
- package/dist/core/command/team-workspace-management-service.js +0 -2
- package/dist/core/contact-bind-registry.js +0 -27
- package/dist/event-center/ledger.js +0 -52
- package/dist/services/reply.js +0 -55
- package/kits/templates/message-fragments/item.md +0 -3
- package/scripts/agent-template/pack.mjs +0 -169
|
@@ -1,14 +1,100 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
2
3
|
|
|
3
4
|
export const TEAM_SCHEMA_VERSION = 1;
|
|
5
|
+
export const PACKAGE_SCHEMA_VERSION = 1;
|
|
4
6
|
export const TEAM_SCHEMA_ID = 'urn:evolcore:agent-template:team:v1';
|
|
7
|
+
export const SELECTION_TTL_MS = 900000;
|
|
8
|
+
export const TEMPLATE_ACTIONS = ['inspect', 'build', 'push', 'pull', 'preview', 'deploy', 'status', 'resume', 'cancel', 'capabilities'];
|
|
5
9
|
const schema = JSON.parse(fs.readFileSync(new URL('./team-schema.json', import.meta.url), 'utf8'));
|
|
6
10
|
export const readTeamSchema = () => structuredClone(schema);
|
|
7
11
|
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
8
12
|
const own = (value, key) => Object.hasOwn(value, key);
|
|
13
|
+
export const MEMBER_KEY_PATTERN = '^[a-z0-9][a-z0-9_-]{0,31}$';
|
|
14
|
+
export const AID_PATTERN = '^[a-z0-9][a-z0-9_-]*\\.(?:[a-z0-9-]+\\.)*[a-z0-9-]+$';
|
|
15
|
+
const string = { type: 'string', minLength: 1 };
|
|
16
|
+
const aid = { ...string, pattern: AID_PATTERN };
|
|
17
|
+
const digest = { type: 'string', pattern: '^sha256:[0-9a-f]{64}$' };
|
|
18
|
+
const strings = { type: 'array', uniqueItems: true, items: string };
|
|
19
|
+
const object = (properties, required = Object.keys(properties)) => ({ type: 'object', properties, required, additionalProperties: false });
|
|
20
|
+
const members = item => ({ type: 'object', minProperties: 1, propertyNames: { pattern: MEMBER_KEY_PATTERN }, additionalProperties: item });
|
|
21
|
+
const jobId = { ...string, pattern: '^job_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' };
|
|
22
|
+
const location = object({ aid, path: { ...string, pattern: '^/[^\\\\\\u0000]*$' } });
|
|
23
|
+
const metadata = object({
|
|
24
|
+
id: schema.properties.name, name: { type: 'string', minLength: 1, maxLength: 64 },
|
|
25
|
+
version: schema.properties.version, description: schema.properties.description,
|
|
26
|
+
platforms: schema.properties.host.properties.platform,
|
|
27
|
+
}, ['id', 'name', 'version', 'platforms']);
|
|
9
28
|
const versionPattern = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
|
|
29
|
+
const source = { oneOf: [
|
|
30
|
+
object({ kind: { const: 'artifact' }, packageId: string }),
|
|
31
|
+
object({ kind: { const: 'file' }, path: string }),
|
|
32
|
+
object({ kind: { const: 'remote' }, location, download: object({ shareId: string }), digest }),
|
|
33
|
+
] };
|
|
34
|
+
const include = object({ baseagents: strings, triggers: strings, skills: strings, files: strings });
|
|
35
|
+
const provider = object({ provider: string, model: string, effort: { type: ['string', 'null'], minLength: 1 } }, ['provider', 'model']);
|
|
36
|
+
const selection = object({
|
|
37
|
+
target: object({ aid: { oneOf: [aid, { const: 'auto' }] }, project: string }),
|
|
38
|
+
providers: { type: 'object', propertyNames: { enum: ['claude', 'codex', 'gemini', 'ecagent'] }, additionalProperties: provider },
|
|
39
|
+
externalAids: { type: 'object', propertyNames: aid, additionalProperties: aid },
|
|
40
|
+
}, ['target']);
|
|
41
|
+
const inputSchemas = {
|
|
42
|
+
inspect: object({ members: members(object({ source: { oneOf: [
|
|
43
|
+
object({ kind: { const: 'agent' }, aid }),
|
|
44
|
+
object({ kind: { const: 'directory' }, path: string }),
|
|
45
|
+
] } })) }),
|
|
46
|
+
build: object({ inspectionJobId: jobId, inventoryDigest: digest, metadata, members: members(object({ include })) }),
|
|
47
|
+
push: object({ packageId: string, location, releasedFindings: strings }),
|
|
48
|
+
pull: object({ source }),
|
|
49
|
+
preview: object({ packageId: string, installMode: { enum: ['create', 'overwrite'] }, members: members(selection), issuer: aid }, ['packageId', 'installMode', 'members']),
|
|
50
|
+
deploy: object({ previewId: string, planDigest: digest }),
|
|
51
|
+
status: { oneOf: [object({ jobId }), object({ requestId: string })] },
|
|
52
|
+
resume: object({ jobId }),
|
|
53
|
+
cancel: object({ jobId }),
|
|
54
|
+
capabilities: object({}),
|
|
55
|
+
};
|
|
56
|
+
export const readTemplateInputSchemas = () => structuredClone(inputSchemas);
|
|
57
|
+
export const packageSchema = object({
|
|
58
|
+
$schema_version: { const: PACKAGE_SCHEMA_VERSION },
|
|
59
|
+
id: schema.properties.name, name: { type: 'string', minLength: 1, maxLength: 64 }, version: schema.properties.version,
|
|
60
|
+
description: schema.properties.description, publisher: { type: 'object' }, createdAt: { type: 'number', minimum: 0 },
|
|
61
|
+
compat: object({ platforms: schema.properties.host.properties.platform, evolcore: string, baseagents: strings, templateFeatures: strings }, ['platforms', 'evolcore', 'baseagents']),
|
|
62
|
+
externalAids: { ...strings, items: aid },
|
|
63
|
+
}, ['$schema_version', 'id', 'name', 'version', 'compat', 'externalAids']);
|
|
64
|
+
export const packageRefSchema = object({
|
|
65
|
+
packageId: string, digest, size: { type: 'integer', minimum: 1 }, metadata,
|
|
66
|
+
members: members(schema.properties.agents.items), externalAids: { ...strings, items: aid },
|
|
67
|
+
scan: object({ findings: { type: 'array', items: object({ id: string, memberKey: string, path: string, code: string, message: string }) } }),
|
|
68
|
+
excluded: { type: 'array', items: string },
|
|
69
|
+
});
|
|
70
|
+
const freezeSchema = object({
|
|
71
|
+
state: { enum: ['acquiring', 'held', 'transferred', 'releasing', 'released'] },
|
|
72
|
+
generation: { type: 'integer', minimum: 1 }, frozenAt: { type: ['integer', 'null'] },
|
|
73
|
+
selectionExpiresAt: { type: ['integer', 'null'] }, inventoryDigest: digest, buildJobId: jobId,
|
|
74
|
+
releaseReason: string, pendingReleases: { type: 'array', items: { type: 'object' } },
|
|
75
|
+
}, ['state', 'generation', 'frozenAt', 'selectionExpiresAt']);
|
|
76
|
+
export const jobSchema = object({
|
|
77
|
+
jobId, requestId: string, action: { enum: TEMPLATE_ACTIONS }, status: { enum: ['queued', 'running', 'paused', 'failed', 'cancelling', 'cancelled', 'succeeded'] },
|
|
78
|
+
phase: string, seq: { type: 'integer', minimum: 0 }, attempt: { type: 'integer', minimum: 1 }, resumable: { type: 'boolean' },
|
|
79
|
+
createdAt: { type: 'integer', minimum: 0 }, updatedAt: { type: 'integer', minimum: 0 },
|
|
80
|
+
members: { type: 'object' }, result: { type: 'object' }, error: { type: 'object' }, committed: { type: 'boolean' },
|
|
81
|
+
readiness: { type: 'object' }, freeze: freezeSchema,
|
|
82
|
+
}, ['jobId', 'requestId', 'action', 'status', 'phase', 'seq', 'attempt', 'resumable', 'createdAt', 'updatedAt']);
|
|
83
|
+
|
|
84
|
+
export function contractError(code, message, details) {
|
|
85
|
+
return Object.assign(new Error(message), { code, retryable: false, ...(details ? { details } : {}) });
|
|
86
|
+
}
|
|
87
|
+
export function canonicalJson(value) {
|
|
88
|
+
const visit = item => {
|
|
89
|
+
if (Array.isArray(item)) return item.map(visit);
|
|
90
|
+
if (record(item)) return Object.fromEntries(Object.keys(item).sort().map(key => [key, visit(item[key])]));
|
|
91
|
+
if (item === null || ['string', 'boolean'].includes(typeof item) || typeof item === 'number' && Number.isFinite(item)) return item;
|
|
92
|
+
throw contractError('INVALID_ARGUMENT', 'JSON value required');
|
|
93
|
+
};
|
|
94
|
+
return JSON.stringify(visit(value));
|
|
95
|
+
}
|
|
96
|
+
export const contractDigest = value => 'sha256:' + createHash('sha256').update(canonicalJson(value)).digest('hex');
|
|
10
97
|
|
|
11
|
-
/** Upgrade field locations while retaining a template author's extra fields and restrictions. */
|
|
12
98
|
export function normalizeTeamSchema(local = {}) {
|
|
13
99
|
if (!record(local) || local.type !== 'object') throw new Error('team.schema.json must be a JSON Schema object');
|
|
14
100
|
const merge = (base, custom) => {
|
|
@@ -43,10 +129,18 @@ export function normalizeTeamSchema(local = {}) {
|
|
|
43
129
|
return out;
|
|
44
130
|
}
|
|
45
131
|
|
|
46
|
-
/** JSON Schema subset used by the shared declaration; full runtime validation remains mode-specific. */
|
|
47
132
|
export function validateContractSchema(value, rule, at = '$') {
|
|
48
133
|
const errors = [];
|
|
134
|
+
if (rule === true) return [];
|
|
135
|
+
if (rule === false) return [`${at}: not allowed`];
|
|
49
136
|
if (!record(rule)) return [`${at}: schema must be an object`];
|
|
137
|
+
for (const group of ['allOf', 'anyOf', 'oneOf']) if (rule[group]) {
|
|
138
|
+
const branches = rule[group].map(branch => validateContractSchema(value, branch, at));
|
|
139
|
+
const count = branches.filter(branch => branch.length === 0).length;
|
|
140
|
+
if (group === 'allOf') errors.push(...branches.flat());
|
|
141
|
+
else if (group === 'anyOf' && count === 0 || group === 'oneOf' && count !== 1) errors.push(at + ': must match ' + group);
|
|
142
|
+
}
|
|
143
|
+
if (rule.not && validateContractSchema(value, rule.not, at).length === 0) errors.push(at + ': forbidden shape');
|
|
50
144
|
const types = Array.isArray(rule.type) ? rule.type : rule.type ? [rule.type] : [];
|
|
51
145
|
const actual = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
|
|
52
146
|
if (types.length && !types.some(t => t === actual || t === 'integer' && Number.isInteger(value))) {
|
|
@@ -71,6 +165,9 @@ export function validateContractSchema(value, rule, at = '$') {
|
|
|
71
165
|
if (record(rule.items)) value.forEach((item, i) => errors.push(...validateContractSchema(item, rule.items, `${at}[${i}]`)));
|
|
72
166
|
}
|
|
73
167
|
if (record(value)) {
|
|
168
|
+
if (rule.minProperties !== undefined && Object.keys(value).length < rule.minProperties) errors.push(at + ': too few properties');
|
|
169
|
+
if (rule.maxProperties !== undefined && Object.keys(value).length > rule.maxProperties) errors.push(at + ': too many properties');
|
|
170
|
+
if (rule.propertyNames) for (const key of Object.keys(value)) errors.push(...validateContractSchema(key, rule.propertyNames, at + '.<key>'));
|
|
74
171
|
for (const key of rule.required ?? []) if (!own(value, key)) errors.push(`${at}: missing "${key}"`);
|
|
75
172
|
for (const [key, item] of Object.entries(value)) {
|
|
76
173
|
const child = own(rule.properties ?? {}, key) ? rule.properties[key] : rule.additionalProperties;
|
|
@@ -81,7 +178,6 @@ export function validateContractSchema(value, rule, at = '$') {
|
|
|
81
178
|
return errors;
|
|
82
179
|
}
|
|
83
180
|
|
|
84
|
-
/** Pure read normalization; does not mutate input or write files. Conversions are returned as changes. */
|
|
85
181
|
export function normalizeTeam(input, { fallbackName, packageInfo } = {}) {
|
|
86
182
|
const errors = []; const changes = [];
|
|
87
183
|
if (!record(input)) return { errors: ['team: object required'], changes };
|
|
@@ -152,3 +248,90 @@ export function normalizeTeam(input, { fallbackName, packageInfo } = {}) {
|
|
|
152
248
|
return { ...(errors.length ? {} : { team }), errors, changes,
|
|
153
249
|
metadata: { id: team.name, name: team.title ?? packageInfo?.name ?? team.name, version: team.version } };
|
|
154
250
|
}
|
|
251
|
+
|
|
252
|
+
/** Internal index; public declarations and manifests continue to use agents[]. */
|
|
253
|
+
export function indexTeamAgents(team) {
|
|
254
|
+
const normalized = normalizeTeam(team);
|
|
255
|
+
if (normalized.errors.length) throw contractError('INVALID_ARGUMENT', normalized.errors.join('; '));
|
|
256
|
+
return new Map(normalized.team.agents.map(agent => [agent.key, agent]));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function validateTemplateRequest(request) {
|
|
260
|
+
const errors = validateContractSchema(request, object({ requestId: { ...string, maxLength: 200 }, action: { enum: TEMPLATE_ACTIONS }, args: { type: 'object' } }));
|
|
261
|
+
if (!errors.length) errors.push(...validateContractSchema(request.args, inputSchemas[request.action], 'args'));
|
|
262
|
+
if (!errors.length && request.action === 'preview') {
|
|
263
|
+
const keys = Object.keys(request.args.members);
|
|
264
|
+
if (request.args.installMode === 'overwrite' && (keys.length !== 1 || request.args.issuer !== undefined || request.args.members[keys[0]].target.aid === 'auto')) errors.push('overwrite requires one existing target and forbids issuer');
|
|
265
|
+
if (request.args.installMode === 'create' && keys.some(key => request.args.members[key].target.aid === 'auto') && !request.args.issuer) errors.push('issuer required for auto targets');
|
|
266
|
+
}
|
|
267
|
+
return errors;
|
|
268
|
+
}
|
|
269
|
+
export function normalizeTemplateRequest(request) {
|
|
270
|
+
const errors = validateTemplateRequest(request);
|
|
271
|
+
if (errors.length) throw contractError('INVALID_ARGUMENT', errors.join('; '), { errors });
|
|
272
|
+
const out = structuredClone(request);
|
|
273
|
+
if (out.action === 'build') {
|
|
274
|
+
out.args.metadata.platforms.sort();
|
|
275
|
+
for (const member of Object.values(out.args.members)) for (const values of Object.values(member.include)) values.sort();
|
|
276
|
+
}
|
|
277
|
+
if (out.action === 'push') out.args.releasedFindings.sort();
|
|
278
|
+
return JSON.parse(canonicalJson(out));
|
|
279
|
+
}
|
|
280
|
+
export function templateRequestDigest(request) {
|
|
281
|
+
const normalized = normalizeTemplateRequest(request);
|
|
282
|
+
return contractDigest({ action: normalized.action, args: normalized.args });
|
|
283
|
+
}
|
|
284
|
+
export function readTemplateCapabilities({ actions = TEMPLATE_ACTIONS, installModes = ['create', 'overwrite'], platforms = ['linux', 'darwin', 'win32'], features = {} } = {}) {
|
|
285
|
+
if (actions.some(action => !TEMPLATE_ACTIONS.includes(action))) throw contractError('INVALID_ARGUMENT', 'Unknown capability action');
|
|
286
|
+
return {
|
|
287
|
+
actions: [...actions], inputSchemas: Object.fromEntries(actions.map(action => [action, structuredClone(inputSchemas[action])])),
|
|
288
|
+
resultSchemas: Object.fromEntries(actions.map(action => [action, action === 'capabilities' ? { type: 'object' } : structuredClone(jobSchema)])),
|
|
289
|
+
packageSchema: structuredClone(packageSchema), installModes: [...installModes], platforms: [...platforms],
|
|
290
|
+
limits: { selectionTtlMs: SELECTION_TTL_MS, waitSeconds: { minimum: 0, maximum: 300 } },
|
|
291
|
+
jobPolicy: { packageRetentionMs: 604800000, previewTtlMs: 3600000, resultRetentionMs: 2592000000, event: 'template.job', unknownEffectsPinned: true },
|
|
292
|
+
features: structuredClone(features),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
export function validateBuildSelection(inventory, args) {
|
|
296
|
+
const keys = Object.keys(inventory.members).sort();
|
|
297
|
+
if (canonicalJson(keys) !== canonicalJson(Object.keys(args.members).sort())) throw contractError('INVALID_ARGUMENT', 'Complete member selection required');
|
|
298
|
+
if (args.inventoryDigest !== inventory.inventoryDigest) throw contractError('SOURCE_CHANGED', 'Inventory digest differs');
|
|
299
|
+
if (args.metadata.platforms.some(platform => !inventory.platforms.includes(platform))) throw contractError('INCOMPATIBLE', 'No common selected platform');
|
|
300
|
+
for (const key of keys) {
|
|
301
|
+
const member = inventory.members[key];
|
|
302
|
+
for (const [kind, chosen] of Object.entries(args.members[key].include)) if (chosen.some(item => !member.resources[kind].includes(item))) throw contractError('INVALID_ARGUMENT', 'Selection outside inventory', { memberKey: key, kind });
|
|
303
|
+
if (!args.members[key].include.baseagents.includes(member.defaultBaseagent)) throw contractError('INVALID_ARGUMENT', 'Default baseagent is required', { memberKey: key });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
export function jobExitCode(view, { wait = 0, timedOut = false } = {}) {
|
|
307
|
+
if (view.status === 'succeeded') return 0;
|
|
308
|
+
if (['failed', 'cancelled'].includes(view.status)) return 1;
|
|
309
|
+
if (view.status === 'paused' || timedOut || wait > 0) return 3;
|
|
310
|
+
return 0;
|
|
311
|
+
}
|
|
312
|
+
export function readinessProjection({ committed = false, runtimeReady = null, directoryReady = null } = {}) {
|
|
313
|
+
const values = [runtimeReady, directoryReady];
|
|
314
|
+
if (values.some(value => value !== null && typeof value !== 'boolean')) throw contractError('INVALID_ARGUMENT', 'Readiness must be boolean or null');
|
|
315
|
+
const teamReady = values.includes(false) ? false : values.every(value => value === true) ? true : null;
|
|
316
|
+
return { runtimeReady, directoryReady, teamReady, health: !committed ? 'unknown' : teamReady === false ? 'degraded' : teamReady === true ? 'ready' : 'unknown' };
|
|
317
|
+
}
|
|
318
|
+
export function transitionTemplateJob(job, patch, { expectedSeq, now = Date.now() } = {}) {
|
|
319
|
+
if (expectedSeq !== job.seq) throw contractError('CONFLICT', 'Stale job revision');
|
|
320
|
+
if (['succeeded', 'cancelled'].includes(job.status)) throw contractError('CONFLICT', 'Terminal job is immutable');
|
|
321
|
+
const legal = { queued: ['running', 'cancelling', 'failed'], running: ['paused', 'failed', 'cancelling', 'succeeded'], paused: ['queued', 'running', 'cancelling', 'failed'], failed: ['queued', 'running', 'cancelling'], cancelling: ['cancelled', 'failed'] };
|
|
322
|
+
const status = patch.status ?? job.status;
|
|
323
|
+
const handoff = job.action === 'inspect' && job.status === 'paused' && status === 'succeeded' && patch.phase === 'handed_off';
|
|
324
|
+
if (status !== job.status && !handoff && !legal[job.status]?.includes(status)) throw contractError('CONFLICT', 'Illegal job transition');
|
|
325
|
+
const resumed = ['paused', 'failed'].includes(job.status) && ['queued', 'running'].includes(status);
|
|
326
|
+
if (resumed && !job.resumable) throw contractError('CONFLICT', 'Job cannot resume');
|
|
327
|
+
if (job.committed && status === 'cancelling') throw contractError('CONFLICT', 'Committed job cannot cancel');
|
|
328
|
+
for (const key of ['jobId', 'requestId', 'action', 'seq', 'attempt', 'createdAt']) if (own(patch, key)) throw contractError('CONFLICT', 'Immutable job field: ' + key);
|
|
329
|
+
const out = { ...structuredClone(job), ...structuredClone(patch), seq: job.seq + 1, attempt: job.attempt + (resumed ? 1 : 0), updatedAt: now };
|
|
330
|
+
if (patch.committed === true && (job.action !== 'deploy' || job.status !== 'running' || !['running', 'succeeded'].includes(status))) throw contractError('CONFLICT', 'Commit requires a running deploy revision');
|
|
331
|
+
if (job.committed && patch.committed === false) throw contractError('CONFLICT', 'Commit is permanent');
|
|
332
|
+
if (['failed', 'cancelled', 'succeeded'].includes(status) && ['inspect', 'build'].includes(job.action) && out.freeze
|
|
333
|
+
&& out.freeze.state !== 'released' && !(status === 'succeeded' && out.phase === 'handed_off' && out.freeze.state === 'transferred' && out.freeze.buildJobId)) throw contractError('RECOVERY_REQUIRED', 'Release or handoff proof required');
|
|
334
|
+
const errors = validateContractSchema(out, jobSchema);
|
|
335
|
+
if (errors.length) throw contractError('INVALID_ARGUMENT', errors.join('; '));
|
|
336
|
+
return out;
|
|
337
|
+
}
|
|
@@ -4,7 +4,7 @@ import path from 'node:path';
|
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
5
|
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
6
6
|
import { loadTemplate } from './template.mjs';
|
|
7
|
-
import { normalizeTeam, normalizeTeamSchema, validateContractSchema, readTeamSchema } from './template-contract.mjs';
|
|
7
|
+
import { normalizeTeam, normalizeTeamSchema, validateContractSchema, readTeamSchema, packageSchema, contractDigest, canonicalJson, validateBuildSelection } from './template-contract.mjs';
|
|
8
8
|
import { BASEAGENTS } from './template-runtime.mjs';
|
|
9
9
|
|
|
10
10
|
export const PACKAGE_LIMITS = { file: 20 * 1024 * 1024, total: 200 * 1024 * 1024, entries: 20000 };
|
|
@@ -107,9 +107,7 @@ export function inspectTemplatePackage(bytes, { digest } = {}) {
|
|
|
107
107
|
const entries = decodePackageEntries(bytes);
|
|
108
108
|
const read = name => { check(entries.has(name), 'Missing package entry: ' + name, 'INTEGRITY_FAILED'); return JSON.parse(entries.get(name).bytes.toString('utf8')); };
|
|
109
109
|
const metadata = read('PACKAGE.json'); const manifest = read('MANIFEST.json');
|
|
110
|
-
check(
|
|
111
|
-
&& metadata.name.length <= 64 && record(metadata.compat) && typeof metadata.compat.evolcore === 'string'
|
|
112
|
-
&& metadata.compat.evolcore.length > 0, 'Invalid package metadata', 'INTEGRITY_FAILED');
|
|
110
|
+
check(!validateContractSchema(metadata, packageSchema).length, 'Invalid package v2 metadata', 'INTEGRITY_FAILED');
|
|
113
111
|
check(Array.isArray(manifest) && manifest.length && entries.size === manifest.length + 2, 'Invalid manifest', 'INTEGRITY_FAILED');
|
|
114
112
|
const seen = new Set();
|
|
115
113
|
for (const entry of manifest) {
|
|
@@ -124,15 +122,119 @@ export function inspectTemplatePackage(bytes, { digest } = {}) {
|
|
|
124
122
|
const team = normalized.team; const schema = normalizeTeamSchema(read('template/team.schema.json'));
|
|
125
123
|
const errors = validateContractSchema(team, schema);
|
|
126
124
|
check(!errors.length, errors.join('; '));
|
|
127
|
-
const platforms = metadata.compat.platforms;
|
|
128
|
-
check(Array.isArray(platforms) && platforms.length === team.host.platform.length
|
|
129
|
-
&& new Set(platforms).size === platforms.length && platforms.every(p => team.host.platform.includes(p)), 'Conflicting platform metadata', 'INTEGRITY_FAILED');
|
|
130
125
|
const keys = team.agents.map(agent => agent.key);
|
|
131
126
|
for (const { path: name } of manifest) check(portableFile(name, keys), 'Unsupported portable resource: ' + name);
|
|
132
127
|
return { metadata, team, schema, entries, digest: actual, changes: normalized.changes,
|
|
133
128
|
resources: manifest.map(({ path: name, size }) => ({ path: name, size })) };
|
|
134
129
|
}
|
|
135
130
|
|
|
131
|
+
/** Directory adapter: reads exactly one keyed member and snapshots all source bytes/permissions. */
|
|
132
|
+
export function collectTemplateDirectory(templateDir, memberKey) {
|
|
133
|
+
regularAncestors(templateDir);
|
|
134
|
+
const { tpl, errors } = loadTemplate(templateDir);
|
|
135
|
+
check(!errors.length, errors.join('; '));
|
|
136
|
+
check(tpl.keys.includes(memberKey), 'Unknown directory member: ' + memberKey);
|
|
137
|
+
const excluded = [];
|
|
138
|
+
const readOptional = relative => {
|
|
139
|
+
const file = path.join(tpl.root, ...relative.split('/'));
|
|
140
|
+
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
|
|
141
|
+
};
|
|
142
|
+
const defaults = readOptional('.evolcore/agents/defaults.json');
|
|
143
|
+
const providers = readOptional('.evolcore/providers.json').providers ?? {};
|
|
144
|
+
const member = structuredClone(tpl.team.agents.find(agent => agent.key === memberKey));
|
|
145
|
+
const source = { ...structuredClone(defaults), ...member.config,
|
|
146
|
+
baseagents: { ...defaults.baseagents, ...member.config?.baseagents } };
|
|
147
|
+
const config = {};
|
|
148
|
+
for (const name of ['chatmode', 'memory']) if (source[name] !== undefined) config[name] = source[name];
|
|
149
|
+
config.active_baseagent = source.active_baseagent ?? 'claude'; config.baseagents = {};
|
|
150
|
+
for (const [name, sourceBlock] of Object.entries(source.baseagents)) {
|
|
151
|
+
const block = { ...defaults.baseagents?.[name], ...sourceBlock };
|
|
152
|
+
check(BASEAGENTS.includes(name) && record(block), 'Invalid baseagent block');
|
|
153
|
+
const ref = typeof block.provider === 'string' ? { id: block.provider, name: providers[block.provider]?.name ?? block.provider } : block.provider;
|
|
154
|
+
check(record(ref) && /^provider-[0-9]{8}$/.test(ref.id), 'Provider identity required: ' + memberKey + '/' + name);
|
|
155
|
+
config.baseagents[name] = { provider: { id: ref.id, ...(ref.name !== undefined ? { name: ref.name } : {}) } };
|
|
156
|
+
for (const field of ['model', 'effort', 'params']) if (block[field] !== undefined) config.baseagents[name][field] = structuredClone(block[field]);
|
|
157
|
+
}
|
|
158
|
+
check(config.baseagents[config.active_baseagent], 'Default baseagent must have a binding: ' + memberKey);
|
|
159
|
+
for (const field of Object.keys(member.config ?? {})) if (!Object.hasOwn(config, field)) excluded.push('members/' + memberKey + '/config/' + field);
|
|
160
|
+
member.config = config;
|
|
161
|
+
const entries = new Map(); const snapshot = [];
|
|
162
|
+
for (const relative of tpl.files) {
|
|
163
|
+
const name = relative.split(path.sep).join('/');
|
|
164
|
+
const file = path.join(tpl.root, relative);
|
|
165
|
+
const stat = fs.statSync(file); const bytes = fs.readFileSync(file);
|
|
166
|
+
snapshot.push({ path: name, mode: stat.mode & 0o777, digest: packageDigest(bytes), size: bytes.length });
|
|
167
|
+
if (['team.json', 'team.schema.json'].includes(name)) continue;
|
|
168
|
+
if (!portableFile(name, [memberKey])) { excluded.push(name); continue; }
|
|
169
|
+
entries.set(name, { bytes, mode: stat.mode & 0o777 });
|
|
170
|
+
}
|
|
171
|
+
const resources = { baseagents: Object.keys(config.baseagents).sort(), triggers: [], skills: [], files: [] };
|
|
172
|
+
for (const name of entries.keys()) {
|
|
173
|
+
if (name.startsWith('workspace/' + memberKey + '/')) resources.files.push(name.slice(('workspace/' + memberKey + '/').length));
|
|
174
|
+
if (name.startsWith('agents/' + memberKey + '/triggers/')) resources.triggers.push(name.split('/')[3]);
|
|
175
|
+
if (name.startsWith('.evolcore/skills/')) resources.skills.push(name.split('/')[2]);
|
|
176
|
+
}
|
|
177
|
+
resources.skills.push(...Object.keys(member.skills ?? {}));
|
|
178
|
+
for (const kind of Object.keys(resources)) resources[kind] = [...new Set(resources[kind])].sort();
|
|
179
|
+
return { member, entries, excluded, platforms: [...tpl.team.host.platform].sort(),
|
|
180
|
+
sourceDigest: contractDigest({ snapshot, member, metadata: { name: tpl.team.name, version: tpl.team.version } }), resources,
|
|
181
|
+
defaultBaseagent: config.active_baseagent, warnings: [] };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** One pure package planner for both runtime-agent and directory collection adapters. */
|
|
185
|
+
export function buildTemplatePackage({ metadata, members, externalAids = [], publisher, createdAt, evolcoreRange = '>=0.0.43-test.8' }) {
|
|
186
|
+
const team = { $schema_version: 1, name: metadata.id, title: metadata.name, version: metadata.version,
|
|
187
|
+
...(metadata.description !== undefined ? { description: metadata.description } : {}), host: { platform: structuredClone(metadata.platforms) }, agents: [] };
|
|
188
|
+
const entries = new Map(); const excluded = []; const external = new Set(externalAids);
|
|
189
|
+
for (const [key, collected] of Object.entries(members)) {
|
|
190
|
+
const { member, include } = collected;
|
|
191
|
+
check(record(member) && record(include), 'Collected member and selection required');
|
|
192
|
+
check(include.baseagents.includes(member.config?.active_baseagent), 'Default baseagent is required: ' + key);
|
|
193
|
+
const chosen = structuredClone(member);
|
|
194
|
+
chosen.config.baseagents = Object.fromEntries(Object.entries(chosen.config.baseagents).filter(([name]) => include.baseagents.includes(name)));
|
|
195
|
+
chosen.skills = Object.fromEntries(Object.entries(chosen.skills ?? {}).filter(([name]) => include.skills.includes(name)));
|
|
196
|
+
team.agents.push({ ...chosen, key });
|
|
197
|
+
excluded.push(...(collected.excluded ?? []));
|
|
198
|
+
for (const [name, entry] of collected.entries) {
|
|
199
|
+
packagePath(name);
|
|
200
|
+
check(portableFile(name, [key]), 'Unsupported collected resource: ' + name);
|
|
201
|
+
const selected = name.startsWith('workspace/') ? include.files.includes(name.slice(('workspace/' + key + '/').length))
|
|
202
|
+
: name.startsWith('.evolcore/skills/') ? include.skills.includes(name.split('/')[2])
|
|
203
|
+
: name.startsWith('agents/' + key + '/triggers/') ? include.triggers.includes(name.split('/')[3]) : true;
|
|
204
|
+
if (!selected) { excluded.push(name); continue; }
|
|
205
|
+
const target = 'template/' + name;
|
|
206
|
+
if (entries.has(target)) check(entries.get(target).bytes.equals(entry.bytes) && entries.get(target).mode === entry.mode, 'Conflicting shared resource', 'SOURCE_CHANGED');
|
|
207
|
+
entries.set(target, { bytes: Buffer.from(entry.bytes), mode: entry.mode });
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const normalized = normalizeTeam(team);
|
|
211
|
+
check(!normalized.errors.length, normalized.errors.join('; '));
|
|
212
|
+
entries.set('template/team.json', { bytes: json(team), mode: 0o644 });
|
|
213
|
+
entries.set('template/team.schema.json', { bytes: json(readTeamSchema()), mode: 0o644 });
|
|
214
|
+
for (const [name, entry] of entries) {
|
|
215
|
+
if (entry.bytes.includes(0) || !Buffer.from(entry.bytes.toString('utf8')).equals(entry.bytes)) continue;
|
|
216
|
+
for (const line of entry.bytes.toString('utf8').split('\n')) {
|
|
217
|
+
check(!/(?:sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|AKIA[A-Z0-9]{16}|-----BEGIN .*PRIVATE KEY|(?:API_KEY|TOKEN|SECRET|PASSWORD)\s*=\s*(?!\$\{)\S{8,})/i.test(line),
|
|
218
|
+
'Credential content in portable resource: ' + name, 'SCAN_BLOCKED');
|
|
219
|
+
for (const aid of line.match(/[a-z0-9][a-z0-9_-]*\.(?:[a-z0-9-]+\.)+[a-z]{2,}/gi) ?? []) {
|
|
220
|
+
if (!line.includes('://' + aid) && !aid.startsWith('www.') && !line.includes('{{' + aid + '}}') && !new RegExp('\\{\\{\\s*' + aid.replaceAll('.', '\\.') + '\\s*\\}\\}').test(line)) external.add(aid);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const info = { $schema_version: 1, id: metadata.id, name: metadata.name, version: metadata.version,
|
|
225
|
+
...(publisher !== undefined ? { publisher: structuredClone(publisher) } : {}), ...(createdAt !== undefined ? { createdAt } : {}),
|
|
226
|
+
...(metadata.description !== undefined ? { description: metadata.description } : {}),
|
|
227
|
+
compat: { platforms: structuredClone(metadata.platforms), evolcore: evolcoreRange, baseagents: [...new Set(team.agents.flatMap(member => Object.keys(member.config.baseagents)))].sort() },
|
|
228
|
+
externalAids: [...external].sort() };
|
|
229
|
+
const manifest = [...entries].map(([name, entry]) => ({ path: name.slice('template/'.length), size: entry.bytes.length, sha256: packageDigest(entry.bytes).slice(7) }));
|
|
230
|
+
entries.set('PACKAGE.json', { bytes: json(info), mode: 0o644 });
|
|
231
|
+
entries.set('MANIFEST.json', { bytes: json(manifest), mode: 0o644 });
|
|
232
|
+
const bytes = encodePackageEntries(entries);
|
|
233
|
+
inspectTemplatePackage(bytes);
|
|
234
|
+
return { bytes, metadata: info, digest: packageDigest(bytes), excluded: [...new Set(excluded)].sort(),
|
|
235
|
+
scan: { findings: [] }, filename: metadata.id + '-' + metadata.version + '.ectpl' };
|
|
236
|
+
}
|
|
237
|
+
|
|
136
238
|
/** Export behavior/resources only; credentials and host infrastructure never enter the share package. */
|
|
137
239
|
export function exportTemplatePackage(templateDir, { publisher, createdAt = Date.now(), evolcoreRange = '>=0.0.43' } = {}) {
|
|
138
240
|
regularAncestors(templateDir);
|
|
@@ -178,19 +280,26 @@ export function exportTemplatePackage(templateDir, { publisher, createdAt = Date
|
|
|
178
280
|
entries.set('template/team.json', { bytes: json(team), mode: 0o644 });
|
|
179
281
|
entries.set('template/team.schema.json', { bytes: json(readTeamSchema()), mode: 0o644 });
|
|
180
282
|
const external = new Set();
|
|
283
|
+
let memberReferences = false;
|
|
181
284
|
for (const [name, entry] of entries) {
|
|
182
285
|
if (entry.bytes.includes(0) || !Buffer.from(entry.bytes.toString('utf8')).equals(entry.bytes)) continue;
|
|
183
286
|
for (const line of entry.bytes.toString('utf8').split('\n')) {
|
|
287
|
+
memberReferences ||= /\{\{\s*members\./.test(line);
|
|
184
288
|
check(!/(?:sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|AKIA[A-Z0-9]{16}|-----BEGIN .*PRIVATE KEY|(?:API_KEY|TOKEN|SECRET|PASSWORD)\s*=\s*(?!\$\{)\S{8,})/i.test(line),
|
|
185
289
|
'Credential content in portable resource: ' + name, 'SENSITIVE_CONTENT');
|
|
186
290
|
for (const aid of line.match(/[a-z0-9][a-z0-9_-]*\.(?:[a-z0-9-]+\.)+[a-z]{2,}/gi) ?? []) {
|
|
187
|
-
if (!line.includes('://' + aid) && !aid.startsWith('www.')) external.add(aid);
|
|
291
|
+
if (!line.includes('://' + aid) && !aid.startsWith('www.') && !line.includes('{{' + aid + '}}') && !new RegExp('\\{\\{\\s*' + aid.replaceAll('.', '\\.') + '\\s*\\}\\}').test(line)) external.add(aid);
|
|
188
292
|
}
|
|
189
293
|
}
|
|
190
294
|
}
|
|
295
|
+
// Older readers normalize test builds to the final version. The upper bound
|
|
296
|
+
// makes those readers reject member references instead of leaving old AIDs.
|
|
297
|
+
if (memberReferences && evolcoreRange === '>=0.0.43') evolcoreRange = '>=0.0.43-test.8 <0.0.43 || >=0.0.44';
|
|
191
298
|
const metadata = { $schema_version: 1, id: team.name, name: team.title ?? team.name, version: team.version,
|
|
192
299
|
...(team.description !== undefined ? { description: team.description } : {}), ...(publisher ? { publisher } : {}), createdAt,
|
|
193
|
-
compat: { platforms: team.host.platform, evolcore: evolcoreRange,
|
|
300
|
+
compat: { platforms: team.host.platform, evolcore: evolcoreRange,
|
|
301
|
+
...(memberReferences ? { templateFeatures: ['member-references-v1'] } : {}),
|
|
302
|
+
baseagents: [...new Set(team.agents.flatMap(agent => Object.keys(agent.config.baseagents)))] }, externalAids: [...external].sort() };
|
|
194
303
|
const manifest = [...entries].map(([name, entry]) => ({ path: name.slice('template/'.length), size: entry.bytes.length, sha256: packageDigest(entry.bytes).slice(7) }));
|
|
195
304
|
entries.set('PACKAGE.json', { bytes: json(metadata), mode: 0o644 });
|
|
196
305
|
entries.set('MANIFEST.json', { bytes: json(manifest), mode: 0o644 });
|
|
@@ -244,7 +353,7 @@ export function attachBuildEnvironment(templateDir, sourceDir) {
|
|
|
244
353
|
check(!base.errors.length, 'Invalid build environment: ' + base.errors.join('; '));
|
|
245
354
|
const teamFile = path.join(templateDir, 'team.json');
|
|
246
355
|
const team = JSON.parse(fs.readFileSync(teamFile, 'utf8'));
|
|
247
|
-
if (base.tpl.team.host
|
|
356
|
+
if (base.tpl.team.host?.config !== undefined) team.host.config = structuredClone(base.tpl.team.host.config);
|
|
248
357
|
if (base.tpl.team.issuer !== undefined) team.issuer = base.tpl.team.issuer;
|
|
249
358
|
for (const name of ['providers.json', 'agents/defaults.json', '.env']) {
|
|
250
359
|
const source = path.join(base.tpl.root, '.evolcore', ...name.split('/'));
|
|
@@ -4,15 +4,19 @@ const record = value => value !== null && typeof value === 'object' && !Array.is
|
|
|
4
4
|
const fail = message => { throw Object.assign(new Error(message), { code: 'INVALID_ARGUMENT' }); };
|
|
5
5
|
|
|
6
6
|
export function renderText(text, vars = {}, externalAids = {}) {
|
|
7
|
-
let out = text
|
|
8
|
-
|
|
7
|
+
let out = text;
|
|
8
|
+
const interpolate = value => value.replace(/\{\{\s*([a-z]+\.[a-z]+|members\.[a-z0-9][a-z0-9_-]{0,31}\.(?:aid|project))\s*\}\}/g,
|
|
9
|
+
(token, key) => {
|
|
10
|
+
if (key.startsWith('members.') && !Object.hasOwn(vars, key)) fail('Unknown team member reference: ' + key);
|
|
11
|
+
return Object.hasOwn(vars, key) ? String(vars[key]) : token;
|
|
12
|
+
});
|
|
9
13
|
// One pass avoids cascading A -> B -> C substitutions.
|
|
10
14
|
const keys = Object.keys(externalAids).sort((a, b) => b.length - a.length);
|
|
11
15
|
if (keys.length) {
|
|
12
16
|
const pattern = keys.map(key => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
|
|
13
|
-
out = out.replace(new RegExp(pattern, 'g'), match => String(externalAids[match]));
|
|
17
|
+
out = out.replace(new RegExp('(?<![a-zA-Z0-9_.-])(?:' + pattern + ')(?![a-zA-Z0-9_.-])', 'g'), match => String(externalAids[match]));
|
|
14
18
|
}
|
|
15
|
-
return out;
|
|
19
|
+
return interpolate(out);
|
|
16
20
|
}
|
|
17
21
|
|
|
18
22
|
/** Parse JSON first, then render string values so quotes/newlines cannot change types or structure. */
|
|
@@ -39,7 +43,7 @@ export function providerUsable(providers, id, baseagent) {
|
|
|
39
43
|
}
|
|
40
44
|
|
|
41
45
|
/** Match by exact stable ID, never by display name. Missing matches can be previewed, not installed. */
|
|
42
|
-
export function bindTemplateProviders(config, { providers = {}, defaults = {}, selections = {}, allowMissing = false } = {}) {
|
|
46
|
+
export function bindTemplateProviders(config, { providers = {}, defaults = {}, selections = {}, allowMissing = false, modelCatalog } = {}) {
|
|
43
47
|
if (!record(config) || !record(providers) || !record(defaults) || !record(selections)) fail('Invalid Provider binding input');
|
|
44
48
|
const out = structuredClone(config);
|
|
45
49
|
const blocks = out.baseagents ?? {};
|
|
@@ -58,9 +62,17 @@ export function bindTemplateProviders(config, { providers = {}, defaults = {}, s
|
|
|
58
62
|
if (ref !== undefined && (!record(ref) || typeof ref.id !== 'string')) fail('Provider identity required: ' + name);
|
|
59
63
|
if (select.provider !== undefined && (typeof select.provider !== 'string' || !select.provider)) fail('Invalid selected Provider: ' + name);
|
|
60
64
|
if (select.model !== undefined && (typeof select.model !== 'string' || !select.model.trim())) fail('Invalid model: ' + name);
|
|
61
|
-
if (select.effort !== undefined && select.effort !== null &&
|
|
65
|
+
if (select.effort !== undefined && select.effort !== null && (typeof select.effort !== 'string' || !select.effort)) fail('Invalid effort: ' + name);
|
|
62
66
|
const selected = select.provider ?? ref?.id;
|
|
63
67
|
const usable = providerUsable(providers, selected, name);
|
|
68
|
+
const model = select.model ?? block.model ?? defaults.baseagents?.[name]?.model;
|
|
69
|
+
const effort = Object.hasOwn(select, 'effort') ? select.effort : block.effort;
|
|
70
|
+
if (modelCatalog && usable) {
|
|
71
|
+
const catalog = typeof modelCatalog === 'function' ? modelCatalog({ provider: selected, baseagent: name }) : modelCatalog[selected]?.[name];
|
|
72
|
+
const definition = Array.isArray(catalog) ? catalog.find(item => (typeof item === 'string' ? item : item.id) === model) : catalog?.[model];
|
|
73
|
+
if (!definition) throw Object.assign(new Error('Model is not in the selected Provider catalog: ' + model), { code: 'UNRESOLVED' });
|
|
74
|
+
if (effort !== undefined && effort !== null && (!Array.isArray(definition.efforts) || !definition.efforts.includes(effort))) fail('Effort is unsupported by model: ' + model);
|
|
75
|
+
}
|
|
64
76
|
refs.push({ baseagent: name, template: { ...(ref ?? {}), model: block.model, effort: block.effort },
|
|
65
77
|
match: usable ? 'reused' : 'select', provider: usable ? selected : null });
|
|
66
78
|
if (!usable && (!allowMissing || select.provider !== undefined)) {
|
|
@@ -78,3 +90,34 @@ export function bindTemplateProviders(config, { providers = {}, defaults = {}, s
|
|
|
78
90
|
}
|
|
79
91
|
return { config: out, refs };
|
|
80
92
|
}
|
|
93
|
+
|
|
94
|
+
export const MEMBER_KEY = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
95
|
+
|
|
96
|
+
export function teamMemberVariables(members, ownerAid, hostAid) {
|
|
97
|
+
if (!record(members) || !Object.keys(members).length) fail('Team members required');
|
|
98
|
+
const variables = { 'owner.aid': ownerAid, 'host.aid': hostAid };
|
|
99
|
+
const aids = new Set();
|
|
100
|
+
for (const [key, member] of Object.entries(members)) {
|
|
101
|
+
if (!MEMBER_KEY.test(key) || !record(member) || typeof member.aid !== 'string' || !member.aid
|
|
102
|
+
|| aids.has(member.aid) || typeof member.projectPath !== 'string' || !member.projectPath) fail('Invalid or duplicate member context: ' + key);
|
|
103
|
+
aids.add(member.aid);
|
|
104
|
+
variables['members.' + key + '.aid'] = member.aid;
|
|
105
|
+
variables['members.' + key + '.project'] = member.projectPath;
|
|
106
|
+
}
|
|
107
|
+
return Object.fromEntries(Object.entries(members).map(([key, member]) => [key,
|
|
108
|
+
{ ...variables, 'agent.aid': member.aid, 'project.path': member.projectPath }]));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function planMemberConfig({ member, vars, providers, defaults = {}, selections = {}, allowMissing = false, modelCatalog, mode = 'create_prebuilt' }) {
|
|
112
|
+
if (!record(member) || !MEMBER_KEY.test(member.key) || !record(vars)) fail('Invalid member plan');
|
|
113
|
+
if (!['create_prebuilt', 'create_on_host', 'overlay_existing'].includes(mode)) fail('Invalid member plan mode');
|
|
114
|
+
const rendered = renderValue(member, vars);
|
|
115
|
+
if (mode !== 'create_prebuilt' && (!record(rendered.config) || Object.keys(rendered.config)
|
|
116
|
+
.some(key => !['chatmode', 'memory', 'active_baseagent', 'baseagents'].includes(key)))) fail('Unsupported live-host member configuration');
|
|
117
|
+
const binding = bindTemplateProviders(rendered.config ?? {}, { providers, defaults, selections, allowMissing, modelCatalog });
|
|
118
|
+
return { key: member.key, profile: rendered.profile, skills: rendered.skills ?? {}, config: binding.config, providers: binding.refs };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function renderMemberResource(bytes, relative, vars) {
|
|
122
|
+
return renderResource(bytes, vars, {}, { json: relative.endsWith('.json') });
|
|
123
|
+
}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* │ └── skills/<技能名>/ 本机技能,所有 agent 共用
|
|
11
11
|
* ├── agents/<key>/ 每个 agent 的资源(不含配置)
|
|
12
12
|
* │ ├── personal/soul/*.md
|
|
13
|
-
* │ └── triggers/<id>/trigger.json 可用 {{
|
|
13
|
+
* │ └── triggers/<id>/trigger.json 可用 {{members.<key>.aid}} {{owner.aid}} {{host.aid}}
|
|
14
14
|
* └── workspace/<key>/ 可选:该项目目录的初始内容
|
|
15
15
|
*
|
|
16
16
|
* 配置不进模板文件:agent config.json 与 daemon.json 由 pa-team-build 按 team.json 的
|
|
@@ -82,12 +82,12 @@ export function loadTemplate(dir) {
|
|
|
82
82
|
try { schema = normalizeTeamSchema(schema); } catch (err) { return { errors: [err.message] }; }
|
|
83
83
|
errors.push(...validateContractSchema(team, schema, 'team.json'));
|
|
84
84
|
|
|
85
|
-
const name = team.name
|
|
86
|
-
const version = team.version
|
|
85
|
+
const name = team.name;
|
|
86
|
+
const version = team.version;
|
|
87
87
|
if (typeof name !== 'string' || !NAME_RE.test(name)) errors.push(`team.json name must match ${NAME_RE}`);
|
|
88
|
-
const keys =
|
|
88
|
+
const keys = team.agents.map(agent => agent.key);
|
|
89
89
|
if (keys.length === 0 || !keys.every(k => typeof k === 'string' && KEY_RE.test(k))) {
|
|
90
|
-
errors.push('team.json agents
|
|
90
|
+
errors.push('team.json agents keys are required and must be path-safe');
|
|
91
91
|
}
|
|
92
92
|
if (!schema || schema.type !== 'object') errors.push('team.schema.json must be a JSON Schema object');
|
|
93
93
|
|