evolcore 0.0.43-test.6 → 0.0.43-test.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/bin/ecmsg.js +171 -54
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/codex/app-server-client.js +22 -0
- package/dist/agents/codex-runner.js +69 -2
- package/dist/aun/msg/p2p.js +6 -1
- package/dist/channels/aun.js +234 -21
- package/dist/cli/agent-create.js +2 -2
- package/dist/cli/daemon-commands.js +6 -66
- package/dist/cli/daemon-lifecycle-client.js +61 -0
- package/dist/cli/ecmsg-gateway.js +35 -2
- package/dist/cli/events-command.js +73 -0
- package/dist/cli/index.js +31 -14
- package/dist/cli/invoke-command.js +182 -0
- package/dist/cli/managed-command-guard.js +6 -1
- package/dist/cli/restart-monitor.js +45 -47
- package/dist/cli/services-command.js +111 -0
- package/dist/cli/team-workspace-command.js +134 -0
- package/dist/cli/thread-command.js +6 -2
- package/dist/cli/watch-msg.js +1 -1
- package/dist/config/config-field-policy.js +2 -2
- package/dist/config/config-manager.js +0 -7
- package/dist/config/invoke-ipc-service.js +118 -0
- package/dist/config/schema-migration.js +6 -1
- package/dist/config-store.js +2 -1
- package/dist/core/agent-reload-coordinator.js +6 -4
- package/dist/core/agent-runtime.js +104 -10
- package/dist/core/auth/delegation-authorization.js +66 -0
- package/dist/core/auth/operation-catalog.js +20 -0
- package/dist/core/baseagent-loader.js +60 -130
- package/dist/core/channel-loader.js +10 -1
- package/dist/core/channel-runtime.js +4 -3
- package/dist/core/command/agent-control.js +1 -1
- package/dist/core/command/agent-storage-menu.js +1 -1
- package/dist/core/command/chatmode-config.js +2 -36
- package/dist/core/command/command-handler.js +53 -11
- package/dist/core/command/data-root-resolver.js +32 -23
- package/dist/core/command/eventcenter-menu.js +338 -0
- package/dist/core/command/menu-catalog.js +8 -0
- package/dist/core/command/menu-handler.js +198 -84
- package/dist/core/command/menu-protocol.js +60 -11
- package/dist/core/command/menu-query-batch.js +194 -0
- package/dist/core/command/slash-gate.js +1 -1
- package/dist/core/command/slash-handler.js +34 -42
- package/dist/core/command/team-workspace-bootstrap.js +350 -0
- package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
- package/dist/core/command/team-workspace-initializer.js +2 -0
- package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
- package/dist/core/command/team-workspace-job-store.js +88 -0
- package/dist/core/command/team-workspace-management-service.js +2 -0
- package/dist/core/command/team-workspace-management-store.js +96 -0
- package/dist/core/command/team-workspace-management.js +265 -0
- package/dist/core/command/team-workspace-members-menu.js +88 -0
- package/dist/core/command/team-workspace-store.js +612 -0
- package/dist/core/command/team-workspace-team.js +193 -0
- package/dist/core/daemon-control.js +8 -5
- package/dist/core/daemon-lifecycle.js +132 -73
- package/dist/core/handoff/runtime.js +3 -3
- package/dist/core/invoke/executors/index.js +13 -0
- package/dist/core/invoke/executors/media.js +283 -0
- package/dist/core/invoke/executors/text.js +198 -0
- package/dist/core/invoke/invoke-service.js +157 -0
- package/dist/core/invoke/style-router.js +48 -0
- package/dist/core/invoke/types.js +19 -0
- package/dist/core/ipc-registration.js +46 -7
- package/dist/core/memory/consolidation.js +7 -5
- package/dist/core/message/aun-ipc-sender.js +147 -17
- package/dist/core/message/im-renderer.js +28 -84
- package/dist/core/message/message-bridge.js +4 -0
- package/dist/core/message/message-utils.js +10 -2
- package/dist/core/message/peer-mode.js +7 -34
- package/dist/core/message/response-engine.js +157 -54
- package/dist/core/message/send-options.js +7 -4
- package/dist/core/message/send-routing.js +43 -5
- package/dist/core/ownership/owner-resolver.js +7 -0
- package/dist/core/permission/ec-command-parser.js +3 -2
- package/dist/core/permission/protected-paths.js +12 -2
- package/dist/core/permission/shell-environment.js +9 -0
- package/dist/core/session/session-file-health.js +243 -0
- package/dist/core/session/session-fs-store.js +2 -3
- package/dist/core/task/task-recovery-service.js +13 -2
- package/dist/core/thread/command-parser.js +9 -2
- package/dist/core/thread/thread-operation.js +21 -2
- package/dist/core/thread/thread-route.js +13 -2
- package/dist/directory/owner-directory-admission.js +40 -53
- package/dist/directory/owner-directory-cache.js +89 -113
- package/dist/directory/owner-directory-query-operation.js +8 -10
- package/dist/eck/kit-renderer.js +7 -5
- package/dist/ecweb/basic-settings-service.js +1 -1
- package/dist/ecweb/message-context-service.js +0 -4
- package/dist/ecweb/runtime/lifecycle.js +6 -2
- package/dist/ecweb/runtime/supervisor.js +19 -4
- package/dist/event-center/admission-materializer.js +114 -0
- package/dist/event-center/bus-gate.js +136 -0
- package/dist/event-center/bus-host.js +290 -0
- package/dist/event-center/bus-resolver.js +120 -0
- package/dist/event-center/center-config.js +100 -0
- package/dist/event-center/client-factory.js +50 -0
- package/dist/event-center/daemon.js +45 -0
- package/dist/event-center/directory-source.js +53 -0
- package/dist/event-center/dispatcher.js +157 -0
- package/dist/event-center/event-log.js +110 -0
- package/dist/event-center/index-generator.js +63 -0
- package/dist/event-center/ipc-operation.js +308 -0
- package/dist/event-center/ledger.js +52 -0
- package/dist/event-center/pack-loader.js +202 -0
- package/dist/event-center/pack-manager.js +85 -0
- package/dist/event-center/registry.js +238 -0
- package/dist/event-center/runtime.js +641 -0
- package/dist/event-center/script-runner.js +356 -0
- package/dist/event-center/types.js +35 -0
- package/dist/event-center/validation.js +413 -0
- package/dist/index.js +285 -99
- package/dist/ipc.js +66 -12
- package/dist/paths.js +20 -0
- package/dist/product.js +14 -0
- package/dist/proxy/manager.js +5 -1
- package/dist/proxy/service-supervisor.js +13 -4
- package/dist/response-system/engines/v1/index.js +0 -1
- package/dist/response-system/modes/single-session/index.js +1 -1
- package/dist/services/dispatcher.js +100 -0
- package/dist/services/idempotency.js +90 -0
- package/dist/services/identity.js +52 -0
- package/dist/services/index-generator.js +70 -0
- package/dist/services/index.js +449 -0
- package/dist/services/ipc-operation.js +458 -0
- package/dist/services/ledger.js +52 -0
- package/dist/services/message-log.js +112 -0
- package/dist/services/pack-manager.js +204 -0
- package/dist/services/reply.js +55 -0
- package/dist/services/router.js +95 -0
- package/dist/services/script-runner.js +422 -0
- package/dist/services/service-payload.js +70 -0
- package/dist/services/types.js +18 -0
- package/dist/services/validation.js +297 -0
- package/dist/trigger/application-service.js +18 -0
- package/dist/trigger/event-source.js +1 -1
- package/dist/trigger/ipc-service.js +3 -1
- package/dist/trigger/script-sandbox.js +118 -22
- package/dist/utils/cross-platform.js +24 -10
- package/dist/utils/evolcore-version.js +69 -27
- package/dist/utils/instance-registry.js +19 -13
- package/dist/utils/process-introspect.js +45 -9
- package/dist/utils/startup-trace.js +74 -37
- package/dist/utils/windows-shell-trust.js +80 -6
- package/kits/docs/INDEX.md +2 -2
- package/kits/docs/aun/ABILITY_CALLING.md +7 -14
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +2 -0
- package/kits/docs/evolcore/ability.md +4 -0
- package/kits/docs/evolcore/aid.md +1 -1
- package/kits/docs/evolcore/event-center.md +207 -0
- package/kits/docs/evolcore/file-navigation.md +10 -264
- package/kits/docs/evolcore/fs.md +3 -2
- package/kits/docs/evolcore/group.md +1 -1
- package/kits/docs/evolcore/memory-architecture.md +2 -0
- package/kits/docs/evolcore/menu-protocol.md +21 -0
- package/kits/docs/evolcore/msg.md +15 -3
- package/kits/docs/evolcore/provider.md +3 -1
- package/kits/docs/evolcore/response.md +5 -5
- package/kits/docs/evolcore/services.md +277 -0
- package/kits/docs/evolcore/task.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +41 -0
- package/kits/eck_manifest.json +26 -0
- package/kits/rules/02-navigation.md +10 -1
- package/kits/schemas/_meta.json +17 -6
- package/kits/schemas/agent-config.schema.19.json +5 -7
- package/kits/schemas/agent-config.schema.20.json +936 -0
- package/kits/schemas/relation-config.schema.12.json +2 -3
- package/kits/schemas/role-config.schema.2.json +4 -4
- package/kits/skills/.switches.json +1 -5
- package/kits/skills/ability/SKILL.md +56 -0
- package/kits/skills/ability/references/calling.md +56 -0
- package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
- package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
- package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
- package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
- package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
- package/kits/skills/ec-agent-create/SKILL.md +0 -1
- package/kits/skills/ec-service-proxy/SKILL.md +34 -5
- package/kits/skills/personal-assistant/SKILL.md +6 -6
- package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
- package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
- package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
- package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
- package/kits/templates/system-fragments/channel.md +3 -3
- package/kits/templates/system-fragments/commands.md +5 -3
- package/kits/templates/system-fragments/reply.md +0 -5
- package/kits/templates/system-fragments/thread.md +10 -8
- package/package.json +3 -5
- package/dist/cli/pa-workspace-command.js +0 -225
- package/dist/core/command/pa-workspace-store.js +0 -468
- package/dist/core/relation/pa-team.js +0 -132
- package/kits/docs/evolcore/pa-workspace.md +0 -51
- package/kits/skills/aid-ability/SKILL.md +0 -244
- package/kits/skills/ec-ability/SKILL.md +0 -67
- package/kits/skills/ec-ability/references/workflows.md +0 -15
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 服务包扫描、加载与激活:services/<pak>/service.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
|
+
export const SERVICE_JSON = 'service.json';
|
|
15
|
+
export const SCRIPTS_DIR = 'scripts';
|
|
16
|
+
export const LEDGER_FILE = 'ledger.jsonl';
|
|
17
|
+
export const LOGS_DIR = 'logs';
|
|
18
|
+
export const IDEMPOTENCY_FILE = '.idempotency.jsonl';
|
|
19
|
+
/** realpath 全级校验:目标真实路径必须仍在包目录内(防中间目录符号链接逃逸)。 */
|
|
20
|
+
function assertInsidePackDir(packDir, target, errors, field) {
|
|
21
|
+
let realTarget;
|
|
22
|
+
try {
|
|
23
|
+
realTarget = fs.realpathSync(target);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
errors.push(`${field} not found: ${path.relative(packDir, target)}`);
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
const realPackDir = fs.realpathSync(packDir);
|
|
30
|
+
if (realTarget !== realPackDir && !realTarget.startsWith(realPackDir + path.sep)) {
|
|
31
|
+
errors.push(`${field} escapes pack directory via symlink`);
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
/** 加载单个包目录。返回 null 表示该包 invalid(errors 已填)。 */
|
|
37
|
+
export function loadPackDir(packDir, errors) {
|
|
38
|
+
const packId = path.basename(packDir);
|
|
39
|
+
const serviceJsonPath = path.join(packDir, SERVICE_JSON);
|
|
40
|
+
let rawText;
|
|
41
|
+
try {
|
|
42
|
+
rawText = fs.readFileSync(serviceJsonPath, 'utf8');
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
errors.push(`cannot read ${SERVICE_JSON}: ${error instanceof Error ? error.message : String(error)}`);
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
let raw;
|
|
49
|
+
try {
|
|
50
|
+
raw = JSON.parse(rawText);
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
errors.push(`${SERVICE_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
const validated = validateServiceJson(raw);
|
|
57
|
+
if (!validated.ok) {
|
|
58
|
+
errors.push(...validated.errors);
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
const canonicalScripts = path.join(packDir, SCRIPTS_DIR);
|
|
62
|
+
const scriptsDir = fs.existsSync(canonicalScripts) ? canonicalScripts : canonicalScripts;
|
|
63
|
+
if (!fs.existsSync(scriptsDir)) {
|
|
64
|
+
errors.push(`scripts directory not found: expected ${SCRIPTS_DIR}/`);
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
// 脚本存在性 + realpath 越界校验。
|
|
68
|
+
for (const entry of validated.value.listen) {
|
|
69
|
+
const relativeUnderScripts = entry.handler.script.slice(SCRIPTS_DIR.length + 1);
|
|
70
|
+
const scriptPath = path.join(scriptsDir, relativeUnderScripts);
|
|
71
|
+
if (!assertInsidePackDir(packDir, scriptPath, errors, `listen[].handler.script "${entry.handler.script}"`))
|
|
72
|
+
continue;
|
|
73
|
+
const stat = fs.lstatSync(fs.realpathSync(scriptPath));
|
|
74
|
+
if (!stat.isFile())
|
|
75
|
+
errors.push(`listen[].handler.script "${entry.handler.script}" is not a regular file`);
|
|
76
|
+
}
|
|
77
|
+
const logsDir = path.join(packDir, LOGS_DIR);
|
|
78
|
+
if (!fs.existsSync(logsDir)) {
|
|
79
|
+
try {
|
|
80
|
+
fs.mkdirSync(logsDir, { recursive: true });
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
errors.push(`cannot create logs directory: ${logsDir}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (errors.length)
|
|
87
|
+
return null;
|
|
88
|
+
const paths = {
|
|
89
|
+
serviceJson: serviceJsonPath,
|
|
90
|
+
scriptsDir,
|
|
91
|
+
ledger: path.join(packDir, LEDGER_FILE),
|
|
92
|
+
logsDir,
|
|
93
|
+
idempotency: path.join(packDir, IDEMPOTENCY_FILE),
|
|
94
|
+
};
|
|
95
|
+
return {
|
|
96
|
+
id: packId,
|
|
97
|
+
dir: packDir,
|
|
98
|
+
name: validated.value.name,
|
|
99
|
+
...(validated.value.description !== undefined ? { description: validated.value.description } : {}),
|
|
100
|
+
enabled: validated.value.enabled,
|
|
101
|
+
requires: validated.value.requires,
|
|
102
|
+
listen: validated.value.listen,
|
|
103
|
+
unmatched: validated.value.unmatched,
|
|
104
|
+
reply: validated.value.reply,
|
|
105
|
+
revision: sha256(rawText),
|
|
106
|
+
paths,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/** 扫描 services/ 下全部包目录。单包失败只废该包。 */
|
|
110
|
+
export function loadPacks(servicesDir) {
|
|
111
|
+
const valid = [];
|
|
112
|
+
const invalid = [];
|
|
113
|
+
let entries;
|
|
114
|
+
try {
|
|
115
|
+
entries = fs.readdirSync(servicesDir, { withFileTypes: true });
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return { valid: [], invalid: [] };
|
|
119
|
+
}
|
|
120
|
+
for (const entry of entries) {
|
|
121
|
+
if (!entry.isDirectory())
|
|
122
|
+
continue;
|
|
123
|
+
if (entry.name.startsWith('.') || entry.name.startsWith('_'))
|
|
124
|
+
continue;
|
|
125
|
+
const packDir = path.join(servicesDir, entry.name);
|
|
126
|
+
const errors = [];
|
|
127
|
+
const pack = loadPackDir(packDir, errors);
|
|
128
|
+
if (pack)
|
|
129
|
+
valid.push(pack);
|
|
130
|
+
else
|
|
131
|
+
invalid.push({ dir: packDir, packId: entry.name, errors });
|
|
132
|
+
}
|
|
133
|
+
return { valid, invalid };
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* 从加载结果构建运行时状态:
|
|
137
|
+
* - enabled=false → disabled;
|
|
138
|
+
* - requires 不满足 → skipped(不是错误);
|
|
139
|
+
* - 跨包同 listen.type 且两包都 active → 两个包都 invalid。
|
|
140
|
+
*/
|
|
141
|
+
export function buildPackState(packs, invalidPacks, identity, previousRevision = 0) {
|
|
142
|
+
const disabledPacks = packs.filter(pack => !pack.enabled).map(pack => pack.id);
|
|
143
|
+
const candidates = packs.filter(pack => pack.enabled);
|
|
144
|
+
const skippedPacks = [];
|
|
145
|
+
const activeCandidates = [];
|
|
146
|
+
for (const pack of candidates) {
|
|
147
|
+
if (requiresSatisfied(pack.requires, identity))
|
|
148
|
+
activeCandidates.push(pack);
|
|
149
|
+
else
|
|
150
|
+
skippedPacks.push({ id: pack.id, reason: 'requires.unsatisfied' });
|
|
151
|
+
}
|
|
152
|
+
// 跨包冲突:同一 listen.type 出现在两个 active 包里。
|
|
153
|
+
const typeOwners = new Map();
|
|
154
|
+
for (const pack of activeCandidates) {
|
|
155
|
+
for (const entry of pack.listen) {
|
|
156
|
+
const owners = typeOwners.get(entry.type) ?? [];
|
|
157
|
+
owners.push(pack.id);
|
|
158
|
+
typeOwners.set(entry.type, owners);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const conflicts = [];
|
|
162
|
+
const conflictPackIds = new Set();
|
|
163
|
+
for (const [type, packIds] of typeOwners) {
|
|
164
|
+
if (packIds.length > 1) {
|
|
165
|
+
conflicts.push({ type, packs: packIds });
|
|
166
|
+
for (const id of packIds)
|
|
167
|
+
conflictPackIds.add(id);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const conflictInvalid = [];
|
|
171
|
+
for (const pack of activeCandidates) {
|
|
172
|
+
if (!conflictPackIds.has(pack.id))
|
|
173
|
+
continue;
|
|
174
|
+
const types = conflicts.filter(item => item.packs.includes(pack.id)).map(item => item.type);
|
|
175
|
+
conflictInvalid.push({
|
|
176
|
+
id: pack.id,
|
|
177
|
+
errors: [`listen.type conflict: ${types.join(', ')} (also declared by ${[...conflictPackIds].filter(id => id !== pack.id).join(', ')})`],
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
const activePacks = activeCandidates.filter(pack => !conflictPackIds.has(pack.id));
|
|
181
|
+
const routeIndex = new Map();
|
|
182
|
+
const wildcardIndex = [];
|
|
183
|
+
for (const pack of activePacks) {
|
|
184
|
+
for (const entry of pack.listen) {
|
|
185
|
+
if (entry.type.endsWith('.*')) {
|
|
186
|
+
wildcardIndex.push({ pack, entry });
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const list = routeIndex.get(entry.type) ?? [];
|
|
190
|
+
list.push({ pack, entry });
|
|
191
|
+
routeIndex.set(entry.type, list);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
activePacks,
|
|
196
|
+
skippedPacks,
|
|
197
|
+
disabledPacks,
|
|
198
|
+
invalidPacks: [...invalidPacks, ...conflictInvalid],
|
|
199
|
+
conflicts,
|
|
200
|
+
routeIndex,
|
|
201
|
+
wildcardIndex,
|
|
202
|
+
revision: previousRevision + 1,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
@@ -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,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* services/router.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
|
+
export const ROUTER_JSON = 'router.json';
|
|
11
|
+
export const DEFAULT_ROUTER_CONFIG = {
|
|
12
|
+
v: 1,
|
|
13
|
+
enabled: false,
|
|
14
|
+
rateLimit: {
|
|
15
|
+
builtin: { perMinute: 20, perHour: 200 },
|
|
16
|
+
service: { perMinute: 50, perHour: 1000 },
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
/** 读取 services/router.json;不存在或缺 v 时返回缺省(enabled=false)。 */
|
|
20
|
+
export function loadRouterConfig(servicesDir) {
|
|
21
|
+
const filePath = path.join(servicesDir, ROUTER_JSON);
|
|
22
|
+
let rawText;
|
|
23
|
+
try {
|
|
24
|
+
rawText = fs.readFileSync(filePath, 'utf8');
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return { config: DEFAULT_ROUTER_CONFIG, exists: false, errors: [] };
|
|
28
|
+
}
|
|
29
|
+
let raw;
|
|
30
|
+
try {
|
|
31
|
+
raw = JSON.parse(rawText);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
return {
|
|
35
|
+
config: DEFAULT_ROUTER_CONFIG,
|
|
36
|
+
exists: true,
|
|
37
|
+
errors: [`${ROUTER_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`],
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const validated = validateRouterConfig(raw);
|
|
41
|
+
if (!validated.ok)
|
|
42
|
+
return { config: DEFAULT_ROUTER_CONFIG, exists: true, errors: validated.errors };
|
|
43
|
+
return { config: validated.value, exists: true, errors: [] };
|
|
44
|
+
}
|
|
45
|
+
/** 滑动窗口(分钟/小时各一格,超过窗口即重置),按 (bucket, fromAid) 独立计数。 */
|
|
46
|
+
export class RateLimiter {
|
|
47
|
+
windows = new Map();
|
|
48
|
+
config;
|
|
49
|
+
constructor(config) {
|
|
50
|
+
this.config = config;
|
|
51
|
+
}
|
|
52
|
+
setConfig(config) {
|
|
53
|
+
this.config = config;
|
|
54
|
+
}
|
|
55
|
+
quota(bucket) {
|
|
56
|
+
return bucket === 'builtin' ? this.config.rateLimit.builtin : this.config.rateLimit.service;
|
|
57
|
+
}
|
|
58
|
+
/** 记一次消费;超限时不计数并给出 retryAfter。 */
|
|
59
|
+
consume(bucket, fromAid, now = Date.now()) {
|
|
60
|
+
const quota = this.quota(bucket);
|
|
61
|
+
const key = `${bucket}\u0000${fromAid}`;
|
|
62
|
+
const minuteMs = 60_000;
|
|
63
|
+
const hourMs = 3_600_000;
|
|
64
|
+
let window = this.windows.get(key);
|
|
65
|
+
if (!window) {
|
|
66
|
+
window = { minuteStart: now, minuteCount: 0, hourStart: now, hourCount: 0 };
|
|
67
|
+
this.windows.set(key, window);
|
|
68
|
+
}
|
|
69
|
+
if (now - window.minuteStart >= minuteMs) {
|
|
70
|
+
window.minuteStart = now;
|
|
71
|
+
window.minuteCount = 0;
|
|
72
|
+
}
|
|
73
|
+
if (now - window.hourStart >= hourMs) {
|
|
74
|
+
window.hourStart = now;
|
|
75
|
+
window.hourCount = 0;
|
|
76
|
+
}
|
|
77
|
+
if (window.minuteCount >= quota.perMinute) {
|
|
78
|
+
return { allow: false, retryAfter: Math.max(1, Math.ceil((window.minuteStart + minuteMs - now) / 1000)) };
|
|
79
|
+
}
|
|
80
|
+
if (window.hourCount >= quota.perHour) {
|
|
81
|
+
return { allow: false, retryAfter: Math.max(1, Math.ceil((window.hourStart + hourMs - now) / 1000)) };
|
|
82
|
+
}
|
|
83
|
+
window.minuteCount++;
|
|
84
|
+
window.hourCount++;
|
|
85
|
+
return { allow: true };
|
|
86
|
+
}
|
|
87
|
+
/** 定期清理空窗口,避免长期运行后按 AID 无限增长。 */
|
|
88
|
+
prune(now = Date.now()) {
|
|
89
|
+
const hourMs = 3_600_000;
|
|
90
|
+
for (const [key, window] of this.windows) {
|
|
91
|
+
if (now - window.hourStart >= hourMs && now - window.minuteStart >= hourMs)
|
|
92
|
+
this.windows.delete(key);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|