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.
- package/CHANGELOG.md +95 -0
- package/bin/ecmsg.js +188 -58
- package/dist/agent-template/jobs.js +62 -0
- package/dist/agent-template/runtime.js +214 -0
- package/dist/agent-template/service.js +465 -0
- package/dist/agent-template/tool-runner.js +45 -0
- package/dist/agent-template/types.js +5 -0
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/claude-runner.js +1 -1
- package/dist/agents/codex/app-server-client.js +22 -0
- package/dist/agents/codex-runner.js +69 -2
- package/dist/aun/aid/agentmd.js +56 -1
- package/dist/aun/aid/client.js +3 -1
- package/dist/aun/menu/client.js +3 -2
- package/dist/aun/msg/p2p.js +6 -1
- package/dist/channels/aun.js +277 -49
- package/dist/cli/agent-command.js +5 -0
- package/dist/cli/agent-create.js +7 -3
- package/dist/cli/agent-template.js +124 -0
- package/dist/cli/aun-commands.js +2 -2
- package/dist/cli/ctl-command.js +2 -1
- package/dist/cli/daemon-commands.js +11 -66
- package/dist/cli/daemon-lifecycle-client.js +61 -0
- package/dist/cli/ecmsg-gateway.js +35 -2
- package/dist/cli/events-command.js +109 -0
- package/dist/cli/index.js +60 -14
- package/dist/cli/invoke-command.js +182 -0
- package/dist/cli/managed-command-guard.js +6 -1
- package/dist/cli/net-check.js +1 -1
- package/dist/cli/restart-monitor.js +160 -83
- package/dist/cli/services-command.js +137 -0
- package/dist/cli/team-workspace-command.js +134 -0
- package/dist/cli/thread-command.js +103 -13
- package/dist/cli/watch-msg.js +1 -1
- package/dist/config/boot-log.js +8 -8
- 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 +45 -15
- package/dist/config-store.js +2 -1
- package/dist/core/agent-ipc-registration.js +25 -4
- package/dist/core/agent-reload-coordinator.js +6 -4
- package/dist/core/agent-runtime.js +106 -10
- package/dist/core/auth/delegation-authorization.js +66 -0
- package/dist/core/auth/operation-authorizer.js +2 -0
- package/dist/core/auth/operation-catalog.js +29 -0
- package/dist/core/baseagent-loader.js +60 -130
- package/dist/core/channel-loader.js +10 -1
- package/dist/core/channel-runtime.js +20 -12
- package/dist/core/command/agent-control.js +12 -2
- package/dist/core/command/agent-storage-menu.js +1 -1
- package/dist/core/command/agent-template-menu.js +147 -0
- package/dist/core/command/chatmode-config.js +2 -36
- package/dist/core/command/command-handler.js +80 -17
- package/dist/core/command/data-root-resolver.js +32 -23
- package/dist/core/command/eventcenter-menu.js +468 -0
- package/dist/core/command/menu-catalog.js +15 -0
- package/dist/core/command/menu-handler.js +216 -90
- package/dist/core/command/menu-protocol.js +71 -13
- 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 +22 -5
- package/dist/core/daemon-lifecycle.js +323 -191
- package/dist/core/handoff/runtime.js +45 -13
- 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 +50 -7
- package/dist/core/legacy-rename.js +41 -0
- package/dist/core/memory/consolidation.js +7 -5
- package/dist/core/message/aun-ipc-sender.js +252 -17
- package/dist/core/message/im-renderer.js +116 -85
- package/dist/core/message/message-bridge.js +4 -0
- package/dist/core/message/message-queue.js +66 -15
- 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 +29 -5
- package/dist/core/message/response-engine.js +194 -61
- package/dist/core/message/send-options.js +7 -4
- package/dist/core/message/send-routing.js +50 -5
- package/dist/core/ownership/owner-resolver.js +7 -0
- package/dist/core/pack-auth.js +94 -0
- package/dist/core/pack-install.js +194 -0
- package/dist/core/permission/ec-command-parser.js +51 -17
- package/dist/core/permission/protected-paths.js +12 -2
- package/dist/core/permission/shell-environment.js +9 -0
- package/dist/core/rate-window.js +48 -0
- package/dist/core/relation/peer-identity.js +28 -0
- package/dist/core/session/session-file-health.js +243 -0
- package/dist/core/session/session-fs-store.js +67 -28
- package/dist/core/session/session-idle-monitor.js +59 -19
- package/dist/core/session/session-manager.js +13 -4
- 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/core/thread/thread-service.js +52 -3
- 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/eck/message-renderer.js +2 -0
- 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 +124 -0
- package/dist/event-center/bus-gate.js +154 -0
- package/dist/event-center/bus-host.js +307 -0
- package/dist/event-center/bus-resolver.js +120 -0
- package/dist/event-center/center-config.js +127 -0
- package/dist/event-center/daemon.js +44 -0
- package/dist/event-center/directory-source.js +55 -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 +73 -0
- package/dist/event-center/ipc-operation.js +423 -0
- package/dist/event-center/ledger.js +52 -0
- package/dist/event-center/pack-loader.js +207 -0
- package/dist/event-center/pack-manager.js +85 -0
- package/dist/event-center/registry.js +463 -0
- package/dist/event-center/runtime.js +837 -0
- package/dist/event-center/script-runner.js +356 -0
- package/dist/event-center/types.js +51 -0
- package/dist/event-center/validation.js +435 -0
- package/dist/index.js +424 -135
- package/dist/ipc.js +106 -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/engines/v1/proactive-flow.js +4 -2
- 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 +550 -0
- package/dist/services/ledger.js +52 -0
- package/dist/services/message-log.js +112 -0
- package/dist/services/pack-manager.js +215 -0
- package/dist/services/reply.js +55 -0
- package/dist/services/router.js +98 -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/scheduler.js +38 -0
- package/dist/trigger/script-sandbox.js +170 -24
- 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/npm-ops.js +2 -1
- package/dist/utils/package-version-info.js +6 -3
- 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 +9 -15
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +3 -1
- package/kits/docs/evolcore/ability.md +4 -0
- package/kits/docs/evolcore/agent.md +22 -1
- package/kits/docs/evolcore/aid.md +1 -1
- package/kits/docs/evolcore/event-center.md +227 -0
- package/kits/docs/evolcore/file-navigation.md +10 -264
- package/kits/docs/evolcore/fs.md +5 -3
- package/kits/docs/evolcore/group.md +1 -1
- package/kits/docs/evolcore/memory-architecture.md +2 -0
- package/kits/docs/evolcore/menu-protocol.md +28 -1
- package/kits/docs/evolcore/msg.md +21 -9
- package/kits/docs/evolcore/provider.md +3 -1
- package/kits/docs/evolcore/response.md +5 -5
- package/kits/docs/evolcore/services.md +294 -0
- package/kits/docs/evolcore/task.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +41 -0
- package/kits/docs/evolcore/thread-chain.md +15 -3
- package/kits/eck_manifest.json +26 -0
- package/kits/rules/02-navigation.md +10 -1
- package/kits/rules/06-channel.md +1 -0
- 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-group/SKILL.md +5 -8
- 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/message-fragments/item.md +1 -1
- 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 +1 -5
- package/kits/templates/system-fragments/thread.md +13 -10
- package/package.json +5 -6
- package/scripts/agent-template/index.mjs +40 -0
- package/scripts/agent-template/inspect.mjs +240 -0
- package/scripts/agent-template/overlay.mjs +71 -0
- package/scripts/agent-template/pack.mjs +169 -0
- package/scripts/agent-template/shared/common.mjs +235 -0
- package/scripts/agent-template/shared/evolcore.mjs +75 -0
- package/scripts/agent-template/shared/plan.mjs +129 -0
- package/scripts/agent-template/shared/team-schema.json +70 -0
- package/scripts/agent-template/shared/template-contract.mjs +154 -0
- package/scripts/agent-template/shared/template-package.mjs +265 -0
- package/scripts/agent-template/shared/template-runtime.mjs +80 -0
- package/scripts/agent-template/shared/template.mjs +142 -0
- 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,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 单个 agent 的事件中心 Bus 宿主:复用 agent 主 AUN 连接(消息连接)上的
|
|
3
|
+
* fastaun EventService `bus` 角色。0.5.34 起同一 client 可在同 Bus 上多角色绑定,
|
|
4
|
+
* 不再需要专用 slot 连接;BusHost 只拥有 bus 绑定的生命周期,不拥有连接本身。
|
|
5
|
+
* 配置源是事件包合并目录 + events-config.json 的 rules。
|
|
6
|
+
* - apply(config):写路径(events-config.json 变更/rules 变更),成功 ⇒ running;失败抛错且配置不变。
|
|
7
|
+
* - ensureRunning(config):生命周期入口,失败转后台自愈(指数退避,DEVICE_CONFLICT 固定间隔)。
|
|
8
|
+
* - SDK 失租后 binding 自行关闭且门面不感知,用定时探测兜底。
|
|
9
|
+
*/
|
|
10
|
+
import { logger } from '../utils/logger.js';
|
|
11
|
+
import { EventCenterError, errorCode, errorMessage, } from './types.js';
|
|
12
|
+
import { installEventBusRequestGate } from './bus-gate.js';
|
|
13
|
+
function withTimeout(promise, ms, code) {
|
|
14
|
+
let timer;
|
|
15
|
+
return Promise.race([
|
|
16
|
+
promise,
|
|
17
|
+
new Promise((_, reject) => {
|
|
18
|
+
timer = setTimeout(() => reject(new EventCenterError(code, `timed out after ${ms}ms`)), ms);
|
|
19
|
+
timer.unref?.();
|
|
20
|
+
}),
|
|
21
|
+
]).finally(() => { if (timer)
|
|
22
|
+
clearTimeout(timer); });
|
|
23
|
+
}
|
|
24
|
+
export class BusHost {
|
|
25
|
+
options;
|
|
26
|
+
/** agent 主 client 引用(不拥有;stopInner 只关 bus 绑定,不关连接)。 */
|
|
27
|
+
handle;
|
|
28
|
+
statusValue = 'stopped';
|
|
29
|
+
detail = null;
|
|
30
|
+
config;
|
|
31
|
+
probeTimer;
|
|
32
|
+
retryTimer;
|
|
33
|
+
retryDelay = 0;
|
|
34
|
+
generation = 0;
|
|
35
|
+
op = Promise.resolve();
|
|
36
|
+
closed = false;
|
|
37
|
+
gateInstalledValue = false;
|
|
38
|
+
constructor(options) {
|
|
39
|
+
this.options = options;
|
|
40
|
+
}
|
|
41
|
+
get status() { return this.statusValue; }
|
|
42
|
+
get statusDetail() { return this.detail; }
|
|
43
|
+
get gateInstalled() { return this.gateInstalledValue; }
|
|
44
|
+
/** Retry capability detection without restarting the Bus. */
|
|
45
|
+
refreshGate() {
|
|
46
|
+
if (!this.options.requestGate || !this.handle)
|
|
47
|
+
return false;
|
|
48
|
+
this.gateInstalledValue = installEventBusRequestGate(this.handle.EventService, this.options.aid, this.options.requestGate);
|
|
49
|
+
return this.gateInstalledValue;
|
|
50
|
+
}
|
|
51
|
+
/** 串行化所有生命周期操作。 */
|
|
52
|
+
serial(action) {
|
|
53
|
+
const next = this.op.then(action, action);
|
|
54
|
+
this.op = next.catch(() => { });
|
|
55
|
+
return next;
|
|
56
|
+
}
|
|
57
|
+
setStatus(status, detail = null) {
|
|
58
|
+
const from = this.statusValue;
|
|
59
|
+
const changed = from !== status;
|
|
60
|
+
if (changed || this.detail !== detail) {
|
|
61
|
+
logger.info(`[EventCenter] ${this.options.aid} bus ${from} → ${status}${detail ? ` (${detail})` : ''}`);
|
|
62
|
+
}
|
|
63
|
+
this.statusValue = status;
|
|
64
|
+
this.detail = detail;
|
|
65
|
+
// 只在真正迁移时通知:starting→stopped 这类中间态由调用方自行决定要不要记。
|
|
66
|
+
if (changed) {
|
|
67
|
+
try {
|
|
68
|
+
this.options.onTransition?.({ from, to: status, ...(detail ? { detail } : {}) });
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
logger.warn(`[EventCenter] ${this.options.aid} bus transition hook failed: ${errorMessage(error)}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** 写路径:同步生效或失败(失败不改变当前运行配置)。 */
|
|
76
|
+
apply(config) {
|
|
77
|
+
return this.serial(async () => {
|
|
78
|
+
if (this.closed)
|
|
79
|
+
throw new EventCenterError('BUS_UNAVAILABLE', 'event center bus host is closed');
|
|
80
|
+
if (!config || Object.keys(config.catalog).length === 0) {
|
|
81
|
+
await this.stopInner();
|
|
82
|
+
this.config = undefined;
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (this.statusValue === 'running' && this.handle) {
|
|
86
|
+
await this.handle.EventService.updateConfig(this.options.aid, config);
|
|
87
|
+
this.config = config;
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
// 未运行(stopped / 自愈中):同步启动一次,成功后接管。
|
|
91
|
+
this.clearRetry();
|
|
92
|
+
await this.startInner(config, true);
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** 生命周期入口:失败转后台自愈。 */
|
|
96
|
+
ensureRunning(config) {
|
|
97
|
+
return this.serial(async () => {
|
|
98
|
+
// close() 置 closed 是为了让调用方显式停用;但 EventRuntime.close() 之后
|
|
99
|
+
// 同一个 BusHost 实例会被 reload 复用(registry.reload = remove + ensureStarted)。
|
|
100
|
+
// 不在这里复位,reload 后 Bus 永远起不来,且重试链被 closed 短路,
|
|
101
|
+
// 表现为 publish/subscribe 都在、Bus 却停在 stopped/conflict。
|
|
102
|
+
if (this.closed) {
|
|
103
|
+
this.closed = false;
|
|
104
|
+
this.generation++;
|
|
105
|
+
}
|
|
106
|
+
this.config = config;
|
|
107
|
+
if (this.statusValue === 'running')
|
|
108
|
+
return;
|
|
109
|
+
try {
|
|
110
|
+
await this.startInner(config, false);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
this.scheduleRetry(error);
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
async stats(params = {}) {
|
|
118
|
+
if (this.statusValue !== 'running' || !this.handle)
|
|
119
|
+
return null;
|
|
120
|
+
return await this.handle.EventService.stats(this.options.aid, params);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The SDK currently exposes subscriber counts through stats but not the AID
|
|
124
|
+
* list. Read the in-process service snapshot when the SDK facade exposes it;
|
|
125
|
+
* callers must handle unavailable as a normal capability result.
|
|
126
|
+
*/
|
|
127
|
+
subscribers() {
|
|
128
|
+
if (this.statusValue !== 'running' || !this.handle)
|
|
129
|
+
return { available: false, subscribers: [], reason: 'bus_not_running' };
|
|
130
|
+
const facade = this.handle.EventService;
|
|
131
|
+
const service = facade.buses?.get?.(this.options.aid)?.service;
|
|
132
|
+
if (!service?.subscriptions)
|
|
133
|
+
return { available: false, subscribers: [], reason: 'sdk_subscriber_details_unavailable' };
|
|
134
|
+
try {
|
|
135
|
+
service.pruneSubscriptions?.();
|
|
136
|
+
}
|
|
137
|
+
catch { /* stats remains usable if pruning is private/unavailable */ }
|
|
138
|
+
const subscribers = [];
|
|
139
|
+
for (const sub of service.subscriptions.values()) {
|
|
140
|
+
const aid = typeof sub.aid === 'string' ? sub.aid : '';
|
|
141
|
+
const event = typeof sub.event === 'string' ? sub.event : '';
|
|
142
|
+
if (!aid || !event)
|
|
143
|
+
continue;
|
|
144
|
+
const lease = typeof sub.leaseId === 'string' ? service.leases?.get(sub.leaseId) : undefined;
|
|
145
|
+
const expiresAt = typeof lease?.expires_at === 'number' ? lease.expires_at : undefined;
|
|
146
|
+
subscribers.push({ aid, event, ...(typeof sub.leaseId === 'string' ? { leaseId: sub.leaseId } : {}), ...(expiresAt !== undefined ? { expiresAt } : {}), active: expiresAt === undefined || expiresAt > Date.now() });
|
|
147
|
+
}
|
|
148
|
+
subscribers.sort((a, b) => a.event.localeCompare(b.event) || a.aid.localeCompare(b.aid));
|
|
149
|
+
return { available: true, subscribers };
|
|
150
|
+
}
|
|
151
|
+
stop() {
|
|
152
|
+
return this.serial(async () => {
|
|
153
|
+
await this.stopInner();
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
async close() {
|
|
157
|
+
this.closed = true;
|
|
158
|
+
await this.stop();
|
|
159
|
+
}
|
|
160
|
+
async startInner(config, strict) {
|
|
161
|
+
const generation = ++this.generation;
|
|
162
|
+
const previousStatus = this.statusValue;
|
|
163
|
+
const previousDetail = this.detail;
|
|
164
|
+
this.setStatus('starting');
|
|
165
|
+
const aid = this.options.aid;
|
|
166
|
+
try {
|
|
167
|
+
await withTimeout((async () => {
|
|
168
|
+
if (!this.handle) {
|
|
169
|
+
const client = await this.options.getClient(aid);
|
|
170
|
+
if (!client) {
|
|
171
|
+
throw new EventCenterError('BUS_UNAVAILABLE', 'agent AUN client unavailable (channel not ready)');
|
|
172
|
+
}
|
|
173
|
+
this.handle = client;
|
|
174
|
+
}
|
|
175
|
+
const service = this.handle.EventService;
|
|
176
|
+
// 配置唯一真源是包目录 + events-config.json;SDK state.load 会覆盖 start 参数,因此 load 返回同一份配置。
|
|
177
|
+
const current = this.config ?? config;
|
|
178
|
+
// 这里只**登记** gate(把拦截器挂进 facade.start 的包装器),不更新
|
|
179
|
+
// gateInstalledValue:此刻 SDK 的 buses 映射还是空的,包不住 handle,
|
|
180
|
+
// 必然返回 false。若把它当结果上报,每次启动都会先记一条假的
|
|
181
|
+
// gate.degraded。真正的结果看 start() 之后那次 refreshGate()。
|
|
182
|
+
this.options.requestGate && installEventBusRequestGate(service, aid, this.options.requestGate);
|
|
183
|
+
await service.start(aid, {
|
|
184
|
+
catalog: current.catalog,
|
|
185
|
+
allowlist: current.allowlist,
|
|
186
|
+
state: {
|
|
187
|
+
load: () => ({ service_aid: aid, catalog: current.catalog, allowlist: current.allowlist, issued_grants: [], paused_cids: [] }),
|
|
188
|
+
save: () => { },
|
|
189
|
+
},
|
|
190
|
+
});
|
|
191
|
+
this.refreshGate();
|
|
192
|
+
await service.updateConfig(aid, config);
|
|
193
|
+
})(), this.options.startTimeoutMs ?? 10_000, 'BUS_UNAVAILABLE');
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
if (generation === this.generation) {
|
|
197
|
+
await this.releaseClient();
|
|
198
|
+
const code = errorCode(error);
|
|
199
|
+
const conflict = code === 'DEVICE_CONFLICT';
|
|
200
|
+
if (strict) {
|
|
201
|
+
this.setStatus(previousStatus === 'starting' ? 'stopped' : previousStatus, previousDetail);
|
|
202
|
+
if (previousStatus !== 'running' && previousStatus !== 'stopped')
|
|
203
|
+
this.scheduleRetry(error);
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
this.setStatus(conflict ? 'conflict' : 'error', `${code}: ${errorMessage(error)}`);
|
|
207
|
+
}
|
|
208
|
+
throw new EventCenterError(conflict ? 'BUS_CONFLICT' : 'BUS_UNAVAILABLE', conflict ? 'another instance of this agent already hosts the event bus' : `event bus unavailable: ${errorMessage(error)}`, { retryable: !conflict });
|
|
209
|
+
}
|
|
210
|
+
throw error;
|
|
211
|
+
}
|
|
212
|
+
this.config = config;
|
|
213
|
+
this.retryDelay = 0;
|
|
214
|
+
this.setStatus('running');
|
|
215
|
+
this.startProbe();
|
|
216
|
+
}
|
|
217
|
+
async stopInner() {
|
|
218
|
+
this.generation++;
|
|
219
|
+
this.clearRetry();
|
|
220
|
+
this.stopProbe();
|
|
221
|
+
if (this.handle && (this.statusValue === 'running' || this.statusValue === 'lease_lost')) {
|
|
222
|
+
const service = this.handle.EventService;
|
|
223
|
+
try {
|
|
224
|
+
await withTimeout(service.drain(this.options.aid), 2_000, 'TIMEOUT');
|
|
225
|
+
}
|
|
226
|
+
catch { }
|
|
227
|
+
// 只关 bus 角色绑定;EventService.close(busAid) 对自有 bus 会连 sub/pub 角色一起关——
|
|
228
|
+
// 主连接归渠道所有,这里绝不能触碰连接本身。同 bus 的 sub/pub(自订阅)由 runtime
|
|
229
|
+
// 的差集基线持有,被连带关闭后靠下一次 reconfigure/reconcile 重建。
|
|
230
|
+
try {
|
|
231
|
+
await service.close(this.options.aid);
|
|
232
|
+
}
|
|
233
|
+
catch { }
|
|
234
|
+
}
|
|
235
|
+
this.releaseClient();
|
|
236
|
+
this.setStatus('stopped');
|
|
237
|
+
}
|
|
238
|
+
releaseClient() {
|
|
239
|
+
this.handle = undefined;
|
|
240
|
+
this.gateInstalledValue = false;
|
|
241
|
+
}
|
|
242
|
+
/** binding 是否仍持有实例租约。优先读 SDK 内部状态,读不到时用 stats 探测。 */
|
|
243
|
+
async leaseAlive() {
|
|
244
|
+
const service = this.handle?.EventService;
|
|
245
|
+
const running = service?.buses?.get?.(this.options.aid)?.binding?.running;
|
|
246
|
+
if (typeof running === 'boolean')
|
|
247
|
+
return running;
|
|
248
|
+
try {
|
|
249
|
+
await this.handle.EventService.stats(this.options.aid, {});
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
startProbe() {
|
|
257
|
+
this.stopProbe();
|
|
258
|
+
const generation = this.generation;
|
|
259
|
+
this.probeTimer = setInterval(() => {
|
|
260
|
+
void this.serial(async () => {
|
|
261
|
+
if (generation !== this.generation || this.statusValue !== 'running' || !this.handle)
|
|
262
|
+
return;
|
|
263
|
+
if (await this.leaseAlive())
|
|
264
|
+
return;
|
|
265
|
+
this.stopProbe();
|
|
266
|
+
this.setStatus('lease_lost', 'SERVICE_LEASE_LOST');
|
|
267
|
+
this.scheduleRetry(new EventCenterError('SERVICE_LEASE_LOST', 'event bus lease lost'));
|
|
268
|
+
});
|
|
269
|
+
}, this.options.probeIntervalMs ?? 15_000);
|
|
270
|
+
this.probeTimer.unref?.();
|
|
271
|
+
}
|
|
272
|
+
stopProbe() {
|
|
273
|
+
if (this.probeTimer)
|
|
274
|
+
clearInterval(this.probeTimer);
|
|
275
|
+
this.probeTimer = undefined;
|
|
276
|
+
}
|
|
277
|
+
clearRetry() {
|
|
278
|
+
if (this.retryTimer)
|
|
279
|
+
clearTimeout(this.retryTimer);
|
|
280
|
+
this.retryTimer = undefined;
|
|
281
|
+
}
|
|
282
|
+
scheduleRetry(error) {
|
|
283
|
+
if (this.closed || !this.config)
|
|
284
|
+
return;
|
|
285
|
+
this.clearRetry();
|
|
286
|
+
const conflict = errorCode(error) === 'DEVICE_CONFLICT' || (error instanceof EventCenterError && error.code === 'BUS_CONFLICT');
|
|
287
|
+
const max = this.options.maxBackoffMs ?? 60_000;
|
|
288
|
+
this.retryDelay = conflict
|
|
289
|
+
? (this.options.conflictRetryMs ?? 60_000)
|
|
290
|
+
: Math.min(max, this.retryDelay ? this.retryDelay * 2 : 1_000);
|
|
291
|
+
const generation = this.generation;
|
|
292
|
+
this.retryTimer = setTimeout(() => {
|
|
293
|
+
this.retryTimer = undefined;
|
|
294
|
+
void this.serial(async () => {
|
|
295
|
+
if (this.closed || generation !== this.generation || this.statusValue === 'running')
|
|
296
|
+
return;
|
|
297
|
+
try {
|
|
298
|
+
await this.startInner(this.config, false);
|
|
299
|
+
}
|
|
300
|
+
catch (retryError) {
|
|
301
|
+
this.scheduleRetry(retryError);
|
|
302
|
+
}
|
|
303
|
+
});
|
|
304
|
+
}, this.retryDelay);
|
|
305
|
+
this.retryTimer.unref?.();
|
|
306
|
+
}
|
|
307
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bus 占位符解析:$self / $owner / $pa / $pa.<role> / 字面 AID。
|
|
3
|
+
* 设计:detailed-design.md §三。$pa.<role> 多匹配取 AID 字典序第一个,不报错、不并发。
|
|
4
|
+
*/
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { atomicWriteJson } from '../utils/atomic-write.js';
|
|
8
|
+
import { AID_PATTERN, ROLE_NAME_PATTERN } from './validation.js';
|
|
9
|
+
export class BusResolveError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code, message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.name = 'BusResolveError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function isBusPlaceholder(ref) {
|
|
18
|
+
return ref === '$self' || ref === '$owner' || ref === '$pa' || ref.startsWith('$pa.');
|
|
19
|
+
}
|
|
20
|
+
/** 解析单个 bus 引用。失败抛 BusResolveError。 */
|
|
21
|
+
export function resolveBusRef(ref, context) {
|
|
22
|
+
if (ref === '$self') {
|
|
23
|
+
if (!context.self)
|
|
24
|
+
throw new BusResolveError('INVALID_AID', '$self resolved to empty AID');
|
|
25
|
+
return context.self;
|
|
26
|
+
}
|
|
27
|
+
if (ref === '$owner') {
|
|
28
|
+
if (!context.owner)
|
|
29
|
+
throw new BusResolveError('OWNER_MISSING', 'this AID has no owner');
|
|
30
|
+
return context.owner;
|
|
31
|
+
}
|
|
32
|
+
if (ref === '$pa') {
|
|
33
|
+
if (!context.pa)
|
|
34
|
+
throw new BusResolveError('PA_MISSING', 'contacts has no personalAssistant/personal_assistant');
|
|
35
|
+
return context.pa;
|
|
36
|
+
}
|
|
37
|
+
if (ref.startsWith('$pa.')) {
|
|
38
|
+
const role = ref.slice('$pa.'.length);
|
|
39
|
+
if (!ROLE_NAME_PATTERN.test(role)) {
|
|
40
|
+
throw new BusResolveError('INVALID_ROLE', `invalid role name: ${role}`);
|
|
41
|
+
}
|
|
42
|
+
const candidates = context.paRoles?.[role];
|
|
43
|
+
if (!candidates || candidates.length === 0) {
|
|
44
|
+
throw new BusResolveError('ROLE_NOT_FOUND', `pa_roles has no role "${role}"`);
|
|
45
|
+
}
|
|
46
|
+
// 多匹配取字典序第一个:同一目录在多个 Agent 上解析结果稳定可复现。
|
|
47
|
+
return [...candidates].sort()[0];
|
|
48
|
+
}
|
|
49
|
+
if (!AID_PATTERN.test(ref)) {
|
|
50
|
+
throw new BusResolveError('INVALID_AID', `invalid literal AID: ${ref}`);
|
|
51
|
+
}
|
|
52
|
+
return ref;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 解析一个包内全部 bus 引用(publish + subscribe 去重)。
|
|
56
|
+
* strict:任一失败即失败(failures 非空,resolved 不含该引用)。
|
|
57
|
+
* keep-last:失败引用沿用 lastResolved 中的上次结果并记 degraded;无上次结果仍算失败。
|
|
58
|
+
*/
|
|
59
|
+
export function resolvePackBuses(refs, context, strategy, lastResolved) {
|
|
60
|
+
const resolved = new Map();
|
|
61
|
+
const failures = [];
|
|
62
|
+
const degraded = [];
|
|
63
|
+
for (const ref of new Set(refs)) {
|
|
64
|
+
try {
|
|
65
|
+
resolved.set(ref, resolveBusRef(ref, context));
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error instanceof BusResolveError) {
|
|
69
|
+
const last = lastResolved?.get(ref);
|
|
70
|
+
if (strategy === 'keep-last' && last) {
|
|
71
|
+
resolved.set(ref, last);
|
|
72
|
+
degraded.push({ ref, lastAid: last });
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
failures.push({ ref, code: error.code, message: error.message });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { resolved, failures, degraded };
|
|
84
|
+
}
|
|
85
|
+
/** keep-last 上次成功解析的持久化:events/.bus-resolve-state.json,结构 { <packId>: { <ref>: aid } }。 */
|
|
86
|
+
export class BusResolveState {
|
|
87
|
+
filePath;
|
|
88
|
+
data = {};
|
|
89
|
+
constructor(filePath) {
|
|
90
|
+
this.filePath = filePath;
|
|
91
|
+
}
|
|
92
|
+
static forEventsDir(eventsDir) {
|
|
93
|
+
return new BusResolveState(path.join(eventsDir, '.bus-resolve-state.json'));
|
|
94
|
+
}
|
|
95
|
+
load() {
|
|
96
|
+
try {
|
|
97
|
+
const parsed = JSON.parse(fs.readFileSync(this.filePath, 'utf8'));
|
|
98
|
+
this.data = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
this.data = {};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
get(packId) {
|
|
105
|
+
const entry = this.data[packId];
|
|
106
|
+
return new Map(Object.entries(entry ?? {}));
|
|
107
|
+
}
|
|
108
|
+
set(packId, resolved) {
|
|
109
|
+
this.data[packId] = Object.fromEntries(resolved);
|
|
110
|
+
}
|
|
111
|
+
save() {
|
|
112
|
+
try {
|
|
113
|
+
fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
|
|
114
|
+
atomicWriteJson(this.filePath, this.data);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
// 持久化失败不致命:下次 keep-last 退化为 strict 行为。
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* events-config.json 管理:读、原子写、rules 增删查;变更联动 SDK updateConfig 由调用方(runtime)执行。
|
|
3
|
+
*/
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { atomicWriteJson } from '../utils/atomic-write.js';
|
|
7
|
+
import { centerLedger } from './ledger.js';
|
|
8
|
+
import { EVENTS_CONFIG_JSON } from './pack-loader.js';
|
|
9
|
+
import { EventCenterError } from './types.js';
|
|
10
|
+
import { AID_PATTERN, validateCenterConfig } from './validation.js';
|
|
11
|
+
export class CenterConfigStore {
|
|
12
|
+
filePath;
|
|
13
|
+
ledger;
|
|
14
|
+
constructor(options) {
|
|
15
|
+
this.filePath = path.join(options.eventsDir, EVENTS_CONFIG_JSON);
|
|
16
|
+
this.ledger = options.ledger ?? centerLedger(options.eventsDir);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 严格读取:只用于**会写回磁盘**的路径(rules 增删、center 开关)。
|
|
20
|
+
*
|
|
21
|
+
* 与 `read()` 的区别只在"文件存在但非法"这一种情况:此时抛错,绝不返回缺省值。
|
|
22
|
+
* 缺省值一旦被当作基准再写回去,磁盘上那份(可能只是某个 AID 写错的)配置就被
|
|
23
|
+
* 整份覆盖成 `enabled:false / rules:{}`——静默丢规则,且违背 admission-coupling.md
|
|
24
|
+
* §4.3 "配置校验失败时原配置保持不变"的承诺。
|
|
25
|
+
*
|
|
26
|
+
* 只读路径(status / doctor / 菜单展示)仍用 `read()`:那里展示缺省值是合理的,
|
|
27
|
+
* 因为紧接着会带上 errors 提示配置有问题。
|
|
28
|
+
*/
|
|
29
|
+
readStrict() {
|
|
30
|
+
const { config, exists, errors } = this.read();
|
|
31
|
+
if (exists && errors.length > 0) {
|
|
32
|
+
throw new EventCenterError('CONFIG_INVALID', `${EVENTS_CONFIG_JSON} is invalid, refusing to overwrite: ${errors.join('; ')}`);
|
|
33
|
+
}
|
|
34
|
+
return config;
|
|
35
|
+
}
|
|
36
|
+
/** 读取并校验;校验失败返回缺省并带 errors(Bus 不启动,不覆盖磁盘)。 */
|
|
37
|
+
read() {
|
|
38
|
+
let rawText;
|
|
39
|
+
try {
|
|
40
|
+
rawText = fs.readFileSync(this.filePath, 'utf8');
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } }, exists: false, errors: [] };
|
|
44
|
+
}
|
|
45
|
+
let raw;
|
|
46
|
+
try {
|
|
47
|
+
raw = JSON.parse(rawText);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
return {
|
|
51
|
+
config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } },
|
|
52
|
+
exists: true,
|
|
53
|
+
errors: [`${EVENTS_CONFIG_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const validated = validateCenterConfig(raw);
|
|
57
|
+
if (!validated.ok) {
|
|
58
|
+
return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } }, exists: true, errors: validated.errors };
|
|
59
|
+
}
|
|
60
|
+
return { config: validated.value, exists: true, errors: [] };
|
|
61
|
+
}
|
|
62
|
+
write(config) {
|
|
63
|
+
fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
|
|
64
|
+
atomicWriteJson(this.filePath, {
|
|
65
|
+
v: 1,
|
|
66
|
+
enabled: config.enabled,
|
|
67
|
+
authMode: config.authMode,
|
|
68
|
+
admission: config.admission,
|
|
69
|
+
rules: config.rules,
|
|
70
|
+
rateLimit: config.rateLimit,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** 白名单增删。返回更新后的配置;不做磁盘之外的生效动作。 */
|
|
74
|
+
mutateAllowlist(input) {
|
|
75
|
+
// 必须严格读:校验失败时若拿缺省值当基准写回,会把整份配置清零。
|
|
76
|
+
const config = this.readStrict();
|
|
77
|
+
for (const aid of input.aids) {
|
|
78
|
+
// 写路径同样校验 AID 格式——只在读时校验等于"先写脏数据,下次读就报错"。
|
|
79
|
+
if (!AID_PATTERN.test(aid)) {
|
|
80
|
+
throw new EventCenterError('INVALID_ARGS', `invalid AID: ${aid}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const current = config.rules[input.event];
|
|
84
|
+
const entry = current
|
|
85
|
+
? { allow: { publish: [...current.allow.publish], subscribe: [...current.allow.subscribe] }, deny: { publish: [...current.deny.publish], subscribe: [...current.deny.subscribe] } }
|
|
86
|
+
: { allow: { publish: [], subscribe: [] }, deny: { publish: [], subscribe: [] } };
|
|
87
|
+
const rules = input.rule === 'deny' ? entry.deny : entry.allow;
|
|
88
|
+
const list = input.role === 'publish' ? rules.publish : rules.subscribe;
|
|
89
|
+
const added = [];
|
|
90
|
+
const removed = [];
|
|
91
|
+
for (const aid of input.aids) {
|
|
92
|
+
if (input.action === 'add') {
|
|
93
|
+
const opposite = input.role === 'publish'
|
|
94
|
+
? (input.rule === 'deny' ? entry.allow.publish : entry.deny.publish)
|
|
95
|
+
: (input.rule === 'deny' ? entry.allow.subscribe : entry.deny.subscribe);
|
|
96
|
+
if (opposite.includes(aid)) {
|
|
97
|
+
throw new EventCenterError('INVALID_ARGS', `AID appears in both allow and deny for ${input.event}/${input.role}: ${aid}`);
|
|
98
|
+
}
|
|
99
|
+
if (!list.includes(aid)) {
|
|
100
|
+
list.push(aid);
|
|
101
|
+
added.push(aid);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
const index = list.indexOf(aid);
|
|
106
|
+
if (index >= 0) {
|
|
107
|
+
list.splice(index, 1);
|
|
108
|
+
removed.push(aid);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
config.rules[input.event] = entry;
|
|
113
|
+
this.write(config);
|
|
114
|
+
this.ledger.append({
|
|
115
|
+
action: 'allowlist.update',
|
|
116
|
+
result: 'ok',
|
|
117
|
+
event: input.event,
|
|
118
|
+
...(added.length ? { added } : {}),
|
|
119
|
+
...(removed.length ? { removed } : {}),
|
|
120
|
+
...(input.rule ? { rule: input.rule } : {}),
|
|
121
|
+
// 目前唯一的写入口是 CLI 与菜单,没有脚本侧通道;`by`/actor=script 曾是死代码。
|
|
122
|
+
// 等真出现脚本改规则的需求时再引入,避免文档承诺一个不存在的分支。
|
|
123
|
+
actor: 'menu',
|
|
124
|
+
});
|
|
125
|
+
return { config, changed: entry, added, removed };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* daemon 接线:事件中心随 agent 的 Trigger 调度器启停(与旧事件总线相同的生命周期挂点)。
|
|
3
|
+
* daemon 自身的 Trigger owner 不是 agent,不承载事件中心。
|
|
4
|
+
*/
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import { agentDir } from '../paths.js';
|
|
7
|
+
import { EventCenterRegistry } from './registry.js';
|
|
8
|
+
/**
|
|
9
|
+
* 解析 agent 工程目录:只接受真实存在的目录。
|
|
10
|
+
*
|
|
11
|
+
* `EvolAgent.projectPath` 在 `projects.defaultPath` 为空时回落到 `process.cwd()`,
|
|
12
|
+
* 那会把整个 EvolCore 仓当成工程目录,沙箱边界与 trigger 的 cwd 都会漂。
|
|
13
|
+
* 这里改为 fail-closed 到 `undefined`:沙箱明确报 `SCRIPT_SANDBOX_UNAVAILABLE`,
|
|
14
|
+
* 而不是拿到一个语义可疑的目录继续跑。
|
|
15
|
+
*/
|
|
16
|
+
export function resolveAgentProjectPath(aid, candidate) {
|
|
17
|
+
const trimmed = candidate?.trim();
|
|
18
|
+
if (!trimmed)
|
|
19
|
+
return undefined;
|
|
20
|
+
try {
|
|
21
|
+
return fs.statSync(trimmed).isDirectory() ? trimmed : undefined;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function createDaemonEventCenter(options) {
|
|
28
|
+
const registry = new EventCenterRegistry({
|
|
29
|
+
agentDir,
|
|
30
|
+
getClient: options.getClient,
|
|
31
|
+
getProjectPath: options.getProjectPath
|
|
32
|
+
?? (aid => resolveAgentProjectPath(aid, options.agentRegistry.get(aid)?.projectPath)),
|
|
33
|
+
getScheduler: aid => options.triggerSchedulers.get(aid),
|
|
34
|
+
});
|
|
35
|
+
options.triggerSchedulers.addLifecycleListener({
|
|
36
|
+
started: aid => {
|
|
37
|
+
if (options.agentRegistry.get(aid))
|
|
38
|
+
void registry.ensureStarted(aid);
|
|
39
|
+
},
|
|
40
|
+
removed: aid => { void registry.remove(aid); },
|
|
41
|
+
suspending: () => { void registry.closeAll(); },
|
|
42
|
+
});
|
|
43
|
+
return registry;
|
|
44
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 占位符解析上下文的数据源:直读 agents/<aid>/directory/contacts.json。
|
|
3
|
+
* 与 OwnerDirectoryCache 同一文件(cachePath('contacts')),只读、防御式:
|
|
4
|
+
* 文件缺失/字段非法 → 相应上下文项留空(strict 包会因此 invalid)。
|
|
5
|
+
* pa_roles 为新增顶层字段,暂不参与 content_digest。
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { AID_PATTERN } from './validation.js';
|
|
10
|
+
export function readBusResolverContext(aid, agentDir) {
|
|
11
|
+
const context = { self: aid, paRoles: {} };
|
|
12
|
+
let raw;
|
|
13
|
+
try {
|
|
14
|
+
raw = JSON.parse(fs.readFileSync(path.join(agentDir, 'directory', 'contacts.json'), 'utf8'));
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return context;
|
|
18
|
+
}
|
|
19
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
20
|
+
return context;
|
|
21
|
+
const record = raw;
|
|
22
|
+
const ownerAid = identityAid(record.owner);
|
|
23
|
+
if (ownerAid)
|
|
24
|
+
context.owner = ownerAid;
|
|
25
|
+
// 本地快照持久化为 camelCase personalAssistant(owner-directory-cache 的写盘格式),
|
|
26
|
+
// 设计文档口径是 snake_case personal_assistant;两种都读,camelCase 优先。
|
|
27
|
+
const paAid = identityAid(record.personalAssistant) ?? identityAid(record.personal_assistant);
|
|
28
|
+
if (paAid)
|
|
29
|
+
context.pa = paAid;
|
|
30
|
+
const paRoles = parsePaRoles(record.pa_roles);
|
|
31
|
+
if (paRoles)
|
|
32
|
+
context.paRoles = paRoles;
|
|
33
|
+
return context;
|
|
34
|
+
}
|
|
35
|
+
function identityAid(value) {
|
|
36
|
+
if (!value || typeof value !== 'object')
|
|
37
|
+
return undefined;
|
|
38
|
+
const aid = value.aid;
|
|
39
|
+
return typeof aid === 'string' && AID_PATTERN.test(aid) ? aid : undefined;
|
|
40
|
+
}
|
|
41
|
+
function parsePaRoles(value) {
|
|
42
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
43
|
+
return undefined;
|
|
44
|
+
const out = {};
|
|
45
|
+
for (const [role, aids] of Object.entries(value)) {
|
|
46
|
+
if (!/^[a-z0-9_-]+$/.test(role))
|
|
47
|
+
continue;
|
|
48
|
+
if (!Array.isArray(aids))
|
|
49
|
+
continue;
|
|
50
|
+
const valid = aids.filter((item) => typeof item === 'string' && AID_PATTERN.test(item));
|
|
51
|
+
if (valid.length > 0)
|
|
52
|
+
out[role] = valid;
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|