evolcore 0.0.43-test.7 → 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 +47 -0
- package/bin/ecmsg.js +22 -9
- 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/claude-runner.js +1 -1
- 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 +1 -1
- package/dist/channels/aun.js +47 -32
- package/dist/cli/agent-command.js +5 -0
- package/dist/cli/agent-create.js +5 -1
- 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 +5 -0
- package/dist/cli/ecmsg-gateway.js +2 -2
- package/dist/cli/events-command.js +45 -9
- package/dist/cli/index.js +29 -0
- package/dist/cli/net-check.js +1 -1
- package/dist/cli/restart-monitor.js +115 -36
- package/dist/cli/services-command.js +29 -3
- package/dist/cli/thread-command.js +97 -11
- package/dist/config/boot-log.js +8 -8
- package/dist/config/schema-migration.js +41 -16
- package/dist/core/agent-ipc-registration.js +25 -4
- package/dist/core/agent-runtime.js +2 -0
- package/dist/core/auth/operation-authorizer.js +2 -0
- package/dist/core/auth/operation-catalog.js +11 -2
- package/dist/core/channel-runtime.js +16 -9
- package/dist/core/command/agent-control.js +11 -1
- package/dist/core/command/agent-template-menu.js +147 -0
- package/dist/core/command/command-handler.js +27 -6
- package/dist/core/command/eventcenter-menu.js +158 -28
- package/dist/core/command/menu-catalog.js +8 -1
- package/dist/core/command/menu-handler.js +18 -6
- package/dist/core/command/menu-protocol.js +11 -2
- package/dist/core/daemon-control.js +14 -0
- package/dist/core/daemon-lifecycle.js +262 -189
- package/dist/core/handoff/runtime.js +42 -10
- package/dist/core/ipc-registration.js +5 -1
- package/dist/core/legacy-rename.js +41 -0
- package/dist/core/message/aun-ipc-sender.js +118 -13
- package/dist/core/message/im-renderer.js +88 -1
- package/dist/core/message/message-queue.js +66 -15
- package/dist/core/message/pending-hints.js +29 -5
- package/dist/core/message/response-engine.js +37 -7
- package/dist/core/message/send-routing.js +13 -6
- package/dist/core/pack-auth.js +94 -0
- package/dist/core/pack-install.js +194 -0
- package/dist/core/permission/ec-command-parser.js +49 -16
- package/dist/core/rate-window.js +48 -0
- package/dist/core/relation/peer-identity.js +28 -0
- package/dist/core/session/session-fs-store.js +66 -26
- package/dist/core/session/session-idle-monitor.js +59 -19
- package/dist/core/session/session-manager.js +13 -4
- package/dist/core/thread/thread-route.js +2 -2
- package/dist/core/thread/thread-service.js +52 -3
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +2 -0
- package/dist/event-center/admission-materializer.js +22 -12
- package/dist/event-center/bus-gate.js +20 -2
- package/dist/event-center/bus-host.js +46 -29
- package/dist/event-center/bus-resolver.js +1 -1
- package/dist/event-center/center-config.js +41 -14
- package/dist/event-center/daemon.js +1 -2
- package/dist/event-center/directory-source.js +3 -1
- package/dist/event-center/index-generator.js +12 -2
- package/dist/event-center/ipc-operation.js +140 -25
- package/dist/event-center/pack-loader.js +61 -56
- package/dist/event-center/pack-manager.js +2 -2
- package/dist/event-center/registry.js +242 -17
- package/dist/event-center/runtime.js +271 -75
- package/dist/event-center/types.js +20 -4
- package/dist/event-center/validation.js +34 -12
- package/dist/index.js +147 -44
- package/dist/ipc.js +44 -4
- package/dist/paths.js +2 -2
- package/dist/response-system/engines/v1/proactive-flow.js +4 -2
- package/dist/services/index.js +3 -3
- package/dist/services/ipc-operation.js +99 -7
- package/dist/services/pack-manager.js +17 -6
- package/dist/services/router.js +8 -5
- package/dist/services/validation.js +5 -5
- package/dist/trigger/scheduler.js +38 -0
- package/dist/trigger/script-sandbox.js +52 -2
- package/dist/utils/npm-ops.js +2 -1
- package/dist/utils/package-version-info.js +6 -3
- package/kits/docs/aun/ABILITY_CALLING.md +4 -3
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +3 -3
- package/kits/docs/evolcore/agent.md +22 -1
- package/kits/docs/evolcore/event-center.md +30 -10
- package/kits/docs/evolcore/fs.md +4 -3
- package/kits/docs/evolcore/menu-protocol.md +7 -1
- package/kits/docs/evolcore/msg.md +8 -8
- package/kits/docs/evolcore/response.md +2 -2
- package/kits/docs/evolcore/services.md +27 -10
- package/kits/docs/evolcore/thread-chain.md +15 -3
- package/kits/rules/06-channel.md +1 -0
- package/kits/skills/ability/references/calling.md +2 -2
- package/kits/skills/ec-group/SKILL.md +5 -8
- package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
- package/kits/skills/ec-trigger/SKILL.md +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 +1 -1
- package/kits/templates/system-fragments/commands.md +1 -1
- package/kits/templates/system-fragments/reply.md +1 -0
- package/kits/templates/system-fragments/thread.md +3 -2
- package/package.json +4 -3
- 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/event-center/client-factory.js +0 -50
|
@@ -7,10 +7,12 @@ import { logger } from '../utils/logger.js';
|
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { BusHost } from './bus-host.js';
|
|
10
|
+
import { isBusPlaceholder } from './bus-resolver.js';
|
|
10
11
|
import { packLedger } from './ledger.js';
|
|
11
12
|
import { toSdkAllowlist, toSdkCatalog } from './pack-manager.js';
|
|
12
|
-
import {
|
|
13
|
+
import { eventListenerOff, EventCenterError, errorCode, errorMessage } from './types.js';
|
|
13
14
|
import { evaluateEventBusRequest } from './bus-gate.js';
|
|
15
|
+
import { RateWindow } from '../core/rate-window.js';
|
|
14
16
|
/** SDK app.pubsub.v1 事件载荷 → 归一化事件。 */
|
|
15
17
|
export function toReceivedEvent(busAid, payload) {
|
|
16
18
|
const eventName = typeof payload.event_name === 'string' ? payload.event_name : '';
|
|
@@ -38,8 +40,11 @@ function sameBusConfig(left, right) {
|
|
|
38
40
|
export class EventRuntime {
|
|
39
41
|
options;
|
|
40
42
|
busHost;
|
|
41
|
-
|
|
42
|
-
|
|
43
|
+
/** 共享主 client(sub/pub 角色共用;bus 宿主同源)。 */
|
|
44
|
+
client;
|
|
45
|
+
/** state_change 监听摘除器:client 换代/停机时摘掉,避免共享连接上累积监听。 */
|
|
46
|
+
clientReadyOff;
|
|
47
|
+
clientReadyHandler;
|
|
43
48
|
unsubscribers = [];
|
|
44
49
|
current;
|
|
45
50
|
rematerializeTimer;
|
|
@@ -51,12 +56,26 @@ export class EventRuntime {
|
|
|
51
56
|
registeredSubBuses = new Map();
|
|
52
57
|
/** 已授权的发布:busAid → 事件名集合。 */
|
|
53
58
|
registeredPubBuses = new Map();
|
|
59
|
+
/** onEvent 回调已挂载的 bus。挂载与"订阅完全成功"是两件事:authorize 成功后回调即挂,
|
|
60
|
+
* 若 subscribe 失败重试,不能重复挂(真 SDK 上回调会累积)。生命周期同 unsubscribers。 */
|
|
61
|
+
handlerBuses = new Set();
|
|
62
|
+
/** 接入失败待重试的目标:`sub:<busAid>` / `pub:<busAid>` / `client` → 连续失败次数。 */
|
|
63
|
+
pendingRetry = new Map();
|
|
64
|
+
reconcileTimer;
|
|
65
|
+
reconciling = false;
|
|
66
|
+
/** 发布限流:按发布方 AID 独立计数(events-config.json 的 rateLimit)。 */
|
|
67
|
+
publishLimiter = new RateWindow();
|
|
54
68
|
constructor(options) {
|
|
55
69
|
this.options = options;
|
|
56
70
|
this.busHost = new BusHost({
|
|
57
71
|
aid: options.aid,
|
|
58
|
-
|
|
72
|
+
getClient: options.getClient,
|
|
59
73
|
requestGate: (senderAid, request, service) => this.gateRemoteRequest(senderAid, request, service),
|
|
74
|
+
// bus.start / bus.stop:只在进入 / 离开 running 时通知,中间态(starting、
|
|
75
|
+
// 自愈退避)不入台账——记了只会淹没真事件。写入由调用方(registry)负责。
|
|
76
|
+
onTransition: ({ from, to, detail }) => this.options.onBusTransition?.({
|
|
77
|
+
from, to, ...(detail ? { detail } : {}),
|
|
78
|
+
}),
|
|
60
79
|
});
|
|
61
80
|
}
|
|
62
81
|
get packs() { return this.current?.state.enabledPacks ?? []; }
|
|
@@ -154,6 +173,9 @@ export class EventRuntime {
|
|
|
154
173
|
this.current = input;
|
|
155
174
|
this.configureRematerializeTimer();
|
|
156
175
|
this.configureContactsWatcher();
|
|
176
|
+
// 配置已变(新包集合/新解析结果):接入重试从头计退避,随后 diff 自会重排队列。
|
|
177
|
+
this.pendingRetry.clear();
|
|
178
|
+
this.clearReconcileTimer();
|
|
157
179
|
// ① Bus:只有 center 配置或 catalog 变了才动;运行中走 updateConfig(不重启 client)。
|
|
158
180
|
const nextBus = input.center.enabled && input.state.catalog.length > 0
|
|
159
181
|
? {
|
|
@@ -189,8 +211,125 @@ export class EventRuntime {
|
|
|
189
211
|
?? toSdkAllowlist(input.center),
|
|
190
212
|
};
|
|
191
213
|
}
|
|
214
|
+
// ── 失败驱动的对账重试(M1)─────────────────────────────────────────────
|
|
215
|
+
// 设计:接入(authorize/subscribe/建连接)失败的目标进 pendingRetry;单个
|
|
216
|
+
// unref 定时器仅在 pending 非空时存在,触发时只跑订阅/发布差集(稳态零
|
|
217
|
+
// RPC/零日志/零台账),成功即出队,失败指数退避。SDK 的 recover() 只救
|
|
218
|
+
// "authorize 成功过"的会话,初次失败的洞由这里补。
|
|
219
|
+
/** 对账入口:只做差集,不重建连接、不动 Bus/定时器/watcher(与 reconfigure 的区别)。 */
|
|
220
|
+
async reconcile() {
|
|
221
|
+
if (this.closed || !this.current || this.reconciling)
|
|
222
|
+
return;
|
|
223
|
+
this.reconciling = true;
|
|
224
|
+
try {
|
|
225
|
+
this.prunePendingKeys();
|
|
226
|
+
await this.diffSubscribers(this.current, 'daemon.reconcile');
|
|
227
|
+
await this.diffPublishers(this.current);
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
this.reconciling = false;
|
|
231
|
+
if (this.pendingRetry.size === 0)
|
|
232
|
+
this.clearReconcileTimer();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/** 丢掉已不在期望集合里的重试目标(包删了/改了 bus),否则空差集会空转重试。 */
|
|
236
|
+
prunePendingKeys() {
|
|
237
|
+
const current = this.current;
|
|
238
|
+
if (!current)
|
|
239
|
+
return;
|
|
240
|
+
const subs = new Set(this.subscriptionTargets(current).map(target => target.busAid));
|
|
241
|
+
const pubs = new Set(this.publisherTargets(current).map(target => target.busAid));
|
|
242
|
+
for (const key of this.pendingRetry.keys()) {
|
|
243
|
+
if (key === 'client')
|
|
244
|
+
continue;
|
|
245
|
+
const [kind, ...rest] = key.split(':');
|
|
246
|
+
const busAid = rest.join(':');
|
|
247
|
+
if (kind === 'sub' && !subs.has(busAid))
|
|
248
|
+
this.pendingRetry.delete(key);
|
|
249
|
+
else if (kind === 'pub' && !pubs.has(busAid))
|
|
250
|
+
this.pendingRetry.delete(key);
|
|
251
|
+
}
|
|
252
|
+
if (this.pendingRetry.size === 0)
|
|
253
|
+
this.clearReconcileTimer();
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* 获取(并缓存)agent 主 client。连接不归事件中心所有,但 AUN 渠道会在重连/复权时
|
|
257
|
+
* 整个换掉 client 对象——换代即视为全新会话:旧监听摘除、订阅/发布差集基线清空
|
|
258
|
+
* (新连接上没有任何 authorize/subscribe 痕迹),下一次差集自然全量重建。
|
|
259
|
+
* 渠道未就绪返回 undefined(进退避重试;ready 事件会提前唤醒)。
|
|
260
|
+
*/
|
|
261
|
+
async ensureClient() {
|
|
262
|
+
let fresh;
|
|
263
|
+
try {
|
|
264
|
+
fresh = await this.options.getClient(this.options.aid) ?? undefined;
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
// 渠道读取异常按"未就绪"处理:进退避,不向 reconcile/publish 传播成未处理拒绝。
|
|
268
|
+
logger.warn(`[EventCenter] ${this.options.aid} client lookup failed: ${errorMessage(error)}`);
|
|
269
|
+
this.scheduleReconcileRetry('client');
|
|
270
|
+
return undefined;
|
|
271
|
+
}
|
|
272
|
+
if (!fresh) {
|
|
273
|
+
this.scheduleReconcileRetry('client');
|
|
274
|
+
return undefined;
|
|
275
|
+
}
|
|
276
|
+
if (fresh !== this.client) {
|
|
277
|
+
this.forgetClient('replaced');
|
|
278
|
+
}
|
|
279
|
+
if (!this.clientReadyOff) {
|
|
280
|
+
const handler = (value) => {
|
|
281
|
+
if (value?.state === 'ready' && this.pendingRetry.size > 0)
|
|
282
|
+
void this.reconcile();
|
|
283
|
+
};
|
|
284
|
+
this.clientReadyHandler = handler;
|
|
285
|
+
const subscription = fresh.on('state_change', handler);
|
|
286
|
+
this.clientReadyOff = eventListenerOff(fresh, 'state_change', subscription, handler);
|
|
287
|
+
this.client = fresh;
|
|
288
|
+
}
|
|
289
|
+
return fresh;
|
|
290
|
+
}
|
|
291
|
+
/** 摘监听、清差集基线。`reason` 只用于日志口径:replaced(换连接)/ stopped(停机)。 */
|
|
292
|
+
forgetClient(reason) {
|
|
293
|
+
this.clientReadyOff?.();
|
|
294
|
+
this.clientReadyOff = undefined;
|
|
295
|
+
this.clientReadyHandler = undefined;
|
|
296
|
+
this.client = undefined;
|
|
297
|
+
for (const off of this.unsubscribers.splice(0)) {
|
|
298
|
+
try {
|
|
299
|
+
off();
|
|
300
|
+
}
|
|
301
|
+
catch { /* 已失效 */ }
|
|
302
|
+
}
|
|
303
|
+
// 新连接/停机后差集基线必须清空:否则"事件看起来已注册过"会跳过 authorize,
|
|
304
|
+
// 后续 publish/subscribe 在全新会话上必失败。基线描述的是当前连接上的事实。
|
|
305
|
+
this.registeredSubBuses.clear();
|
|
306
|
+
this.registeredPubBuses.clear();
|
|
307
|
+
this.handlerBuses.clear();
|
|
308
|
+
void reason;
|
|
309
|
+
}
|
|
310
|
+
scheduleReconcileRetry(key) {
|
|
311
|
+
if (this.closed)
|
|
312
|
+
return;
|
|
313
|
+
this.pendingRetry.set(key, (this.pendingRetry.get(key) ?? 0) + 1);
|
|
314
|
+
const attempts = this.pendingRetry.get(key);
|
|
315
|
+
const base = Math.max(1, this.options.reconcileBaseMs ?? 5_000);
|
|
316
|
+
const max = Math.max(base, this.options.reconcileMaxMs ?? 60_000);
|
|
317
|
+
const delay = Math.min(max, base * 2 ** Math.min(attempts - 1, 4));
|
|
318
|
+
if (this.reconcileTimer)
|
|
319
|
+
return; // 已有定时器:到点统一对账,失败各自续退避
|
|
320
|
+
this.reconcileTimer = setTimeout(() => {
|
|
321
|
+
this.reconcileTimer = undefined;
|
|
322
|
+
void this.reconcile();
|
|
323
|
+
}, delay);
|
|
324
|
+
this.reconcileTimer.unref?.();
|
|
325
|
+
}
|
|
326
|
+
clearReconcileTimer() {
|
|
327
|
+
if (this.reconcileTimer)
|
|
328
|
+
clearTimeout(this.reconcileTimer);
|
|
329
|
+
this.reconcileTimer = undefined;
|
|
330
|
+
}
|
|
192
331
|
/** 订阅增量:新增 bus 走完整接入;已有 bus 只补新增事件、退掉删除事件。 */
|
|
193
|
-
async diffSubscribers(input) {
|
|
332
|
+
async diffSubscribers(input, actor = 'daemon.reload') {
|
|
194
333
|
const desired = new Map();
|
|
195
334
|
for (const target of this.subscriptionTargets(input)) {
|
|
196
335
|
const set = desired.get(target.busAid) ?? new Set();
|
|
@@ -200,16 +339,10 @@ export class EventRuntime {
|
|
|
200
339
|
}
|
|
201
340
|
if (desired.size === 0 && this.registeredSubBuses.size === 0)
|
|
202
341
|
return;
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
catch (error) {
|
|
208
|
-
logger.error(`[EventCenter] ${this.options.aid} sub client create failed: ${errorMessage(error)}`);
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
const client = this.subClient.client.EventService;
|
|
342
|
+
const handle = await this.ensureClient();
|
|
343
|
+
if (!handle)
|
|
344
|
+
return; // 渠道未就绪:已排退避重试,ready 事件可提前唤醒。
|
|
345
|
+
const client = handle.EventService;
|
|
213
346
|
// 退订:已注册但当前包不再需要的 bus / 事件。
|
|
214
347
|
for (const [busAid, events] of [...this.registeredSubBuses]) {
|
|
215
348
|
const wanted = desired.get(busAid);
|
|
@@ -220,6 +353,7 @@ export class EventRuntime {
|
|
|
220
353
|
for (const event of removed)
|
|
221
354
|
events.delete(event);
|
|
222
355
|
logger.info(`[EventCenter] ${this.options.aid} unsubscribed ${busAid}: ${removed.join(', ')}`);
|
|
356
|
+
this.options.onUnsubscribe?.({ busAid, events: removed });
|
|
223
357
|
}
|
|
224
358
|
catch (error) {
|
|
225
359
|
logger.warn(`[EventCenter] ${this.options.aid} unsubscribe ${busAid} failed: ${errorMessage(error)}`);
|
|
@@ -238,23 +372,26 @@ export class EventRuntime {
|
|
|
238
372
|
try {
|
|
239
373
|
// authorize 必须整批带上前面的全部事件:SDK 续期不会自动扩 scope。
|
|
240
374
|
await client.authorize(busAid, 'sub', 'allowlist', [...events]);
|
|
241
|
-
if (!
|
|
375
|
+
if (!this.handlerBuses.has(busAid)) {
|
|
242
376
|
const off = client.onEvent(busAid, payload => {
|
|
243
377
|
const event = toReceivedEvent(busAid, payload);
|
|
244
378
|
if (event)
|
|
245
379
|
this.options.onEvent(event);
|
|
246
380
|
});
|
|
247
381
|
this.unsubscribers.push(() => { off(); });
|
|
382
|
+
this.handlerBuses.add(busAid);
|
|
248
383
|
}
|
|
249
384
|
await client.subscribe(busAid, added);
|
|
250
385
|
this.registeredSubBuses.set(busAid, new Set(events));
|
|
386
|
+
this.pendingRetry.delete(`sub:${busAid}`);
|
|
251
387
|
for (const target of this.subscriptionTargets(input).filter(item => item.busAid === busAid)) {
|
|
252
|
-
packLedger(target.pack).append({ action: 'subscribe', result: 'ok', bus: busAid, events: target.events, actor
|
|
388
|
+
packLedger(target.pack).append({ action: 'subscribe', result: 'ok', bus: busAid, events: target.events, actor, revision: target.pack.revision });
|
|
253
389
|
}
|
|
254
390
|
logger.info(`[EventCenter] ${this.options.aid} subscribed ${busAid}: ${added.join(', ')}`);
|
|
255
391
|
}
|
|
256
392
|
catch (error) {
|
|
257
393
|
logger.warn(`[EventCenter] ${this.options.aid} subscribe ${busAid} failed: ${errorMessage(error)}`);
|
|
394
|
+
this.scheduleReconcileRetry(`sub:${busAid}`);
|
|
258
395
|
}
|
|
259
396
|
}
|
|
260
397
|
}
|
|
@@ -269,16 +406,10 @@ export class EventRuntime {
|
|
|
269
406
|
}
|
|
270
407
|
if (desired.size === 0)
|
|
271
408
|
return;
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
catch (error) {
|
|
277
|
-
logger.error(`[EventCenter] ${this.options.aid} pub client create failed: ${errorMessage(error)}`);
|
|
278
|
-
return;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
const client = this.pubClient.client.EventService;
|
|
409
|
+
const handle = await this.ensureClient();
|
|
410
|
+
if (!handle)
|
|
411
|
+
return; // 渠道未就绪:已排退避重试。
|
|
412
|
+
const client = handle.EventService;
|
|
282
413
|
for (const [busAid, events] of desired) {
|
|
283
414
|
const registered = this.registeredPubBuses.get(busAid);
|
|
284
415
|
const added = [...events].filter(event => !registered?.has(event));
|
|
@@ -287,10 +418,12 @@ export class EventRuntime {
|
|
|
287
418
|
try {
|
|
288
419
|
await client.authorize(busAid, 'pub', 'allowlist', [...events]);
|
|
289
420
|
this.registeredPubBuses.set(busAid, new Set(events));
|
|
421
|
+
this.pendingRetry.delete(`pub:${busAid}`);
|
|
290
422
|
logger.info(`[EventCenter] ${this.options.aid} publish authorized ${busAid}: ${[...events].join(', ')}`);
|
|
291
423
|
}
|
|
292
424
|
catch (error) {
|
|
293
425
|
logger.warn(`[EventCenter] ${this.options.aid} publish authorize ${busAid} failed: ${errorMessage(error)}`);
|
|
426
|
+
this.scheduleReconcileRetry(`pub:${busAid}`);
|
|
294
427
|
}
|
|
295
428
|
}
|
|
296
429
|
}
|
|
@@ -332,16 +465,15 @@ export class EventRuntime {
|
|
|
332
465
|
const targets = this.subscriptionTargets(input);
|
|
333
466
|
if (targets.length === 0)
|
|
334
467
|
return;
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
catch (error) {
|
|
339
|
-
logger.error(`[EventCenter] ${this.options.aid} sub client create failed: ${errorMessage(error)}`);
|
|
468
|
+
const handle = await this.ensureClient();
|
|
469
|
+
if (!handle) {
|
|
470
|
+
// 渠道未就绪:整批记台账(对齐旧 client create 失败的口径),退避重试。
|
|
340
471
|
for (const target of targets) {
|
|
341
|
-
packLedger(target.pack).append({ action: 'subscribe', result: 'failed', bus: target.busAid, events: target.events, code:
|
|
472
|
+
packLedger(target.pack).append({ action: 'subscribe', result: 'failed', bus: target.busAid, events: target.events, code: 'CLIENT_UNAVAILABLE', reason: 'agent AUN client unavailable', actor: 'daemon.start', revision: target.pack.revision });
|
|
342
473
|
}
|
|
343
474
|
return;
|
|
344
475
|
}
|
|
476
|
+
const service = handle.EventService;
|
|
345
477
|
// 同一 Bus 聚合订阅集(跨包共享一条连接,角色绑定 per (client, bus))。
|
|
346
478
|
const busEvents = new Map();
|
|
347
479
|
for (const target of targets) {
|
|
@@ -355,7 +487,7 @@ export class EventRuntime {
|
|
|
355
487
|
// 已绑定;绑定发生在 authorize() 内部的 bindBus。首次接入某个 bus 时若先调 onEvent,
|
|
356
488
|
// 必然抛 BUS_NOT_BOUND,订阅虽然成功但回调永远挂不上(事件被静默吞掉)。
|
|
357
489
|
try {
|
|
358
|
-
await
|
|
490
|
+
await service.authorize(busAid, 'sub', 'allowlist', [...events]);
|
|
359
491
|
}
|
|
360
492
|
catch (error) {
|
|
361
493
|
const code = errorCode(error);
|
|
@@ -366,16 +498,20 @@ export class EventRuntime {
|
|
|
366
498
|
});
|
|
367
499
|
}
|
|
368
500
|
logger.warn(`[EventCenter] ${this.options.aid} subscribe ${busAid} failed: ${code}: ${errorMessage(error)}`);
|
|
501
|
+
this.scheduleReconcileRetry(`sub:${busAid}`);
|
|
369
502
|
continue;
|
|
370
503
|
}
|
|
371
504
|
// ② 回调注册(SDK 按 bus 串行派发,此处必须非阻塞)。
|
|
372
505
|
try {
|
|
373
|
-
|
|
374
|
-
const
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
506
|
+
if (!this.handlerBuses.has(busAid)) {
|
|
507
|
+
const off = service.onEvent(busAid, payload => {
|
|
508
|
+
const event = toReceivedEvent(busAid, payload);
|
|
509
|
+
if (event)
|
|
510
|
+
this.options.onEvent(event);
|
|
511
|
+
});
|
|
512
|
+
this.unsubscribers.push(() => { off(); });
|
|
513
|
+
this.handlerBuses.add(busAid);
|
|
514
|
+
}
|
|
379
515
|
}
|
|
380
516
|
catch (error) {
|
|
381
517
|
const code = errorCode(error);
|
|
@@ -385,12 +521,14 @@ export class EventRuntime {
|
|
|
385
521
|
});
|
|
386
522
|
}
|
|
387
523
|
logger.warn(`[EventCenter] ${this.options.aid} onEvent(${busAid}) register failed: ${code}: ${errorMessage(error)}`);
|
|
524
|
+
this.scheduleReconcileRetry(`sub:${busAid}`);
|
|
388
525
|
continue;
|
|
389
526
|
}
|
|
390
527
|
// ③ 订阅;失败记台账(FORBIDDEN 等),继续其它 Bus。
|
|
391
528
|
try {
|
|
392
|
-
await
|
|
529
|
+
await service.subscribe(busAid, [...events]);
|
|
393
530
|
this.registeredSubBuses.set(busAid, new Set(events));
|
|
531
|
+
this.pendingRetry.delete(`sub:${busAid}`);
|
|
394
532
|
for (const target of targets.filter(item => item.busAid === busAid)) {
|
|
395
533
|
packLedger(target.pack).append({ action: 'subscribe', result: 'ok', bus: busAid, events: [...events], actor: 'daemon.start', revision: target.pack.revision });
|
|
396
534
|
}
|
|
@@ -405,6 +543,7 @@ export class EventRuntime {
|
|
|
405
543
|
});
|
|
406
544
|
}
|
|
407
545
|
logger.warn(`[EventCenter] ${this.options.aid} subscribe ${busAid} failed: ${code}: ${errorMessage(error)}`);
|
|
546
|
+
this.scheduleReconcileRetry(`sub:${busAid}`);
|
|
408
547
|
}
|
|
409
548
|
}
|
|
410
549
|
}
|
|
@@ -423,17 +562,16 @@ export class EventRuntime {
|
|
|
423
562
|
}
|
|
424
563
|
if (targets.size === 0)
|
|
425
564
|
return;
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
catch (error) {
|
|
430
|
-
logger.error(`[EventCenter] ${this.options.aid} pub client create failed: ${errorMessage(error)}`);
|
|
565
|
+
const handle = await this.ensureClient();
|
|
566
|
+
if (!handle) {
|
|
567
|
+
this.scheduleReconcileRetry('client');
|
|
431
568
|
return;
|
|
432
569
|
}
|
|
433
570
|
for (const [busAid, group] of targets) {
|
|
434
571
|
try {
|
|
435
|
-
await
|
|
572
|
+
await handle.EventService.authorize(busAid, 'pub', 'allowlist', [...group.events]);
|
|
436
573
|
this.registeredPubBuses.set(busAid, new Set(group.events));
|
|
574
|
+
this.pendingRetry.delete(`pub:${busAid}`);
|
|
437
575
|
logger.info(`[EventCenter] ${this.options.aid} publish authorized ${busAid}: ${[...group.events].join(', ')}`);
|
|
438
576
|
}
|
|
439
577
|
catch (error) {
|
|
@@ -442,13 +580,12 @@ export class EventRuntime {
|
|
|
442
580
|
packLedger(pack).append({ action: 'authorize.failed', result: 'failed', bus: busAid, code, reason: errorMessage(error), actor: 'daemon.start', revision: pack.revision });
|
|
443
581
|
}
|
|
444
582
|
logger.warn(`[EventCenter] ${this.options.aid} publish authorize ${busAid} failed: ${code}: ${errorMessage(error)}`);
|
|
583
|
+
this.scheduleReconcileRetry(`pub:${busAid}`);
|
|
445
584
|
}
|
|
446
585
|
}
|
|
447
586
|
}
|
|
448
587
|
/** 发布事件(CLI/IPC 入口)。 */
|
|
449
|
-
async publish(packId, eventName, data, ttlSeconds) {
|
|
450
|
-
if (!this.pubClient)
|
|
451
|
-
throw new EventCenterError('PUB_NOT_CONFIGURED', 'no publish entries loaded; publisher client not started');
|
|
588
|
+
async publish(packId, eventName, data, ttlSeconds, publisherAid) {
|
|
452
589
|
const pack = this.packs.find(candidate => candidate.id === packId);
|
|
453
590
|
if (!pack)
|
|
454
591
|
throw new EventCenterError('PACK_NOT_FOUND', `pack not found or invalid: ${packId}`);
|
|
@@ -458,7 +595,21 @@ export class EventRuntime {
|
|
|
458
595
|
const busAid = this.resolutions.get(packId)?.get(entry.bus) ?? entry.busResolved;
|
|
459
596
|
if (!busAid)
|
|
460
597
|
throw new EventCenterError('BUS_UNRESOLVED', `bus "${entry.bus}" unresolved for pack "${packId}"`);
|
|
461
|
-
|
|
598
|
+
// 每次发布都经 ensureClient 刷新引用:渠道可能已换代(重连重建 client),
|
|
599
|
+
// 缓存的旧引用上发布必然失败。对象未变时这只是一次轻量的 provider 读取。
|
|
600
|
+
const handle = await this.ensureClient();
|
|
601
|
+
if (!handle)
|
|
602
|
+
throw new EventCenterError('PUB_NOT_CONFIGURED', 'agent AUN client unavailable; publish not possible yet');
|
|
603
|
+
// 限流:保护订阅方脚本,不是保护传输。超限不回包——事件本身没有应答语义,
|
|
604
|
+
// 调用方拿到明确错误码才知道被限了。
|
|
605
|
+
const quota = this.current?.center.rateLimit ?? { perMinute: 60, perHour: 600 };
|
|
606
|
+
const decision = this.publishLimiter.consume(publisherAid ?? this.options.aid, quota);
|
|
607
|
+
if (!decision.allow) {
|
|
608
|
+
throw new EventCenterError('RATE_LIMITED', `publish rate limited; retry after ${decision.retryAfter ?? 60}s`, {
|
|
609
|
+
retryAfter: decision.retryAfter ?? 60,
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
return await handle.EventService.publish(busAid, eventName, data, ttlSeconds !== undefined ? { ttlSeconds } : undefined);
|
|
462
613
|
}
|
|
463
614
|
async stopConnections() {
|
|
464
615
|
if (this.rematerializeTimer) {
|
|
@@ -466,42 +617,48 @@ export class EventRuntime {
|
|
|
466
617
|
this.rematerializeTimer = undefined;
|
|
467
618
|
}
|
|
468
619
|
this.stopContactsWatcher();
|
|
469
|
-
// ① 注销回调 ② 退订 ③
|
|
620
|
+
// ① 注销回调 ② 退订 ③ 释放远程 bus 上的 sub/pub 角色绑定 ④ 停 Bus 宿主。
|
|
470
621
|
for (const off of this.unsubscribers.splice(0)) {
|
|
471
622
|
try {
|
|
472
623
|
off();
|
|
473
624
|
}
|
|
474
625
|
catch { /* 已失效 */ }
|
|
475
626
|
}
|
|
476
|
-
|
|
627
|
+
const client = this.client;
|
|
628
|
+
if (client && this.current) {
|
|
477
629
|
const busEvents = new Map();
|
|
478
630
|
for (const target of this.subscriptionTargets(this.current)) {
|
|
479
631
|
busEvents.set(target.busAid, [...new Set([...(busEvents.get(target.busAid) ?? []), ...target.events])]);
|
|
480
632
|
}
|
|
481
633
|
for (const [busAid, events] of busEvents) {
|
|
482
634
|
try {
|
|
483
|
-
await
|
|
635
|
+
await client.EventService.unsubscribe(busAid, events);
|
|
484
636
|
}
|
|
485
637
|
catch { /* 对端可能已不可达 */ }
|
|
638
|
+
// 远程 bus 上的 sub/pub 角色绑定显式关闭(停 renew 定时器与待发布队列)。
|
|
639
|
+
// 自有 bus 跳过:EventService.close(busAid) 会连 bus 宿主绑定一起关,
|
|
640
|
+
// 那是 BusHost 的生命周期,见 ④。
|
|
641
|
+
if (busAid !== this.options.aid) {
|
|
642
|
+
try {
|
|
643
|
+
await client.EventService.close(busAid);
|
|
644
|
+
}
|
|
645
|
+
catch { /* 未绑定或已失效 */ }
|
|
646
|
+
}
|
|
486
647
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
}
|
|
495
|
-
if (this.pubClient) {
|
|
496
|
-
try {
|
|
497
|
-
await this.pubClient.close();
|
|
648
|
+
for (const busAid of this.registeredPubBuses.keys()) {
|
|
649
|
+
if (busAid !== this.options.aid) {
|
|
650
|
+
try {
|
|
651
|
+
await client.EventService.close(busAid);
|
|
652
|
+
}
|
|
653
|
+
catch { /* 同上 */ }
|
|
654
|
+
}
|
|
498
655
|
}
|
|
499
|
-
catch { /* 忽略 */ }
|
|
500
|
-
this.pubClient = undefined;
|
|
501
656
|
}
|
|
502
|
-
//
|
|
503
|
-
|
|
504
|
-
this.
|
|
657
|
+
// 主连接不归事件中心所有,不能 close;只摘自己的 state_change 监听并清差集基线
|
|
658
|
+
//(下次接入是全新会话,不是增量)。
|
|
659
|
+
this.forgetClient('stopped');
|
|
660
|
+
this.pendingRetry.clear();
|
|
661
|
+
this.clearReconcileTimer();
|
|
505
662
|
await this.busHost.close().catch(() => { });
|
|
506
663
|
this.reportGateStatus();
|
|
507
664
|
}
|
|
@@ -560,7 +717,12 @@ export class EventRuntime {
|
|
|
560
717
|
this.stopContactsWatcher();
|
|
561
718
|
const current = this.current;
|
|
562
719
|
const contactsPath = this.options.contactsPath;
|
|
563
|
-
|
|
720
|
+
// 监听条件:bus 宿主活动(allowlist 重物化需要)或 已启用包用占位符($pa 等重解析需要);
|
|
721
|
+
// registry 可通过 input.contactsWatch 强制开(解析失败的包不在 enabledPacks 里,runtime 推导不到)。
|
|
722
|
+
const busHostActive = Boolean(current?.center.enabled) && (current?.state.catalog.length ?? 0) > 0;
|
|
723
|
+
const usesPlaceholders = (current?.state.enabledPacks ?? []).some(pack => [...pack.publish, ...pack.subscribe].some(entry => isBusPlaceholder(entry.bus)));
|
|
724
|
+
const shouldWatch = current?.contactsWatch ?? (busHostActive || usesPlaceholders);
|
|
725
|
+
if (!contactsPath || !current || !shouldWatch)
|
|
564
726
|
return;
|
|
565
727
|
const contactsDir = path.dirname(contactsPath);
|
|
566
728
|
const agentDir = path.dirname(contactsDir);
|
|
@@ -569,7 +731,13 @@ export class EventRuntime {
|
|
|
569
731
|
clearTimeout(this.contactsRefreshTimer);
|
|
570
732
|
this.contactsRefreshTimer = setTimeout(() => {
|
|
571
733
|
this.contactsRefreshTimer = undefined;
|
|
734
|
+
// 联系人变化会影响两件事,不能只做一件:
|
|
735
|
+
// ① 准入集合(allowlist 物化)—— 这里直接重算,立即可见;
|
|
736
|
+
// ② `$owner` / `$pa` 这类占位符的解析结果 —— 必须重扫包集合才知道,
|
|
737
|
+
// 交给调用方(registry)做整轮重扫;它内部同样会重算 ①。
|
|
738
|
+
// 只做 ① 会让订阅继续挂在旧 Bus 上,直到下一次 reload 才纠正。
|
|
572
739
|
void this.rematerialize();
|
|
740
|
+
this.options.onContactsChanged?.();
|
|
573
741
|
}, 2_000);
|
|
574
742
|
this.contactsRefreshTimer.unref?.();
|
|
575
743
|
};
|
|
@@ -609,16 +777,43 @@ export class EventRuntime {
|
|
|
609
777
|
watcher.close();
|
|
610
778
|
}
|
|
611
779
|
/** 状态快照(CLI status 用)。 */
|
|
780
|
+
/**
|
|
781
|
+
* 运行时状态。
|
|
782
|
+
*
|
|
783
|
+
* `subscriptions` 只列**真正建立**的订阅(`registeredSubBuses`),不是包声明。
|
|
784
|
+
* 这个区分很重要:声明态在"Bus running 但订阅没建起来"时照样显示有订阅,
|
|
785
|
+
* 会把排查引向错误方向(实测踩过:start() 自等待死锁时 status 显示正常)。
|
|
786
|
+
* 包声明里尚未生效的部分单独列在 `pendingSubscriptions`。
|
|
787
|
+
*/
|
|
612
788
|
status() {
|
|
613
789
|
const subscriptions = new Map();
|
|
790
|
+
const activeByBus = new Map();
|
|
791
|
+
for (const [busAid, events] of this.registeredSubBuses)
|
|
792
|
+
activeByBus.set(busAid, new Set(events));
|
|
793
|
+
const pending = new Map();
|
|
614
794
|
const publishers = new Map();
|
|
615
795
|
if (this.current) {
|
|
616
796
|
for (const target of this.subscriptionTargets(this.current)) {
|
|
617
|
-
const
|
|
618
|
-
|
|
797
|
+
const active = activeByBus.get(target.busAid);
|
|
798
|
+
const bucket = pending;
|
|
799
|
+
const pendingEvents = target.events.filter(event => !active?.has(event));
|
|
800
|
+
if (pendingEvents.length > 0) {
|
|
801
|
+
const entry = bucket.get(target.busAid) ?? { events: new Set(), packs: new Set() };
|
|
802
|
+
for (const event of pendingEvents)
|
|
803
|
+
entry.events.add(event);
|
|
804
|
+
entry.packs.add(target.pack.id);
|
|
805
|
+
bucket.set(target.busAid, entry);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
for (const [busAid, events] of activeByBus) {
|
|
809
|
+
const entry = subscriptions.get(busAid) ?? { events: new Set(), packs: new Set() };
|
|
810
|
+
for (const event of events)
|
|
619
811
|
entry.events.add(event);
|
|
620
|
-
|
|
621
|
-
|
|
812
|
+
for (const target of this.subscriptionTargets(this.current)) {
|
|
813
|
+
if (target.busAid === busAid && target.events.some(event => events.has(event)))
|
|
814
|
+
entry.packs.add(target.pack.id);
|
|
815
|
+
}
|
|
816
|
+
subscriptions.set(busAid, entry);
|
|
622
817
|
}
|
|
623
818
|
for (const pack of this.current.state.enabledPacks) {
|
|
624
819
|
for (const item of pack.publish) {
|
|
@@ -635,6 +830,7 @@ export class EventRuntime {
|
|
|
635
830
|
return {
|
|
636
831
|
bus: { status: this.busHost.status, statusDetail: this.busHost.statusDetail },
|
|
637
832
|
subscriptions: [...subscriptions.entries()].map(([busAid, entry]) => ({ busAid, events: [...entry.events], packs: [...entry.packs] })),
|
|
833
|
+
pendingSubscriptions: [...pending.entries()].map(([busAid, entry]) => ({ busAid, events: [...entry.events], packs: [...entry.packs] })),
|
|
638
834
|
publishers: [...publishers.entries()].map(([busAid, entry]) => ({ busAid, events: [...entry.events], packs: [...entry.packs] })),
|
|
639
835
|
};
|
|
640
836
|
}
|
|
@@ -29,7 +29,23 @@ export function errorCode(error) {
|
|
|
29
29
|
export function errorMessage(error) {
|
|
30
30
|
return error instanceof Error ? error.message : String(error);
|
|
31
31
|
}
|
|
32
|
-
/**
|
|
33
|
-
export
|
|
34
|
-
|
|
35
|
-
|
|
32
|
+
/** 统一摘除 `client.on` 监听:兼容 Subscription 句柄 / 退订函数 / off()。 */
|
|
33
|
+
export function eventListenerOff(client, event, subscription, handler) {
|
|
34
|
+
const direct = subscription?.unsubscribe;
|
|
35
|
+
if (typeof direct === 'function')
|
|
36
|
+
return () => { try {
|
|
37
|
+
direct.call(subscription);
|
|
38
|
+
}
|
|
39
|
+
catch { /* 已失效 */ } };
|
|
40
|
+
if (typeof subscription === 'function')
|
|
41
|
+
return () => { try {
|
|
42
|
+
subscription();
|
|
43
|
+
}
|
|
44
|
+
catch { /* 已失效 */ } };
|
|
45
|
+
if (typeof client.off === 'function')
|
|
46
|
+
return () => { try {
|
|
47
|
+
client.off(event, handler);
|
|
48
|
+
}
|
|
49
|
+
catch { /* 已失效 */ } };
|
|
50
|
+
return () => { };
|
|
51
|
+
}
|