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,112 @@
1
+ /**
2
+ * 服务消息日志(logs/messages-YYYYMMDD.jsonl):写前日志,先 received 再执行,结束补 handled。
3
+ * 与 src/event-center/event-log.ts 同构。
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ /** data 只在是 JSON 对象时按原样落盘,其它形态包成 {@raw: string}。 */
8
+ function normalizeData(data) {
9
+ if (data !== null && typeof data === 'object' && !Array.isArray(data))
10
+ return data;
11
+ return { '@raw': JSON.stringify(data) };
12
+ }
13
+ export class ServiceMessageLog {
14
+ logsDir;
15
+ constructor(logsDir) {
16
+ this.logsDir = logsDir;
17
+ }
18
+ static forPack(pack) {
19
+ return new ServiceMessageLog(pack.paths.logsDir);
20
+ }
21
+ writeReceived(message) {
22
+ this.write({
23
+ ts: Date.now(),
24
+ kind: 'received',
25
+ type: message.type,
26
+ requestId: message.requestId,
27
+ from: message.fromAid,
28
+ messageId: message.messageId,
29
+ data: normalizeData(message.payload),
30
+ });
31
+ }
32
+ writeHandled(message, detail) {
33
+ this.write({
34
+ ts: Date.now(),
35
+ kind: 'handled',
36
+ type: message.type,
37
+ requestId: message.requestId,
38
+ from: message.fromAid,
39
+ messageId: message.messageId,
40
+ cmd: detail.cmd,
41
+ exit: detail.exit,
42
+ ms: detail.ms,
43
+ outcome: detail.outcome,
44
+ ...(detail.reason !== undefined ? { reason: detail.reason } : {}),
45
+ ...(detail.sandboxAbsent !== undefined ? { sandbox_absent: detail.sandboxAbsent } : {}),
46
+ });
47
+ }
48
+ writeDropped(message, reason) {
49
+ this.write({
50
+ ts: Date.now(),
51
+ kind: 'dropped',
52
+ type: message.type,
53
+ requestId: message.requestId,
54
+ from: message.fromAid,
55
+ messageId: message.messageId,
56
+ reason,
57
+ });
58
+ }
59
+ writeFiltered(message, reason) {
60
+ this.write({
61
+ ts: Date.now(),
62
+ kind: 'filtered',
63
+ type: message.type,
64
+ requestId: message.requestId,
65
+ from: message.fromAid,
66
+ messageId: message.messageId,
67
+ reason,
68
+ });
69
+ }
70
+ /** 按天分文件(本地日期);IO 失败吞掉。 */
71
+ write(line) {
72
+ const now = new Date();
73
+ const date = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
74
+ try {
75
+ fs.mkdirSync(this.logsDir, { recursive: true });
76
+ fs.appendFileSync(path.join(this.logsDir, `messages-${date}.jsonl`), `${JSON.stringify(line)}\n`, 'utf8');
77
+ }
78
+ catch {
79
+ // 日志写失败不中断服务处理。
80
+ }
81
+ }
82
+ /** 读最近 N 行(CLI tail 用)。 */
83
+ tail(count) {
84
+ let files;
85
+ try {
86
+ files = fs.readdirSync(this.logsDir).filter(name => /^messages-\d{8}\.jsonl$/.test(name)).sort();
87
+ }
88
+ catch {
89
+ return [];
90
+ }
91
+ const lines = [];
92
+ for (const file of [...files].reverse()) {
93
+ try {
94
+ const text = fs.readFileSync(path.join(this.logsDir, file), 'utf8');
95
+ lines.unshift(...text.split('\n').filter(Boolean));
96
+ }
97
+ catch {
98
+ break;
99
+ }
100
+ if (lines.length >= count)
101
+ break;
102
+ }
103
+ return lines.slice(-count).map(line => {
104
+ try {
105
+ return JSON.parse(line);
106
+ }
107
+ catch {
108
+ return { ts: 0, kind: 'dropped', reason: 'unparseable log line' };
109
+ }
110
+ });
111
+ }
112
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * 服务包扫描、加载与激活:services/<pack>/pack.json (+脚本 realpath 校验),
3
+ * requires 对本机名片判定,跨包 listen.type 冲突检测。
4
+ *
5
+ * 三层判据的落点在这里:
6
+ * 1. payload.type 形状 —— 已由 service-payload.ts 判定,本模块不重做;
7
+ * 2. requires —— 本文件(对本机名片,不是对消息);
8
+ * 3. listen[].type —— 本文件(构建索引,对消息匹配)。
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { sha256 } from '../trigger/validation.js';
13
+ import { requiresSatisfied, validateServiceJson } from './validation.js';
14
+ import { migrateLegacyFileName } from '../core/legacy-rename.js';
15
+ import { PACK_ARCHIVED_MARKER } from '../core/pack-install.js';
16
+ /**
17
+ * 服务包声明文件。与事件包统一叫 `pack.json`(不留 `service.json` 别名):
18
+ * 包主要由 agent 生成,两侧同名能省掉一次"这里该写哪个名"的判断。
19
+ */
20
+ export const PACK_JSON = 'pack.json';
21
+ export const SCRIPTS_DIR = 'scripts';
22
+ export const LEDGER_FILE = 'ledger.jsonl';
23
+ export const LOGS_DIR = 'logs';
24
+ export const IDEMPOTENCY_FILE = '.idempotency.jsonl';
25
+ /** realpath 全级校验:目标真实路径必须仍在包目录内(防中间目录符号链接逃逸)。 */
26
+ function assertInsidePackDir(packDir, target, errors, field) {
27
+ let realTarget;
28
+ try {
29
+ realTarget = fs.realpathSync(target);
30
+ }
31
+ catch {
32
+ errors.push(`${field} not found: ${path.relative(packDir, target)}`);
33
+ return false;
34
+ }
35
+ const realPackDir = fs.realpathSync(packDir);
36
+ if (realTarget !== realPackDir && !realTarget.startsWith(realPackDir + path.sep)) {
37
+ errors.push(`${field} escapes pack directory via symlink`);
38
+ return false;
39
+ }
40
+ return true;
41
+ }
42
+ /** 加载单个包目录。返回 null 表示该包 invalid(errors 已填)。 */
43
+ export function loadPackDir(packDir, errors) {
44
+ const packId = path.basename(packDir);
45
+ // 旧名 service.json 一次性迁移成 pack.json(与事件包统一)。
46
+ migrateLegacyFileName(packDir, 'service.json', PACK_JSON, `services pack ${packId}`);
47
+ const serviceJsonPath = path.join(packDir, PACK_JSON);
48
+ let rawText;
49
+ try {
50
+ rawText = fs.readFileSync(serviceJsonPath, 'utf8');
51
+ }
52
+ catch (error) {
53
+ errors.push(`cannot read ${PACK_JSON}: ${error instanceof Error ? error.message : String(error)}`);
54
+ return null;
55
+ }
56
+ let raw;
57
+ try {
58
+ raw = JSON.parse(rawText);
59
+ }
60
+ catch (error) {
61
+ errors.push(`${PACK_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
62
+ return null;
63
+ }
64
+ const validated = validateServiceJson(raw);
65
+ if (!validated.ok) {
66
+ errors.push(...validated.errors);
67
+ return null;
68
+ }
69
+ const canonicalScripts = path.join(packDir, SCRIPTS_DIR);
70
+ const scriptsDir = canonicalScripts;
71
+ if (!fs.existsSync(scriptsDir)) {
72
+ errors.push(`scripts directory not found: expected ${SCRIPTS_DIR}/`);
73
+ return null;
74
+ }
75
+ // 脚本存在性 + realpath 越界校验。
76
+ for (const entry of validated.value.listen) {
77
+ const relativeUnderScripts = entry.handler.script.slice(SCRIPTS_DIR.length + 1);
78
+ const scriptPath = path.join(scriptsDir, relativeUnderScripts);
79
+ if (!assertInsidePackDir(packDir, scriptPath, errors, `listen[].handler.script "${entry.handler.script}"`))
80
+ continue;
81
+ const stat = fs.lstatSync(fs.realpathSync(scriptPath));
82
+ if (!stat.isFile())
83
+ errors.push(`listen[].handler.script "${entry.handler.script}" is not a regular file`);
84
+ }
85
+ const logsDir = path.join(packDir, LOGS_DIR);
86
+ if (!fs.existsSync(logsDir)) {
87
+ try {
88
+ fs.mkdirSync(logsDir, { recursive: true });
89
+ }
90
+ catch {
91
+ errors.push(`cannot create logs directory: ${logsDir}`);
92
+ }
93
+ }
94
+ if (errors.length)
95
+ return null;
96
+ const paths = {
97
+ serviceJson: serviceJsonPath,
98
+ scriptsDir,
99
+ ledger: path.join(packDir, LEDGER_FILE),
100
+ logsDir,
101
+ idempotency: path.join(packDir, IDEMPOTENCY_FILE),
102
+ };
103
+ return {
104
+ id: packId,
105
+ dir: packDir,
106
+ name: validated.value.name,
107
+ ...(validated.value.description !== undefined ? { description: validated.value.description } : {}),
108
+ enabled: validated.value.enabled,
109
+ requires: validated.value.requires,
110
+ listen: validated.value.listen,
111
+ unmatched: validated.value.unmatched,
112
+ reply: validated.value.reply,
113
+ revision: sha256(rawText),
114
+ paths,
115
+ };
116
+ }
117
+ /** 扫描 services/ 下全部包目录。单包失败只废该包。 */
118
+ export function loadPacks(servicesDir) {
119
+ const valid = [];
120
+ const invalid = [];
121
+ let entries;
122
+ try {
123
+ entries = fs.readdirSync(servicesDir, { withFileTypes: true });
124
+ }
125
+ catch {
126
+ return { valid: [], invalid: [] };
127
+ }
128
+ for (const entry of entries) {
129
+ if (!entry.isDirectory())
130
+ continue;
131
+ if (entry.name.startsWith('.') || entry.name.startsWith('_'))
132
+ continue;
133
+ const packDir = path.join(servicesDir, entry.name);
134
+ // 已卸载但保留归档的目录:不是包,也不是坏包(见 pack-install 的 removePack)。
135
+ if (fs.existsSync(path.join(packDir, PACK_ARCHIVED_MARKER)))
136
+ continue;
137
+ const errors = [];
138
+ const pack = loadPackDir(packDir, errors);
139
+ if (pack)
140
+ valid.push(pack);
141
+ else
142
+ invalid.push({ dir: packDir, packId: entry.name, errors });
143
+ }
144
+ return { valid, invalid };
145
+ }
146
+ /**
147
+ * 从加载结果构建运行时状态:
148
+ * - enabled=false → disabled;
149
+ * - requires 不满足 → skipped(不是错误);
150
+ * - 跨包同 listen.type 且两包都 active → 两个包都 invalid。
151
+ */
152
+ export function buildPackState(packs, invalidPacks, identity, previousRevision = 0) {
153
+ const disabledPacks = packs.filter(pack => !pack.enabled).map(pack => pack.id);
154
+ const candidates = packs.filter(pack => pack.enabled);
155
+ const skippedPacks = [];
156
+ const activeCandidates = [];
157
+ for (const pack of candidates) {
158
+ if (requiresSatisfied(pack.requires, identity))
159
+ activeCandidates.push(pack);
160
+ else
161
+ skippedPacks.push({ id: pack.id, reason: 'requires.unsatisfied' });
162
+ }
163
+ // 跨包冲突:同一 listen.type 出现在两个 active 包里。
164
+ const typeOwners = new Map();
165
+ for (const pack of activeCandidates) {
166
+ for (const entry of pack.listen) {
167
+ const owners = typeOwners.get(entry.type) ?? [];
168
+ owners.push(pack.id);
169
+ typeOwners.set(entry.type, owners);
170
+ }
171
+ }
172
+ const conflicts = [];
173
+ const conflictPackIds = new Set();
174
+ for (const [type, packIds] of typeOwners) {
175
+ if (packIds.length > 1) {
176
+ conflicts.push({ type, packs: packIds });
177
+ for (const id of packIds)
178
+ conflictPackIds.add(id);
179
+ }
180
+ }
181
+ const conflictInvalid = [];
182
+ for (const pack of activeCandidates) {
183
+ if (!conflictPackIds.has(pack.id))
184
+ continue;
185
+ const types = conflicts.filter(item => item.packs.includes(pack.id)).map(item => item.type);
186
+ conflictInvalid.push({
187
+ id: pack.id,
188
+ errors: [`listen.type conflict: ${types.join(', ')} (also declared by ${[...conflictPackIds].filter(id => id !== pack.id).join(', ')})`],
189
+ });
190
+ }
191
+ const activePacks = activeCandidates.filter(pack => !conflictPackIds.has(pack.id));
192
+ const routeIndex = new Map();
193
+ const wildcardIndex = [];
194
+ for (const pack of activePacks) {
195
+ for (const entry of pack.listen) {
196
+ if (entry.type.endsWith('.*')) {
197
+ wildcardIndex.push({ pack, entry });
198
+ continue;
199
+ }
200
+ const list = routeIndex.get(entry.type) ?? [];
201
+ list.push({ pack, entry });
202
+ routeIndex.set(entry.type, list);
203
+ }
204
+ }
205
+ return {
206
+ activePacks,
207
+ skippedPacks,
208
+ disabledPacks,
209
+ invalidPacks: [...invalidPacks, ...conflictInvalid],
210
+ conflicts,
211
+ routeIndex,
212
+ wildcardIndex,
213
+ revision: previousRevision + 1,
214
+ };
215
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 回复构造:脚本只决定「回什么」,daemon 决定「怎么发」。
3
+ *
4
+ * 回复 type 一律是「请求 type + .result」;脚本不能指定 type(reply.payloadTypes
5
+ * 只是允许派生出的形状,当前唯一合法值是 service-result)。失败信息放 error.code。
6
+ */
7
+ import { resultTypeFor } from './service-payload.js';
8
+ /** 成功:{type, request_id, ok:true, data}。 */
9
+ export function buildSuccessReply(requestType, requestId, data) {
10
+ const type = resultTypeFor(requestType);
11
+ return {
12
+ type,
13
+ requestId,
14
+ shouldSend: true,
15
+ payload: {
16
+ type,
17
+ request_id: requestId,
18
+ ok: true,
19
+ ...(data !== undefined ? { data } : {}),
20
+ },
21
+ };
22
+ }
23
+ /** 失败:{type, request_id, ok:false, error:{code,message}}。 */
24
+ export function buildErrorReply(requestType, requestId, code, message, extra) {
25
+ const type = resultTypeFor(requestType);
26
+ return {
27
+ type,
28
+ requestId: requestId ?? '',
29
+ shouldSend: true,
30
+ payload: {
31
+ type,
32
+ request_id: requestId,
33
+ ok: false,
34
+ error: { code, message },
35
+ ...(extra ?? {}),
36
+ },
37
+ };
38
+ }
39
+ /** 静默:不回,调用方只能等到超时(blocked / unmatched=silent / 总闸关闭)。 */
40
+ export function buildSilentReply(requestType, requestId) {
41
+ return {
42
+ type: resultTypeFor(requestType),
43
+ requestId,
44
+ shouldSend: false,
45
+ payload: {},
46
+ };
47
+ }
48
+ /** 脚本执行结果 → 回复。noop 不回。 */
49
+ export function replyFromOutcome(requestType, requestId, outcome) {
50
+ if (outcome.outcome === 'noop')
51
+ return buildSilentReply(requestType, requestId);
52
+ if (outcome.outcome === 'success')
53
+ return buildSuccessReply(requestType, requestId, outcome.data);
54
+ return buildErrorReply(requestType, requestId, outcome.error?.code ?? 'HANDLER_FAILED', outcome.error?.message ?? 'service handler failed');
55
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * services/services-config.json 加载 + 两套按来源 AID 独立计数的限流。
3
+ *
4
+ * builtin 用于内置查询服务与 services 模式下给非 Owner 的错误回复;
5
+ * service 用于业务服务调用。两套分开计,按 fromAid 独立。
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { validateRouterConfig } from './validation.js';
10
+ import { migrateLegacyFileName } from '../core/legacy-rename.js';
11
+ export const SERVICES_CONFIG_JSON = 'services-config.json';
12
+ export const DEFAULT_ROUTER_CONFIG = {
13
+ v: 1,
14
+ enabled: false,
15
+ rateLimit: {
16
+ builtin: { perMinute: 20, perHour: 200 },
17
+ service: { perMinute: 50, perHour: 1000 },
18
+ },
19
+ };
20
+ /** 读取 services/services-config.json;不存在或缺 v 时返回缺省(enabled=false)。 */
21
+ export function loadRouterConfig(servicesDir) {
22
+ // 旧名 router.json 一次性迁移成 services-config.json。
23
+ migrateLegacyFileName(servicesDir, 'router.json', SERVICES_CONFIG_JSON, 'services config');
24
+ const filePath = path.join(servicesDir, SERVICES_CONFIG_JSON);
25
+ let rawText;
26
+ try {
27
+ rawText = fs.readFileSync(filePath, 'utf8');
28
+ }
29
+ catch {
30
+ return { config: DEFAULT_ROUTER_CONFIG, exists: false, errors: [] };
31
+ }
32
+ let raw;
33
+ try {
34
+ raw = JSON.parse(rawText);
35
+ }
36
+ catch (error) {
37
+ return {
38
+ config: DEFAULT_ROUTER_CONFIG,
39
+ exists: true,
40
+ errors: [`${SERVICES_CONFIG_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`],
41
+ };
42
+ }
43
+ const validated = validateRouterConfig(raw);
44
+ if (!validated.ok)
45
+ return { config: DEFAULT_ROUTER_CONFIG, exists: true, errors: validated.errors };
46
+ return { config: validated.value, exists: true, errors: [] };
47
+ }
48
+ /** 滑动窗口(分钟/小时各一格,超过窗口即重置),按 (bucket, fromAid) 独立计数。 */
49
+ export class RateLimiter {
50
+ windows = new Map();
51
+ config;
52
+ constructor(config) {
53
+ this.config = config;
54
+ }
55
+ setConfig(config) {
56
+ this.config = config;
57
+ }
58
+ quota(bucket) {
59
+ return bucket === 'builtin' ? this.config.rateLimit.builtin : this.config.rateLimit.service;
60
+ }
61
+ /** 记一次消费;超限时不计数并给出 retryAfter。 */
62
+ consume(bucket, fromAid, now = Date.now()) {
63
+ const quota = this.quota(bucket);
64
+ const key = `${bucket}\u0000${fromAid}`;
65
+ const minuteMs = 60_000;
66
+ const hourMs = 3_600_000;
67
+ let window = this.windows.get(key);
68
+ if (!window) {
69
+ window = { minuteStart: now, minuteCount: 0, hourStart: now, hourCount: 0 };
70
+ this.windows.set(key, window);
71
+ }
72
+ if (now - window.minuteStart >= minuteMs) {
73
+ window.minuteStart = now;
74
+ window.minuteCount = 0;
75
+ }
76
+ if (now - window.hourStart >= hourMs) {
77
+ window.hourStart = now;
78
+ window.hourCount = 0;
79
+ }
80
+ if (window.minuteCount >= quota.perMinute) {
81
+ return { allow: false, retryAfter: Math.max(1, Math.ceil((window.minuteStart + minuteMs - now) / 1000)) };
82
+ }
83
+ if (window.hourCount >= quota.perHour) {
84
+ return { allow: false, retryAfter: Math.max(1, Math.ceil((window.hourStart + hourMs - now) / 1000)) };
85
+ }
86
+ window.minuteCount++;
87
+ window.hourCount++;
88
+ return { allow: true };
89
+ }
90
+ /** 定期清理空窗口,避免长期运行后按 AID 无限增长。 */
91
+ prune(now = Date.now()) {
92
+ const hourMs = 3_600_000;
93
+ for (const [key, window] of this.windows) {
94
+ if (now - window.hourStart >= hourMs && now - window.minuteStart >= hourMs)
95
+ this.windows.delete(key);
96
+ }
97
+ }
98
+ }