evolcore 0.0.43-test.6 → 0.0.43-test.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  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/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -27,14 +27,17 @@ import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInbo
27
27
  import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
28
28
  import { chatDirPath } from '../core/session/session-fs-store.js';
29
29
  import { readSessionLoopConfig, resolveSessionLoopTarget } from '../core/session/session-idle-monitor.js';
30
- import { sessionFullAccessStatus } from '../core/role/runtime-policy.js';
30
+ import { resolveRuntimePermissionMode, sessionFullAccessStatus } from '../core/role/runtime-policy.js';
31
31
  import { readTopicLabel, readTopicStatus } from '../core/session/session-mapper.js';
32
32
  import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
33
33
  import { appendAidLifecycle } from '../aun/aid/identity.js';
34
34
  import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
35
+ import { classifyServicePayloadType, getServiceRouter, readLocalSelfIdentity, } from '../services/index.js';
36
+ import { agentServicesDir } from '../paths.js';
35
37
  import { MAX_AUN_ATTACHMENT_SIZE, uploadBufferAndBuildPayload, uploadFileAndBuildPayload } from '../aun/msg/upload.js';
36
38
  import { loadAgent } from '../config-store.js';
37
39
  import { configuredOwnerList, firstConfiguredOwner } from '../config/owner-config.js';
40
+ import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
38
41
  import { resolveAgentLifecycle } from '../config/lifecycle.js';
39
42
  import { resolveEffective } from '../config/config-manager.js';
40
43
  import { isManagementRole } from '../config/builtin-roles.js';
@@ -84,6 +87,10 @@ const AUN_TOPIC_NAME_PAYLOAD_TYPES = new Set([
84
87
  'text', 'file', 'image', 'audio', 'voice', 'video', 'quote', 'link', 'merge',
85
88
  'action_card', 'card', 'notice', 'error', 'activity', 'thought',
86
89
  ]);
90
+ /** Automatic PA output shares the activity queue, not the ordinary reply path. */
91
+ function isAgentFinalPayload(payload) {
92
+ return payload.type === 'custom' && payload.kind === 'agent_final';
93
+ }
87
94
  function jsonUtf8Size(value) {
88
95
  return Buffer.byteLength(JSON.stringify(value), 'utf8');
89
96
  }
@@ -805,7 +812,15 @@ export class AUNChannel {
805
812
  ownerDirectoryRetryAttempts = 0;
806
813
  ownerDirectoryResolvedSignature;
807
814
  store = null;
808
- /** 实际连接的网关 URL(来自 authenticate() 返回值 / connection.state 事件),替代旧 (client as any)._gatewayUrl。 */
815
+ /** 服务路由实例(懒建;services-config.json 不存在时也建,只是总闸关闭)。 */
816
+ serviceRouter = null;
817
+ /**
818
+ * 本 agent 的工程目录,由插件从 `ChannelBuildContext.defaultProjectPath` 注入。
819
+ * 与 `onProjectPathRequest`(附件落盘)同源;服务脚本沙箱的 cwd 也用它,
820
+ * 保证同一条 invoke 链路上所有消费方看到的是同一个目录。
821
+ */
822
+ defaultProjectPath;
823
+ /** 实际连接的网关 URL,来自 SDK 连接状态事件。 */
809
824
  gatewayUrl = '';
810
825
  projectPathProvider;
811
826
  sessionStateResolver;
@@ -2007,11 +2022,12 @@ export class AUNChannel {
2007
2022
  if (runtime.ownerAid !== senderAid || !sameContactBinding(binding, currentContactBinding(selfAid)))
2008
2023
  return;
2009
2024
  runtime.cache.saveAuthorization(parsed);
2010
- logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}`);
2011
- // 授权被撤销/拒绝时 saveAuthorization 已经清掉凭证和快照,这里无事可做:
2012
- // 下一次 owner.directory.changed 会写 pending,准入回落到"名录不可用"。
2013
- if (runtime.cache.scopeAccess('contacts') !== 'authorized')
2025
+ if (runtime.cache.isRevoked())
2014
2026
  return;
2027
+ logger.info(`${this.logPrefix()} owner.directory.grant: grant applied for ${selfAid}`);
2028
+ // 撤销/拒绝时 saveAuthorization 已经清掉本地快照,这里无事可做:
2029
+ // 持久化撤权边界会阻止后续 changed 或共享广播恢复旧快照。
2030
+ // 生效时 grant 清除撤权状态,并触发拉取。
2015
2031
  // 授权是 Owner 的主动操作,用户点完就在等结果。写标记 + 立即拉取 + 落地,
2016
2032
  // 不再等"下一条入站消息"——那条消息可能几小时后才来。
2017
2033
  await runtime.cache.handleOwnerChangedEvent(senderAid);
@@ -2459,6 +2475,12 @@ export class AUNChannel {
2459
2475
  // Peer snapshots refresh lazily on the next lookup. The self name is
2460
2476
  // held separately by this channel, so refresh it with the existing API.
2461
2477
  if (aid === (this._aid || this.config.aid)) {
2478
+ // 名片 type/exttype 是 requires 判定的依据:变更后重新扫描包。
2479
+ if (this.serviceRouter) {
2480
+ const identity = readLocalSelfIdentity(aid) ?? { aid, type: 'agent', exttype: '' };
2481
+ this.serviceRouter.ensureStarted(identity);
2482
+ this.serviceRouter.reload();
2483
+ }
2462
2484
  void refreshAgentDisplayName(aid).then(name => {
2463
2485
  if (!name || !isCurrentClient() || this.intentionalDisconnect)
2464
2486
  return;
@@ -2631,29 +2653,8 @@ export class AUNChannel {
2631
2653
  }
2632
2654
  });
2633
2655
  }
2634
- // Authenticate(拿权威 gateway 用于日志/状态;connect 内部也会复用 token)
2635
- try {
2636
- logger.info(`${this.logPrefix()} Authenticating as ${aidName}...`);
2637
- this.trace('OUT', 'auth.authenticate', { aid: aidName });
2638
- const auth = await client.authenticate();
2639
- this.trace('OUT', 'auth.authenticate.ok', { aid: client.aid, gateway: auth?.gateway, hasToken: !!auth?.access_token });
2640
- this.trace('IN', 'auth.result', { aid: client.aid, gateway: auth?.gateway, hasToken: !!auth?.access_token });
2641
- const resolvedGateway = typeof auth?.gateway === 'string' ? auth.gateway : '';
2642
- this.gatewayUrl = resolvedGateway;
2643
- logger.info(`${this.logPrefix()} Authenticated as ${client.aid ?? '?'}, gateway=${resolvedGateway}`);
2644
- }
2645
- catch (e) {
2646
- const errMsg = e.message || String(e);
2647
- const errName = e.constructor?.name || 'Error';
2648
- this.trace('OUT', 'auth.authenticate.error', { error: errMsg, name: errName });
2649
- logger.error(`${this.logPrefix()} Authentication failed (${errName}): ${errMsg}`);
2650
- if (e.stack)
2651
- logger.debug(`${this.logPrefix()} Auth stack: ${e.stack}`);
2652
- this.setAidStatus('failed', { lastError: `${errName}: ${errMsg}`.slice(0, 80) });
2653
- this.scheduleReconnect();
2654
- throw new Error(`Authentication failed: ${errName}: ${errMsg}`);
2655
- }
2656
- // Connect (SDK auto_reconnect handles transient failures)
2656
+ // connect() owns discovery and authentication. Calling authenticate() first
2657
+ // makes the SDK discover the gateway twice; state events provide its URL.
2657
2658
  try {
2658
2659
  const extraInfo = buildConnectExtraInfo({
2659
2660
  aid: this.config.aid,
@@ -2959,7 +2960,7 @@ export class AUNChannel {
2959
2960
  }
2960
2961
  async downloadAttachment(att, channelId, delivery) {
2961
2962
  const ownerAid = att.owner_aid
2962
- || (delivery?.chatType === 'private' ? channelId : '')
2963
+ || (delivery?.chatType === 'private' && !delivery.service ? channelId : '')
2963
2964
  || this._aid
2964
2965
  || '';
2965
2966
  const objectKey = att.object_key;
@@ -3309,7 +3310,50 @@ export class AUNChannel {
3309
3310
  }
3310
3311
  return;
3311
3312
  }
3313
+ // ── 服务路由:应答与请求分两支,应答优先。 ──
3314
+ // 应答必须早于请求分支,否则会被 unmatched 静默丢弃,等待者永远收不到结果。
3315
+ // 插在这里(claim 之前):服务分支无条件自己 claim 一次,之后既有路径原样不动。
3316
+ const serviceKind = classifyServicePayloadType(msg.payload?.type);
3317
+ if (serviceKind === 'result') {
3318
+ // 交给既有请求注册表匹配;命中后由它更新记录并唤醒等待者。
3319
+ const matched = getAunRequestRegistry().resolveIncoming({
3320
+ selfAid: this._aid || this.config.aid,
3321
+ fromAid,
3322
+ fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
3323
+ messageId,
3324
+ payload: msg.payload,
3325
+ encrypted: !!env.encrypted,
3326
+ transport: 'p2p',
3327
+ });
3328
+ if (matched)
3329
+ return;
3330
+ logger.debug(`${this.logPrefix()} Unmatched service result: mid=${messageId} from=${fromAid}`);
3331
+ return;
3332
+ }
3333
+ if (serviceKind === 'request') {
3334
+ if (!this.claimInboundMessage('private', messageId, seq))
3335
+ return;
3336
+ await this.handleServiceMessage({
3337
+ fromAid,
3338
+ messageId,
3339
+ encrypted: !!env.encrypted,
3340
+ receivedAt,
3341
+ payload: (msg.payload && typeof msg.payload === 'object') ? msg.payload : {},
3342
+ });
3343
+ return;
3344
+ }
3312
3345
  const appOwned = !this.config.pureIdentity;
3346
+ // ── 事件中心隔离(P1)──
3347
+ // AUN pubsub 事件(aun.pubsub/1)在传输层是加密 P2P 消息,与聊天共用 message.received 流。
3348
+ // 只凭受保护头判定(SDK 归一化后的可信信号;payload.type 可伪造,不单独作为依据),
3349
+ // 在去重表/observer 镜像/身份解析/入站日志/回声过滤之前早退:
3350
+ // 事件只由 EventService 的 onEvent 消费,消息层不产生会话、不进 thread。
3351
+ const earlyProtectedHeaders = verifiedProtectedHeaders(msg, env);
3352
+ if (earlyProtectedHeaders?.message_class === 'sdk_control'
3353
+ && earlyProtectedHeaders.sdk_control_protocol === 'aun.pubsub') {
3354
+ logger.debug(`${this.logPrefix()} P2P dropped: pubsub control envelope (mid=${messageId})`);
3355
+ return;
3356
+ }
3313
3357
  if (!appOwned && !this.claimInboundMessage('private', messageId, seq))
3314
3358
  return;
3315
3359
  const protectedHeaders = verifiedProtectedHeaders(msg, env);
@@ -3400,6 +3444,18 @@ export class AUNChannel {
3400
3444
  logger.info(`${this.logPrefix()} P2P dropped terminal error: from=${fromAid || 'unknown'} mid=${messageId}`);
3401
3445
  return;
3402
3446
  }
3447
+ // ── services 模式:常规消息只认 Owner,其余一律不进 Agent。 ──
3448
+ // 判定放在准入之后、observer 镜像之前:blocked 静默,非 Owner 回引导语。
3449
+ // 只认本机名片 type === 'services';普通 agent 完全不受影响。
3450
+ if (appOwned && readLocalSelfIdentity(this.config.aid)?.type === 'services') {
3451
+ const decision = evaluateAppContactAdmission(this.config.aid, fromAid);
3452
+ if (!decision.allow || decision.reason !== 'owner') {
3453
+ if (decision.reason !== 'blocked') {
3454
+ await this.replyServiceModeRejection(fromAid, inboundType, !!env.encrypted);
3455
+ }
3456
+ return;
3457
+ }
3458
+ }
3403
3459
  // Observer forward (inbound):在所有过滤之前转发原始明文 payload。
3404
3460
  // forwardInbound 内部排除 self-echo 与 from-owner。
3405
3461
  // 显式排除 observer.inject:它是 owner 对本 agent 的控制消息,不应镜像给观察者
@@ -4857,6 +4913,126 @@ export class AUNChannel {
4857
4913
  onProjectPathRequest(provider) {
4858
4914
  this.projectPathProvider = provider;
4859
4915
  }
4916
+ /**
4917
+ * 注入本 agent 的工程目录(`ChannelBuildContext.defaultProjectPath`)。
4918
+ * 服务脚本在非 fullaccess 档位下以它为沙箱 cwd;未注入时服务脚本按
4919
+ * `SCRIPT_SANDBOX_UNAVAILABLE` 明确拒绝,不回落 `process.cwd()`——
4920
+ * 后者会把整个 EvolCore 仓当成工程目录,沙箱边界会被悄悄放大。
4921
+ */
4922
+ setDefaultProjectPath(projectPath) {
4923
+ const trimmed = projectPath?.trim();
4924
+ this.defaultProjectPath = trimmed ? trimmed : undefined;
4925
+ }
4926
+ // ── 服务路由 ────────────────────────────────────────────────────────────
4927
+ /** 供 daemon 启动时预热与 IPC 运维取用(不改变懒建语义)。 */
4928
+ getServiceRouter() {
4929
+ return this.ensureServiceRouter();
4930
+ }
4931
+ /**
4932
+ * 懒建服务路由实例并完成首次扫描。
4933
+ * identity 用本地名片(不触发网络);requires 判定与 ECK 变量读同一份。
4934
+ */
4935
+ ensureServiceRouter() {
4936
+ if (this.serviceRouter)
4937
+ return this.serviceRouter;
4938
+ const aid = this.config.aid;
4939
+ const identity = readLocalSelfIdentity(aid) ?? { aid, type: 'agent', exttype: '' };
4940
+ this.serviceRouter = getServiceRouter(aid, agentServicesDir(aid), {
4941
+ aid,
4942
+ identity: () => readLocalSelfIdentity(aid) ?? identity,
4943
+ // 与 trigger / 事件中心同源:agent 的工程目录。沙箱要求绝对真实目录,
4944
+ // 存在性与 H/L 分类由 buildTriggerScriptLaunch 自己校验并明确报错。
4945
+ getProjectPath: () => this.defaultProjectPath,
4946
+ permissionMode: () => resolveRuntimePermissionMode({ selfAid: aid }).effectiveValue,
4947
+ // bypass + owner 才免沙箱;角色取调用方(service 消息的 from)。解析失败按未知处理。
4948
+ resolvePeerRole: fromAid => {
4949
+ try {
4950
+ return resolvePeerRoleDetail({
4951
+ selfAid: aid,
4952
+ channelKey: `aun#${aid}#main`,
4953
+ channelType: 'aun',
4954
+ chatType: 'private',
4955
+ actorId: fromAid,
4956
+ conversationId: fromAid,
4957
+ }).effectiveRole;
4958
+ }
4959
+ catch {
4960
+ return undefined;
4961
+ }
4962
+ },
4963
+ });
4964
+ this.serviceRouter.ensureStarted(identity);
4965
+ return this.serviceRouter;
4966
+ }
4967
+ /**
4968
+ * services 模式下给非 Owner 的引导回复。
4969
+ * 协议消息(menu./bind./observer./friend./contact.request.)一律静默;受限流(builtin),超限静默。
4970
+ */
4971
+ async replyServiceModeRejection(toAid, inboundType, encrypted) {
4972
+ const type = typeof inboundType === 'string' ? inboundType : '';
4973
+ if (type.startsWith('menu.') || type.startsWith('bind.') || type.startsWith('observer.')
4974
+ || type.startsWith('friend.') || type.startsWith('contact.request.'))
4975
+ return;
4976
+ const router = this.ensureServiceRouter();
4977
+ const limit = router.consumeBuiltinQuota(toAid);
4978
+ if (!limit.allow)
4979
+ return;
4980
+ const text = `我是服务节点,只接受 Owner 的直接消息。\n可用的服务调用方式:ec services describe ${this.config.aid}\n如需联系,请通过 Owner 申请。`;
4981
+ const result = await this.sendStructuredResult(toAid, { type: 'text', text }, {
4982
+ delivery: { chatType: 'private' },
4983
+ metadata: { encrypted, source: 'daemon' },
4984
+ });
4985
+ if (!result.ok) {
4986
+ logger.debug(`${this.logPrefix()} Service-mode rejection not delivered: code=${result.code ?? 'UNKNOWN'} to=${toAid}`);
4987
+ }
4988
+ }
4989
+ /** 服务调用的准入判决。blocked 静默;其余未通过回 NOT_AUTHORIZED。 */
4990
+ serviceAdmission(fromAid) {
4991
+ const decision = evaluateAppContactAdmission(this.config.aid, fromAid);
4992
+ if (decision.allow)
4993
+ return { admission: 'allow' };
4994
+ if (decision.reason === 'blocked')
4995
+ return { admission: 'blocked' };
4996
+ return { admission: 'not_authorized', requestContact: currentContactBinding(this.config.aid)?.owner_aid };
4997
+ }
4998
+ /**
4999
+ * 入站服务消息(请求支)。调用方已完成 claim。
5000
+ * 应答支不经过这里——那由 AunRequestRegistry 在消息层更早匹配。
5001
+ */
5002
+ async handleServiceMessage(input) {
5003
+ const router = this.ensureServiceRouter();
5004
+ const payload = input.payload;
5005
+ const rawType = typeof payload.type === 'string' ? payload.type : '';
5006
+ const requestId = typeof payload.request_id === 'string' && payload.request_id
5007
+ ? payload.request_id
5008
+ : input.messageId;
5009
+ const message = {
5010
+ type: rawType,
5011
+ requestId,
5012
+ requestIdGenerated: requestId === input.messageId,
5013
+ fromAid: input.fromAid,
5014
+ messageId: input.messageId,
5015
+ encrypted: input.encrypted,
5016
+ payload,
5017
+ receivedAt: input.receivedAt,
5018
+ };
5019
+ const { admission, requestContact } = this.serviceAdmission(input.fromAid);
5020
+ const reply = await router.handleRequest(message, { admission, requestContact });
5021
+ if (!reply.shouldSend)
5022
+ return;
5023
+ await this.sendServiceReply(input.fromAid, input.messageId, input.encrypted, reply);
5024
+ }
5025
+ /** 回复:点对点、带 service 标记位,不带 threadId/topicName/chatmode。 */
5026
+ async sendServiceReply(toAid, replyToMessageId, encrypted, reply) {
5027
+ const result = await this.sendStructuredResult(toAid, reply.payload, {
5028
+ delivery: { chatType: 'private', service: { type: reply.type, requestId: reply.requestId } },
5029
+ metadata: { encrypted, source: 'daemon' },
5030
+ replyToMessageId,
5031
+ });
5032
+ if (!result.ok) {
5033
+ logger.warn(`${this.logPrefix()} Service reply send failed: type=${reply.type} code=${result.code ?? 'UNKNOWN'} error=${result.error ?? ''}`);
5034
+ }
5035
+ }
4860
5036
  setSessionStateResolver(resolver) {
4861
5037
  this.sessionStateResolver = resolver;
4862
5038
  }
@@ -5323,7 +5499,28 @@ export class AUNChannel {
5323
5499
  this.groupInviteDelivered?.(entry.postSend.requestId, messageId);
5324
5500
  }
5325
5501
  }
5502
+ /**
5503
+ * 目标是否为本端自己的 AID(self-address)。
5504
+ *
5505
+ * 跨话题自派不是跨主体通讯:收件人就是本端,联系人名录里有没有自己、名录快照是否
5506
+ * 可用都不该成为门槛。发送器层(`aun-ipc-sender.ts`)已按此短路,这里补上
5507
+ * 渠道层——否则 `sendDaemonMsg` / `callClient` 会再判一次,在名录缺自身
5508
+ * 条目或快照不可用的 Agent 上把跨话题派生挡成 CONTACT_DENIED。
5509
+ */
5510
+ isSelfAddressedTarget(channelId) {
5511
+ const normalize = (value) => String(value ?? '').trim().replace(/^@/, '').toLowerCase();
5512
+ const self = normalize(this.config.aid);
5513
+ const target = normalize(channelId);
5514
+ return !!self && !!target && self === target;
5515
+ }
5326
5516
  appContactOutboundBlock(channelId, delivery, payload, params) {
5517
+ // 服务回复是对一次已到达请求的应答,不是主动联系;且拒绝信息本身必须能送达,
5518
+ // 否则调用方只会看到超时。
5519
+ if (delivery.chatType === 'private' && delivery.service)
5520
+ return undefined;
5521
+ // 跨话题自派:收件人是本端,不是跨主体通讯,不适用联系人准入(同 aun-ipc-sender)。
5522
+ if (this.isSelfAddressedTarget(channelId))
5523
+ return undefined;
5327
5524
  if (delivery.chatType === 'group' || this.config.pureIdentity
5328
5525
  || this.hasContactControlPermit(channelId, payload, params))
5329
5526
  return undefined;
@@ -5338,6 +5535,11 @@ export class AUNChannel {
5338
5535
  error: `联系人准入未通过:${decision.reason}` };
5339
5536
  }
5340
5537
  async prepareAppContactOutbound(channelId, delivery, payload, params) {
5538
+ if (delivery.chatType === 'private' && delivery.service)
5539
+ return undefined;
5540
+ // 跨话题自派:收件人是本端,连通告归属刷新这一跳都不需要。
5541
+ if (this.isSelfAddressedTarget(channelId))
5542
+ return undefined;
5341
5543
  if (delivery.chatType === 'private' && !this.config.pureIdentity
5342
5544
  && !this.hasContactControlPermit(channelId, payload, params)
5343
5545
  && !this.acceptsVerifiedOwnership(channelId, payload, params)) {
@@ -5381,7 +5583,7 @@ export class AUNChannel {
5381
5583
  logger.error(`${this.logPrefix()} Dropped durable AUN payload: invalid payload.mentions (${detail}) code=${code} channel=${channelId}`);
5382
5584
  return { ok: false, status: 'permanent', error: detail, code };
5383
5585
  }
5384
- if (delivery.chatType === 'private') {
5586
+ if (delivery.chatType === 'private' && !delivery.service) {
5385
5587
  normalizedPayload = this.withCurrentTopicName(channelId, normalizedPayload);
5386
5588
  }
5387
5589
  if (!this.client || !this.connected) {
@@ -5406,6 +5608,13 @@ export class AUNChannel {
5406
5608
  // Truncate payload if too large (AUN SDK limit: 1MB)
5407
5609
  const friendPayload = typeof payload.type === 'string' && payload.type.startsWith('friend.');
5408
5610
  const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
5611
+ if ((payload.type === 'activity' && truncatedPayload.type !== 'activity')
5612
+ || (isAgentFinalPayload(payload) && !isAgentFinalPayload(truncatedPayload))) {
5613
+ return {
5614
+ ok: false, status: 'permanent', code: 'PAYLOAD_TOO_LARGE',
5615
+ error: 'automatic output payload cannot fit the AUN limit without losing its structure',
5616
+ };
5617
+ }
5409
5618
  const params = { payload: truncatedPayload, encrypt };
5410
5619
  const isMenuPayload = typeof truncatedPayload.type === 'string' && truncatedPayload.type.startsWith('menu.');
5411
5620
  if (!isGroup && ['menu.response', 'menu.event'].includes(truncatedPayload.type))
@@ -5470,9 +5679,12 @@ export class AUNChannel {
5470
5679
  return payload;
5471
5680
  const entry = ThreadService.findThreadById(this.config.aid, threadId);
5472
5681
  const type = payload.type;
5682
+ // 自发(target=本端)时 peer 是本端,而话题对端是别人;两者不相等不能当成
5683
+ // 话题不匹配。这种情况仍要带上话题名,客户端才能把这条消息正确归位。
5684
+ const selfAddressed = peer.trim().toLowerCase() === this.config.aid.trim().toLowerCase();
5473
5685
  if (!entry || typeof threadId !== 'string' || threadId !== entry.threadId
5474
- || typeof type !== 'string' || !AUN_TOPIC_NAME_PAYLOAD_TYPES.has(type)
5475
- || entry.peer.trim().toLowerCase() !== peer.trim().toLowerCase()
5686
+ || typeof type !== 'string' || (!AUN_TOPIC_NAME_PAYLOAD_TYPES.has(type) && !isAgentFinalPayload(payload))
5687
+ || (!selfAddressed && entry.peer.trim().toLowerCase() !== peer.trim().toLowerCase())
5476
5688
  || (entry.channelType && entry.channelType !== 'aun')) {
5477
5689
  return payload;
5478
5690
  }
@@ -5717,7 +5929,10 @@ export class AUNChannel {
5717
5929
  const result = await this.sendContentPayload(channelId, payload, {
5718
5930
  // Activity items use the durable activity queue so reconnect draining
5719
5931
  // preserves their ordering relative to other lifecycle events.
5720
- queue: payload.type === 'activity' ? 'activity' : undefined,
5932
+ queue: payload.type === 'activity' || isAgentFinalPayload(payload) ? 'activity' : undefined,
5933
+ ...(isAgentFinalPayload(payload) && payload.task_id ? {
5934
+ dedupeKey: `agent-final:${payload.session_id ?? ''}:${payload.task_id}`,
5935
+ } : {}),
5721
5936
  contentKind: 'custom',
5722
5937
  context,
5723
5938
  logText: logText ?? this.payloadLogText(payload, 'custom'),
@@ -5962,7 +6177,7 @@ export class AUNChannel {
5962
6177
  code: 'INVALID_REQUEST_TTL',
5963
6178
  };
5964
6179
  }
5965
- const contactBlock = await this.prepareAppContactOutbound(args.to, { chatType: 'private' }, finalPayload, { encrypt: args.encrypt, rawPayload: preserveRawPayload, ownershipVerified: args.ownershipVerified === true });
6180
+ const contactBlock = await this.prepareAppContactOutbound(args.to, args.service ? { chatType: 'private', service: args.service } : { chatType: 'private' }, finalPayload, { encrypt: args.encrypt, rawPayload: preserveRawPayload, ownershipVerified: args.ownershipVerified === true });
5966
6181
  if (contactBlock)
5967
6182
  return { ok: false, code: contactBlock.code, error: contactBlock.error };
5968
6183
  if (preserveRawPayload && jsonUtf8Size(finalPayload) > AUN_MAX_PAYLOAD_SIZE) {
@@ -5999,7 +6214,8 @@ export class AUNChannel {
5999
6214
  peerKey: formatPeerKey('aun', args.to),
6000
6215
  });
6001
6216
  }
6002
- if (chatmode && !finalPayload.chatmode)
6217
+ // 服务调用不是会话消息:不注入 chatmode,避免对端入站日志与脚本 data 被会话字段污染。
6218
+ if (chatmode && !finalPayload.chatmode && !args.service)
6003
6219
  finalPayload.chatmode = chatmode;
6004
6220
  const parentCausation = preserveRawPayload ? undefined : normalizeCausation(args.causation);
6005
6221
  const outboundCausation = parentCausation ? deriveCausation(parentCausation) : undefined;
@@ -6010,7 +6226,7 @@ export class AUNChannel {
6010
6226
  }
6011
6227
  if (args.debug)
6012
6228
  finalPayload.debug = { ...args.debug, sentAt: localTimestamp() };
6013
- if (!preserveRawPayload) {
6229
+ if (!preserveRawPayload && !args.service) {
6014
6230
  finalPayload = this.withCurrentTopicName(args.to, finalPayload);
6015
6231
  }
6016
6232
  if (!preserveRawPayload) {
@@ -6045,7 +6261,12 @@ export class AUNChannel {
6045
6261
  }
6046
6262
  this.forwardOutbound(result, args.debug);
6047
6263
  let logWritten = false;
6048
- if (args.log?.content !== undefined) {
6264
+ // 跨话题自派(`--to <本端AID>`)不写出站日志:chatDir 会按 (to=本端, self=本端) 算成
6265
+ // 「我↔我」目录,`ThreadService.listPeers` 的磁盘兜底会把它列成真实对端,
6266
+ // 而话题 T 的历史里也会凭空多出一条「发给本端自己」的出站记录。
6267
+ // 「自己收到了什么」由本地注入那条入站记录(source='self-address')表达。
6268
+ const selfAddressed = args.to.replace(/^@/, '').toLowerCase() === this.config.aid.replace(/^@/, '').toLowerCase();
6269
+ if (!selfAddressed && args.log?.content !== undefined) {
6049
6270
  const classified = classifyAunPayloadForLog(finalPayload);
6050
6271
  const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', args.to, this.config.aid);
6051
6272
  fs.mkdirSync(chatDir, { recursive: true });
@@ -6356,7 +6577,7 @@ export class AUNChannel {
6356
6577
  payload.chatmode = context.metadata.chatmode;
6357
6578
  if (context?.metadata?.forkAnchor)
6358
6579
  payload.fork_anchor = context.metadata.forkAnchor;
6359
- if (delivery.chatType === 'private') {
6580
+ if (delivery.chatType === 'private' && !delivery.service) {
6360
6581
  Object.assign(payload, this.withCurrentTopicName(channelId, payload));
6361
6582
  }
6362
6583
  const causation = normalizeCausation(context?.metadata?.causation);
@@ -6763,7 +6984,7 @@ export class AUNChannel {
6763
6984
  if (context?.debug)
6764
6985
  payloadWithChatmode.debug = { ...context.debug, sentAt: localTimestamp() };
6765
6986
  let thoughtPayload = payloadWithChatmode;
6766
- if (delivery.chatType === 'private') {
6987
+ if (delivery.chatType === 'private' && !delivery.service) {
6767
6988
  thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
6768
6989
  }
6769
6990
  thoughtPayload = this.limitThoughtPayload(thoughtPayload);
@@ -6812,7 +7033,7 @@ export class AUNChannel {
6812
7033
  if (!isThoughtTooLargeError(error))
6813
7034
  throw error;
6814
7035
  thoughtPayload = this.thoughtPayloadFallback(thoughtPayload);
6815
- if (delivery.chatType === 'private') {
7036
+ if (delivery.chatType === 'private' && !delivery.service) {
6816
7037
  thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
6817
7038
  }
6818
7039
  params.payload = thoughtPayload;
@@ -6871,7 +7092,7 @@ export class AUNChannel {
6871
7092
  finalPayload.thread_id = context.threadId;
6872
7093
  if (context?.replyToMessageId && !finalPayload.ref_message_id)
6873
7094
  finalPayload.ref_message_id = context.replyToMessageId;
6874
- if (!isGroup) {
7095
+ if (!isGroup && !delivery.service) {
6875
7096
  Object.assign(finalPayload, this.withCurrentTopicName(channelId, finalPayload));
6876
7097
  }
6877
7098
  const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
@@ -6912,7 +7133,8 @@ export class AUNChannel {
6912
7133
  return { ok: false, ...failure };
6913
7134
  }
6914
7135
  logger.info(`${this.logPrefix()} message.send (${payload.type}) ok: to=${this.peerLabel(targetAid)} mid=${mid} encrypt=${encrypt}`);
6915
- if (!isMenuPayload)
7136
+ // 服务回复不进 observer 镜像(回归 13)。
7137
+ if (!isMenuPayload && !delivery.service)
6916
7138
  this.forwardOutbound(result);
6917
7139
  return { ok: true, messageId: mid };
6918
7140
  }
@@ -7191,7 +7413,7 @@ export class AUNChannel {
7191
7413
  attachment: { ...attachment },
7192
7414
  context,
7193
7415
  }), context);
7194
- if (!isGroup) {
7416
+ if (!isGroup && !delivery.service) {
7195
7417
  Object.assign(filePayload, this.withCurrentTopicName(channelId, filePayload));
7196
7418
  }
7197
7419
  const fileTargetAid = channelId;
@@ -7814,6 +8036,8 @@ export class AUNChannelPlugin {
7814
8036
  aunTrace: ctx.debug?.aunTrace,
7815
8037
  aunSdkLog: ctx.debug?.aunSdkLog,
7816
8038
  });
8039
+ // 工程目录:服务脚本沙箱 cwd 与附件落盘共用同一个来源。
8040
+ channel.setDefaultProjectPath(ctx.defaultProjectPath);
7817
8041
  const mode = resolveShowActivities(inst);
7818
8042
  const adapter = {
7819
8043
  channelName: inst.name,
@@ -8038,14 +8262,18 @@ export class AUNChannelPlugin {
8038
8262
  channel.sendProcessingStatus(channelId, 'progress', envelope.sessionId ?? envelope.taskId, envelope.taskId, replyCtx, metadata);
8039
8263
  continue;
8040
8264
  }
8041
- const aunPayload = channel.buildActivityPayload(envelope, replyCtx, item);
8042
- if (envelope.chatmode === 'proactive') {
8265
+ let aunPayload = channel.buildActivityPayload(envelope, replyCtx, item);
8266
+ if (envelope.chatmode === 'proactive' && envelope.activityTransport === 'message'
8267
+ && payload.isFinal === true && (item.kind === 'text' || (item.kind === 'summary' && !item.is_error))) {
8268
+ const { item: _item, type: _type, ...base } = aunPayload;
8269
+ aunPayload = { ...base, type: 'custom', kind: 'agent_final', text: item.text };
8270
+ }
8271
+ if (envelope.chatmode === 'proactive' && envelope.activityTransport !== 'message') {
8043
8272
  await channel.sendThought(channelId, envelope.taskId, aunPayload, replyCtx);
8044
8273
  }
8045
8274
  else {
8046
- // Interactive and PA activities are reliable structured payloads;
8047
- // sendReliableStructured internally selects the activity
8048
- // outbox queue while preserving the common delivery contract.
8275
+ // The PA's proactive activities share interactive's reliable
8276
+ // activity outbox without changing the execution flow.
8049
8277
  const result = await channel.sendReliableStructured(channelId, aunPayload, replyCtx, channel.activityLogText(item));
8050
8278
  // Test and legacy adapters may stub this method without a
8051
8279
  // structured result; the call itself still proves acceptance.
@@ -107,6 +107,10 @@ function printAgentNewHelp() {
107
107
  export async function cmdAgent(args) {
108
108
  args = canonicalizeEvolcoreCommandArgv(['ec', 'agent', ...args]).slice(2);
109
109
  const sub = args[0];
110
+ if (sub === 'template') {
111
+ const { cmdAgentTemplate } = await import('./agent-template.js');
112
+ return cmdAgentTemplate(args.slice(1));
113
+ }
110
114
  if (sub === 'new') {
111
115
  const nameIndex = args.indexOf('--name');
112
116
  if (nameIndex >= 0)
@@ -130,6 +134,7 @@ Commands:
130
134
  list 列出所有 agent
131
135
  show <aid> 查看 agent 详情(身份 + 配置 + 连接 + 会话 + 路径)
132
136
  host <aid> 查看 agent 所在主机信息(位置、daemon、硬件、版本)
137
+ template <command> 模板清单、打包、上传、预检、安装及任务查询
133
138
  new <aid> ... 创建并激活(默认 --initialize,隐含非交互)
134
139
  new <aid> --bootstrap ... 创建后进入 Bootstrap(隐含非交互)
135
140
  initialize <aid> --resume 恢复一次性初始化
@@ -1133,8 +1133,8 @@ export function validateInitializationPlan(plan) {
1133
1133
  if (plan.chatmode !== undefined) {
1134
1134
  if (!plan.chatmode || typeof plan.chatmode !== 'object' || Array.isArray(plan.chatmode)
1135
1135
  || Object.entries(plan.chatmode).some(([scope, value]) => !['private', 'group', 'nothuman'].includes(scope)
1136
- || !(scope === 'group' ? ['proactive'] : ['interactive', 'proactive', ...(scope === 'private' ? ['paactive'] : [])]).includes(value))) {
1137
- failure('INVALID_ARGS', 'chatmode.group must be proactive; paactive is private AUN only');
1136
+ || !(scope === 'group' ? ['proactive'] : ['interactive', 'proactive']).includes(value))) {
1137
+ failure('INVALID_ARGS', 'chatmode.group must be proactive; private/nothuman must be interactive or proactive');
1138
1138
  }
1139
1139
  }
1140
1140
  if (plan.avatarFile !== undefined && plan.avatarUrl !== undefined)
@@ -1596,8 +1596,12 @@ export class AgentInitializationService {
1596
1596
  if (r.configSaved && (!config || config.enabled === false))
1597
1597
  failure('INITIALIZE_TARGET_CHANGED');
1598
1598
  const baseagentConfig = config?.baseagents?.[r.plan.baseagent];
1599
+ // Config loading strips trailing separators; compare canonical paths while
1600
+ // preserving the frozen plan and fingerprint for existing receipts.
1601
+ const project = config?.projects?.defaultPath;
1599
1602
  if (config && (config.initialization?.operationId !== r.operationId || config.initialization.mode !== 'supplied'
1600
- || config.active_baseagent !== r.plan.baseagent || config.projects?.defaultPath !== r.plan.project
1603
+ || config.active_baseagent !== r.plan.baseagent
1604
+ || typeof project !== 'string' || !path.isAbsolute(project) || path.resolve(project) !== path.resolve(r.plan.project)
1601
1605
  || (r.plan.model !== undefined && baseagentConfig?.model !== r.plan.model)
1602
1606
  || (r.plan.effort !== undefined && baseagentConfig?.effort !== r.plan.effort))) {
1603
1607
  failure('INITIALIZE_TARGET_CHANGED');