evolcore 0.0.43-test.5 → 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 +95 -0
- package/bin/ecmsg.js +281 -81
- package/dist/agents/baseagent-availability.js +20 -5
- package/dist/agents/baseagent.js +2 -2
- package/dist/agents/claude-runner.js +19 -4
- package/dist/agents/codex/app-server-client.js +36 -3
- package/dist/agents/codex-runner.js +75 -8
- package/dist/aun/group/invite-service.js +3 -2
- package/dist/aun/msg/p2p.js +6 -1
- package/dist/aun/service-proxy.js +18 -6
- package/dist/channels/aun.js +306 -30
- package/dist/cli/agent-create.js +18 -8
- package/dist/cli/aun-commands.js +9 -1
- package/dist/cli/daemon-commands.js +34 -65
- package/dist/cli/daemon-lifecycle-client.js +61 -0
- package/dist/cli/ecmsg-gateway.js +38 -3
- package/dist/cli/events-command.js +73 -0
- package/dist/cli/index.js +31 -14
- package/dist/cli/init.js +75 -0
- package/dist/cli/invoke-command.js +182 -0
- package/dist/cli/managed-command-guard.js +6 -1
- package/dist/cli/provider-command.js +1 -1
- package/dist/cli/restart-monitor.js +67 -50
- package/dist/cli/services-command.js +111 -0
- package/dist/cli/task-context.js +38 -1
- package/dist/cli/team-workspace-command.js +134 -0
- package/dist/cli/thread-command.js +6 -2
- package/dist/cli/watch-logs.js +6 -4
- package/dist/cli/watch-msg.js +1 -1
- package/dist/config/boot-log.js +6 -4
- package/dist/config/builtin-roles.js +2 -2
- package/dist/config/config-field-policy.js +2 -2
- package/dist/config/config-manager.js +1 -8
- package/dist/config/invoke-ipc-service.js +118 -0
- package/dist/config/peer-role-resolver.js +1 -1
- package/dist/config/provider-identity-migration.js +92 -17
- package/dist/config/provider-local-sync.js +2 -0
- package/dist/config/providers-config.js +13 -0
- package/dist/config/providers-management.js +100 -10
- package/dist/config/role-service.js +8 -8
- package/dist/config/role-store.js +22 -22
- package/dist/config/schema-migration.js +86 -88
- package/dist/config/snapshot.js +70 -41
- package/dist/config-store.js +2 -1
- package/dist/core/agent-reload-coordinator.js +6 -4
- package/dist/core/agent-runtime.js +146 -15
- package/dist/core/auth/delegation-authorization.js +66 -0
- package/dist/core/auth/operation-catalog.js +20 -0
- package/dist/core/baseagent-loader.js +75 -42
- package/dist/core/channel-loader.js +45 -13
- package/dist/core/channel-runtime.js +116 -45
- 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 +58 -16
- 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 +206 -87
- package/dist/core/command/menu-protocol.js +142 -22
- package/dist/core/command/menu-query-batch.js +194 -0
- package/dist/core/command/role-menu.js +27 -15
- 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 +45 -15
- package/dist/core/daemon-lifecycle.js +478 -75
- package/dist/core/handoff/dispatcher.js +9 -3
- package/dist/core/handoff/runtime.js +130 -42
- package/dist/core/handoff/store.js +190 -2
- package/dist/core/handoff/types.js +5 -0
- package/dist/core/initialization/service.js +4 -4
- 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 +51 -11
- package/dist/core/lifecycle-notice.js +10 -4
- package/dist/core/memory/consolidation.js +7 -5
- package/dist/core/message/aun-ipc-sender.js +149 -19
- package/dist/core/message/im-renderer.js +28 -84
- package/dist/core/message/message-bridge.js +57 -4
- package/dist/core/message/message-queue.js +46 -4
- package/dist/core/message/message-utils.js +10 -2
- package/dist/core/message/peer-mode.js +7 -34
- package/dist/core/message/pending-hints.js +4 -10
- package/dist/core/message/response-engine.js +163 -52
- package/dist/core/message/send-options.js +7 -4
- package/dist/core/message/send-routing.js +55 -7
- package/dist/core/ownership/owner-resolver.js +8 -0
- package/dist/core/permission/ec-command-parser.js +14 -3
- package/dist/core/permission/protected-paths.js +12 -2
- package/dist/core/permission/shell-environment.js +9 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
- package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
- package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
- package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
- package/dist/core/session/session-file-health.js +243 -0
- package/dist/core/session/session-fs-store.js +163 -3
- package/dist/core/session/session-idle-monitor.js +9 -1
- package/dist/core/session/session-manager.js +36 -2
- 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 +42 -30
- package/dist/directory/owner-directory-cache.js +143 -126
- package/dist/directory/owner-directory-query-operation.js +9 -8
- 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 +14 -8
- package/dist/ecweb/runtime/supervisor.js +62 -30
- 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 +751 -268
- package/dist/ipc.js +66 -12
- package/dist/paths.js +20 -0
- package/dist/product.js +14 -0
- package/dist/proxy/manager.js +43 -18
- package/dist/proxy/service-supervisor.js +78 -35
- 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 +21 -1
- package/dist/trigger/audit.js +19 -4
- package/dist/trigger/authorization.js +14 -5
- package/dist/trigger/event-source.js +1 -1
- package/dist/trigger/history.js +176 -7
- package/dist/trigger/ipc-service.js +3 -1
- package/dist/trigger/manager.js +1 -3
- package/dist/trigger/scheduler.js +78 -5
- package/dist/trigger/script-sandbox.js +118 -22
- package/dist/utils/cross-platform.js +175 -13
- package/dist/utils/evolcore-version.js +69 -27
- package/dist/utils/host-info.js +11 -8
- package/dist/utils/instance-registry.js +19 -13
- package/dist/utils/npm-ops.js +48 -0
- package/dist/utils/process-introspect.js +109 -10
- package/dist/utils/startup-trace.js +222 -44
- package/dist/utils/windows-shell-trust.js +80 -6
- package/kits/docs/INDEX.md +2 -2
- package/kits/docs/aun/ABILITY_CALLING.md +10 -17
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +5 -2
- package/kits/docs/evolcore/ability.md +4 -0
- package/kits/docs/evolcore/aid.md +1 -1
- package/kits/docs/evolcore/ctl.md +2 -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 +2 -2
- package/kits/docs/evolcore/memory-architecture.md +2 -0
- package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +21 -0
- package/kits/docs/evolcore/msg.md +27 -8
- package/kits/docs/evolcore/provider.md +23 -3
- 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 +45 -7
- package/kits/eck_message_manifest.json +3 -3
- package/kits/rules/02-navigation.md +10 -1
- package/kits/rules/06-channel.md +5 -6
- 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/daemon.schema.1.json +5 -0
- package/kits/schemas/daemon.schema.2.json +5 -0
- package/kits/schemas/daemon.schema.3.json +2 -1
- package/kits/schemas/daemon.schema.4.json +2 -1
- package/kits/schemas/daemon.schema.5.json +2 -1
- package/kits/schemas/daemon.schema.6.json +1 -1
- package/kits/schemas/daemon.schema.7.json +1 -1
- package/kits/schemas/daemon.schema.8.json +2 -1
- package/kits/schemas/daemon.schema.9.json +2 -1
- package/kits/schemas/relation-config.schema.12.json +2 -3
- package/kits/schemas/role-config.schema.2.json +4 -4
- package/kits/schemas/role-registry.schema.1.json +2 -2
- package/kits/schemas/single-session.schema.1.json +1 -1
- package/kits/schemas/single-session.schema.2.json +1 -1
- package/kits/schemas/single-session.schema.3.json +1 -1
- 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-group/SKILL.md +8 -5
- package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
- package/kits/skills/ec-service-proxy/SKILL.md +34 -5
- package/kits/skills/ec-trigger/SKILL.md +4 -4
- 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/skills/thread-ops/SKILL.md +10 -10
- package/kits/templates/system-fragments/channel.md +3 -3
- package/kits/templates/system-fragments/commands.md +9 -7
- package/kits/templates/system-fragments/reply.md +2 -6
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +11 -9
- package/package.json +5 -6
- 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
|
@@ -3,15 +3,17 @@ import path from 'node:path';
|
|
|
3
3
|
import { createServer } from 'node:net';
|
|
4
4
|
import { execFileSync } from 'node:child_process';
|
|
5
5
|
import { parseEcwebInstanceRecord, matchesEcwebInstanceHealth } from '../../contracts/ecweb-instance.js';
|
|
6
|
-
import { getProcessSnapshot, getProcessStartTime, startTimeMatches } from '../../utils/process-introspect.js';
|
|
6
|
+
import { getProcessSnapshot, getProcessStartTime, getProcessStartTimeAsync, startTimeMatches } from '../../utils/process-introspect.js';
|
|
7
7
|
import * as platform from '../../utils/cross-platform.js';
|
|
8
8
|
import { resolveGlobalPkg } from '../../utils/npm-ops.js';
|
|
9
9
|
import { resolveEcwebLaunchCommand } from './launch.js';
|
|
10
10
|
import { WEB_PACKAGE_NAME } from '../../product.js';
|
|
11
|
-
function sameProcess(identity) {
|
|
11
|
+
async function sameProcess(identity) {
|
|
12
|
+
if (!platform.isProcessRunning(identity.pid))
|
|
13
|
+
return false;
|
|
14
|
+
const actual = await getProcessStartTimeAsync(identity.pid);
|
|
12
15
|
if (!platform.isProcessRunning(identity.pid))
|
|
13
16
|
return false;
|
|
14
|
-
const actual = getProcessStartTime(identity.pid);
|
|
15
17
|
if (identity.startedAt === null || actual === null) {
|
|
16
18
|
throw new Error(`Cannot verify ECWeb process identity (PID: ${identity.pid}); refusing to terminate it`);
|
|
17
19
|
}
|
|
@@ -21,6 +23,8 @@ function sameProcess(identity) {
|
|
|
21
23
|
* Prefer a cooperative IPC request for supervised children on every platform.
|
|
22
24
|
* Windows taskkill without /F cannot invoke Node's SIGTERM handler; only
|
|
23
25
|
* POSIX can use SIGTERM when no parent-child IPC channel is available.
|
|
26
|
+
* The cooperative callback must use the captured ChildProcess IPC channel,
|
|
27
|
+
* never a PID-addressed transport. That handle cannot address a reused PID.
|
|
24
28
|
*/
|
|
25
29
|
const IPC_GRACEFUL_STOP_MS = 3_000;
|
|
26
30
|
const POSIX_GRACEFUL_STOP_MS = 1_000;
|
|
@@ -47,21 +51,23 @@ export async function stopEcwebProcess(identity, timeoutMs = FORCED_STOP_MS, onT
|
|
|
47
51
|
catch { }
|
|
48
52
|
}
|
|
49
53
|
};
|
|
50
|
-
if (!sameProcess(identity))
|
|
51
|
-
return;
|
|
52
54
|
if (requestGracefulStop) {
|
|
55
|
+
// Ask our actual child first. Fresh OS identity queries are only needed
|
|
56
|
+
// before falling back to PID-addressed signals, including on IPC failure.
|
|
53
57
|
if (await waitForExit(false, IPC_GRACEFUL_STOP_MS, requestGracefulStop))
|
|
54
58
|
return;
|
|
55
|
-
if (!sameProcess(identity))
|
|
59
|
+
if (!await sameProcess(identity))
|
|
56
60
|
return;
|
|
57
61
|
}
|
|
62
|
+
else if (!await sameProcess(identity))
|
|
63
|
+
return;
|
|
58
64
|
if (!platform.isWindows && await waitForExit(false, POSIX_GRACEFUL_STOP_MS))
|
|
59
65
|
return;
|
|
60
|
-
if (!sameProcess(identity))
|
|
66
|
+
if (!await sameProcess(identity))
|
|
61
67
|
return;
|
|
62
68
|
if (await waitForExit(true, timeoutMs))
|
|
63
69
|
return;
|
|
64
|
-
if (!sameProcess(identity))
|
|
70
|
+
if (!await sameProcess(identity))
|
|
65
71
|
return;
|
|
66
72
|
throw new Error(`ECWeb 进程未能退出 (PID: ${identity.pid})`);
|
|
67
73
|
}
|
|
@@ -3,14 +3,15 @@ import path from 'path';
|
|
|
3
3
|
import { spawn } from 'child_process';
|
|
4
4
|
import { isDevMode, resolvePaths } from '../../paths.js';
|
|
5
5
|
import { SERVICE_HEALTH_INTERVALS, SERVICE_RESTART_BACKOFF_MS, SERVICE_RESTART_MAX_ATTEMPTS, SERVICE_RESTART_WINDOW_MS, SERVICE_STARTUP_TIMEOUT_MS, } from '../../config/daemon-services.js';
|
|
6
|
-
import { WEB_PACKAGE_NAME } from '../../product.js';
|
|
7
|
-
import {
|
|
6
|
+
import { RUNTIME_HOME_ENV, WEB_PACKAGE_NAME } from '../../product.js';
|
|
7
|
+
import { resolveGlobalPkgAsync } from '../../utils/npm-ops.js';
|
|
8
8
|
import { ecwebVersionRequirementError, resolveEcwebLaunchCommand } from './launch.js';
|
|
9
9
|
import * as platform from '../../utils/cross-platform.js';
|
|
10
|
-
import {
|
|
10
|
+
import { getProcessStartTimeAsync } from '../../utils/process-introspect.js';
|
|
11
11
|
import { matchesEcwebInstanceHealth, parseEcwebInstanceRecord } from '../../contracts/ecweb-instance.js';
|
|
12
12
|
import { sanitizeMenuLogValue } from '../../core/command/menu-protocol.js';
|
|
13
13
|
import { stopEcwebProcess } from './lifecycle.js';
|
|
14
|
+
import { sanitizeServiceEnvironment } from '../../core/permission/shell-environment.js';
|
|
14
15
|
const INSTANCE_FILE_RE = /^(?:ecweb|watch-web)-\d+\.json$/;
|
|
15
16
|
function sleep(ms) {
|
|
16
17
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
@@ -52,7 +53,7 @@ function readExitDiagnostics(filePath, startOffset) {
|
|
|
52
53
|
}
|
|
53
54
|
}
|
|
54
55
|
}
|
|
55
|
-
function isAlive(record) {
|
|
56
|
+
async function isAlive(record) {
|
|
56
57
|
if (!Number.isInteger(record.pid) || record.pid <= 0)
|
|
57
58
|
return false;
|
|
58
59
|
// ECWeb versions before the supervisor used a different Linux boot-time
|
|
@@ -61,7 +62,7 @@ function isAlive(record) {
|
|
|
61
62
|
// scoped to this EVOLCORE_HOME; use liveness here and let the HTTP probe be
|
|
62
63
|
// the ownership/health check. PID/start-time validation remains in the
|
|
63
64
|
// explicit kill path below.
|
|
64
|
-
return platform.
|
|
65
|
+
return platform.isProcessRunningAsync(record.pid);
|
|
65
66
|
}
|
|
66
67
|
function readEntries() {
|
|
67
68
|
const dir = resolvePaths().instanceDir;
|
|
@@ -125,6 +126,7 @@ async function probe(record, timeoutMs) {
|
|
|
125
126
|
* ECWeb's own stale-instance cleanup, and daemon startup.
|
|
126
127
|
*/
|
|
127
128
|
export function createEcwebSupervisor(options) {
|
|
129
|
+
const settleInitialHealth = options.startupTrace?.startTask('daemon.ecwebHealthReady', undefined, { initialPhase: 'waiting' });
|
|
128
130
|
let healthConfig = options.health;
|
|
129
131
|
let failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
|
|
130
132
|
let desiredPort = options.port;
|
|
@@ -138,6 +140,7 @@ export function createEcwebSupervisor(options) {
|
|
|
138
140
|
let failureCount = 0;
|
|
139
141
|
let lastHealthFailure = '未发现有效的 ECWeb 实例注册';
|
|
140
142
|
let healthy = false;
|
|
143
|
+
let checkedAt;
|
|
141
144
|
let startInFlight = null;
|
|
142
145
|
let childStartedAt = 0;
|
|
143
146
|
let childIdentityStartedAt = null;
|
|
@@ -166,13 +169,13 @@ export function createEcwebSupervisor(options) {
|
|
|
166
169
|
catch { }
|
|
167
170
|
}
|
|
168
171
|
};
|
|
169
|
-
const setActiveFromEntry = (entry, owned) => {
|
|
172
|
+
const setActiveFromEntry = async (entry, owned) => {
|
|
170
173
|
active = {
|
|
171
174
|
pid: entry.record.pid,
|
|
172
175
|
port: entry.record.port,
|
|
173
176
|
// Capture the current PID start time rather than trusting the record.
|
|
174
177
|
// Older ECWeb builds could write a clock-skewed `startedAt` value.
|
|
175
|
-
startedAt:
|
|
178
|
+
startedAt: await getProcessStartTimeAsync(entry.record.pid)
|
|
176
179
|
?? (typeof entry.record.startedAt === 'number' ? entry.record.startedAt : null),
|
|
177
180
|
owned,
|
|
178
181
|
};
|
|
@@ -180,12 +183,12 @@ export function createEcwebSupervisor(options) {
|
|
|
180
183
|
const findHealthyInstance = async () => {
|
|
181
184
|
lastHealthFailure = '未发现有效的 ECWeb 实例注册';
|
|
182
185
|
for (const entry of readEntries()) {
|
|
183
|
-
if (!isAlive(entry.record)) {
|
|
186
|
+
if (!await isAlive(entry.record)) {
|
|
184
187
|
lastHealthFailure = '实例进程不存在';
|
|
185
188
|
removeEntry(entry);
|
|
186
189
|
continue;
|
|
187
190
|
}
|
|
188
|
-
const actual =
|
|
191
|
+
const actual = await getProcessStartTimeAsync(entry.record.pid);
|
|
189
192
|
if (actual !== null && entry.record.startedAt !== undefined
|
|
190
193
|
&& (entry.record.schemaVersion === 1 ? Math.abs(actual - entry.record.startedAt) >= 2000 : actual - entry.record.startedAt > 2000)) {
|
|
191
194
|
lastHealthFailure = '实例 PID 启动时间不匹配';
|
|
@@ -253,12 +256,13 @@ export function createEcwebSupervisor(options) {
|
|
|
253
256
|
// instance record there is no `active` entry yet, but the daemon still
|
|
254
257
|
// owns the child and must not leave it behind on shutdown.
|
|
255
258
|
const pendingPid = child?.pid;
|
|
256
|
-
if (pendingPid && platform.
|
|
259
|
+
if (pendingPid && (await platform.isProcessRunningAsync(pendingPid))) {
|
|
257
260
|
await stopTrackedProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, onTiming);
|
|
258
261
|
}
|
|
259
262
|
child = null;
|
|
260
263
|
childIdentityStartedAt = null;
|
|
261
264
|
healthy = false;
|
|
265
|
+
checkedAt = undefined;
|
|
262
266
|
return;
|
|
263
267
|
}
|
|
264
268
|
await stopTrackedProcess({ pid: current.pid, startedAt: current.startedAt }, onTiming);
|
|
@@ -267,6 +271,7 @@ export function createEcwebSupervisor(options) {
|
|
|
267
271
|
child = null;
|
|
268
272
|
childIdentityStartedAt = null;
|
|
269
273
|
healthy = false;
|
|
274
|
+
checkedAt = undefined;
|
|
270
275
|
};
|
|
271
276
|
const spawnEcweb = async () => {
|
|
272
277
|
if (stopping || !desiredEnabled || runtimeMode !== 'managed')
|
|
@@ -276,7 +281,9 @@ export function createEcwebSupervisor(options) {
|
|
|
276
281
|
failureCount = 0;
|
|
277
282
|
const root = resolvePaths().root;
|
|
278
283
|
const localEntry = path.join(root, 'ecweb', 'dist', 'index.js');
|
|
279
|
-
const globalPkg =
|
|
284
|
+
const globalPkg = await resolveGlobalPkgAsync(WEB_PACKAGE_NAME);
|
|
285
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed')
|
|
286
|
+
return;
|
|
280
287
|
let launch = resolveEcwebLaunchCommand(['--home', root, '--port', String(desiredPort)], {
|
|
281
288
|
installedPkg: globalPkg,
|
|
282
289
|
});
|
|
@@ -311,7 +318,9 @@ export function createEcwebSupervisor(options) {
|
|
|
311
318
|
scheduleRecovery();
|
|
312
319
|
return;
|
|
313
320
|
}
|
|
314
|
-
const occupiedPids = platform.
|
|
321
|
+
const occupiedPids = await platform.findProcessByPortAsync(desiredPort);
|
|
322
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed')
|
|
323
|
+
return;
|
|
315
324
|
if (occupiedPids.length > 0) {
|
|
316
325
|
options.logger.error(`ECWeb 启动已停止:端口 ${desiredPort} 被占用 (PID: ${occupiedPids.join(', ')})`);
|
|
317
326
|
failureCount = failureThreshold;
|
|
@@ -334,8 +343,8 @@ export function createEcwebSupervisor(options) {
|
|
|
334
343
|
stdio: ['ignore', childLogFd, childLogFd, 'ipc'],
|
|
335
344
|
windowsHide: platform.isWindows,
|
|
336
345
|
env: {
|
|
337
|
-
...process.env,
|
|
338
|
-
|
|
346
|
+
...sanitizeServiceEnvironment(process.env),
|
|
347
|
+
[RUNTIME_HOME_ENV]: root,
|
|
339
348
|
EVOLCORE_ECWEB_SUPERVISED: '1',
|
|
340
349
|
},
|
|
341
350
|
});
|
|
@@ -350,7 +359,6 @@ export function createEcwebSupervisor(options) {
|
|
|
350
359
|
closeLogStream();
|
|
351
360
|
child = spawned;
|
|
352
361
|
childStartedAt = Date.now();
|
|
353
|
-
childIdentityStartedAt = spawned.pid ? getProcessStartTime(spawned.pid) : null;
|
|
354
362
|
spawned.once('error', (error) => {
|
|
355
363
|
options.logger.error(`ECWeb 子进程创建失败: ${error.message}`);
|
|
356
364
|
if (child !== spawned || intentionalStop || stopping)
|
|
@@ -373,18 +381,12 @@ export function createEcwebSupervisor(options) {
|
|
|
373
381
|
childStartedAt = 0;
|
|
374
382
|
childIdentityStartedAt = null;
|
|
375
383
|
healthy = false;
|
|
384
|
+
checkedAt = Date.now();
|
|
376
385
|
if (!expectedExit) {
|
|
377
386
|
if (active?.pid === spawned.pid)
|
|
378
387
|
active = null;
|
|
379
388
|
failureCount = failureThreshold;
|
|
380
|
-
|
|
381
|
-
if (occupiedPids.length > 0) {
|
|
382
|
-
recoveryExhausted = true;
|
|
383
|
-
options.logger.error(`ECWeb 自动恢复已停止:端口 ${desiredPort} 被占用 (PID: ${occupiedPids.join(', ')})`);
|
|
384
|
-
}
|
|
385
|
-
else {
|
|
386
|
-
scheduleRecovery();
|
|
387
|
-
}
|
|
389
|
+
scheduleRecovery();
|
|
388
390
|
}
|
|
389
391
|
}
|
|
390
392
|
closeLogStream();
|
|
@@ -396,6 +398,10 @@ export function createEcwebSupervisor(options) {
|
|
|
396
398
|
options.logger.warn('ECWeb 启动失败:未取得子进程 PID');
|
|
397
399
|
return;
|
|
398
400
|
}
|
|
401
|
+
const startedAt = await getProcessStartTimeAsync(spawned.pid);
|
|
402
|
+
if (child !== spawned)
|
|
403
|
+
return;
|
|
404
|
+
childIdentityStartedAt = startedAt;
|
|
399
405
|
options.logger.info(`✓ ECWeb supervisor 已启动 (PID: ${spawned.pid}),日志: ${logFile}`);
|
|
400
406
|
// ECWeb writes its own instance record after binding. Do not fabricate a
|
|
401
407
|
// record here; the watchdog will adopt the real record on its next tick.
|
|
@@ -411,26 +417,32 @@ export function createEcwebSupervisor(options) {
|
|
|
411
417
|
if (stopping) {
|
|
412
418
|
// 保留已核验的实例身份供 stop 清理,但不再接管运行状态或进入恢复分支。
|
|
413
419
|
if (instance)
|
|
414
|
-
setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
|
|
420
|
+
await setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
|
|
415
421
|
return;
|
|
416
422
|
}
|
|
417
423
|
if (!desiredEnabled || runtimeMode !== 'managed')
|
|
418
424
|
return;
|
|
419
425
|
healthy = instance !== null;
|
|
426
|
+
checkedAt = Date.now();
|
|
420
427
|
if (instance) {
|
|
421
428
|
launchRequested = false;
|
|
422
429
|
cancelRecovery();
|
|
423
430
|
const changed = !active || active.pid !== instance.record.pid || active.port !== instance.record.port;
|
|
424
|
-
setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
|
|
431
|
+
await setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
|
|
432
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed')
|
|
433
|
+
return;
|
|
425
434
|
failureCount = 0;
|
|
426
435
|
hasBeenReady = true;
|
|
436
|
+
settleInitialHealth?.('ok');
|
|
427
437
|
if (changed)
|
|
428
438
|
options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${instance.record.pid}, 端口: ${instance.record.port})`);
|
|
429
439
|
return;
|
|
430
440
|
}
|
|
431
|
-
if (!launchRequested && !hasBeenReady && child?.pid && platform.
|
|
441
|
+
if (!launchRequested && !hasBeenReady && child?.pid && (await platform.isProcessRunningAsync(child.pid))
|
|
432
442
|
&& Date.now() - childStartedAt < (healthConfig?.startupTimeoutMs ?? SERVICE_STARTUP_TIMEOUT_MS))
|
|
433
443
|
return;
|
|
444
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed')
|
|
445
|
+
return;
|
|
434
446
|
if (launchRequested) {
|
|
435
447
|
// A successful probe above cancels recovery without spending a retry.
|
|
436
448
|
// Charge the allowance only when an automatic restart actually begins.
|
|
@@ -465,6 +477,8 @@ export function createEcwebSupervisor(options) {
|
|
|
465
477
|
recoveryTimer = null;
|
|
466
478
|
};
|
|
467
479
|
const scheduleRecovery = () => {
|
|
480
|
+
if (!healthy && desiredEnabled && !stopping)
|
|
481
|
+
settleInitialHealth?.('failed');
|
|
468
482
|
if (stopping || intentionalStop || !desiredEnabled || runtimeMode !== 'managed'
|
|
469
483
|
|| restartConfig?.enabled === false || recoveryTimer || launchRequested || recoveryExhausted)
|
|
470
484
|
return;
|
|
@@ -526,23 +540,28 @@ export function createEcwebSupervisor(options) {
|
|
|
526
540
|
if (stopping)
|
|
527
541
|
return;
|
|
528
542
|
if (!desiredEnabled || runtimeMode !== 'managed') {
|
|
543
|
+
settleInitialHealth?.('skipped');
|
|
529
544
|
scheduleCheck();
|
|
530
545
|
return;
|
|
531
546
|
}
|
|
532
547
|
// Give an independently started ECWeb time to publish its instance record.
|
|
548
|
+
settleInitialHealth?.phase?.('waiting', 'existing ECWeb instance');
|
|
533
549
|
const existing = await waitForHealthyInstance(1_500);
|
|
534
550
|
if (stopping) {
|
|
535
551
|
if (existing)
|
|
536
|
-
setActiveFromEntry(existing, false);
|
|
552
|
+
await setActiveFromEntry(existing, false);
|
|
537
553
|
return;
|
|
538
554
|
}
|
|
539
555
|
if (existing) {
|
|
540
556
|
healthy = true;
|
|
557
|
+
checkedAt = Date.now();
|
|
541
558
|
hasBeenReady = true;
|
|
542
|
-
setActiveFromEntry(existing, false);
|
|
559
|
+
await setActiveFromEntry(existing, false);
|
|
543
560
|
options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${existing.record.pid}, 端口: ${existing.record.port})`);
|
|
561
|
+
settleInitialHealth?.('ok');
|
|
544
562
|
}
|
|
545
563
|
else {
|
|
564
|
+
settleInitialHealth?.phase?.('running');
|
|
546
565
|
failureCount = failureThreshold;
|
|
547
566
|
launchRequested = 'manual';
|
|
548
567
|
await check();
|
|
@@ -563,6 +582,8 @@ export function createEcwebSupervisor(options) {
|
|
|
563
582
|
desiredEnabled = config.enabled;
|
|
564
583
|
desiredPort = config.port;
|
|
565
584
|
runtimeMode = nextMode;
|
|
585
|
+
if (!desiredEnabled || runtimeMode !== 'managed')
|
|
586
|
+
settleInitialHealth?.('skipped');
|
|
566
587
|
restartConfig = config.restart;
|
|
567
588
|
healthConfig = config.health;
|
|
568
589
|
failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
|
|
@@ -582,6 +603,7 @@ export function createEcwebSupervisor(options) {
|
|
|
582
603
|
child = null;
|
|
583
604
|
active = null;
|
|
584
605
|
healthy = false;
|
|
606
|
+
checkedAt = undefined;
|
|
585
607
|
}
|
|
586
608
|
else if (enabledChanged || portChanged || modeChanged) {
|
|
587
609
|
await killActive();
|
|
@@ -604,7 +626,10 @@ export function createEcwebSupervisor(options) {
|
|
|
604
626
|
return {
|
|
605
627
|
start() {
|
|
606
628
|
if (!startup)
|
|
607
|
-
startup = start()
|
|
629
|
+
startup = start().catch(error => {
|
|
630
|
+
settleInitialHealth?.('failed');
|
|
631
|
+
throw error;
|
|
632
|
+
});
|
|
608
633
|
return startup;
|
|
609
634
|
},
|
|
610
635
|
configure(config) {
|
|
@@ -619,16 +644,23 @@ export function createEcwebSupervisor(options) {
|
|
|
619
644
|
await restart();
|
|
620
645
|
},
|
|
621
646
|
status() {
|
|
622
|
-
|
|
647
|
+
// Report the latest supervised state; status reads must not run tasklist.
|
|
648
|
+
const running = active !== null;
|
|
623
649
|
const ready = running && healthy && active.port === desiredPort;
|
|
650
|
+
const health = desiredEnabled && runtimeMode === 'managed' && checkedAt !== undefined ? healthy : null;
|
|
624
651
|
return {
|
|
625
652
|
enabled: desiredEnabled,
|
|
626
653
|
port: desiredPort,
|
|
627
654
|
state: !desiredEnabled ? 'disabled' : ready ? 'ready' : failureCount >= failureThreshold ? 'failed' : 'starting',
|
|
655
|
+
healthy: health,
|
|
656
|
+
hasProbe: runtimeMode === 'managed',
|
|
657
|
+
endpointHealth: health === null ? 'unknown' : health ? 'healthy' : 'unhealthy',
|
|
658
|
+
...(health === null ? {} : { checkedAt }),
|
|
628
659
|
...(running ? { pid: active.pid } : {}),
|
|
629
660
|
};
|
|
630
661
|
},
|
|
631
662
|
stop(onTiming) {
|
|
663
|
+
settleInitialHealth?.('cancelled');
|
|
632
664
|
if (onTiming) {
|
|
633
665
|
stopTimingListeners.add(onTiming);
|
|
634
666
|
for (const timing of completedStopTimings) {
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { AID_PATTERN } from './validation.js';
|
|
4
|
+
function aid(value) {
|
|
5
|
+
return typeof value === 'string' && AID_PATTERN.test(value) ? value : undefined;
|
|
6
|
+
}
|
|
7
|
+
function identityAid(value) {
|
|
8
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
9
|
+
return undefined;
|
|
10
|
+
return aid(value.aid);
|
|
11
|
+
}
|
|
12
|
+
function readContactSnapshot(agentDir, selfAid) {
|
|
13
|
+
let raw;
|
|
14
|
+
try {
|
|
15
|
+
raw = JSON.parse(fs.readFileSync(path.join(agentDir, 'directory', 'contacts.json'), 'utf8'));
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
return { error: error instanceof Error && 'code' in error && error.code === 'ENOENT' ? 'contacts_snapshot_missing' : 'contacts_snapshot_unreadable' };
|
|
19
|
+
}
|
|
20
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
21
|
+
return { error: 'contacts_snapshot_invalid' };
|
|
22
|
+
const record = raw;
|
|
23
|
+
const entries = [];
|
|
24
|
+
if (Array.isArray(record.entries)) {
|
|
25
|
+
for (const item of record.entries) {
|
|
26
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
27
|
+
continue;
|
|
28
|
+
const value = item;
|
|
29
|
+
const entryAid = aid(value.aid);
|
|
30
|
+
if (!entryAid)
|
|
31
|
+
continue;
|
|
32
|
+
const scopeRaw = value.agent_scope;
|
|
33
|
+
const agentScope = scopeRaw && typeof scopeRaw === 'object' && !Array.isArray(scopeRaw)
|
|
34
|
+
? { mode: scopeRaw.mode, agentAids: scopeRaw.agent_aids }
|
|
35
|
+
: undefined;
|
|
36
|
+
entries.push({ aid: entryAid, ...(agentScope ? { agentScope } : {}) });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const blocked = new Set();
|
|
40
|
+
const blockedRaw = record.blocked_aids ?? record.blockedAids;
|
|
41
|
+
if (Array.isArray(blockedRaw)) {
|
|
42
|
+
for (const item of blockedRaw) {
|
|
43
|
+
const blockedAid = typeof item === 'string'
|
|
44
|
+
? aid(item)
|
|
45
|
+
: item && typeof item === 'object' && !Array.isArray(item) ? aid(item.target_id) : undefined;
|
|
46
|
+
if (blockedAid)
|
|
47
|
+
blocked.add(blockedAid);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const owner = identityAid(record.owner);
|
|
51
|
+
const personalAssistant = identityAid(record.personal_assistant);
|
|
52
|
+
if (!owner && entries.length === 0 && !personalAssistant)
|
|
53
|
+
return { error: 'contacts_snapshot_empty' };
|
|
54
|
+
return { owner, personalAssistant, entries, blocked };
|
|
55
|
+
}
|
|
56
|
+
function admittedAids(snapshot, selfAid) {
|
|
57
|
+
const result = new Set();
|
|
58
|
+
for (const candidate of [selfAid, snapshot.owner, snapshot.personalAssistant]) {
|
|
59
|
+
// The current contact admission treats the local Agent and the resolved
|
|
60
|
+
// Owner identity as always reachable; event deny rules can still narrow them.
|
|
61
|
+
if (candidate)
|
|
62
|
+
result.add(candidate);
|
|
63
|
+
}
|
|
64
|
+
for (const entry of snapshot.entries) {
|
|
65
|
+
if (snapshot.blocked.has(entry.aid))
|
|
66
|
+
continue;
|
|
67
|
+
if (entry.agentScope?.mode === 'selected') {
|
|
68
|
+
const selected = Array.isArray(entry.agentScope.agentAids) ? entry.agentScope.agentAids : [];
|
|
69
|
+
if (!selected.includes(selfAid))
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
result.add(entry.aid);
|
|
73
|
+
}
|
|
74
|
+
return [...result].sort();
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Materialize the SDK allowlist from the current contacts snapshot. Empty
|
|
78
|
+
* event allow rules mean the contact admission set; a non-empty rule narrows
|
|
79
|
+
* that set. Deny always wins. Temporary grants and other authorization stores
|
|
80
|
+
* are deliberately not consulted here.
|
|
81
|
+
*/
|
|
82
|
+
export function materializeAllowlist(config, agentDir, selfAid, registeredEvents) {
|
|
83
|
+
const snapshot = readContactSnapshot(agentDir, selfAid);
|
|
84
|
+
if ('error' in snapshot) {
|
|
85
|
+
return { allowlist: explicitAllowlist(config), degraded: true, admittedAids: [], reason: snapshot.error };
|
|
86
|
+
}
|
|
87
|
+
const base = new Set(admittedAids(snapshot, selfAid));
|
|
88
|
+
const allowlist = {};
|
|
89
|
+
const events = registeredEvents === undefined
|
|
90
|
+
? Object.keys(config.allowlist)
|
|
91
|
+
: [...new Set(registeredEvents)];
|
|
92
|
+
for (const event of events) {
|
|
93
|
+
const entry = config.allowlist[event] ?? {
|
|
94
|
+
allow: { publish: [], subscribe: [] },
|
|
95
|
+
deny: { publish: [], subscribe: [] },
|
|
96
|
+
};
|
|
97
|
+
const publishAllow = entry.allow.publish.length > 0 ? entry.allow.publish : [...base];
|
|
98
|
+
const subscribeAllow = entry.allow.subscribe.length > 0 ? entry.allow.subscribe : [...base];
|
|
99
|
+
const publish = publishAllow.filter(candidate => base.has(candidate) && !entry.deny.publish.includes(candidate));
|
|
100
|
+
const subscribe = subscribeAllow.filter(candidate => base.has(candidate) && !entry.deny.subscribe.includes(candidate));
|
|
101
|
+
allowlist[event] = { publish_aids: [...new Set(publish)].sort(), subscribe_aids: [...new Set(subscribe)].sort() };
|
|
102
|
+
}
|
|
103
|
+
return { allowlist, degraded: false, admittedAids: [...base] };
|
|
104
|
+
}
|
|
105
|
+
function explicitAllowlist(config) {
|
|
106
|
+
const result = {};
|
|
107
|
+
for (const [event, entry] of Object.entries(config.allowlist)) {
|
|
108
|
+
result[event] = {
|
|
109
|
+
publish_aids: entry.allow.publish.filter(aid => !entry.deny.publish.includes(aid)),
|
|
110
|
+
subscribe_aids: entry.allow.subscribe.filter(aid => !entry.deny.subscribe.includes(aid)),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
const facadeGates = new WeakMap();
|
|
2
|
+
const coreGates = new WeakMap();
|
|
3
|
+
/** Wrap the SDK's remote request handler when its runtime service map is available. */
|
|
4
|
+
export function installEventBusRequestGate(facadeValue, busAid, gate) {
|
|
5
|
+
if (!facadeValue || typeof facadeValue !== 'object')
|
|
6
|
+
return false;
|
|
7
|
+
const facade = facadeValue;
|
|
8
|
+
if (typeof facade.start !== 'function' || !(facade.buses instanceof Map))
|
|
9
|
+
return false;
|
|
10
|
+
let state = facadeGates.get(facade);
|
|
11
|
+
if (!state) {
|
|
12
|
+
const originalStart = facade.start;
|
|
13
|
+
state = { originalStart, gates: new Map() };
|
|
14
|
+
facadeGates.set(facade, state);
|
|
15
|
+
facade.start = function (...args) {
|
|
16
|
+
const started = state.originalStart.apply(this, args);
|
|
17
|
+
const aid = typeof args[0] === 'string' ? args[0] : '';
|
|
18
|
+
const nextGate = state.gates.get(aid);
|
|
19
|
+
if (aid && nextGate)
|
|
20
|
+
installCoreGate(this.buses?.get(aid)?.service, nextGate);
|
|
21
|
+
return started;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
state.gates.set(busAid, gate);
|
|
25
|
+
return installCoreGate(facade.buses.get(busAid)?.service, gate);
|
|
26
|
+
}
|
|
27
|
+
function installCoreGate(service, gate) {
|
|
28
|
+
if (!service || typeof service.handle !== 'function')
|
|
29
|
+
return false;
|
|
30
|
+
const existing = coreGates.get(service);
|
|
31
|
+
if (existing) {
|
|
32
|
+
existing.gate = gate;
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
const originalHandle = service.handle;
|
|
36
|
+
const state = { originalHandle, gate };
|
|
37
|
+
coreGates.set(service, state);
|
|
38
|
+
service.handle = async function (senderAid, request, ...rest) {
|
|
39
|
+
await state.gate(senderAid, request, this);
|
|
40
|
+
return state.originalHandle.call(this, senderAid, request, ...rest);
|
|
41
|
+
};
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
export function evaluateEventBusRequest(senderAid, request, materialized, service) {
|
|
45
|
+
const operation = typeof request.op === 'string' ? request.op : 'unknown';
|
|
46
|
+
const deny = (reason, event, action) => ({
|
|
47
|
+
allowed: false, operation, reason, ...(event ? { event } : {}), ...(action ? { action } : {}),
|
|
48
|
+
});
|
|
49
|
+
const admitted = new Set(materialized.admittedAids);
|
|
50
|
+
if (operation === 'unsubscribe')
|
|
51
|
+
return { allowed: true, operation };
|
|
52
|
+
if (operation === 'catalog' || operation === 'stats') {
|
|
53
|
+
return admitted.has(senderAid) ? { allowed: true, operation } : deny('contact_admission');
|
|
54
|
+
}
|
|
55
|
+
if (operation === 'publish') {
|
|
56
|
+
const event = typeof request.event_name === 'string' ? request.event_name : undefined;
|
|
57
|
+
if (!event)
|
|
58
|
+
return { allowed: true, operation };
|
|
59
|
+
return isAllowed(materialized, event, 'publish', senderAid)
|
|
60
|
+
? { allowed: true, operation, action: 'publish', event }
|
|
61
|
+
: deny('event_rule', event, 'publish');
|
|
62
|
+
}
|
|
63
|
+
if (operation === 'authorize') {
|
|
64
|
+
if (request.auth_mode !== undefined && request.auth_mode !== 'allowlist')
|
|
65
|
+
return deny('unsupported_auth_mode');
|
|
66
|
+
const scope = requestScope(request);
|
|
67
|
+
if (!scope)
|
|
68
|
+
return { allowed: true, operation };
|
|
69
|
+
for (const item of scope) {
|
|
70
|
+
if (!isAllowed(materialized, item.event, item.action, senderAid))
|
|
71
|
+
return deny('event_rule', item.event, item.action);
|
|
72
|
+
}
|
|
73
|
+
return { allowed: true, operation };
|
|
74
|
+
}
|
|
75
|
+
if (operation === 'subscribe') {
|
|
76
|
+
const events = stringList(request.events);
|
|
77
|
+
if (!events)
|
|
78
|
+
return { allowed: true, operation };
|
|
79
|
+
for (const event of events) {
|
|
80
|
+
if (!isAllowed(materialized, event, 'subscribe', senderAid))
|
|
81
|
+
return deny('event_rule', event, 'subscribe');
|
|
82
|
+
}
|
|
83
|
+
return { allowed: true, operation };
|
|
84
|
+
}
|
|
85
|
+
if (operation === 'renew') {
|
|
86
|
+
const leaseId = typeof request.lease_id === 'string' ? request.lease_id : '';
|
|
87
|
+
const leases = service?.leases;
|
|
88
|
+
const lease = leaseId ? leases?.get(leaseId) : undefined;
|
|
89
|
+
if (!admitted.has(senderAid))
|
|
90
|
+
return deny('contact_admission');
|
|
91
|
+
if (!lease?.scope)
|
|
92
|
+
return { allowed: true, operation };
|
|
93
|
+
if (lease.aid !== senderAid || lease.auth_mode === 'credential')
|
|
94
|
+
return deny('lease_scope');
|
|
95
|
+
for (const item of lease.scope) {
|
|
96
|
+
if ((item.action !== 'publish' && item.action !== 'subscribe')
|
|
97
|
+
|| typeof item.event_name !== 'string'
|
|
98
|
+
|| !isAllowed(materialized, item.event_name, item.action, senderAid)) {
|
|
99
|
+
return deny('event_rule', item.event_name, item.action === 'publish' || item.action === 'subscribe' ? item.action : undefined);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return { allowed: true, operation };
|
|
103
|
+
}
|
|
104
|
+
return deny('unsupported_operation');
|
|
105
|
+
}
|
|
106
|
+
function isAllowed(materialized, event, action, aid) {
|
|
107
|
+
const entry = materialized.allowlist[event];
|
|
108
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
109
|
+
return false;
|
|
110
|
+
const list = entry[action === 'publish' ? 'publish_aids' : 'subscribe_aids'];
|
|
111
|
+
return Array.isArray(list) && list.includes(aid);
|
|
112
|
+
}
|
|
113
|
+
function stringList(value) {
|
|
114
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string'))
|
|
115
|
+
return undefined;
|
|
116
|
+
return value;
|
|
117
|
+
}
|
|
118
|
+
function requestScope(request) {
|
|
119
|
+
if (Array.isArray(request.scope)) {
|
|
120
|
+
const scope = [];
|
|
121
|
+
for (const value of request.scope) {
|
|
122
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
123
|
+
return undefined;
|
|
124
|
+
const item = value;
|
|
125
|
+
if (typeof item.event_name !== 'string' || (item.action !== 'publish' && item.action !== 'subscribe'))
|
|
126
|
+
return undefined;
|
|
127
|
+
scope.push({ event: item.event_name, action: item.action });
|
|
128
|
+
}
|
|
129
|
+
return scope.length ? scope : undefined;
|
|
130
|
+
}
|
|
131
|
+
const events = stringList(request.events);
|
|
132
|
+
const actions = stringList(request.actions);
|
|
133
|
+
if (!events || !actions || actions.some(action => action !== 'publish' && action !== 'subscribe'))
|
|
134
|
+
return undefined;
|
|
135
|
+
return events.flatMap(event => actions.map(action => ({ event, action: action })));
|
|
136
|
+
}
|