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.
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
@@ -264,13 +264,15 @@ export class HandoffRuntime {
264
264
  }
265
265
  return response;
266
266
  }
267
- async enqueueOrigin(selfAid, handoffId, resultId) {
267
+ async enqueueOrigin(selfAid, handoffId, resultId, recovery) {
268
268
  const operationSequence = ++this.lifecycleSequence;
269
269
  await this.mutexes.forKey(this.returnKey(selfAid, handoffId)).runExclusive(async () => {
270
- await this.enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence);
270
+ await this.enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence, recovery);
271
271
  });
272
272
  }
273
- async enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence) {
273
+ async enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence, recovery) {
274
+ if (recovery?.isCancelled?.())
275
+ return;
274
276
  const instance = this.store.get(selfAid, handoffId);
275
277
  const result = resultId
276
278
  ? instance?.return_results?.find(item => item.result_id === resultId)
@@ -286,11 +288,15 @@ export class HandoffRuntime {
286
288
  if (!instance || !deliveryContent)
287
289
  return;
288
290
  const origin = await this.sessionManager.getSessionById(instance.origin_session_id);
291
+ if (recovery?.isCancelled?.())
292
+ return;
289
293
  if (!origin) {
290
294
  if (result)
291
295
  this.store.recordOriginResultEnqueueFailed(selfAid, handoffId, result.result_id, 'origin session not found');
292
296
  else
293
297
  this.store.recordOriginEnqueueFailed(selfAid, handoffId, 'origin session not found');
298
+ if (recovery?.prioritizeOrigin)
299
+ throw new Error(`Handoff origin session not found: ${instance.origin_session_id}`);
294
300
  return;
295
301
  }
296
302
  if ((this.sessionDiscardSequence.get(this.sessionKey(selfAid, instance.origin_session_id)) ?? 0) > operationSequence) {
@@ -339,6 +345,7 @@ export class HandoffRuntime {
339
345
  };
340
346
  try {
341
347
  await this.messageQueue.enqueuePersisted(origin.id, message, origin.projectPath, {
348
+ priority: recovery?.prioritizeOrigin,
342
349
  interruptible: false,
343
350
  interruptSamePeer: false,
344
351
  agentName: selfAid,
@@ -372,6 +379,8 @@ export class HandoffRuntime {
372
379
  else if (current?.state === 'origin_queued') {
373
380
  this.store.recordOriginEnqueueFailed(selfAid, handoffId, error instanceof Error ? error.message : String(error));
374
381
  }
382
+ if (recovery?.prioritizeOrigin)
383
+ throw error;
375
384
  }
376
385
  }
377
386
  isOriginDeliveryPending(instance, resultId) {
@@ -664,7 +673,7 @@ export class HandoffRuntime {
664
673
  }
665
674
  return discarded;
666
675
  }
667
- async discardExpiredCandidates(selfAid, snapshots, retentionMs = HANDOFF_RETENTION_MS) {
676
+ async discardExpiredCandidates(selfAid, snapshots, retentionMs = HANDOFF_RETENTION_MS, isCancelled) {
668
677
  const now = this.now?.() ?? Date.now();
669
678
  const candidates = snapshots.filter(instance => !['failed', 'completed', 'discarded'].includes(instance.state)
670
679
  && now - instance.created_at >= retentionMs);
@@ -681,12 +690,14 @@ export class HandoffRuntime {
681
690
  }
682
691
  for (const instance of candidates) {
683
692
  await yieldToIo();
693
+ if (isCancelled?.())
694
+ break;
684
695
  if ((latestEventVersions.get(instance.handoff_id) ?? 0) !== instance.version)
685
696
  continue;
686
697
  const result = await this.discardWithTargetLock(selfAid, instance.handoff_id, 'retention_expired', {
687
698
  retention_ms: retentionMs,
688
699
  age_ms: now - instance.created_at,
689
- }, instance.version, now);
700
+ }, instance.version, now, isCancelled);
690
701
  if (result) {
691
702
  discarded++;
692
703
  logger.info(`[Handoff] discarded expired handoff: ${instance.handoff_id}`);
@@ -695,17 +706,23 @@ export class HandoffRuntime {
695
706
  return discarded;
696
707
  }
697
708
  async prepareRecovery(selfAid, options = {}) {
709
+ if (options.isCancelled?.())
710
+ return [];
698
711
  let started = Date.now();
699
712
  let scanDetail;
700
713
  const snapshots = options.snapshots ?? await this.store.listAsync(selfAid, stats => {
701
714
  scanDetail = Object.entries(stats).map(([key, value]) => `${key}=${Math.round(value)}`).join('; ');
702
715
  });
703
716
  options.onPhase?.('scan', started, Date.now(), scanDetail, options.snapshots ? 'skipped' : 'ok');
717
+ if (options.isCancelled?.())
718
+ return [];
704
719
  started = Date.now();
705
720
  if (options.discardExpired !== false)
706
- await this.discardExpiredCandidates(selfAid, snapshots);
721
+ await this.discardExpiredCandidates(selfAid, snapshots, HANDOFF_RETENTION_MS, options.isCancelled);
707
722
  for (const snapshot of snapshots.filter(instance => instance.state === 'queued'
708
723
  || (instance.return_policy === 'none' && instance.state === 'return_pending'))) {
724
+ if (options.isCancelled?.())
725
+ break;
709
726
  // Only legacy return=none entries can need this migration. Its store
710
727
  // method rechecks the current state before changing anything.
711
728
  if (snapshot.return_policy === 'none' && snapshot.state === 'return_pending') {
@@ -808,25 +825,40 @@ export class HandoffRuntime {
808
825
  }
809
826
  }
810
827
  else if (instance.state === 'origin_queued') {
811
- originEnqueues.push(this.enqueueOrigin(selfAid, instance.handoff_id));
828
+ const handoffId = instance.handoff_id;
829
+ originEnqueues.push(() => this.enqueueOrigin(selfAid, handoffId, undefined, options));
812
830
  }
813
831
  else if (Array.isArray(instance.return_results)) {
814
832
  for (const result of instance.return_results.filter(item => item.state === 'origin_queued')) {
815
- originEnqueues.push(this.enqueueOrigin(selfAid, instance.handoff_id, result.result_id));
833
+ const handoffId = instance.handoff_id;
834
+ originEnqueues.push(() => this.enqueueOrigin(selfAid, handoffId, result.result_id, options));
816
835
  }
817
836
  }
818
837
  }
819
838
  options.onPhase?.('reconcile', started, Date.now());
820
839
  }
821
840
  const started = Date.now();
822
- await Promise.all(originEnqueues);
841
+ // Register startup results in snapshot/result order while the session gate
842
+ // is held. Deferring execution until here also keeps origin I/O out of the
843
+ // reconciliation measurement and observes failed writes immediately.
844
+ if (options.prioritizeOrigin) {
845
+ for (const enqueue of originEnqueues) {
846
+ if (options.isCancelled?.())
847
+ break;
848
+ await enqueue();
849
+ }
850
+ }
851
+ else
852
+ await Promise.all(originEnqueues.map(enqueue => enqueue()));
823
853
  options.onPhase?.('origin', started, Date.now(), undefined, originEnqueues.length ? 'ok' : 'skipped');
824
854
  }
825
- async discardWithTargetLock(selfAid, handoffId, reason, details, expectedVersion, now = this.now?.()) {
855
+ async discardWithTargetLock(selfAid, handoffId, reason, details, expectedVersion, now = this.now?.(), isCancelled) {
826
856
  const snapshot = this.store.get(selfAid, handoffId);
827
857
  if (!snapshot)
828
858
  return false;
829
859
  const discarded = await this.mutexes.forKey(this.targetKey(selfAid, snapshot.target_session_id)).runExclusive(async () => {
860
+ if (isCancelled?.())
861
+ return null;
830
862
  const current = this.store.get(selfAid, handoffId);
831
863
  if (!current || current.state === 'failed' || current.state === 'completed' || current.state === 'discarded') {
832
864
  return null;
@@ -292,7 +292,10 @@ export function registerDaemonIpc({ lifecycle, ipcServer, agentRegistry, agentDe
292
292
  createCrossThreadReviewTrigger: input => createManagedCrossThreadReviewTrigger(input, triggerIpcDependencies),
293
293
  });
294
294
  if (eventCenter) {
295
- ipcServer.setEventsOperationExecutor(createEventsOperationExecutor({ registry: eventCenter }));
295
+ ipcServer.setEventsOperationExecutor(createEventsOperationExecutor({
296
+ registry: eventCenter,
297
+ daemonAid: () => daemonAid,
298
+ }));
296
299
  }
297
300
  // 服务路由:已连接通道的实例会暴露其 router;启动即预热一次,让 `ec services status`
298
301
  // 看到的是 daemon 真在用的那份状态,而不是磁盘重扫出来的临时实例。
@@ -307,6 +310,7 @@ export function registerDaemonIpc({ lifecycle, ipcServer, agentRegistry, agentDe
307
310
  }
308
311
  ipcServer.setServicesOperationExecutor(createServicesOperationExecutor({
309
312
  defaultAid: () => daemonAid,
313
+ daemonAid: () => daemonAid,
310
314
  getChannel: aid => channelInstances.find(candidate => {
311
315
  if (candidate.channelType !== 'aun')
312
316
  return false;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * 一次性文件名迁移:旧名 → 规范名。
3
+ *
4
+ * 背景:中心/服务两侧的配置文件改成「每个东西只有一个名字」(`events-config.json` /
5
+ * `services-config.json` / 包声明统一 `pack.json`),不留别名。留别名会让 agent 多一次
6
+ * 「这里该写哪个名」的判断,而这正是我们要消除的东西。
7
+ *
8
+ * 但存量机器上还有旧名。取舍:**只搬运、不双读**——启动时把旧名重命名成新名,
9
+ * 之后所有代码只认规范名。这样既不产生"两套名字都能用"的长期负担,也不会把
10
+ * 用户已配好的策略弄丢。
11
+ */
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { logger } from '../utils/logger.js';
15
+ /**
16
+ * 把 `dir/legacyName` 重命名为 `dir/canonicalName`。
17
+ *
18
+ * @returns 是否发生了迁移
19
+ */
20
+ export function migrateLegacyFileName(dir, legacyName, canonicalName, label) {
21
+ const legacyPath = path.join(dir, legacyName);
22
+ const canonicalPath = path.join(dir, canonicalName);
23
+ if (!fs.existsSync(legacyPath))
24
+ return false;
25
+ // 两个都在:不猜哪个是对的,保留规范名并告警,让用户自己处理旧文件。
26
+ if (fs.existsSync(canonicalPath)) {
27
+ logger.warn(`[migration] ${label}: 同时存在 ${legacyName} 与 ${canonicalName},已忽略前者;` +
28
+ `请删除 ${legacyPath}`);
29
+ return false;
30
+ }
31
+ try {
32
+ fs.renameSync(legacyPath, canonicalPath);
33
+ logger.info(`[migration] ${label}: ${legacyName} → ${canonicalName}`);
34
+ return true;
35
+ }
36
+ catch (error) {
37
+ logger.warn(`[migration] ${label}: 无法重命名 ${legacyPath}: ` +
38
+ `${error instanceof Error ? error.message : String(error)};将按缺少配置处理`);
39
+ return false;
40
+ }
41
+ }
@@ -21,6 +21,7 @@ import { sessionTopicThreadId } from '../thread/topic-id.js';
21
21
  import { getAunRequestRegistry, requestDiagnostics, requestTtlSeconds } from './aun-request-registry.js';
22
22
  import { parseJsonObjectArgument } from '../permission/ec-command-parser.js';
23
23
  import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
24
+ import { logger } from '../../utils/logger.js';
24
25
  const TASK_ID_MESSAGE_PAYLOAD_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file']);
25
26
  function normalizeAid(value) {
26
27
  return String(value ?? '').trim().replace(/^@/, '').toLowerCase();
@@ -262,7 +263,7 @@ async function applyManagedCrossThreadSendEffects(input) {
262
263
  * 统一缩成 `main`。
263
264
  */
264
265
  /**
265
- * 自发投递(self-address):把刚刚发给自己那条消息,直接投进话题 T 所属的会话队列。
266
+ * 跨话题自派(self-address):把刚刚发给自己那条消息,直接投进话题 T 所属的会话队列。
266
267
  *
267
268
  * 三条不变量:
268
269
  * 1. **落点由话题索引决定,不由 `to` 决定**。`to` 是本端自己,用它算会话会落到
@@ -272,6 +273,60 @@ async function applyManagedCrossThreadSendEffects(input) {
272
273
  * 3. **失败不抛**:AUN 那一跳已经把消息发出去了,本地投递失败只能作为
273
274
  * `self_delivery_error` 回报,不能把「已发送」变成「发送失败」。
274
275
  */
276
+ /**
277
+ * 跨话题自派的派活指令只进本机队列,对端在 App 里看不到。这里补一条普通消息
278
+ * 给话题对端,让对话里能看到「我给自己派了什么」;正文完整,首行标明这是
279
+ * 本端给自己派的任务,不带图标。失败只告警——任务已经入队,通知不该反过来
280
+ * 影响投递。
281
+ */
282
+ async function sendSelfDispatchNotice(input) {
283
+ const instance = input.channelInstances.find(candidate => (candidate.adapter.channelKey === input.session.metadata?.channelKey
284
+ || candidate.adapter.channelName === input.session.channel));
285
+ const channel = instance?.channel;
286
+ if (!channel || typeof channel.sendDaemonMsg !== 'function') {
287
+ logger.warn('[AUN] self-dispatch notice skipped: AUN channel instance not found');
288
+ return;
289
+ }
290
+ // 对端是人类就发普通文本,App 直接当消息渲染;对端是 agent 就发 notice,
291
+ // 避免把「跨话题自派」当成一条要它执行的聊天消息。
292
+ let peerType = input.peerType;
293
+ if (!peerType && typeof channel.fetchPeerInfo === 'function') {
294
+ try {
295
+ peerType = (await channel.fetchPeerInfo(input.to))?.type ?? undefined;
296
+ }
297
+ catch { /* 类型解析失败按非人类处理,宁可发 notice */ }
298
+ }
299
+ const selfName = typeof channel.getSelfName === 'function'
300
+ ? String(channel.getSelfName() || '').trim() : '';
301
+ const text = `${selfName ? `${selfName} 给自己派了一个任务:` : '自己给自己派了一个任务:'}\n${input.text}`;
302
+ const isHuman = peerType === 'human';
303
+ const payload = isHuman
304
+ ? { type: 'text', text }
305
+ : { type: 'notice', subtype: 'self_dispatch', severity: 'info', text };
306
+ if (input.threadId)
307
+ payload.thread_id = input.threadId;
308
+ try {
309
+ const result = await channel.sendDaemonMsg({
310
+ to: input.to,
311
+ payload,
312
+ ...(typeof input.encrypted === 'boolean' ? { encrypt: input.encrypted } : {}),
313
+ log: {
314
+ content: text,
315
+ sessionId: input.sessionId,
316
+ threadId: input.threadId ?? null,
317
+ msgType: 'text',
318
+ payloadType: isHuman ? 'text' : 'notice',
319
+ source: 'msg',
320
+ },
321
+ });
322
+ if (result && result.ok === false) {
323
+ logger.warn(`[AUN] self-dispatch notice failed: ${result.error ?? 'unknown'}`);
324
+ }
325
+ }
326
+ catch (error) {
327
+ logger.warn(`[AUN] self-dispatch notice failed: ${error instanceof Error ? error.message : String(error)}`);
328
+ }
329
+ }
275
330
  async function deliverSelfAddressed(input) {
276
331
  const { params, sent, threadRoute } = input;
277
332
  if (!sent.ok)
@@ -290,6 +345,14 @@ async function deliverSelfAddressed(input) {
290
345
  }
291
346
  if (!session)
292
347
  return { deliveryError: `target session not found: ${threadRoute.sessionId}` };
348
+ // 跨话题自派仍然是「(本端, 话题对端) 这个话题里」的内部任务,消息对端必须保持
349
+ // 话题对端。写成自己会让会话元数据、回复目标和角色解析全部指向本端:话题显示
350
+ // 成「我↔我」、回复无处可投(静默丢失)、权限从话题对端漂移。
351
+ // 「这是我自己派的活」由 source=self-address 表达,渲染层据此在信封头署名本端。
352
+ const topicPeerId = String(session.channelId || '').trim() || params.to;
353
+ const storedPeerName = String(session.metadata?.peerName || '').trim();
354
+ const topicPeerName = storedPeerName && storedPeerName !== params.aid ? storedPeerName : topicPeerId;
355
+ const topicPeerType = String(session.metadata?.peerType || '').trim() || undefined;
293
356
  const message = {
294
357
  channel: session.channel,
295
358
  channelType: session.channelType,
@@ -298,11 +361,9 @@ async function deliverSelfAddressed(input) {
298
361
  baseagent: session.baseagent,
299
362
  threadId: sessionTopicThreadId(session) ?? '',
300
363
  chatType: session.chatType === 'group' ? 'group' : 'private',
301
- // 发送者就是本端:模型据 peerId + source 应能判断「这是我自己写给自己的任务」,
302
- // 而不是对端发来的消息。
303
- peerId: params.aid,
304
- peerName: params.aid,
305
- peerType: 'agent',
364
+ peerId: topicPeerId,
365
+ peerName: topicPeerName,
366
+ ...(topicPeerType ? { peerType: topicPeerType } : {}),
306
367
  content: input.content,
307
368
  messageId: sent.message_id,
308
369
  timestamp: sent.timestamp ?? Date.now(),
@@ -314,10 +375,31 @@ async function deliverSelfAddressed(input) {
314
375
  },
315
376
  ...(session.chatType === 'group' ? { groupId: session.channelId } : {}),
316
377
  };
378
+ // 信封头的对端角色必须取话题对端:缺省时队列按 message.peerId(本端)算成
379
+ // visitor,与任务实际以 owner 权限运行矛盾,模型会误判自己没有权限。
380
+ let enqueueRole;
381
+ if (session.chatType !== 'group') {
382
+ try {
383
+ const { resolvePeerRoleDetail } = await import('../../config/peer-role-resolver.js');
384
+ enqueueRole = resolvePeerRoleDetail({
385
+ selfAid: params.aid,
386
+ channelKey: session.channel,
387
+ channelType: 'aun',
388
+ chatType: 'private',
389
+ actorId: session.channelId,
390
+ conversationId: session.channelId,
391
+ peerType: undefined,
392
+ }).effectiveRole ?? undefined;
393
+ }
394
+ catch {
395
+ // 角色解析失败按缺省处理,不影响投递。
396
+ }
397
+ }
317
398
  try {
318
399
  await input.messageQueue.enqueue(session.id, message, session.projectPath, {
319
400
  interruptible: false,
320
401
  agentName: params.aid,
402
+ ...(enqueueRole ? { role: enqueueRole } : {}),
321
403
  sessionKeyField: session.sessionKey,
322
404
  selfAID: params.aid,
323
405
  // 入队即返回:调用方(CLI)不需要等模型跑完,回执只表达「已投递」。
@@ -327,6 +409,23 @@ async function deliverSelfAddressed(input) {
327
409
  catch (error) {
328
410
  return { deliveryError: `enqueue failed: ${error instanceof Error ? error.message : String(error)}` };
329
411
  }
412
+ // 不写本机入站历史:这条记录的 from 是本端,客户端会把「本端 → 本端」当成
413
+ // 一条独立会话(App 里表现为同一话题出现两个对话:一个正常的对端会话,一个
414
+ // 「自己与自己」)。派活指令本身已经在队列里;对端可见副本由下面的
415
+ // sendSelfDispatchNotice 负责,历史里也由它那条出站记录表达。
416
+ // 派活指令本身只在本机队列;给话题对端补一条可见副本(App 里能看到)。
417
+ if (input.channelInstances && input.channelInstances.length > 0) {
418
+ await sendSelfDispatchNotice({
419
+ channelInstances: input.channelInstances,
420
+ session,
421
+ to: topicPeerId,
422
+ peerType: topicPeerType,
423
+ threadId: sessionTopicThreadId(session),
424
+ text: input.content,
425
+ encrypted: input.encrypted,
426
+ sessionId: session.id,
427
+ });
428
+ }
330
429
  return { sessionId: session.id };
331
430
  }
332
431
  function targetTopicLabel(topicId) {
@@ -442,7 +541,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
442
541
  }
443
542
  }
444
543
  const runtimeCausation = runtime?.causation;
445
- // 自发(self-address):收件人是本端自己,话题归属仍是 (自端, 对端)。
544
+ // 跨话题自派(self-address):收件人是本端自己,话题归属仍是 (自端, 对端)。
446
545
  // 此时 `params.to` 不是「话题对端」,不能拿它做话题一致性校验。
447
546
  const selfAddressed = isSelfAidTarget(params.aid, params.to);
448
547
  // 话题引用解析:`threadRef` 是调用方写的原值(可能是主话题 id),
@@ -463,8 +562,8 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
463
562
  : undefined;
464
563
  const isSystemEvent = params.trustedSystemEvent === true
465
564
  && params.payload?.type === 'event' && params.payload.event === 'topic.renamed';
466
- // 非托管自发:调用方没有委托凭证,用本机 controlToken 证明「本机控制面调用」。
467
- // 只有「自发 + 会话级 msg 发送」走这条,其余(含一切发给对端的发送)仍必须走委托链。
565
+ // 非托管跨话题自派:调用方没有委托凭证,用本机 controlToken 证明「本机控制面调用」。
566
+ // 只有「跨话题自派 + 会话级 msg 发送」走这条,其余(含一切发给对端的发送)仍必须走委托链。
468
567
  const localSelfSend = !isSystemEvent
469
568
  && params.localControl === true
470
569
  && selfAddressed
@@ -473,7 +572,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
473
572
  const delegation = localSelfSend
474
573
  ? {
475
574
  ok: true,
476
- // 自发不需要「来源会话→目标关系」的授权:本机控制面就是本端自身。
575
+ // 跨话题自派不需要「来源会话→目标关系」的授权:本机控制面就是本端自身。
477
576
  grant: {
478
577
  selfAid: params.aid,
479
578
  actorId: params.aid,
@@ -562,7 +661,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
562
661
  if (!ch) {
563
662
  return { ok: false, error: `AUN channel not found for ${params.aid}`, code: 'AUN_CHANNEL_NOT_FOUND' };
564
663
  }
565
- // 自发(`--to <本端AID>`):收件人就是自己,不属于跨主体通讯,跳过联系人准入。
664
+ // 跨话题自派(`--to <本端AID>`):收件人就是自己,不属于跨主体通讯,跳过联系人准入。
566
665
  // 不放进 evaluateAppContactAdmission 内部:那是通用准入判定,其它调用方
567
666
  // (入站、handoff 等)也用它,在函数内开口子会扩散到所有路径。
568
667
  if (params.scope === 'msg' && !isSelfAidTarget(params.aid, params.to)) {
@@ -674,6 +773,11 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
674
773
  if (params.rawPayload !== true && isTopicThreadId(params.thread) && typeof payload.thread_id !== 'string') {
675
774
  payload = { ...payload, thread_id: params.thread };
676
775
  }
776
+ // 跨话题自派:在线上载荷显式打标。客户端(尤其观察者转发/入站解析)不必只靠
777
+ // `from == to` 推断,可直接认这个字段;同 AID 的其它设备也据此区分「自己派给自己」。
778
+ if (selfAddressed && params.rawPayload !== true) {
779
+ payload = { ...payload, self_dispatch: true };
780
+ }
677
781
  let preparedRequest;
678
782
  let requestTtl;
679
783
  if (params.scope === 'msg' && params.returnPolicy === 'required') {
@@ -708,7 +812,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
708
812
  getAunRequestRegistry().markSending(params.aid, preparedRequest.requestId);
709
813
  }
710
814
  let targetSessionId;
711
- // 自发一律跳过 handoff:目标会话是按话题索引解析出的 (自端, 对端) 会话,
815
+ // 跨话题自派一律跳过 handoff:目标会话是按话题索引解析出的 (自端, 对端) 会话,
712
816
  // 而 handoff 用 `to`(=本端)作为 channelId 去 getOrCreateSession,会建出
713
817
  // 「我↔我」的错误会话目录。话题内与跨话题同此处理(D14)。
714
818
  if (!selfAddressed && params.originSessionId && params.originMessageId && params.returnPolicy !== 'required') {
@@ -877,7 +981,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
877
981
  ...(completed ? { request_diagnostics: requestDiagnostics(completed) } : {}),
878
982
  };
879
983
  }
880
- // 自发:AUN 那一跳只负责让同 AID 的其它设备看到这条消息,本机不会再收到
984
+ // 跨话题自派:AUN 那一跳只负责让同 AID 的其它设备看到这条消息,本机不会再收到
881
985
  // 回环(SDK 按设备屏蔽 self-sync;即便收到也会被 AID 级身份过滤丢弃)。
882
986
  // 「自己处理这条任务」必须由这里直接入队,落点是话题 T 所属的会话。
883
987
  if (selfAddressed) {
@@ -887,6 +991,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
887
991
  threadRoute,
888
992
  sessionManager,
889
993
  messageQueue,
994
+ channelInstances,
890
995
  content: params.log?.content ?? classifyAunPayloadForLog(payload).content,
891
996
  encrypted: encrypt,
892
997
  });
@@ -39,6 +39,8 @@ export class IMRenderer {
39
39
  activityRecordChain = Promise.resolve();
40
40
  /** 是否已投影 text 文本(用于去重 complete.result)。 */
41
41
  hasEmittedText = false;
42
+ pendingProactiveFinal;
43
+ proactiveFinalReady = false;
42
44
  /** 自增 callId 兜底(runner 没提供时用) */
43
45
  syntheticCallSeq = 0;
44
46
  currentAssistantUuid;
@@ -80,6 +82,38 @@ export class IMRenderer {
80
82
  usesProactiveBehavior() {
81
83
  return this.opts.envelope.chatmode === 'proactive';
82
84
  }
85
+ usesCustomFinal() {
86
+ return this.usesProactiveBehavior() && this.opts.envelope.activityTransport === 'message';
87
+ }
88
+ /** Only the engine's successful task commit can publish an automatic final. */
89
+ async flushProactiveFinal() {
90
+ if (!this.usesCustomFinal())
91
+ return;
92
+ const pending = this.pendingProactiveFinal;
93
+ this.pendingProactiveFinal = undefined;
94
+ const ready = this.proactiveFinalReady;
95
+ this.proactiveFinalReady = false;
96
+ if (!pending)
97
+ return;
98
+ const { item } = pending;
99
+ if (!ready) {
100
+ this.emitProactiveItem(item);
101
+ return;
102
+ }
103
+ if (!item.text.trim() || (this.opts.noopSentinel && isNoopText(item.text, this.opts.noopSentinel)))
104
+ return;
105
+ this.recordActivity(item);
106
+ if (!this.suppressProactiveItem(item)) {
107
+ await this.sendPayload({ kind: 'activity.batch', items: [item], isFinal: true });
108
+ }
109
+ }
110
+ releaseProactiveFinal() {
111
+ const pending = this.pendingProactiveFinal;
112
+ this.pendingProactiveFinal = undefined;
113
+ this.proactiveFinalReady = false;
114
+ if (pending)
115
+ this.emitProactiveItem(pending.item);
116
+ }
83
117
  // ── 公开接口 ──
84
118
  /** 推入 AgentEvent,按 chatmode 投影 */
85
119
  emit(event, suppressTextProjection = false) {
@@ -116,6 +150,8 @@ export class IMRenderer {
116
150
  async flush(isFinal, attention) {
117
151
  await this.activityRecordChain;
118
152
  if (this.usesProactiveBehavior()) {
153
+ if (isFinal === false && this.usesCustomFinal())
154
+ this.releaseProactiveFinal();
119
155
  if (isFinal) {
120
156
  const pending = this.deferredProactiveText;
121
157
  this.deferredProactiveText = [];
@@ -131,6 +167,8 @@ export class IMRenderer {
131
167
  // Proactive behavior is fire-and-forget; only release any held tool results.
132
168
  this.releaseHeldToolResults();
133
169
  await this.activityRecordChain;
170
+ if (this.usesCustomFinal())
171
+ await this.sendChain;
134
172
  return;
135
173
  }
136
174
  return this.flushInternal(isFinal, attention);
@@ -234,6 +272,10 @@ export class IMRenderer {
234
272
  this.textBuffer = '';
235
273
  this.allText = '';
236
274
  this.deferredProactiveText = [];
275
+ this.pendingProactiveFinal = undefined;
276
+ this.proactiveFinalReady = false;
277
+ if (this.usesCustomFinal())
278
+ this.hasEmittedText = false;
237
279
  }
238
280
  /** 仅丢弃尚未发送的正文,保留 notice/tool 等活动项。 */
239
281
  discardPendingText() {
@@ -244,6 +286,8 @@ export class IMRenderer {
244
286
  this.itemsQueue = this.itemsQueue.filter(it => it.kind !== 'text');
245
287
  this.textBuffer = '';
246
288
  this.deferredProactiveText = [];
289
+ this.pendingProactiveFinal = undefined;
290
+ this.proactiveFinalReady = false;
247
291
  }
248
292
  /** 当前 buffer 中尚未 flush 的文本 */
249
293
  getRemainingText() {
@@ -937,6 +981,48 @@ export class IMRenderer {
937
981
  if ((event.type === 'tool_use' || event.type === 'tool_result')
938
982
  && event.callId && this.preflightDenialCallIds.has(event.callId))
939
983
  return;
984
+ if (this.usesCustomFinal()) {
985
+ if (event.type === 'text') {
986
+ if (event.synthetic || !event.text)
987
+ return;
988
+ if (event.text.trim())
989
+ this.hasEmittedText = true;
990
+ this.allText += event.text;
991
+ this.proactiveFinalReady = false;
992
+ const pending = this.pendingProactiveFinal;
993
+ if (pending && (pending.phase !== event.phase
994
+ || (pending.assistantUuid && event.assistantUuid && pending.assistantUuid !== event.assistantUuid)
995
+ || (pending.turn !== undefined && event.turn !== undefined && pending.turn !== event.turn))) {
996
+ this.releaseProactiveFinal();
997
+ }
998
+ if (event.phase === 'commentary') {
999
+ this.emitProactiveItem({ kind: 'text', text: event.text });
1000
+ }
1001
+ else if (this.pendingProactiveFinal) {
1002
+ this.pendingProactiveFinal.item.text += event.text;
1003
+ }
1004
+ else {
1005
+ this.pendingProactiveFinal = {
1006
+ item: { kind: 'text', text: event.text }, phase: event.phase,
1007
+ assistantUuid: event.assistantUuid, turn: event.turn,
1008
+ };
1009
+ }
1010
+ return;
1011
+ }
1012
+ if (event.type === 'tool_use' || event.type === 'error'
1013
+ || (event.type === 'complete' && (event.queryFinal === false || event.isError))) {
1014
+ this.releaseProactiveFinal();
1015
+ }
1016
+ if (event.type === 'complete' && event.queryFinal !== false && !event.isError) {
1017
+ if (!this.hasEmittedText && event.result?.trim()) {
1018
+ this.pendingProactiveFinal = { item: { kind: 'summary', text: event.result,
1019
+ ...(event.subtype ? { subtype: event.subtype } : {}),
1020
+ } };
1021
+ }
1022
+ this.proactiveFinalReady = true;
1023
+ return;
1024
+ }
1025
+ }
940
1026
  // 对齐 interactive 的 dedup:流式 text 已推过时,complete.result 不再重复发 summary
941
1027
  if (event.type === 'complete' &&
942
1028
  !event.isError &&
@@ -1007,7 +1093,8 @@ export class IMRenderer {
1007
1093
  const payload = evolCommand
1008
1094
  ? { kind: 'activity.batch', items: [item], ext: { evolCommand } }
1009
1095
  : { kind: 'activity.batch', items: [item] };
1010
- this.opts.send(payload).catch(err => {
1096
+ const sent = this.usesCustomFinal() ? this.sendPayload(payload) : this.opts.send(payload);
1097
+ sent.catch(err => {
1011
1098
  logger.debug(`[IMRenderer] proactive send failed: ${err.message}`);
1012
1099
  });
1013
1100
  }