evolcore 0.0.45 → 0.0.47
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 +113 -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 +22 -6
- package/dist/agents/codex/app-server-client.js +34 -27
- 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/group/fs-download.js +1 -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 +675 -120
- package/dist/channels/daemon.js +1 -1
- 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 +42 -56
- package/dist/cli/daemon-lifecycle-client.js +55 -19
- 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-channel.js +2 -2
- package/dist/cli/init.js +57 -21
- 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 +135 -46
- package/dist/cli/services-command.js +28 -5
- package/dist/cli/task-context.js +83 -15
- package/dist/cli/upgrade-command.js +4 -2
- package/dist/config/config-field-policy.js +24 -0
- package/dist/config/config-manager.js +49 -19
- package/dist/config/peer-book-store.js +167 -127
- package/dist/config/peer-role-resolver.js +24 -4
- package/dist/config/provider-identity-migration.js +158 -6
- 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/schema-migration.js +123 -16
- package/dist/config/schema-registry.js +6 -2
- 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 +91 -43
- package/dist/core/auth/agent-delegation.js +13 -3
- package/dist/core/auth/delegation-diagnostics.js +56 -15
- package/dist/core/auth/operation-authorizer.js +2 -2
- 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 +39 -12
- package/dist/core/command/menu-protocol.js +8 -16
- package/dist/core/command/skill-slash.js +6 -2
- package/dist/core/command/slash-handler.js +4 -6
- 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-bootstrap.js +11 -9
- package/dist/core/daemon-control.js +4 -7
- package/dist/core/daemon-lifecycle.js +189 -143
- package/dist/core/evolagent-registry.js +50 -2
- 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/host-snapshot.js +9 -4
- package/dist/core/inference/text-inference.js +12 -2
- package/dist/core/initialization/service.js +22 -4
- package/dist/core/invoke/invoke-service.js +24 -3
- package/dist/core/ipc-registration.js +7 -3
- package/dist/core/memory/consolidation.js +6 -6
- 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/ownership/owner-resolver.js +27 -10
- 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/relation/peer-identity.js +5 -1
- package/dist/core/relation/same-owner-proof.js +2 -1
- package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
- package/dist/core/session/session-file-health.js +36 -7
- 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/task/task-image-resources.js +1 -1
- 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 +65 -16
- package/dist/ecweb/runtime/supervisor.js +79 -50
- 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 +132 -75
- package/dist/ipc.js +35 -8
- 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 +18 -4
- package/dist/trigger/script-sandbox.js +39 -2
- package/dist/trigger/state.js +7 -0
- package/dist/utils/aid-bind.js +155 -18
- package/dist/utils/atomic-write.js +3 -3
- package/dist/utils/cross-platform.js +59 -16
- package/dist/utils/error-utils.js +26 -1
- package/dist/utils/instance-registry.js +94 -35
- package/dist/utils/process-introspect.js +187 -27
- package/dist/utils/project-path.js +47 -3
- package/dist/utils/upgrade-jobs.js +4 -4
- 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/aid.md +3 -1
- 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 +17 -5
- 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
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import fs from 'node:fs';
|
|
12
12
|
import path from 'node:path';
|
|
13
13
|
import os from 'node:os';
|
|
14
|
+
import { pathToFileURL } from 'node:url';
|
|
14
15
|
import { evolcoreHome, loadDep } from './deps.mjs';
|
|
15
16
|
import { readSkillFrontmatter } from './frontmatter.mjs';
|
|
16
17
|
|
|
@@ -696,7 +697,7 @@ export function cmdPath(name, { json = false } = {}) {
|
|
|
696
697
|
return lines.join('\n');
|
|
697
698
|
}
|
|
698
699
|
|
|
699
|
-
export function cmdLoad(name, { source = null, withFrontmatter = false, json = false } = {}) {
|
|
700
|
+
export async function cmdLoad(name, { source = null, withFrontmatter = false, json = false } = {}) {
|
|
700
701
|
if (!name) throw new Error('缺少技能名。用法:ec skill load <name> [--source builtin|local] [--with-frontmatter]');
|
|
701
702
|
if (source && source !== 'builtin' && source !== 'local') {
|
|
702
703
|
throw new Error('--source 只能是 builtin 或 local');
|
|
@@ -731,7 +732,17 @@ export function cmdLoad(name, { source = null, withFrontmatter = false, json = f
|
|
|
731
732
|
throw new Error(`技能未启用: ${name}\n请先执行: ec skill enable ${name}`);
|
|
732
733
|
}
|
|
733
734
|
|
|
734
|
-
let content
|
|
735
|
+
let content;
|
|
736
|
+
if (isInside(skillMd, roots.builtin) && packageRoot().includes('node_modules')) {
|
|
737
|
+
// 安装包复用 Core 的版本基线,不在技能脚本里维护另一份台账逻辑。
|
|
738
|
+
const runtime = pathToFileURL(path.join(packageRoot(), 'dist', 'core', 'file-integrity', 'read.js')).href;
|
|
739
|
+
const { readVerifiedText } = await import(runtime);
|
|
740
|
+
const checked = readVerifiedText(skillMd, { verify: true, tag: 'skill' });
|
|
741
|
+
if (!checked) throw new Error(`SKILL.md 完整性校验失败,已拒绝加载: ${skillMd}`);
|
|
742
|
+
content = checked.text;
|
|
743
|
+
} else {
|
|
744
|
+
content = fs.readFileSync(skillMd, 'utf-8');
|
|
745
|
+
}
|
|
735
746
|
if (!withFrontmatter) {
|
|
736
747
|
content = content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '');
|
|
737
748
|
}
|
|
@@ -3,7 +3,7 @@ name: thread-ops
|
|
|
3
3
|
description: >-
|
|
4
4
|
话题链(Thread Chain)与话题总结。
|
|
5
5
|
**以下两种消息必须先加载本 skill 再处理**:① 消息开头是
|
|
6
|
-
|
|
6
|
+
「‹提醒:跨话题委托 · 话题:…›」(你跨话题委托出去的消息,对端回复了);
|
|
7
7
|
② 消息开头是「‹【跨话题复查】来源话题:…›」(复查通知)。
|
|
8
8
|
也用于:要联系当前对端/当前群以外的对象("帮我问一下 X"、"转告 Y"、"去查 Z")、
|
|
9
9
|
处理收到的委托、汇报回来源话题。
|
|
@@ -17,11 +17,11 @@ license: MIT
|
|
|
17
17
|
|
|
18
18
|
## 一、必须加载的时机
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
**两种唤醒消息**(看首行前缀,不要逐字比对整行——模板会微调):
|
|
21
21
|
|
|
22
|
-
1.
|
|
23
|
-
|
|
24
|
-
2.
|
|
22
|
+
1. 首行含 `提醒:跨话题委托`(形如 `‹提醒:跨话题委托 · 话题:<id>(对端:<AID>) · 发送于:… · 原消息:<mid> · 来源会话:<sid> · 复查:<trig…> · self:…›`)
|
|
23
|
+
——你此前跨话题委托出去的消息,对端回复了。**有 ⚠️ 空洞提示就先回查来源话题再转达**。
|
|
24
|
+
2. 首行含 `【跨话题复查】`(形如 `‹【跨话题复查】来源话题:…›`)
|
|
25
25
|
——周期复查到期,你在目标话题里被唤醒。
|
|
26
26
|
|
|
27
27
|
**业务动作**:要联系当前对端/当前群以外的对象;受人所托去问第三方;要汇报回来源话题;并发问多方。
|
|
@@ -39,6 +39,9 @@ license: MIT
|
|
|
39
39
|
|
|
40
40
|
| 概念 | 定义 |
|
|
41
41
|
|---|---|
|
|
42
|
+
| 普通消息 | 当前话题的会话对端发来 |
|
|
43
|
+
| 跨话题委托 | 本端从另一个话题委托给该话题的对端;对方回复后回流 |
|
|
44
|
+
| 跨话题自派 | 本端从另一个话题把任务派给自己 |
|
|
42
45
|
| 话题 | agent 与对端之间一条独立的讨论线;消息必须发在某个话题上 |
|
|
43
46
|
| threadId | 跨端统一标识。话题 `thread-<ms>-<seq4>-<rand4>`;主话题 `main:<aidA>:<aidB>`(两种顺序等价,输出为字典序规范形态) |
|
|
44
47
|
| 双端结构 | 同一 threadId 在双方各有一个本地会话 |
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
[{{batchTime}} · 群聊] 群:{{groupTag}} · {{selfLabel}} · {{chatLabel}}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
‹{{now}} · 群:{{groupTag}}{{modePart}}{{topicPart}} · {{fromLabel}} · {{selfLabel}}{{groupRolePart}} · {{speakerRelationLabel}} · {{chatLabel}}{{mentionPart}} · {{midLabel}}›
|
|
2
|
+
{{?senderCtxLine}}{{senderCtxLine}}
|
|
3
|
+
{{/}}{{?lifecycle=bootstrapping}}(本轮只推进首次设定:按 Owner 这条回复更新名片和头像,然后完成激活;回复里的普通任务记为激活后待办,不在本轮执行。)
|
|
4
|
+
{{/}}{{?isHandoff!=true}}{{content}}{{/}}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
‹{{now}}{{modePart}}{{topicPart}} · {{fromLabel}} · {{selfLabel}} · {{speakerRelationLabel}} · {{chatLabel}} · {{midLabel}}›
|
|
2
|
+
{{?senderCtxLine}}{{senderCtxLine}}
|
|
3
|
+
{{/}}{{?lifecycle=bootstrapping}}(本轮只推进首次设定:按 Owner 这条回复更新名片和头像,然后完成激活;回复里的普通任务记为激活后待办,不在本轮执行。)
|
|
4
|
+
{{/}}{{?isHandoff!=true}}{{content}}{{/}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
‹提醒:跨话题委托 · 话题:{{threadContextOriginThreadId}}{{?threadContextOriginPeer}}(对端:{{threadContextOriginPeer}}){{/}} · 发送于:{{threadContextTime}} · 原消息:{{threadContextMessageId}} · 来源会话:{{threadContextOriginSessionId}} · 复查:{{threadContextTriggerId}} · {{selfLabel}}›
|
|
2
2
|
{{?threadContextGapHasNewMessages}}⚠️ 来源话题在发送后已有 {{threadContextGapCount}} 条新消息{{?threadContextGapRange}}({{threadContextGapRange}}){{/}} —— 处理前建议先回查该话题的空洞期消息。
|
|
3
3
|
{{/}}{{?threadContextGapError}}⚠️ 无法检测来源话题的空洞期消息({{threadContextGapError}})—— 如需确认,请手动执行 ec thread history 回查该话题。
|
|
4
4
|
{{/}}
|
|
@@ -16,15 +16,15 @@ ec events 事件中心运维(status/ledger/tail/doctor/reload/rules/pack/publ
|
|
|
16
16
|
ec services 服务路由运维与对端调用(status/types/ledger/tail/doctor/reload/enable/disable;describe/schema/call 调对端服务;服务调用是点对点、要结果、不丢) $KITS_DOCS/evolcore/services.md
|
|
17
17
|
{{?channel=aun}}
|
|
18
18
|
{{?chatType=private}}
|
|
19
|
-
{{?
|
|
19
|
+
{{?speakerRelation=owner}}
|
|
20
20
|
ec team 初始化当前 Agent 的 Team Workspace、发布/删除/替换导航入口、管理团队成员 $KITS_DOCS/evolcore/team-workspace.md
|
|
21
21
|
{{/}}
|
|
22
22
|
{{/}}
|
|
23
23
|
{{/}}
|
|
24
|
-
{{?
|
|
24
|
+
{{?speakerRelation=owner}}
|
|
25
25
|
ec task 恢复暂停或异常中断的会话任务(resume <sessionId>;复用原 baseagent 会话,缺失时失败关闭) $KITS_DOCS/evolcore/task.md
|
|
26
26
|
{{/}}
|
|
27
|
-
{{?
|
|
27
|
+
{{?speakerRelation=admin}}
|
|
28
28
|
ec task 恢复暂停或异常中断的本 Agent 会话任务(resume <sessionId>;复用原 baseagent 会话,缺失时失败关闭) $KITS_DOCS/evolcore/task.md
|
|
29
29
|
{{/}}
|
|
30
30
|
ec skill 技能加载与管理(load 加载正文/path 查路径/list 列技能/info 详情/where 根目录/enable/disable/install/remove) $KITS_DOCS/evolcore/skill.md
|
|
@@ -39,11 +39,11 @@ ec thread 话题管理与话题链(peers 列对端 / list 列话题 / history
|
|
|
39
39
|
{{?selfAid}}
|
|
40
40
|
ec group 群管理(建群/查群/本地群历史/邀请/踢人/角色/封禁/屏蔽/成员状态/规则;发送群消息用 ecmsg,完整协作使用 ec-group-collaboration 技能) $KITS_DOCS/evolcore/group.md
|
|
41
41
|
{{/}}
|
|
42
|
-
{{?
|
|
42
|
+
{{?speakerRelation=owner}}
|
|
43
43
|
ec agent EvolAgent 生命周期与主机信息(创建/启停/热重载/改配置/查主机信息;创建流程使用 ec-agent-create 技能)。ec agent reload 仅对配置/soul/memory 生效,改源码无效 $KITS_DOCS/evolcore/agent.md
|
|
44
44
|
ec peer 对端身份与本地拉黑(查登记/拉黑/解除拉黑;显式 --self) $KITS_DOCS/evolcore/peer.md
|
|
45
45
|
{{/}}
|
|
46
|
-
{{?
|
|
46
|
+
{{?speakerRelation=admin}}
|
|
47
47
|
ec agent EvolAgent 生命周期与主机信息(创建/启停/热重载/改配置/查主机信息;创建流程使用 ec-agent-create 技能)。ec agent reload 仅对配置/soul/memory 生效,改源码无效 $KITS_DOCS/evolcore/agent.md
|
|
48
48
|
ec peer 对端身份与本地拉黑(查登记/拉黑/解除拉黑;显式 --self) $KITS_DOCS/evolcore/peer.md
|
|
49
49
|
{{/}}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
sessionOrigin: evolcore-managed # 本会话由 EvolCore 托管,非直连 base agent 终端
|
|
3
3
|
|
|
4
4
|
你处于 EvolCore 托管会话中。上面已按本会话场景选段注入环境信息:身份层(selfAid 等)、
|
|
5
|
-
关系层(peerId
|
|
5
|
+
关系层(peerId/与发言人/我的群角色/peerType/peerKey)、环境层(chatType/channel/permissionMode)、
|
|
6
6
|
渠道层(本渠道可用能力)、会话层(project/sessionId/timezone 等)、命令集能力卡与核心规则。
|
|
7
7
|
|
|
8
8
|
**工作区 `CLAUDE.md` 中"请先读完 `kits/rules/` 这 6 个文件"的指令面向直连场景**(base agent
|
|
@@ -2,14 +2,10 @@
|
|
|
2
2
|
{{?peerKey}}
|
|
3
3
|
peerName: {{peerName}}
|
|
4
4
|
peerId: {{peerId}} # 对端在当前渠道内的原生 ID
|
|
5
|
-
|
|
6
|
-
{{?
|
|
7
|
-
|
|
5
|
+
{{?chatType=group}}
|
|
6
|
+
{{?myGroupRole}}
|
|
7
|
+
我的群角色: {{myGroupRole}} # owner|admin|member|自定义角色|none(我在本群的角色)
|
|
8
8
|
{{/}}
|
|
9
|
-
peerKey: {{peerKey}} # 跨渠道唯一标识,格式 channel#urlEncode(peerId)
|
|
10
|
-
{{/}}
|
|
11
|
-
{{?groupId}}
|
|
12
|
-
groupId: {{groupId}}
|
|
13
9
|
{{?groupRulesStatus}}
|
|
14
10
|
groupRulesStatus: {{groupRulesStatus}} # ignored/synced/cached/missing/forbidden/invalid_metadata/file_mismatch/too_large/unreadable/error
|
|
15
11
|
{{/}}
|
|
@@ -17,3 +13,11 @@ groupRulesStatus: {{groupRulesStatus}} # ignored/synced/cached/missing/forbidden
|
|
|
17
13
|
groupRulesError: {{groupRulesError}}
|
|
18
14
|
{{/}}
|
|
19
15
|
{{/}}
|
|
16
|
+
{{?speakerRelation}}
|
|
17
|
+
与发言人: {{speakerRelation}} # owner|admin|member|visitor|自定义角色|none(发言人与我的关系;非联系人按 visitor)
|
|
18
|
+
{{/}}
|
|
19
|
+
{{?peerType}}
|
|
20
|
+
peerType: {{peerType}} # human 或 agent
|
|
21
|
+
{{/}}
|
|
22
|
+
peerKey: {{peerKey}} # 跨渠道唯一标识,格式 channel#urlEncode(peerId)
|
|
23
|
+
{{/}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "evolcore",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.47",
|
|
4
4
|
"description": "AI Agent gateway connecting Claude, Codex, Gemini, and the bundled ecagent runner to messaging channels with multi-project session management",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
"!dist/core/file-integrity/write.js",
|
|
24
24
|
"bin/",
|
|
25
25
|
"scripts/agent-template/",
|
|
26
|
+
"scripts/aid-batch/",
|
|
26
27
|
"!dist/experimental/",
|
|
27
28
|
"!dist/ability/protocol-v2.js",
|
|
28
29
|
"!skills/",
|
|
@@ -71,7 +72,7 @@
|
|
|
71
72
|
"chokidar": "^5.0.0",
|
|
72
73
|
"cron-parser": "^5.5.0",
|
|
73
74
|
"dotenv": "^17.4.2",
|
|
74
|
-
"ec-web": "0.0.
|
|
75
|
+
"ec-web": "0.0.47",
|
|
75
76
|
"ignore": "7.0.5",
|
|
76
77
|
"image-type": "^6.0.0",
|
|
77
78
|
"partial-json": "0.1.7",
|
|
@@ -6,7 +6,7 @@ import { parseArgs, readJson } from './shared/common.mjs';
|
|
|
6
6
|
export async function cli(argv) {
|
|
7
7
|
const command = argv[0];
|
|
8
8
|
if (!command || argv.includes('--help')) {
|
|
9
|
-
console.log('Agent template: inspect
|
|
9
|
+
console.log('Agent template: inspect | build | read-package | preview | apply-installation | verify-installation | overlay --options-file <JSON>');
|
|
10
10
|
return 0;
|
|
11
11
|
}
|
|
12
12
|
const args = parseArgs(argv.slice(1), { values: ['options-file', 'agent-dir', 'template', 'out', 'aid', 'owner', 'host', 'providers', 'workspace', 'backup'] });
|
|
@@ -17,9 +17,14 @@ export async function cli(argv) {
|
|
|
17
17
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
18
18
|
options.packageRoot ??= packageRoot;
|
|
19
19
|
const commands = {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
'
|
|
20
|
+
inspect: ['./team-pack.mjs', 'inspectCollection'],
|
|
21
|
+
build: ['./team-pack.mjs', 'buildCollection'],
|
|
22
|
+
'validate-selection': ['./team-pack.mjs', 'validateCollectionSelection'],
|
|
23
|
+
'read-package': ['./team-preview.mjs', 'readPackage'],
|
|
24
|
+
preview: ['./team-preview.mjs', 'previewInstallation'],
|
|
25
|
+
'apply-installation': ['./team-preview.mjs', 'applyInstallationPlan'],
|
|
26
|
+
'verify-installation': ['./team-preview.mjs', 'verifyInstallationPlan'],
|
|
27
|
+
capabilities: ['./shared/template-contract.mjs', 'readTemplateCapabilities'],
|
|
23
28
|
overlay: ['./overlay.mjs', 'overlay'],
|
|
24
29
|
};
|
|
25
30
|
const entry = commands[command];
|
|
@@ -7,9 +7,9 @@ import { readJson, jsonBytes, assert, sha256, walkFiles, inside, unpack, behavio
|
|
|
7
7
|
import { loadTemplate, MANAGED_AGENT_FIELDS, templateDigest } from './shared/template.mjs';
|
|
8
8
|
import { loadEvolcore } from './shared/evolcore.mjs';
|
|
9
9
|
import { validateAgainstSchema, buildAgentTriggers, resolveProviderRefs } from './shared/plan.mjs';
|
|
10
|
-
import { excluded } from './
|
|
10
|
+
import { excludedResource as excluded } from './shared/template-package.mjs';
|
|
11
11
|
import { normalizeTeam } from './shared/template-contract.mjs';
|
|
12
|
-
import { renderValue as renderTemplateValue, renderResource, bindTemplateProviders } from './shared/template-runtime.mjs';
|
|
12
|
+
import { renderValue as renderTemplateValue, renderResource, bindTemplateProviders, teamMemberVariables, planMemberConfig } from './shared/template-runtime.mjs';
|
|
13
13
|
|
|
14
14
|
export async function inspectAgent(options) {
|
|
15
15
|
const config = options.effectiveConfig ?? readJson(path.join(options.agentDir, 'config.json'));
|
|
@@ -71,7 +71,7 @@ export async function inspectPackage(options) {
|
|
|
71
71
|
|| file.startsWith('agents/' + key + '/personal/soul/') && file.endsWith('.md') && !file.endsWith('/00-GUIDE.md')
|
|
72
72
|
|| file === 'agents/' + key + '/personal/welcome.md' || file.startsWith('agents/' + key + '/triggers/')),
|
|
73
73
|
'INVALID_ARGUMENT', 'Unsupported template resource: ' + file);
|
|
74
|
-
const platforms = tpl.team.host
|
|
74
|
+
const platforms = tpl.team.host.platform;
|
|
75
75
|
if (platforms !== undefined) assert(Array.isArray(platforms) && platforms.length
|
|
76
76
|
&& platforms.every(p => ['linux', 'darwin', 'win32'].includes(p)) && platforms.includes(process.platform),
|
|
77
77
|
'INCOMPATIBLE', 'Template host.platform must support this host');
|
|
@@ -87,11 +87,14 @@ export async function inspectPackage(options) {
|
|
|
87
87
|
'INVALID_ARGUMENT', 'Members must map to distinct Agents on the same host');
|
|
88
88
|
assert(Object.keys(options.members ?? {}).every(key => tpl.keys.includes(key)), 'INVALID_ARGUMENT', 'Unknown member selection');
|
|
89
89
|
const writes = new Map(); const members = []; const plans = [];
|
|
90
|
+
const memberVars = teamMemberVariables(Object.fromEntries(tpl.keys.map(key => [key,
|
|
91
|
+
{ aid: options.targets[key].targetAid, projectPath: options.targets[key].projectPath ?? options.targets[key].targetConfig?.projects?.defaultPath }])),
|
|
92
|
+
contexts[0].ownerAid, contexts[0].hostAid);
|
|
90
93
|
for (const key of tpl.keys) {
|
|
91
94
|
const selection = options.members?.[key] ?? {};
|
|
92
95
|
const out = inside(options.out ?? path.dirname(root), 'members/' + key);
|
|
93
96
|
const data = await inspectMember({ ...options.targets[key], out, packageRoot: options.packageRoot, digest: options.digest,
|
|
94
|
-
pullId: options.pullId, selections: selection.providers ?? {}, externalAids: selection.externalAids ?? {} },
|
|
97
|
+
pullId: options.pullId, planMode: options.planMode, memberVars: memberVars[key], selections: selection.providers ?? {}, externalAids: selection.externalAids ?? {} },
|
|
95
98
|
{ pkg, tpl, templateDir, key, files: files.filter(f => !f.startsWith('agents/') && !f.startsWith('workspace/')
|
|
96
99
|
|| f.startsWith('agents/' + key + '/') || f.startsWith('workspace/' + key + '/')) });
|
|
97
100
|
const plan = readJson(data.planFile);
|
|
@@ -118,9 +121,9 @@ async function inspectMember(options, { pkg, tpl, templateDir, files, key }) {
|
|
|
118
121
|
assert(targets?.aid === options.targetAid, 'INVALID_ARGUMENT', 'Target configuration required');
|
|
119
122
|
const project = options.projectPath ?? targets.projects?.defaultPath;
|
|
120
123
|
assert(typeof project === 'string' && path.isAbsolute(project), 'INVALID_ARGUMENT', 'Target default project required');
|
|
121
|
-
const vars = {
|
|
124
|
+
const vars = options.memberVars ?? teamMemberVariables({ [key]: { aid: options.targetAid, projectPath: project } }, options.ownerAid, options.hostAid)[key];
|
|
122
125
|
const renderValue = value => renderTemplateValue(value, vars, options.externalAids ?? {});
|
|
123
|
-
const spec = renderValue(tpl.team.agents.find(
|
|
126
|
+
const spec = renderValue(tpl.team.agents.find(member => member.key === key));
|
|
124
127
|
for (const file of files) assert(file === 'team.json' || file === 'team.schema.json'
|
|
125
128
|
|| file.startsWith('.evolcore/skills/') || file.startsWith('workspace/' + key + '/')
|
|
126
129
|
|| file.startsWith('agents/' + key + '/personal/soul/') && file.endsWith('.md') && !file.endsWith('/00-GUIDE.md')
|
|
@@ -139,15 +142,19 @@ async function inspectMember(options, { pkg, tpl, templateDir, files, key }) {
|
|
|
139
142
|
try {
|
|
140
143
|
const { default: semver } = await import('semver');
|
|
141
144
|
assert(Array.isArray(pkg.compat?.platforms) && pkg.compat.platforms.includes(process.platform)
|
|
142
|
-
&& semver.validRange(pkg.compat.evolcore)
|
|
145
|
+
&& semver.validRange(pkg.compat.evolcore)
|
|
146
|
+
&& (semver.satisfies(ec.version, pkg.compat.evolcore, { includePrerelease: true })
|
|
147
|
+
|| !pkg.compat.templateFeatures?.length && semver.satisfies(ec.version.replace(/-test\.\d+$/, ''), pkg.compat.evolcore, { includePrerelease: true }))
|
|
148
|
+
&& (pkg.compat.templateFeatures === undefined || Array.isArray(pkg.compat.templateFeatures)
|
|
149
|
+
&& pkg.compat.templateFeatures.every(feature => feature === 'member-references-v1')),
|
|
143
150
|
'INCOMPATIBLE', 'Platform or EvolCore version is incompatible', { incompatible: ['platform/version'] });
|
|
144
151
|
const selections = options.selections ?? {};
|
|
145
152
|
for (const [name, block] of Object.entries(spec.config.baseagents ?? {})) {
|
|
146
153
|
assert(BASEAGENTS.includes(name) && isRecord(block) && Object.keys(block).every(f => ['provider', 'model', 'effort', 'params'].includes(f)),
|
|
147
154
|
'INVALID_ARGUMENT', 'Invalid baseagent block');
|
|
148
155
|
}
|
|
149
|
-
const {
|
|
150
|
-
|
|
156
|
+
const planned = planMemberConfig({ member: spec, vars, providers: options.providers ?? {}, selections, allowMissing: true, mode: options.planMode ?? 'overlay_existing' });
|
|
157
|
+
const resolved = planned.config; const refs = planned.providers;
|
|
151
158
|
assert(resolved.baseagents?.[resolved.active_baseagent], 'INVALID_ARGUMENT', 'Default baseagent must be selected');
|
|
152
159
|
assert(Object.keys(selections).every(name => resolved.baseagents?.[name]), 'INVALID_ARGUMENT', 'Unknown baseagent selection');
|
|
153
160
|
const config = mergeObjects(targets, resolveProviderRefs(resolved));
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import fs from 'node:fs';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { renderText, renderValue } from './template-runtime.mjs';
|
|
9
|
+
import { validateContractSchema } from './template-contract.mjs';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* 替换 {{x.y}} 占位符;vars 里没有的保留原文。
|
|
@@ -25,38 +26,7 @@ export function renderPlaceholders(text, vars) {
|
|
|
25
26
|
* @param {string} at
|
|
26
27
|
* @returns {string[]}
|
|
27
28
|
*/
|
|
28
|
-
export
|
|
29
|
-
const errors = [];
|
|
30
|
-
if (!schema || typeof schema !== 'object') return [`${at}: schema missing`];
|
|
31
|
-
const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
|
|
32
|
-
if (types.length) {
|
|
33
|
-
const actual = Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;
|
|
34
|
-
const matches = types.some(t => t === actual || (t === 'integer' && Number.isInteger(value)) || (t === 'number' && typeof value === 'number'));
|
|
35
|
-
if (!matches) return [`${at}: expected ${types.join('|')}, got ${actual}`];
|
|
36
|
-
}
|
|
37
|
-
if (schema.enum && !schema.enum.includes(value)) errors.push(`${at}: must be one of ${schema.enum.join(', ')}`);
|
|
38
|
-
if (typeof value === 'string') {
|
|
39
|
-
if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${at}: shorter than ${schema.minLength}`);
|
|
40
|
-
if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(`${at}: does not match ${schema.pattern}`);
|
|
41
|
-
}
|
|
42
|
-
if (typeof value === 'number' && schema.minimum !== undefined && value < schema.minimum) errors.push(`${at}: below ${schema.minimum}`);
|
|
43
|
-
if (Array.isArray(value)) {
|
|
44
|
-
if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${at}: needs at least ${schema.minItems} items`);
|
|
45
|
-
if (schema.items) value.forEach((v, i) => errors.push(...validateAgainstSchema(v, schema.items, `${at}[${i}]`)));
|
|
46
|
-
}
|
|
47
|
-
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
48
|
-
for (const req of schema.required ?? []) if (!Object.hasOwn(value, req)) errors.push(`${at}: missing "${req}"`);
|
|
49
|
-
const props = schema.properties ?? {};
|
|
50
|
-
for (const [k, v] of Object.entries(value)) {
|
|
51
|
-
if (Object.hasOwn(props, k)) errors.push(...validateAgainstSchema(v, props[k], `${at}.${k}`));
|
|
52
|
-
else if (schema.additionalProperties === false) errors.push(`${at}.${k}: not allowed`);
|
|
53
|
-
else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
|
|
54
|
-
errors.push(...validateAgainstSchema(v, schema.additionalProperties, `${at}.${k}`));
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return errors;
|
|
59
|
-
}
|
|
29
|
+
export const validateAgainstSchema = validateContractSchema;
|
|
60
30
|
|
|
61
31
|
/**
|
|
62
32
|
* 把 baseagents.<x>.provider 的 { id, name } 换成 mapping[id] ?? id;字符串原样保留。
|
|
@@ -101,7 +71,7 @@ export function checkAgentProvider({ config, defaults = {}, providers = {}, base
|
|
|
101
71
|
}
|
|
102
72
|
|
|
103
73
|
/**
|
|
104
|
-
* 读 <templateRoot>/agents/<key>/triggers/<id>/trigger.json,用
|
|
74
|
+
* 读 <templateRoot>/agents/<key>/triggers/<id>/trigger.json,用 成员变量 渲染,
|
|
105
75
|
* 经 ec.validateTrigger 校验,并核对 agentAid、id。不落盘。
|
|
106
76
|
* 每个 trigger 记一条 rec.check(`trigger[<key>/<id>]`, …),名称与现在相同。
|
|
107
77
|
* @param {{ templateRoot: string, key: string, aid: string, vars: Record<string, string>, ec: any, rec: any }} opts
|
|
@@ -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
|
+
}
|