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.
Files changed (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +22 -6
  12. package/dist/agents/codex/app-server-client.js +34 -27
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/group/fs-download.js +1 -1
  18. package/dist/aun/menu/client.js +142 -182
  19. package/dist/aun/rpc/client.js +33 -17
  20. package/dist/aun/service-proxy.js +6 -23
  21. package/dist/channels/aun.js +675 -120
  22. package/dist/channels/daemon.js +1 -1
  23. package/dist/cli/agent-create.js +37 -10
  24. package/dist/cli/agent-template.js +105 -84
  25. package/dist/cli/agent.js +31 -18
  26. package/dist/cli/daemon-commands.js +42 -56
  27. package/dist/cli/daemon-lifecycle-client.js +55 -19
  28. package/dist/cli/directory.js +12 -4
  29. package/dist/cli/ecmsg-gateway.js +5 -2
  30. package/dist/cli/events-command.js +2 -1
  31. package/dist/cli/init-channel.js +2 -2
  32. package/dist/cli/init.js +57 -21
  33. package/dist/cli/integrity-command.js +2 -0
  34. package/dist/cli/managed-command-guard.js +20 -1
  35. package/dist/cli/menu-client.js +7 -5
  36. package/dist/cli/restart-monitor.js +135 -46
  37. package/dist/cli/services-command.js +28 -5
  38. package/dist/cli/task-context.js +83 -15
  39. package/dist/cli/upgrade-command.js +4 -2
  40. package/dist/config/config-field-policy.js +24 -0
  41. package/dist/config/config-manager.js +49 -19
  42. package/dist/config/peer-book-store.js +167 -127
  43. package/dist/config/peer-role-resolver.js +24 -4
  44. package/dist/config/provider-identity-migration.js +158 -6
  45. package/dist/config/provider-identity.js +10 -4
  46. package/dist/config/provider-ipc-service.js +10 -2
  47. package/dist/config/provider-local-sync.js +2 -2
  48. package/dist/config/providers-config.js +95 -10
  49. package/dist/config/providers-import.js +4 -6
  50. package/dist/config/providers.js +14 -3
  51. package/dist/config/role-store.js +1 -1
  52. package/dist/config/schema-migration.js +123 -16
  53. package/dist/config/schema-registry.js +6 -2
  54. package/dist/config-store.js +9 -1
  55. package/dist/core/agent-application-service.js +56 -29
  56. package/dist/core/agent-create-status.js +3 -1
  57. package/dist/core/agent-creation-claim.js +1 -0
  58. package/dist/core/agent-ipc-registration.js +2 -2
  59. package/dist/core/agent-reload-coordinator.js +38 -1
  60. package/dist/core/agent-runtime.js +91 -43
  61. package/dist/core/auth/agent-delegation.js +13 -3
  62. package/dist/core/auth/delegation-diagnostics.js +56 -15
  63. package/dist/core/auth/operation-authorizer.js +2 -2
  64. package/dist/core/auth/operation-catalog.js +3 -3
  65. package/dist/core/bootstrap-service.js +3 -0
  66. package/dist/core/capability/capability-manager.js +3 -1
  67. package/dist/core/channel-loader.js +29 -3
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-control.js +6 -5
  70. package/dist/core/command/agent-template-menu.js +32 -97
  71. package/dist/core/command/eventcenter-menu.js +61 -13
  72. package/dist/core/command/menu-catalog.js +11 -4
  73. package/dist/core/command/menu-handler.js +39 -12
  74. package/dist/core/command/menu-protocol.js +8 -16
  75. package/dist/core/command/skill-slash.js +6 -2
  76. package/dist/core/command/slash-handler.js +4 -6
  77. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  78. package/dist/core/command/team-workspace-management-store.js +83 -0
  79. package/dist/core/command/team-workspace-management.js +1 -2
  80. package/dist/core/command/team-workspace-team.js +26 -3
  81. package/dist/core/daemon-bootstrap.js +11 -9
  82. package/dist/core/daemon-control.js +4 -7
  83. package/dist/core/daemon-lifecycle.js +189 -143
  84. package/dist/core/evolagent-registry.js +50 -2
  85. package/dist/core/evolagent.js +2 -1
  86. package/dist/core/file-integrity/read.js +9 -16
  87. package/dist/core/file-integrity/store.js +94 -34
  88. package/dist/core/handoff/dispatcher.js +33 -7
  89. package/dist/core/handoff/runtime.js +8 -0
  90. package/dist/core/host-snapshot.js +9 -4
  91. package/dist/core/inference/text-inference.js +12 -2
  92. package/dist/core/initialization/service.js +22 -4
  93. package/dist/core/invoke/invoke-service.js +24 -3
  94. package/dist/core/ipc-registration.js +7 -3
  95. package/dist/core/memory/consolidation.js +6 -6
  96. package/dist/core/message/aun-ipc-sender.js +109 -7
  97. package/dist/core/message/contact-admission.js +6 -2
  98. package/dist/core/message/message-bridge.js +13 -0
  99. package/dist/core/message/message-queue.js +131 -30
  100. package/dist/core/message/pending-hints.js +8 -0
  101. package/dist/core/message/response-engine.js +48 -2
  102. package/dist/core/message/send-routing.js +3 -12
  103. package/dist/core/model/catalog-service.js +13 -0
  104. package/dist/core/model/model-catalog.js +57 -18
  105. package/dist/core/ownership/owner-resolver.js +27 -10
  106. package/dist/core/pack-auth.js +163 -31
  107. package/dist/core/pack-install.js +42 -1
  108. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  109. package/dist/core/permission/ec-command-parser.js +3 -1
  110. package/dist/core/permission/shell-environment.js +23 -0
  111. package/dist/core/rate-window.js +6 -1
  112. package/dist/core/relation/peer-identity.js +5 -1
  113. package/dist/core/relation/same-owner-proof.js +2 -1
  114. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  115. package/dist/core/session/session-file-health.js +36 -7
  116. package/dist/core/session/session-idle-monitor.js +0 -1
  117. package/dist/core/session/session-manager.js +14 -0
  118. package/dist/core/session/session-title.js +26 -6
  119. package/dist/core/skill/index-generator.js +3 -4
  120. package/dist/core/task/task-image-resources.js +1 -1
  121. package/dist/core/thread/thread-service.js +0 -1
  122. package/dist/core/thread/topic-id.js +8 -0
  123. package/dist/directory/owner-directory-admission.js +17 -0
  124. package/dist/directory/owner-directory-cache.js +3 -1
  125. package/dist/directory/owner-directory-markdown.js +145 -23
  126. package/dist/directory/owner-directory-policy.js +23 -0
  127. package/dist/directory/owner-directory-query-operation.js +20 -6
  128. package/dist/directory/owner-directory-search.js +47 -0
  129. package/dist/eck/message-renderer.js +171 -32
  130. package/dist/ecweb/basic-settings-service.js +7 -3
  131. package/dist/ecweb/providers-service.js +17 -10
  132. package/dist/ecweb/runtime/lifecycle.js +65 -16
  133. package/dist/ecweb/runtime/supervisor.js +79 -50
  134. package/dist/event-center/admission-materializer.js +1 -1
  135. package/dist/event-center/bus-gate.js +48 -4
  136. package/dist/event-center/bus-host.js +3 -3
  137. package/dist/event-center/center-config.js +57 -28
  138. package/dist/event-center/dispatcher.js +8 -0
  139. package/dist/event-center/event-log.js +69 -27
  140. package/dist/event-center/index-generator.js +6 -1
  141. package/dist/event-center/ipc-operation.js +66 -25
  142. package/dist/event-center/pack-loader.js +12 -55
  143. package/dist/event-center/pack-manager.js +5 -3
  144. package/dist/event-center/registry.js +48 -52
  145. package/dist/event-center/runtime.js +219 -81
  146. package/dist/event-center/script-runner.js +18 -7
  147. package/dist/event-center/types.js +9 -1
  148. package/dist/event-center/validation.js +33 -4
  149. package/dist/index.js +132 -75
  150. package/dist/ipc.js +35 -8
  151. package/dist/product.js +1 -0
  152. package/dist/proxy/manager.js +52 -11
  153. package/dist/proxy/service-supervisor.js +265 -67
  154. package/dist/services/dispatcher.js +26 -3
  155. package/dist/services/idempotency.js +128 -0
  156. package/dist/services/identity.js +3 -27
  157. package/dist/services/index-generator.js +5 -1
  158. package/dist/services/index.js +244 -45
  159. package/dist/services/ipc-operation.js +164 -20
  160. package/dist/services/pack-manager.js +37 -9
  161. package/dist/services/router.js +100 -31
  162. package/dist/services/script-runner.js +15 -4
  163. package/dist/services/service-payload.js +50 -2
  164. package/dist/services/validation.js +107 -3
  165. package/dist/trigger/scheduler.js +18 -4
  166. package/dist/trigger/script-sandbox.js +39 -2
  167. package/dist/trigger/state.js +7 -0
  168. package/dist/utils/aid-bind.js +155 -18
  169. package/dist/utils/atomic-write.js +3 -3
  170. package/dist/utils/cross-platform.js +59 -16
  171. package/dist/utils/error-utils.js +26 -1
  172. package/dist/utils/instance-registry.js +94 -35
  173. package/dist/utils/process-introspect.js +187 -27
  174. package/dist/utils/project-path.js +47 -3
  175. package/dist/utils/upgrade-jobs.js +4 -4
  176. package/dist/utils/windows-shell-trust.js +174 -68
  177. package/kits/docs/context-assembly.md +3 -3
  178. package/kits/docs/evolcore/agent.md +28 -10
  179. package/kits/docs/evolcore/aid.md +3 -1
  180. package/kits/docs/evolcore/config.md +22 -0
  181. package/kits/docs/evolcore/directory.md +46 -12
  182. package/kits/docs/evolcore/event-center.md +6 -6
  183. package/kits/docs/evolcore/group-collaboration.md +1 -1
  184. package/kits/docs/evolcore/menu-client.md +7 -5
  185. package/kits/docs/evolcore/menu-protocol.md +5 -3
  186. package/kits/docs/evolcore/msg.md +10 -3
  187. package/kits/docs/evolcore/provider.md +17 -5
  188. package/kits/docs/evolcore/services.md +145 -12
  189. package/kits/docs/evolcore/thread-chain.md +17 -9
  190. package/kits/docs/prompt-loading-architecture.md +4 -4
  191. package/kits/eck_message_manifest.json +46 -3
  192. package/kits/rules/04-relation.md +10 -2
  193. package/kits/rules/06-channel.md +2 -1
  194. package/kits/schemas/providers.schema.2.json +1 -0
  195. package/kits/skills/ec-group/SKILL.md +4 -0
  196. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  197. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  198. package/kits/skills/thread-ops/SKILL.md +8 -5
  199. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  200. package/kits/templates/message-fragments/group-batch.md +1 -0
  201. package/kits/templates/message-fragments/item-group.md +4 -0
  202. package/kits/templates/message-fragments/item-private.md +4 -0
  203. package/kits/templates/message-fragments/thread-context.md +1 -1
  204. package/kits/templates/system-fragments/commands.md +5 -5
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +11 -7
  207. package/package.json +3 -2
  208. package/scripts/agent-template/index.mjs +9 -4
  209. package/scripts/agent-template/inspect.mjs +16 -9
  210. package/scripts/agent-template/shared/plan.mjs +3 -33
  211. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  212. package/scripts/agent-template/shared/template-package.mjs +119 -10
  213. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  214. package/scripts/agent-template/shared/template.mjs +5 -5
  215. package/scripts/agent-template/team-pack.mjs +245 -0
  216. package/scripts/agent-template/team-preview.mjs +111 -0
  217. package/scripts/aid-batch/identity-batch.mjs +143 -0
  218. package/dist/ability/versions.js +0 -32
  219. package/dist/aun/model-headers.js +0 -17
  220. package/dist/channels/builtin-plugins.js +0 -19
  221. package/dist/core/command/team-workspace-initializer.js +0 -2
  222. package/dist/core/command/team-workspace-job-store.js +0 -88
  223. package/dist/core/command/team-workspace-management-service.js +0 -2
  224. package/dist/core/contact-bind-registry.js +0 -27
  225. package/dist/event-center/ledger.js +0 -52
  226. package/dist/services/reply.js +0 -55
  227. package/kits/templates/message-fragments/item.md +0 -3
  228. 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 = fs.readFileSync(skillMd, 'utf-8');
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. `‹【跨话题上下文】来源话题:<id> · 对端:<AID> · 发送于:… · 复查:<trig…|无> → self:…›`
23
- ——你此前跨话题发出的消息,对端回复了。**有 ⚠️ 空洞提示就先回查来源话题再转达**。
24
- 2. `‹【跨话题复查】来源话题:<id> · 对端:<AID> · 发送于:… · 复查:<trig…> → self:…›`
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,3 @@
1
+ ‹{{shortNow}}{{modePart}}{{topicPart}} · {{fromLabel}}{{groupRolePart}} · {{speakerRelationLabel}}{{mentionPart}} · {{midLabel}}›
2
+ {{?senderCtxLine}}{{senderCtxLine}}
3
+ {{/}}{{content}}
@@ -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
- ‹【跨话题上下文】来源话题:{{threadContextOriginThreadId}}{{?threadContextOriginPeer}} · 对端:{{threadContextOriginPeer}}{{/}}{{?threadContextTime}} · 发送于:{{threadContextTime}}{{/}} · 复查:{{threadContextTriggerId}} → self:{{selfAid}}›
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
- {{?peerRole=owner}}
19
+ {{?speakerRelation=owner}}
20
20
  ec team 初始化当前 Agent 的 Team Workspace、发布/删除/替换导航入口、管理团队成员 $KITS_DOCS/evolcore/team-workspace.md
21
21
  {{/}}
22
22
  {{/}}
23
23
  {{/}}
24
- {{?peerRole=owner}}
24
+ {{?speakerRelation=owner}}
25
25
  ec task 恢复暂停或异常中断的会话任务(resume <sessionId>;复用原 baseagent 会话,缺失时失败关闭) $KITS_DOCS/evolcore/task.md
26
26
  {{/}}
27
- {{?peerRole=admin}}
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
- {{?peerRole=owner}}
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
- {{?peerRole=admin}}
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/peerRole/peerType/peerKey)、环境层(chatType/channel/permissionMode)、
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
- peerRole: {{peerRole}} # owner|admin|member|visitor|自定义角色|none
6
- {{?peerType}}
7
- peerType: {{peerType}} # human 或 agent
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.45",
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.45",
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-agent | pack | inspect-package | overlay --options-file <JSON>');
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
- 'inspect-agent': ['./inspect.mjs', 'inspectAgent'],
21
- pack: ['./pack.mjs', 'pack'],
22
- 'inspect-package': ['./inspect.mjs', 'inspectPackage'],
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 './pack.mjs';
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?.platform;
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 = { 'agent.aid': options.targetAid, 'owner.aid': options.ownerAid, 'host.aid': options.hostAid, 'project.path': project };
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(agent => agent.key === key));
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) && semver.satisfies(ec.version.replace(/-test\.\d+$/, ''), pkg.compat.evolcore, { includePrerelease: true }),
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 { config: resolved, refs } = bindTemplateProviders(spec.config,
150
- { providers: options.providers ?? {}, selections, allowMissing: true });
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 function validateAgainstSchema(value, schema, at = '$') {
29
- const errors = [];
30
- if (!schema || typeof schema !== 'object') return [`${at}: schema missing`];
31
- const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
32
- if (types.length) {
33
- const actual = Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;
34
- const matches = types.some(t => t === actual || (t === 'integer' && Number.isInteger(value)) || (t === 'number' && typeof value === 'number'));
35
- if (!matches) return [`${at}: expected ${types.join('|')}, got ${actual}`];
36
- }
37
- if (schema.enum && !schema.enum.includes(value)) errors.push(`${at}: must be one of ${schema.enum.join(', ')}`);
38
- if (typeof value === 'string') {
39
- if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${at}: shorter than ${schema.minLength}`);
40
- if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(`${at}: does not match ${schema.pattern}`);
41
- }
42
- if (typeof value === 'number' && schema.minimum !== undefined && value < schema.minimum) errors.push(`${at}: below ${schema.minimum}`);
43
- if (Array.isArray(value)) {
44
- if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${at}: needs at least ${schema.minItems} items`);
45
- if (schema.items) value.forEach((v, i) => errors.push(...validateAgainstSchema(v, schema.items, `${at}[${i}]`)));
46
- }
47
- if (value && typeof value === 'object' && !Array.isArray(value)) {
48
- for (const req of schema.required ?? []) if (!Object.hasOwn(value, req)) errors.push(`${at}: missing "${req}"`);
49
- const props = schema.properties ?? {};
50
- for (const [k, v] of Object.entries(value)) {
51
- if (Object.hasOwn(props, k)) errors.push(...validateAgainstSchema(v, props[k], `${at}.${k}`));
52
- else if (schema.additionalProperties === false) errors.push(`${at}.${k}: not allowed`);
53
- else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
54
- errors.push(...validateAgainstSchema(v, schema.additionalProperties, `${at}.${k}`));
55
- }
56
- }
57
- }
58
- return errors;
59
- }
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,用 vars + { 'agent.aid': aid } 渲染,
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
+ }