evolcore 0.0.43-test.7 → 0.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +22 -9
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/claude-runner.js +1 -1
  9. package/dist/aun/aid/agentmd.js +56 -1
  10. package/dist/aun/aid/client.js +3 -1
  11. package/dist/aun/menu/client.js +3 -2
  12. package/dist/aun/msg/p2p.js +1 -1
  13. package/dist/channels/aun.js +47 -32
  14. package/dist/cli/agent-command.js +5 -0
  15. package/dist/cli/agent-create.js +5 -1
  16. package/dist/cli/agent-template.js +124 -0
  17. package/dist/cli/aun-commands.js +2 -2
  18. package/dist/cli/ctl-command.js +2 -1
  19. package/dist/cli/daemon-commands.js +5 -0
  20. package/dist/cli/ecmsg-gateway.js +2 -2
  21. package/dist/cli/events-command.js +45 -9
  22. package/dist/cli/index.js +29 -0
  23. package/dist/cli/net-check.js +1 -1
  24. package/dist/cli/restart-monitor.js +115 -36
  25. package/dist/cli/services-command.js +29 -3
  26. package/dist/cli/thread-command.js +97 -11
  27. package/dist/config/boot-log.js +8 -8
  28. package/dist/config/schema-migration.js +41 -16
  29. package/dist/core/agent-ipc-registration.js +25 -4
  30. package/dist/core/agent-runtime.js +2 -0
  31. package/dist/core/auth/operation-authorizer.js +2 -0
  32. package/dist/core/auth/operation-catalog.js +11 -2
  33. package/dist/core/channel-runtime.js +16 -9
  34. package/dist/core/command/agent-control.js +11 -1
  35. package/dist/core/command/agent-template-menu.js +147 -0
  36. package/dist/core/command/command-handler.js +27 -6
  37. package/dist/core/command/eventcenter-menu.js +158 -28
  38. package/dist/core/command/menu-catalog.js +8 -1
  39. package/dist/core/command/menu-handler.js +18 -6
  40. package/dist/core/command/menu-protocol.js +11 -2
  41. package/dist/core/daemon-control.js +14 -0
  42. package/dist/core/daemon-lifecycle.js +262 -189
  43. package/dist/core/handoff/runtime.js +42 -10
  44. package/dist/core/ipc-registration.js +5 -1
  45. package/dist/core/legacy-rename.js +41 -0
  46. package/dist/core/message/aun-ipc-sender.js +118 -13
  47. package/dist/core/message/im-renderer.js +88 -1
  48. package/dist/core/message/message-queue.js +66 -15
  49. package/dist/core/message/pending-hints.js +29 -5
  50. package/dist/core/message/response-engine.js +37 -7
  51. package/dist/core/message/send-routing.js +13 -6
  52. package/dist/core/pack-auth.js +94 -0
  53. package/dist/core/pack-install.js +194 -0
  54. package/dist/core/permission/ec-command-parser.js +49 -16
  55. package/dist/core/rate-window.js +48 -0
  56. package/dist/core/relation/peer-identity.js +28 -0
  57. package/dist/core/session/session-fs-store.js +66 -26
  58. package/dist/core/session/session-idle-monitor.js +59 -19
  59. package/dist/core/session/session-manager.js +13 -4
  60. package/dist/core/thread/thread-route.js +2 -2
  61. package/dist/core/thread/thread-service.js +52 -3
  62. package/dist/eck/kit-renderer.js +1 -1
  63. package/dist/eck/message-renderer.js +2 -0
  64. package/dist/event-center/admission-materializer.js +22 -12
  65. package/dist/event-center/bus-gate.js +20 -2
  66. package/dist/event-center/bus-host.js +46 -29
  67. package/dist/event-center/bus-resolver.js +1 -1
  68. package/dist/event-center/center-config.js +41 -14
  69. package/dist/event-center/daemon.js +1 -2
  70. package/dist/event-center/directory-source.js +3 -1
  71. package/dist/event-center/index-generator.js +12 -2
  72. package/dist/event-center/ipc-operation.js +140 -25
  73. package/dist/event-center/pack-loader.js +61 -56
  74. package/dist/event-center/pack-manager.js +2 -2
  75. package/dist/event-center/registry.js +242 -17
  76. package/dist/event-center/runtime.js +271 -75
  77. package/dist/event-center/types.js +20 -4
  78. package/dist/event-center/validation.js +34 -12
  79. package/dist/index.js +147 -44
  80. package/dist/ipc.js +44 -4
  81. package/dist/paths.js +2 -2
  82. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  83. package/dist/services/index.js +3 -3
  84. package/dist/services/ipc-operation.js +99 -7
  85. package/dist/services/pack-manager.js +17 -6
  86. package/dist/services/router.js +8 -5
  87. package/dist/services/validation.js +5 -5
  88. package/dist/trigger/scheduler.js +38 -0
  89. package/dist/trigger/script-sandbox.js +52 -2
  90. package/dist/utils/npm-ops.js +2 -1
  91. package/dist/utils/package-version-info.js +6 -3
  92. package/kits/docs/aun/ABILITY_CALLING.md +4 -3
  93. package/kits/docs/context-assembly.md +1 -1
  94. package/kits/docs/evolcore/INDEX.md +3 -3
  95. package/kits/docs/evolcore/agent.md +22 -1
  96. package/kits/docs/evolcore/event-center.md +30 -10
  97. package/kits/docs/evolcore/fs.md +4 -3
  98. package/kits/docs/evolcore/menu-protocol.md +7 -1
  99. package/kits/docs/evolcore/msg.md +8 -8
  100. package/kits/docs/evolcore/response.md +2 -2
  101. package/kits/docs/evolcore/services.md +27 -10
  102. package/kits/docs/evolcore/thread-chain.md +15 -3
  103. package/kits/rules/06-channel.md +1 -0
  104. package/kits/skills/ability/references/calling.md +2 -2
  105. package/kits/skills/ec-group/SKILL.md +5 -8
  106. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  107. package/kits/skills/ec-trigger/SKILL.md +4 -4
  108. package/kits/skills/thread-ops/SKILL.md +10 -10
  109. package/kits/templates/message-fragments/item.md +1 -1
  110. package/kits/templates/system-fragments/channel.md +1 -1
  111. package/kits/templates/system-fragments/commands.md +1 -1
  112. package/kits/templates/system-fragments/reply.md +1 -0
  113. package/kits/templates/system-fragments/thread.md +3 -2
  114. package/package.json +4 -3
  115. package/scripts/agent-template/index.mjs +40 -0
  116. package/scripts/agent-template/inspect.mjs +240 -0
  117. package/scripts/agent-template/overlay.mjs +71 -0
  118. package/scripts/agent-template/pack.mjs +169 -0
  119. package/scripts/agent-template/shared/common.mjs +235 -0
  120. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  121. package/scripts/agent-template/shared/plan.mjs +129 -0
  122. package/scripts/agent-template/shared/team-schema.json +70 -0
  123. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  124. package/scripts/agent-template/shared/template-package.mjs +265 -0
  125. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  126. package/scripts/agent-template/shared/template.mjs +142 -0
  127. package/dist/event-center/client-factory.js +0 -50
@@ -7,6 +7,7 @@ import { isSystemControlChannel } from '../system-channels.js';
7
7
  import { logger } from '../../utils/logger.js';
8
8
  import { atomicWriteJson } from './session-fs-store.js';
9
9
  import { createRootCausation } from '../causation/context.js';
10
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
10
11
  export const DEFAULT_SESSION_LOOP_SECONDS = 300;
11
12
  export const MIN_SESSION_LOOP_SECONDS = 30;
12
13
  export const MAX_SESSION_LOOP_SECONDS = 86400;
@@ -187,6 +188,7 @@ export class SessionIdleMonitor {
187
188
  persistedState;
188
189
  started = false;
189
190
  active = false;
191
+ activation = 0;
190
192
  onTaskTerminal = (event) => {
191
193
  if (!isTaskTerminalEvent(event) || !event.sessionId)
192
194
  return;
@@ -255,27 +257,60 @@ export class SessionIdleMonitor {
255
257
  this.options.eventBus.subscribe('session:created', this.onSessionCreated);
256
258
  this.options.eventBus.subscribe('session:loop-changed', this.onSessionLoopChanged);
257
259
  }
258
- /** Arm restored timers only after event-trigger subscriptions are registered. */
259
- activate() {
260
+ /** Subscribe first; restore cold history only after normal task Ready. */
261
+ activate(options = {}) {
260
262
  if (this.active)
261
- return;
263
+ return Promise.resolve();
262
264
  this.active = true;
263
265
  this.refreshSessionIdleTriggerIds();
264
- for (const sessionId of this.sessions.keys())
265
- void this.restorePendingSession(sessionId);
266
- }
267
- async restorePendingSession(sessionId) {
268
- try {
269
- const session = await this.options.getSessionById(sessionId);
270
- const state = this.sessions.get(sessionId);
271
- const pending = session && readSessionLoopOnceConfig(session);
272
- if (state && pending && state.onceRequestId === pending.requestId)
273
- state.emitted = false;
274
- this.scheduleSession(sessionId);
275
- }
276
- catch (error) {
277
- this.warn(`Failed to restore pending idle check for ${sessionId}`, error);
266
+ const activation = ++this.activation;
267
+ const cutoff = this.now() - 24 * 60 * 60 * 1000;
268
+ // Capture identity and generation now, not when the cold group is admitted:
269
+ // intervening task/configuration changes own their timers and must win.
270
+ const entries = [...this.sessions].map(([id, state]) => ({ id, state,
271
+ generation: this.generations.get(id) ?? 0 }));
272
+ const recent = entries.filter(({ state }) => !options.waitForBackground
273
+ || Math.max(state.lastEndedAt, state.armedAt ?? 0) >= cutoff || !!state.onceRequestId);
274
+ const recentIds = new Set(recent.map(entry => entry.id));
275
+ const older = entries.filter(entry => !recentIds.has(entry.id));
276
+ return (async () => {
277
+ await this.restorePendingSessions(recent, activation, 'recent', options.onRestored);
278
+ if (!this.active || this.activation !== activation || !older.length)
279
+ return;
280
+ if (options.waitForBackground && !await options.waitForBackground())
281
+ return;
282
+ await this.restorePendingSessions(older, activation, 'older', options.onRestored);
283
+ })();
284
+ }
285
+ async restorePendingSessions(entries, activation, group, onRestored) {
286
+ const started = Date.now();
287
+ // getSessionById currently performs synchronous filesystem work. A burst
288
+ // of restored timers must not hold Runner microtasks or AUN admission.
289
+ for (let offset = 0; offset < entries.length; offset += 4) {
290
+ await yieldToIo();
291
+ if (!this.active || this.activation !== activation)
292
+ return;
293
+ await Promise.all(entries.slice(offset, offset + 4).map(async ({ id, state, generation }) => {
294
+ const current = () => this.active && this.activation === activation && this.sessions.get(id) === state
295
+ && (this.generations.get(id) ?? 0) === generation;
296
+ if (!current())
297
+ return;
298
+ try {
299
+ const session = await this.options.getSessionById(id);
300
+ if (!current())
301
+ return;
302
+ const pending = session && readSessionLoopOnceConfig(session);
303
+ if (pending && state.onceRequestId === pending.requestId)
304
+ state.emitted = false;
305
+ await this.scheduleSessionAsync(id, { session });
306
+ }
307
+ catch (error) {
308
+ this.warn(`Failed to restore pending idle check for ${id}`, error);
309
+ }
310
+ }));
278
311
  }
312
+ if (this.active && this.activation === activation)
313
+ onRestored?.(group, started, Date.now(), entries.length);
279
314
  }
280
315
  /**
281
316
  * 重新采集 session:idle trigger 身份。
@@ -351,7 +386,12 @@ export class SessionIdleMonitor {
351
386
  }
352
387
  stop() {
353
388
  this.active = false;
389
+ this.activation++;
354
390
  this.clearAllTimers();
391
+ // Also invalidate scheduling/emission already awaiting a configuration read.
392
+ for (const sessionId of this.sessions.keys()) {
393
+ this.generations.set(sessionId, (this.generations.get(sessionId) ?? 0) + 1);
394
+ }
355
395
  if (!this.started)
356
396
  return;
357
397
  this.started = false;
@@ -394,7 +434,7 @@ export class SessionIdleMonitor {
394
434
  scheduleSession(sessionId) {
395
435
  void this.scheduleSessionAsync(sessionId);
396
436
  }
397
- async scheduleSessionAsync(sessionId) {
437
+ async scheduleSessionAsync(sessionId, restored) {
398
438
  const state = this.sessions.get(sessionId);
399
439
  if (!state || !this.active)
400
440
  return;
@@ -403,7 +443,7 @@ export class SessionIdleMonitor {
403
443
  return;
404
444
  let session;
405
445
  try {
406
- session = await this.options.getSessionById(sessionId);
446
+ session = restored ? restored.session : await this.options.getSessionById(sessionId);
407
447
  }
408
448
  catch (error) {
409
449
  this.warn(`Failed to load session ${sessionId} while scheduling idle check`, error);
@@ -1401,11 +1401,13 @@ export class SessionManager {
1401
1401
  if (chatType === 'private' && userId) {
1402
1402
  if (!session.metadata)
1403
1403
  session.metadata = {};
1404
- if (!session.metadata.peerId) {
1404
+ // 本端不能成为话题对端:跨话题自派等内部消息即使把 peerId 写成自己,
1405
+ // 会话对端也必须保持原来的私聊对端,否则话题会变成「我↔我」。
1406
+ if (!session.metadata.peerId && userId !== selfAID) {
1405
1407
  session.metadata.peerId = userId;
1406
1408
  mutated = true;
1407
1409
  }
1408
- if (!session.metadata.peerName && metadata?.peerName) {
1410
+ if (!session.metadata.peerName && metadata?.peerName && metadata.peerName !== selfAID) {
1409
1411
  session.metadata.peerName = metadata.peerName;
1410
1412
  mutated = true;
1411
1413
  }
@@ -1464,10 +1466,10 @@ export class SessionManager {
1464
1466
  logger.info(`[SessionManager] Updating chatType for session ${session.id}: ${session.chatType} -> ${chatType}`);
1465
1467
  session.chatType = chatType;
1466
1468
  }
1467
- if (chatType === 'private' && userId && !session.metadata.peerId) {
1469
+ if (chatType === 'private' && userId && !session.metadata.peerId && userId !== selfAID) {
1468
1470
  session.metadata.peerId = userId;
1469
1471
  }
1470
- if (chatType === 'private' && metadata?.peerName && !session.metadata.peerName) {
1472
+ if (chatType === 'private' && metadata?.peerName && !session.metadata.peerName && metadata.peerName !== selfAID) {
1471
1473
  session.metadata.peerName = metadata.peerName;
1472
1474
  }
1473
1475
  if (metadata?.peerType) {
@@ -1807,6 +1809,13 @@ export class SessionManager {
1807
1809
  upsertAgentThreadIndex(input) {
1808
1810
  if (!input.selfAid || !input.threadId)
1809
1811
  return;
1812
+ // 只收话题会话。daemon 内部会话(记忆整理 `bg:<kind>`、trigger 会话
1813
+ // `trigger:<id>`)也带 threadId,但它们是伪话题,会话清理后会留下永远查不到
1814
+ // 会话的悬空条目,让 `rebuild-index --check` 永久报「严重」。
1815
+ if (input.channelType === 'daemon')
1816
+ return;
1817
+ if (!input.threadId.startsWith('thread-'))
1818
+ return;
1810
1819
  try {
1811
1820
  const indexPath = agentThreadIndexPath(input.selfAid);
1812
1821
  const raw = readJsonFile(indexPath);
@@ -20,7 +20,7 @@ export function resolveThreadRouteTarget(selfAid, threadRef, scope, target, opti
20
20
  if (!selfAid)
21
21
  return undefined;
22
22
  const normalizedSelf = selfAid.replace(/^@/, '');
23
- // 自发:收件人是本端,不能拿它和话题对端比。
23
+ // 跨话题自派:收件人是本端,不能拿它和话题对端比。
24
24
  const selfTargeted = options.allowSelfTarget === true
25
25
  && target !== undefined
26
26
  && target.replace(/^@/, '').toLowerCase() === normalizedSelf.toLowerCase();
@@ -84,7 +84,7 @@ export function resolveThreadRouteTarget(selfAid, threadRef, scope, target, opti
84
84
  }
85
85
  if (target === undefined)
86
86
  return entry;
87
- // 自发:收件人是本端,话题归属仍由 entry.peer 决定,不做一致性校验。
87
+ // 跨话题自派:收件人是本端,话题归属仍由 entry.peer 决定,不做一致性校验。
88
88
  if (selfTargeted)
89
89
  return entry;
90
90
  const normalizedTarget = target.replace(/^@/, '');
@@ -143,6 +143,29 @@ export class ThreadService {
143
143
  readThreadIndex(selfAid) {
144
144
  return readIndex(agentThreadIndexPath(selfAid));
145
145
  }
146
+ /**
147
+ * 读索引并带上文件状态。`readIndex` 会把缺失/损坏都折成空集,
148
+ * 列表命令因此无法区分「没记录」和「索引坏了」——这里保留状态用于诊断。
149
+ */
150
+ readThreadIndexWithState(selfAid) {
151
+ const indexPath = agentThreadIndexPath(selfAid);
152
+ const legacyPath = path.join(path.dirname(path.dirname(indexPath)), 'thread-index.json');
153
+ const existing = fs.existsSync(indexPath)
154
+ ? indexPath
155
+ : (legacyPath !== indexPath && fs.existsSync(legacyPath) ? legacyPath : undefined);
156
+ if (!existing)
157
+ return { index: { version: 1, threads: [] }, state: 'missing' };
158
+ try {
159
+ const raw = atomicReadJson(existing);
160
+ if (!raw || !Array.isArray(raw.threads)) {
161
+ return { index: { version: 1, threads: [] }, state: 'corrupt' };
162
+ }
163
+ return { index: readIndex(indexPath), state: 'ok' };
164
+ }
165
+ catch {
166
+ return { index: { version: 1, threads: [] }, state: 'corrupt' };
167
+ }
168
+ }
146
169
  writeThreadIndex(selfAid, index) {
147
170
  const indexPath = agentThreadIndexPath(selfAid);
148
171
  fs.mkdirSync(path.dirname(indexPath), { recursive: true });
@@ -538,7 +561,12 @@ export class ThreadService {
538
561
  const { selfAid, status, label, unlabeled, sort, page = 1, limit: rawLimit } = input;
539
562
  const peer = normalizeThreadPeer(input.peer);
540
563
  const limit = Math.min(rawLimit ?? LIST_DEFAULT_LIMIT, LIST_MAX_LIMIT);
541
- const index = this.readThreadIndex(selfAid);
564
+ const { index, state: indexState } = this.readThreadIndexWithState(selfAid);
565
+ // 未套过滤条件的话题数:用于把「该对端确实没有话题」与
566
+ // 「有话题但被 --status/--label 挡掉」区分开。
567
+ const peerTopicCount = peer
568
+ ? index.threads.filter(t => normalizeThreadPeer(t.peer) === peer).length
569
+ : index.threads.length;
542
570
  let threads = index.threads.filter(t => {
543
571
  if (peer && normalizeThreadPeer(t.peer) !== peer)
544
572
  return false;
@@ -553,8 +581,10 @@ export class ThreadService {
553
581
  // 主话题由会话文件产生、从不进话题索引。只列话题会让「和某对端聊过什么」
554
582
  // 在列表里看不到主线,而 `history <peer>` 不传话题读的恰恰是主话题消息。
555
583
  // 指定对端时补一条合成记录,让 list 与 history 的口径一致。
584
+ let hasMainChat = false;
556
585
  if (peer) {
557
586
  const hasMain = threads.some(t => isMainSessionThreadId(t.threadId));
587
+ hasMainChat = hasMain;
558
588
  if (!hasMain) {
559
589
  const chatDir = this.chatDirFor(selfAid, peer);
560
590
  const logPath = path.join(chatDir, 'messages.jsonl');
@@ -568,6 +598,7 @@ export class ThreadService {
568
598
  }
569
599
  catch { /* skip corrupt file */ }
570
600
  }
601
+ hasMainChat = lastTs > 0;
571
602
  // 群标识与私聊 AID 语法相同,只能靠会话记录里的 chatType 判定;
572
603
  // 没有会话文件时退回私聊(`ec thread list <peer>` 的常见用法)。
573
604
  const active = this.sessionManager.getActiveSessionSync('aun', peer, 'aun', selfAid);
@@ -676,7 +707,20 @@ export class ThreadService {
676
707
  };
677
708
  });
678
709
  const totalMsgCount = threads.reduce((sum, t) => sum + (t.msgTotal ?? 0), 0);
679
- return { threads, total, page, limit, hasMore: offset + threads.length < total, totalMsgCount, peer, selfAid, sort, status, label };
710
+ // 对端是否有任何往来证据:索引里的独立话题、主话题消息、聊天目录或活跃会话。
711
+ // 只看索引会把「索引丢了但聊天记录还在」误报成对端不存在。
712
+ const peerKnown = peer
713
+ ? peerTopicCount > 0
714
+ || hasMainChat
715
+ || fs.existsSync(this.chatDirFor(selfAid, peer))
716
+ || !!this.sessionManager.getActiveSessionSync('aun', peer, 'aun', selfAid)
717
+ : index.threads.length > 0;
718
+ return {
719
+ threads, total, page, limit,
720
+ hasMore: offset + threads.length < total,
721
+ totalMsgCount, peer, selfAid, sort, status, label, unlabeled,
722
+ peerKnown, peerTopicCount, hasMainChat, indexState,
723
+ };
680
724
  }
681
725
  // ── show ──
682
726
  async showThread(input) {
@@ -793,11 +837,16 @@ export class ThreadService {
793
837
  continue;
794
838
  // 渠道类型从目录名(channelSessionKey)解析,避免把 daemon 会话记成 aun。
795
839
  const parsedDir = tryParseChannelSessionKey(dirEntry.name);
840
+ const channelType = parsedDir?.channelType ?? 'aun';
841
+ // daemon 内部会话(记忆整理 `bg:`、trigger 会话 `trigger:`)是伪话题,
842
+ // 不属于话题体系,重建时跳过,否则它们会被一直写回索引。
843
+ if (channelType === 'daemon' || !String(last.threadId).startsWith('thread-'))
844
+ continue;
796
845
  entries.push({
797
846
  threadId: last.threadId,
798
847
  sessionId,
799
848
  peer: last.channelId ?? '',
800
- channelType: parsedDir?.channelType ?? 'aun',
849
+ channelType,
801
850
  peerKind: last.chatType === 'group' ? 'group' : 'private',
802
851
  name: last.name ?? last.threadId,
803
852
  ...(typeof last.metadata?.nameUpdatedAt === 'number'
@@ -239,7 +239,7 @@ const PARAM_DESCRIPTIONS = {
239
239
  lifecycle: '当前 agent 生命周期(created/ownerpending/bootstrapping/active)',
240
240
  isBootstrapping: '当前 agent 是否处于 bootstrap 首次设定阶段',
241
241
  hasPersona: '是否有自我定义内容(soul/ 下除指南外有非空文件)',
242
- hasServicePacks: '是否有已激活的服务包(services/*/service.json 且 requires 对名片通过)',
242
+ hasServicePacks: '是否有已激活的服务包(services/*/pack.json 且 requires 对名片通过)',
243
243
  hasEventPacks: '是否有已启用的事件包(events/*/pack.json 且 enabled)',
244
244
  hasOwnerDirectory: '是否有 Owner 名录注入文件($AGENT_DIR/directory/directory.md)',
245
245
  ownerAid: 'Owner 的 AID(归属协议共识为准,与记忆写入同源;名录快照仅在与之一致时提供名字)',
@@ -112,6 +112,8 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel) {
112
112
  peerId: item.peerId ?? sessionVars.peerId,
113
113
  peerName: item.peerName ?? sessionVars.peerName,
114
114
  peerType: item.peerType ?? sessionVars.peerType,
115
+ // 本端给自己派的任务:信封头标「跨话题自派」,让模型分清「我派的活」和「对端说的话」。
116
+ selfAddressed: item.selfAddressed || undefined,
115
117
  peerRole: item.peerRole ?? sessionVars.peerRole,
116
118
  sameDevice: item.sameDevice ?? sessionVars.sameDevice,
117
119
  sameNetwork: item.sameNetwork ?? sessionVars.sameNetwork,
@@ -48,7 +48,8 @@ function readContactSnapshot(agentDir, selfAid) {
48
48
  }
49
49
  }
50
50
  const owner = identityAid(record.owner);
51
- const personalAssistant = identityAid(record.personal_assistant);
51
+ // camelCase 优先(本地快照持久化格式),snake_case 兜底(协议/设计文档口径)。
52
+ const personalAssistant = identityAid(record.personalAssistant) ?? identityAid(record.personal_assistant);
52
53
  if (!owner && entries.length === 0 && !personalAssistant)
53
54
  return { error: 'contacts_snapshot_empty' };
54
55
  return { owner, personalAssistant, entries, blocked };
@@ -74,10 +75,11 @@ function admittedAids(snapshot, selfAid) {
74
75
  return [...result].sort();
75
76
  }
76
77
  /**
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.
78
+ * Materialize the SDK allowlist from the current contacts snapshot.
79
+ *
80
+ * 语义(与 menu 侧的准入一致):联系人是基础集合;`allow` 额外放行(可以包含
81
+ * 联系人之外的人);`deny` 额外限制(命中即拒,优先于 allow)。两者都只对该事件
82
+ * 生效。临时授权与其他授权存储刻意不读——它们会随时间变化,事件订阅不该跟着抖。
81
83
  */
82
84
  export function materializeAllowlist(config, agentDir, selfAid, registeredEvents) {
83
85
  const snapshot = readContactSnapshot(agentDir, selfAid);
@@ -87,24 +89,32 @@ export function materializeAllowlist(config, agentDir, selfAid, registeredEvents
87
89
  const base = new Set(admittedAids(snapshot, selfAid));
88
90
  const allowlist = {};
89
91
  const events = registeredEvents === undefined
90
- ? Object.keys(config.allowlist)
92
+ ? Object.keys(config.rules)
91
93
  : [...new Set(registeredEvents)];
92
94
  for (const event of events) {
93
- const entry = config.allowlist[event] ?? {
95
+ const entry = config.rules[event] ?? {
94
96
  allow: { publish: [], subscribe: [] },
95
97
  deny: { publish: [], subscribe: [] },
96
98
  };
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));
99
+ // 准入模型:**联系人快照是基础集合,allow 在其上额外放行,deny 在其上额外限制**。
100
+ //
101
+ // 早期实现是交集(`base.has(candidate)`),结果 allow 只能"收窄"、没法给
102
+ // 联系人之外的人开口子;而黑名单又只能靠 deny 表达。两者语义不对称。
103
+ // 现在改成:
104
+ // - allow 为空 → 基础集合(联系人口径,与之前一致)
105
+ // - allow 非空 → 基础集合 ∪ allow(白名单可以放行联系人之外的人)
106
+ // - deny → 从结果里减掉(无论它在不在基础集合里)
107
+ const publishAllow = entry.allow.publish.length > 0 ? [...base, ...entry.allow.publish] : [...base];
108
+ const subscribeAllow = entry.allow.subscribe.length > 0 ? [...base, ...entry.allow.subscribe] : [...base];
109
+ const publish = publishAllow.filter(candidate => !entry.deny.publish.includes(candidate));
110
+ const subscribe = subscribeAllow.filter(candidate => !entry.deny.subscribe.includes(candidate));
101
111
  allowlist[event] = { publish_aids: [...new Set(publish)].sort(), subscribe_aids: [...new Set(subscribe)].sort() };
102
112
  }
103
113
  return { allowlist, degraded: false, admittedAids: [...base] };
104
114
  }
105
115
  function explicitAllowlist(config) {
106
116
  const result = {};
107
- for (const [event, entry] of Object.entries(config.allowlist)) {
117
+ for (const [event, entry] of Object.entries(config.rules)) {
108
118
  result[event] = {
109
119
  publish_aids: entry.allow.publish.filter(aid => !entry.deny.publish.includes(aid)),
110
120
  subscribe_aids: entry.allow.subscribe.filter(aid => !entry.deny.subscribe.includes(aid)),
@@ -47,10 +47,28 @@ export function evaluateEventBusRequest(senderAid, request, materialized, servic
47
47
  allowed: false, operation, reason, ...(event ? { event } : {}), ...(action ? { action } : {}),
48
48
  });
49
49
  const admitted = new Set(materialized.admittedAids);
50
+ // 白名单可以给联系人之外的人开口子,所以"是否被本机接纳"要看 allow 结果,
51
+ // 不只看联系人集合。catalog/stats/renew 这三类没有具体事件可判,只能退回到
52
+ // 「联系人集合 ∪ 任一事件白名单」这个近似。
53
+ const allowlisted = new Set();
54
+ for (const entry of Object.values(materialized.allowlist)) {
55
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
56
+ continue;
57
+ const record = entry;
58
+ for (const key of ['publish_aids', 'subscribe_aids']) {
59
+ const list = record[key];
60
+ if (!Array.isArray(list))
61
+ continue;
62
+ for (const candidate of list)
63
+ if (typeof candidate === 'string')
64
+ allowlisted.add(candidate);
65
+ }
66
+ }
67
+ const reachable = (candidate) => admitted.has(candidate) || allowlisted.has(candidate);
50
68
  if (operation === 'unsubscribe')
51
69
  return { allowed: true, operation };
52
70
  if (operation === 'catalog' || operation === 'stats') {
53
- return admitted.has(senderAid) ? { allowed: true, operation } : deny('contact_admission');
71
+ return reachable(senderAid) ? { allowed: true, operation } : deny('contact_admission');
54
72
  }
55
73
  if (operation === 'publish') {
56
74
  const event = typeof request.event_name === 'string' ? request.event_name : undefined;
@@ -86,7 +104,7 @@ export function evaluateEventBusRequest(senderAid, request, materialized, servic
86
104
  const leaseId = typeof request.lease_id === 'string' ? request.lease_id : '';
87
105
  const leases = service?.leases;
88
106
  const lease = leaseId ? leases?.get(leaseId) : undefined;
89
- if (!admitted.has(senderAid))
107
+ if (!reachable(senderAid))
90
108
  return deny('contact_admission');
91
109
  if (!lease?.scope)
92
110
  return { allowed: true, operation };
@@ -1,12 +1,14 @@
1
1
  /**
2
- * 单个 agent 的事件中心 Bus 宿主:专用 slot client + fastaun EventService。
3
- * 移植自旧 src/aun/event-bus/bus-host.ts(配置源改为事件包合并目录 + center.json 白名单):
4
- * - apply(config):写路径(center.json 变更/白名单变更),成功 ⇒ running;失败抛错且配置不变。
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;失败抛错且配置不变。
5
7
  * - ensureRunning(config):生命周期入口,失败转后台自愈(指数退避,DEVICE_CONFLICT 固定间隔)。
6
8
  * - SDK 失租后 binding 自行关闭且门面不感知,用定时探测兜底。
7
9
  */
8
10
  import { logger } from '../utils/logger.js';
9
- import { EVENT_CENTER_BUS_SLOT, EventCenterError, errorCode, errorMessage, } from './types.js';
11
+ import { EventCenterError, errorCode, errorMessage, } from './types.js';
10
12
  import { installEventBusRequestGate } from './bus-gate.js';
11
13
  function withTimeout(promise, ms, code) {
12
14
  let timer;
@@ -21,6 +23,7 @@ function withTimeout(promise, ms, code) {
21
23
  }
22
24
  export class BusHost {
23
25
  options;
26
+ /** agent 主 client 引用(不拥有;stopInner 只关 bus 绑定,不关连接)。 */
24
27
  handle;
25
28
  statusValue = 'stopped';
26
29
  detail = null;
@@ -42,7 +45,7 @@ export class BusHost {
42
45
  refreshGate() {
43
46
  if (!this.options.requestGate || !this.handle)
44
47
  return false;
45
- this.gateInstalledValue = installEventBusRequestGate(this.handle.client.EventService, this.options.aid, this.options.requestGate);
48
+ this.gateInstalledValue = installEventBusRequestGate(this.handle.EventService, this.options.aid, this.options.requestGate);
46
49
  return this.gateInstalledValue;
47
50
  }
48
51
  /** 串行化所有生命周期操作。 */
@@ -52,11 +55,22 @@ export class BusHost {
52
55
  return next;
53
56
  }
54
57
  setStatus(status, detail = null) {
55
- if (this.statusValue !== status || this.detail !== detail) {
56
- logger.info(`[EventCenter] ${this.options.aid} bus ${this.statusValue} → ${status}${detail ? ` (${detail})` : ''}`);
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})` : ''}`);
57
62
  }
58
63
  this.statusValue = status;
59
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
+ }
60
74
  }
61
75
  /** 写路径:同步生效或失败(失败不改变当前运行配置)。 */
62
76
  apply(config) {
@@ -69,7 +83,7 @@ export class BusHost {
69
83
  return;
70
84
  }
71
85
  if (this.statusValue === 'running' && this.handle) {
72
- await this.handle.client.EventService.updateConfig(this.options.aid, config);
86
+ await this.handle.EventService.updateConfig(this.options.aid, config);
73
87
  this.config = config;
74
88
  return;
75
89
  }
@@ -103,7 +117,7 @@ export class BusHost {
103
117
  async stats(params = {}) {
104
118
  if (this.statusValue !== 'running' || !this.handle)
105
119
  return null;
106
- return await this.handle.client.EventService.stats(this.options.aid, params);
120
+ return await this.handle.EventService.stats(this.options.aid, params);
107
121
  }
108
122
  /**
109
123
  * The SDK currently exposes subscriber counts through stats but not the AID
@@ -113,7 +127,7 @@ export class BusHost {
113
127
  subscribers() {
114
128
  if (this.statusValue !== 'running' || !this.handle)
115
129
  return { available: false, subscribers: [], reason: 'bus_not_running' };
116
- const facade = this.handle.client.EventService;
130
+ const facade = this.handle.EventService;
117
131
  const service = facade.buses?.get?.(this.options.aid)?.service;
118
132
  if (!service?.subscriptions)
119
133
  return { available: false, subscribers: [], reason: 'sdk_subscriber_details_unavailable' };
@@ -151,12 +165,21 @@ export class BusHost {
151
165
  const aid = this.options.aid;
152
166
  try {
153
167
  await withTimeout((async () => {
154
- if (!this.handle)
155
- this.handle = await this.options.createClient(aid, EVENT_CENTER_BUS_SLOT);
156
- const service = this.handle.client.EventService;
157
- // 配置唯一真源是包目录+center.json;SDK state.load 会覆盖 start 参数,因此 load 返回同一份配置。
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 返回同一份配置。
158
177
  const current = this.config ?? config;
159
- this.refreshGate();
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);
160
183
  await service.start(aid, {
161
184
  catalog: current.catalog,
162
185
  allowlist: current.allowlist,
@@ -196,40 +219,34 @@ export class BusHost {
196
219
  this.clearRetry();
197
220
  this.stopProbe();
198
221
  if (this.handle && (this.statusValue === 'running' || this.statusValue === 'lease_lost')) {
199
- const service = this.handle.client.EventService;
222
+ const service = this.handle.EventService;
200
223
  try {
201
224
  await withTimeout(service.drain(this.options.aid), 2_000, 'TIMEOUT');
202
225
  }
203
226
  catch { }
227
+ // 只关 bus 角色绑定;EventService.close(busAid) 对自有 bus 会连 sub/pub 角色一起关——
228
+ // 主连接归渠道所有,这里绝不能触碰连接本身。同 bus 的 sub/pub(自订阅)由 runtime
229
+ // 的差集基线持有,被连带关闭后靠下一次 reconfigure/reconcile 重建。
204
230
  try {
205
231
  await service.close(this.options.aid);
206
232
  }
207
233
  catch { }
208
234
  }
209
- await this.releaseClient();
235
+ this.releaseClient();
210
236
  this.setStatus('stopped');
211
237
  }
212
- async releaseClient() {
213
- const handle = this.handle;
238
+ releaseClient() {
214
239
  this.handle = undefined;
215
240
  this.gateInstalledValue = false;
216
- if (handle) {
217
- try {
218
- await handle.close();
219
- }
220
- catch (error) {
221
- logger.warn(`[EventCenter] ${this.options.aid} bus client close failed: ${errorMessage(error)}`);
222
- }
223
- }
224
241
  }
225
242
  /** binding 是否仍持有实例租约。优先读 SDK 内部状态,读不到时用 stats 探测。 */
226
243
  async leaseAlive() {
227
- const service = this.handle?.client.EventService;
244
+ const service = this.handle?.EventService;
228
245
  const running = service?.buses?.get?.(this.options.aid)?.binding?.running;
229
246
  if (typeof running === 'boolean')
230
247
  return running;
231
248
  try {
232
- await this.handle.client.EventService.stats(this.options.aid, {});
249
+ await this.handle.EventService.stats(this.options.aid, {});
233
250
  return true;
234
251
  }
235
252
  catch {
@@ -31,7 +31,7 @@ export function resolveBusRef(ref, context) {
31
31
  }
32
32
  if (ref === '$pa') {
33
33
  if (!context.pa)
34
- throw new BusResolveError('PA_MISSING', 'contacts has no personal_assistant');
34
+ throw new BusResolveError('PA_MISSING', 'contacts has no personalAssistant/personal_assistant');
35
35
  return context.pa;
36
36
  }
37
37
  if (ref.startsWith('$pa.')) {