evolcore 0.0.43-test.6 → 0.0.43-test.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -0,0 +1,80 @@
1
+ /** Shared, pure template binding/rendering. No home discovery or runtime writes. */
2
+ export const BASEAGENTS = ['claude', 'codex', 'gemini', 'ecagent'];
3
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const fail = message => { throw Object.assign(new Error(message), { code: 'INVALID_ARGUMENT' }); };
5
+
6
+ export function renderText(text, vars = {}, externalAids = {}) {
7
+ let out = text.replace(/\{\{\s*([a-z]+\.[a-z]+)\s*\}\}/g,
8
+ (token, key) => Object.hasOwn(vars, key) ? String(vars[key]) : token);
9
+ // One pass avoids cascading A -> B -> C substitutions.
10
+ const keys = Object.keys(externalAids).sort((a, b) => b.length - a.length);
11
+ if (keys.length) {
12
+ const pattern = keys.map(key => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
13
+ out = out.replace(new RegExp(pattern, 'g'), match => String(externalAids[match]));
14
+ }
15
+ return out;
16
+ }
17
+
18
+ /** Parse JSON first, then render string values so quotes/newlines cannot change types or structure. */
19
+ export function renderValue(value, vars = {}, externalAids = {}) {
20
+ if (typeof value === 'string') return renderText(value, vars, externalAids);
21
+ if (Array.isArray(value)) return value.map(item => renderValue(item, vars, externalAids));
22
+ if (record(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, renderValue(item, vars, externalAids)]));
23
+ return value;
24
+ }
25
+
26
+ /** Binary and non-UTF8 files are byte-preserved. JSON resources keep their data structure. */
27
+ export function renderResource(bytes, vars = {}, externalAids = {}, { json = false } = {}) {
28
+ if (bytes.includes(0) || !Buffer.from(bytes.toString('utf8')).equals(bytes)) return bytes;
29
+ const text = bytes.toString('utf8');
30
+ return Buffer.from(json ? JSON.stringify(renderValue(JSON.parse(text), vars, externalAids), null, 2) + '\n'
31
+ : renderText(text, vars, externalAids));
32
+ }
33
+
34
+ export function providerUsable(providers, id, baseagent) {
35
+ if (typeof id !== 'string' || !Object.hasOwn(providers, id)) return false;
36
+ const services = providers[id]?.services;
37
+ return record(services) && (baseagent === 'ecagent' ? ['ecagent', 'text'] : [baseagent])
38
+ .some(name => Object.hasOwn(services, name));
39
+ }
40
+
41
+ /** Match by exact stable ID, never by display name. Missing matches can be previewed, not installed. */
42
+ export function bindTemplateProviders(config, { providers = {}, defaults = {}, selections = {}, allowMissing = false } = {}) {
43
+ if (!record(config) || !record(providers) || !record(defaults) || !record(selections)) fail('Invalid Provider binding input');
44
+ const out = structuredClone(config);
45
+ const blocks = out.baseagents ?? {};
46
+ if (!record(blocks)) fail('baseagents must be an object');
47
+ const active = out.active_baseagent ?? defaults.active_baseagent ?? 'claude';
48
+ const names = [...new Set([...Object.keys(blocks), active])];
49
+ if (Object.keys(selections).some(name => !names.includes(name))) fail('Unknown baseagent selection');
50
+ const refs = [];
51
+ for (const name of names) {
52
+ if (!BASEAGENTS.includes(name)) fail('Invalid baseagent: ' + name);
53
+ const block = blocks[name] ?? defaults.baseagents?.[name] ?? {};
54
+ const select = selections[name] ?? {};
55
+ if (!record(block) || !record(select) || Object.keys(select).some(key => !['provider', 'model', 'effort'].includes(key))) fail('Invalid baseagent selection: ' + name);
56
+ const reference = block.provider ?? defaults.baseagents?.[name]?.provider;
57
+ const ref = typeof reference === 'string' ? { id: reference } : reference;
58
+ if (ref !== undefined && (!record(ref) || typeof ref.id !== 'string')) fail('Provider identity required: ' + name);
59
+ if (select.provider !== undefined && (typeof select.provider !== 'string' || !select.provider)) fail('Invalid selected Provider: ' + name);
60
+ if (select.model !== undefined && (typeof select.model !== 'string' || !select.model.trim())) fail('Invalid model: ' + name);
61
+ if (select.effort !== undefined && select.effort !== null && !['low', 'medium', 'high', 'xhigh', 'max'].includes(select.effort)) fail('Invalid effort: ' + name);
62
+ const selected = select.provider ?? ref?.id;
63
+ const usable = providerUsable(providers, selected, name);
64
+ refs.push({ baseagent: name, template: { ...(ref ?? {}), model: block.model, effort: block.effort },
65
+ match: usable ? 'reused' : 'select', provider: usable ? selected : null });
66
+ if (!usable && (!allowMissing || select.provider !== undefined)) {
67
+ throw Object.assign(new Error('Provider binding required or unsupported service: ' + name), { code: 'PROVIDER_NOT_FOUND', refs });
68
+ }
69
+ if (Object.hasOwn(blocks, name) || Object.hasOwn(selections, name)) {
70
+ out.baseagents ??= {};
71
+ const bound = { ...structuredClone(block) };
72
+ if (selected !== undefined) bound.provider = selected;
73
+ if (select.model !== undefined) bound.model = select.model;
74
+ if (select.effort === null) delete bound.effort;
75
+ else if (select.effort !== undefined) bound.effort = select.effort;
76
+ out.baseagents[name] = bound;
77
+ }
78
+ }
79
+ return { config: out, refs };
80
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * 模板目录的读取与校验。
3
+ *
4
+ * <模板>/
5
+ * ├── team.json 团队声明(值的来源)
6
+ * ├── team.schema.json 模板 schema:允许写哪些字段、什么类型
7
+ * ├── .evolcore/ 只放「原样放进容器」的资源
8
+ * │ ├── providers.json 模型服务凭证(可用 ${VAR} 引用环境变量)
9
+ * │ ├── agents/defaults.json 全局默认配置
10
+ * │ └── skills/<技能名>/ 本机技能,所有 agent 共用
11
+ * ├── agents/<key>/ 每个 agent 的资源(不含配置)
12
+ * │ ├── personal/soul/*.md
13
+ * │ └── triggers/<id>/trigger.json 可用 {{agent.aid}} {{owner.aid}} {{host.aid}}
14
+ * └── workspace/<key>/ 可选:该项目目录的初始内容
15
+ *
16
+ * 配置不进模板文件:agent config.json 与 daemon.json 由 pa-team-build 按 team.json 的
17
+ * config 段 + 工具管理的字段生成,避免「改模板配置」和「工具写配置」两处打架。
18
+ */
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { createHash } from 'node:crypto';
22
+ import { normalizeTeam, normalizeTeamSchema, validateContractSchema } from './template-contract.mjs';
23
+
24
+ /** 由工具写入,模板里出现即视为错误。 */
25
+ export const MANAGED_AGENT_FIELDS = ['aid', 'enabled', 'lifecycle', 'owner', 'owners', 'channels', 'projects'];
26
+ export const MANAGED_DAEMON_FIELDS = ['aid', 'owner', 'owners'];
27
+
28
+ /** 允许放进模板 .evolcore/ 的条目。AIDs/、agents/<aid>/ 等运行时目录不能出现。 */
29
+ export const HOME_ALLOWED = ['providers.json', 'agents', 'skills', '.env'];
30
+ const HOME_AGENTS_ALLOWED = ['defaults.json'];
31
+
32
+ /** 每个 agent 目录里允许出现的条目。配置文件不在其中——它由工具生成。 */
33
+ const AGENT_DIR_ALLOWED = ['personal', 'triggers'];
34
+
35
+ const KEY_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
36
+ const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
37
+
38
+ function readJson(file) {
39
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
40
+ }
41
+
42
+ function listRel(root) {
43
+ const out = [];
44
+ const walk = (dir) => {
45
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
46
+ const abs = path.join(dir, e.name);
47
+ if (e.isSymbolicLink()) throw new Error(`symlinks are not allowed in templates: ${path.relative(root, abs)}`);
48
+ if (e.isDirectory()) walk(abs);
49
+ else out.push(path.relative(root, abs));
50
+ }
51
+ };
52
+ if (fs.existsSync(root)) walk(root);
53
+ return out.sort();
54
+ }
55
+
56
+ /** 模板内容摘要:文件路径 + 内容。用于记录「这支团队套的是哪一版模板」。 */
57
+ export function templateDigest(dir) {
58
+ const h = createHash('sha256');
59
+ for (const rel of listRel(dir)) {
60
+ h.update(rel).update('\0').update(fs.readFileSync(path.join(dir, rel))).update('\0');
61
+ }
62
+ return h.digest('hex').slice(0, 12);
63
+ }
64
+
65
+ /**
66
+ * 读取并做结构校验(不依赖 EvolCore)。返回 { tpl, errors }。
67
+ * schema 是否与 EvolCore 一致由 prepare 阶段用 validateConfig 复核。
68
+ */
69
+ export function loadTemplate(dir) {
70
+ const root = path.resolve(dir);
71
+ const errors = [];
72
+ for (const f of ['team.json', 'team.schema.json']) {
73
+ if (!fs.existsSync(path.join(root, f))) return { errors: [`${f} not found in ${root}`] };
74
+ }
75
+
76
+ let team; let schema;
77
+ try { team = readJson(path.join(root, 'team.json')); } catch (err) { return { errors: [`team.json: ${err.message}`] }; }
78
+ try { schema = readJson(path.join(root, 'team.schema.json')); } catch (err) { return { errors: [`team.schema.json: ${err.message}`] }; }
79
+ const normalized = normalizeTeam(team, { fallbackName: path.basename(root) });
80
+ if (normalized.errors.length) return { errors: normalized.errors };
81
+ team = normalized.team;
82
+ try { schema = normalizeTeamSchema(schema); } catch (err) { return { errors: [err.message] }; }
83
+ errors.push(...validateContractSchema(team, schema, 'team.json'));
84
+
85
+ const name = team.name ?? path.basename(root);
86
+ const version = team.version !== undefined ? String(team.version) : '';
87
+ if (typeof name !== 'string' || !NAME_RE.test(name)) errors.push(`team.json name must match ${NAME_RE}`);
88
+ const keys = Array.isArray(team.agents) ? team.agents.map(a => a?.key) : [];
89
+ if (keys.length === 0 || !keys.every(k => typeof k === 'string' && KEY_RE.test(k))) {
90
+ errors.push('team.json agents[].key are required and must be path-safe');
91
+ }
92
+ if (!schema || schema.type !== 'object') errors.push('team.schema.json must be a JSON Schema object');
93
+
94
+ let files;
95
+ try { files = listRel(root); } catch (err) { return { errors: [err.message] }; }
96
+
97
+ // .evolcore/ 只允许白名单内的条目
98
+ const homeFiles = files.filter(f => f.startsWith('.evolcore/')).map(f => f.slice('.evolcore/'.length));
99
+ for (const f of homeFiles) {
100
+ const top = f.split('/')[0];
101
+ if (!HOME_ALLOWED.includes(top)) errors.push(`.evolcore/${top} is not allowed in templates`);
102
+ else if (top === 'agents' && !HOME_AGENTS_ALLOWED.includes(f.slice('agents/'.length))) {
103
+ errors.push(`.evolcore/${f} is not allowed; per-agent files go under agents/<key>/`);
104
+ }
105
+ }
106
+
107
+ // daemon.json 不再来自模板;模板若还留着就明确报错,避免以为它生效
108
+ for (const stale of ['daemon.json']) {
109
+ if (fs.existsSync(path.join(root, '.evolcore', stale))) {
110
+ errors.push(`.evolcore/${stale} is no longer read; put daemon fields under host.config in team.json`);
111
+ }
112
+ }
113
+
114
+ // agents/<key>/ 必须和 team.json 对上,且不能自带 config.json
115
+ const agentDirs = fs.existsSync(path.join(root, 'agents'))
116
+ ? fs.readdirSync(path.join(root, 'agents'), { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name)
117
+ : [];
118
+ for (const d of agentDirs) if (!keys.includes(d)) errors.push(`agents/${d} has no matching key in team.json`);
119
+ for (const key of keys) {
120
+ const agentRoot = path.join(root, 'agents', key);
121
+ if (!fs.existsSync(agentRoot)) continue;
122
+ for (const e of fs.readdirSync(agentRoot, { withFileTypes: true })) {
123
+ if (!AGENT_DIR_ALLOWED.includes(e.name)) errors.push(`agents/${key}/${e.name} is not allowed; configuration is generated from team.json`);
124
+ }
125
+ const cfg = path.join(agentRoot, 'config.json');
126
+ if (fs.existsSync(cfg)) errors.push(`agents/${key}/config.json is not read; put agent fields under agents[].config in team.json`);
127
+ }
128
+
129
+ const wsDirs = fs.existsSync(path.join(root, 'workspace'))
130
+ ? fs.readdirSync(path.join(root, 'workspace'), { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name)
131
+ : [];
132
+ for (const d of wsDirs) if (!keys.includes(d)) errors.push(`workspace/${d} has no matching key in team.json`);
133
+
134
+ if (errors.length) return { errors };
135
+ return {
136
+ errors,
137
+ tpl: {
138
+ root, name, version, keys, files, team, schema, changes: normalized.changes,
139
+ label: `${name}@${version || templateDigest(root)}`,
140
+ },
141
+ };
142
+ }
@@ -1,225 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { spawn } from 'node:child_process';
4
- import { authorizeLocalCommand } from './task-context.js';
5
- import { bindPaWorkspace, paWorkspaceStore, readPaWorkspaceNavigation, updatePaWorkspaceNavigation } from '../core/command/pa-workspace-store.js';
6
- import { getPackageRoot } from '../paths.js';
7
- const USAGE = `用法: ec pa-workspace init --workspace <绝对路径> [--force] [--with-triggers]
8
- ec pa-workspace bind --workspace <已有工作区绝对路径>
9
- ec pa-workspace navigation show
10
- ec pa-workspace navigation update --expected-revision <n> --entries-json <json>
11
-
12
- 所有子命令都只输出 JSON,--format json / --json 可省略。
13
- 仅限当前 Agent 的 AUN owner 私聊托管会话。`;
14
- const MAX_SKILL_OUTPUT_CHARS = 2 * 1024 * 1024;
15
- export class PaWorkspaceCommandError extends Error {
16
- code;
17
- details;
18
- constructor(code, message, details) {
19
- super(message);
20
- this.code = code;
21
- this.details = details;
22
- this.name = 'PaWorkspaceCommandError';
23
- }
24
- }
25
- function sanitizedInitializationResult(value) {
26
- const output = {};
27
- for (const key of ['mode', 'version', 'created', 'errors', 'triggers', 'occupancy']) {
28
- if (value[key] !== undefined)
29
- output[key] = value[key];
30
- }
31
- return output;
32
- }
33
- function runSkillInitialization(args) {
34
- const packageRoot = getPackageRoot();
35
- const script = path.join(packageRoot, 'kits', 'skills', 'personal-assistant', 'scripts', 'init.mjs');
36
- if (!fs.existsSync(script)) {
37
- return Promise.reject(new PaWorkspaceCommandError('NOT_CONFIGURED', 'EvolCore personal-assistant initialization script is unavailable'));
38
- }
39
- return new Promise((resolve, reject) => {
40
- const child = spawn(process.execPath, [script, ...args], {
41
- cwd: packageRoot,
42
- windowsHide: true,
43
- stdio: ['ignore', 'pipe', 'pipe'],
44
- });
45
- let stdout = '';
46
- let stderr = '';
47
- let outputTooLarge = false;
48
- const collect = (current, chunk) => {
49
- if (current.length + chunk.length > MAX_SKILL_OUTPUT_CHARS) {
50
- outputTooLarge = true;
51
- child.kill();
52
- return current;
53
- }
54
- return current + chunk;
55
- };
56
- child.stdout.setEncoding('utf8').on('data', chunk => { stdout = collect(stdout, String(chunk)); });
57
- child.stderr.setEncoding('utf8').on('data', chunk => { stderr = collect(stderr, String(chunk)); });
58
- child.once('error', error => reject(new PaWorkspaceCommandError('SKILL_INIT_FAILED', error.message)));
59
- child.once('close', code => {
60
- if (outputTooLarge) {
61
- reject(new PaWorkspaceCommandError('SKILL_INIT_OUTPUT_TOO_LARGE', 'Personal-assistant initialization output exceeded its limit'));
62
- return;
63
- }
64
- resolve({ code, stdout, stderr });
65
- });
66
- });
67
- }
68
- /** Runs the unmodified Skill initializer and registers its exact workspace only after success. */
69
- export async function initializePaWorkspace(input) {
70
- if (!path.isAbsolute(input.workspacePath)) {
71
- throw new PaWorkspaceCommandError('INVALID_ARGUMENT', '--workspace must be an absolute path');
72
- }
73
- const workspacePath = path.resolve(input.workspacePath);
74
- const args = [
75
- '--workspace', workspacePath,
76
- '--owner', input.ownerAid,
77
- '--json',
78
- ...(input.force ? ['--force'] : []),
79
- ...(input.withTriggers ? ['--with-triggers', '--self', input.paAid] : []),
80
- ];
81
- const result = await runSkillInitialization(args);
82
- let initialized;
83
- try {
84
- initialized = JSON.parse(result.stdout);
85
- }
86
- catch {
87
- throw new PaWorkspaceCommandError('SKILL_INIT_FAILED', 'Personal-assistant Skill returned an invalid result', {
88
- exitCode: result.code,
89
- });
90
- }
91
- if ((result.code !== 0 && result.code !== 10) || initialized.ok !== true) {
92
- throw new PaWorkspaceCommandError(typeof initialized.code === 'string' ? initialized.code : 'SKILL_INIT_FAILED', 'Personal-assistant initialization did not complete; no Core workspace binding was created', { exitCode: result.code, ...sanitizedInitializationResult(initialized) });
93
- }
94
- const state = bindPaWorkspace(input.paAid, input.ownerAid, workspacePath);
95
- return {
96
- workspaceId: state.workspaceId,
97
- navigationRevision: state.navigationRevision,
98
- initialization: sanitizedInitializationResult(initialized),
99
- };
100
- }
101
- function value(args, flag) {
102
- const index = args.indexOf(flag);
103
- return index >= 0 ? args[index + 1] : undefined;
104
- }
105
- /**
106
- * 摘掉输出格式参数。
107
- *
108
- * 本命令**只输出 JSON**,所以 `--format json` 和 `--json` 都不改变行为。
109
- * 但别的命令(`ec thread`、`ec agent welcome show` …)都接受这两个参数,
110
- * 调用方很容易顺手写上;直接报 INVALID_ARGUMENT 只会让人以为是用法错误。
111
- * 这里统一接受,真正的非法值(如 `--format text`)才报错并说清原因。
112
- */
113
- function normalizeFormatArgs(args) {
114
- const out = [];
115
- for (let index = 0; index < args.length; index++) {
116
- const argument = args[index];
117
- if (argument === '--json')
118
- continue;
119
- if (argument === '--format') {
120
- const format = args[++index];
121
- if (format !== 'json') {
122
- throw new PaWorkspaceCommandError('INVALID_ARGUMENT', `ec pa-workspace 只输出 JSON,--format 只能取 json(收到 ${format ?? '空'})`);
123
- }
124
- continue;
125
- }
126
- if (argument.startsWith('--format=')) {
127
- const format = argument.slice('--format='.length);
128
- if (format !== 'json') {
129
- throw new PaWorkspaceCommandError('INVALID_ARGUMENT', `ec pa-workspace 只输出 JSON,--format 只能取 json(收到 ${format || '空'})`);
130
- }
131
- continue;
132
- }
133
- out.push(argument);
134
- }
135
- return out;
136
- }
137
- function assertOwnerPrivateRuntime(context) {
138
- if (context.channel !== 'aun' || context.chatType !== 'private' || context.peerRole !== 'owner'
139
- || !context.selfAid || !context.peerId) {
140
- throw Object.assign(new Error('PA workspace changes require the current Agent owner in an AUN private chat'), { code: 'NOT_ALLOWED' });
141
- }
142
- }
143
- function output(value) {
144
- process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
145
- }
146
- export async function cmdPaWorkspace(rawArgs) {
147
- if (rawArgs.length === 0 || rawArgs.includes('--help') || rawArgs.includes('-h')) {
148
- console.log(USAGE);
149
- return;
150
- }
151
- try {
152
- const args = normalizeFormatArgs(rawArgs);
153
- const context = await authorizeLocalCommand(['pa-workspace', ...args]);
154
- assertOwnerPrivateRuntime(context);
155
- if (args[0] === 'init') {
156
- let workspacePath;
157
- let force = false;
158
- let withTriggers = false;
159
- for (let index = 1; index < args.length; index++) {
160
- const argument = args[index];
161
- if (argument === '--workspace')
162
- workspacePath = args[++index];
163
- else if (argument === '--force')
164
- force = true;
165
- else if (argument === '--with-triggers')
166
- withTriggers = true;
167
- else
168
- throw new PaWorkspaceCommandError('INVALID_ARGUMENT', USAGE);
169
- }
170
- if (!workspacePath)
171
- throw new PaWorkspaceCommandError('INVALID_ARGUMENT', USAGE);
172
- output({ ok: true, ...await initializePaWorkspace({
173
- paAid: context.selfAid,
174
- ownerAid: context.peerId,
175
- workspacePath,
176
- force,
177
- withTriggers,
178
- }) });
179
- return;
180
- }
181
- if (args[0] === 'bind') {
182
- if (args.length !== 3 || args[1] !== '--workspace' || !args[2])
183
- throw Object.assign(new Error(USAGE), { code: 'INVALID_ARGUMENT' });
184
- const state = bindPaWorkspace(context.selfAid, context.peerId, args[2]);
185
- output({ ok: true, workspaceId: state.workspaceId, navigationRevision: state.navigationRevision });
186
- return;
187
- }
188
- if (args[0] === 'navigation' && args[1] === 'show' && args.length === 2) {
189
- output({ ok: true, ...readPaWorkspaceNavigation(context.selfAid) });
190
- return;
191
- }
192
- if (args[0] === 'navigation' && args[1] === 'update') {
193
- const expected = value(args, '--expected-revision');
194
- const entriesJson = value(args, '--entries-json');
195
- if (!expected || !entriesJson || args.length !== 6 || !/^\d+$/.test(expected))
196
- throw Object.assign(new Error(USAGE), { code: 'INVALID_ARGUMENT' });
197
- let entries;
198
- try {
199
- entries = JSON.parse(entriesJson);
200
- }
201
- catch {
202
- throw Object.assign(new Error('--entries-json must contain valid JSON'), { code: 'INVALID_ARGUMENT' });
203
- }
204
- output({ ok: true, ...updatePaWorkspaceNavigation(context.selfAid, Number(expected), entries) });
205
- return;
206
- }
207
- if (args[0] === 'navigation' && args[1] === 'status' && args.length === 2) {
208
- const state = paWorkspaceStore.require(context.selfAid);
209
- output({ ok: true, workspaceId: state.workspaceId, navigationRevision: state.navigationRevision, entries: state.entries });
210
- return;
211
- }
212
- throw Object.assign(new Error(USAGE), { code: 'INVALID_ARGUMENT' });
213
- }
214
- catch (error) {
215
- const source = error;
216
- const result = {
217
- ok: false,
218
- code: source.code ?? 'PA_WORKSPACE_FAILED',
219
- error: error instanceof Error ? error.message : String(error),
220
- ...(error instanceof PaWorkspaceCommandError && error.details ? { details: error.details } : {}),
221
- };
222
- process.stderr.write(`${JSON.stringify(result)}\n`);
223
- process.exitCode = 1;
224
- }
225
- }