evolcore 0.0.48 → 0.0.50

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 (302) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/bin/ecmsg.js +9 -4
  3. package/dist/ability/caller/authorization.js +21 -0
  4. package/dist/ability/caller/command.js +164 -0
  5. package/dist/ability/caller/contract.js +102 -0
  6. package/dist/ability/caller/daemon.js +158 -0
  7. package/dist/ability/caller/service.js +380 -0
  8. package/dist/ability/command-contract.js +5 -0
  9. package/dist/ability/daemon.js +5 -1
  10. package/dist/ability/interop-v1.js +10 -3
  11. package/dist/ability/management.js +1 -0
  12. package/dist/agent-template/jobs.js +173 -1
  13. package/dist/agent-template/runtime.js +285 -8
  14. package/dist/agent-template/service.js +1159 -40
  15. package/dist/agent-template/types.js +2 -1
  16. package/dist/agents/baseagent-availability.js +27 -3
  17. package/dist/agents/baseagent-capability-adapter.js +102 -0
  18. package/dist/agents/baseagent-plugin-descriptor.js +274 -0
  19. package/dist/agents/baseagent-plugin-loader.js +145 -0
  20. package/dist/agents/baseagent.js +68 -2
  21. package/dist/agents/claude-gateway/agent-registration.js +389 -0
  22. package/dist/agents/claude-gateway/binding.js +96 -0
  23. package/dist/agents/claude-gateway/inbox.js +138 -0
  24. package/dist/agents/claude-gateway/index.js +125 -0
  25. package/dist/agents/claude-gateway/listing.js +330 -0
  26. package/dist/agents/claude-gateway/router.js +328 -0
  27. package/dist/agents/claude-gateway/sessions.js +128 -0
  28. package/dist/agents/claude-gateway/terminal.js +250 -0
  29. package/dist/agents/claude-gateway/transcript.js +272 -0
  30. package/dist/agents/claude-gateway/types.js +14 -0
  31. package/dist/agents/claude-runner.js +6 -10
  32. package/dist/agents/codex-runner.js +9 -2
  33. package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
  34. package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
  35. package/dist/agents/gemini/index.js +51 -0
  36. package/dist/aun/aid/control-aid.js +52 -32
  37. package/dist/aun/group/invite-service.js +6 -36
  38. package/dist/aun/group/operations.js +6 -0
  39. package/dist/aun/msg/mention-schema.js +1 -1
  40. package/dist/aun/msg/p2p.js +31 -2
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +1175 -457
  44. package/dist/cli/ability-command.js +42 -0
  45. package/dist/cli/agent-command.js +20 -1
  46. package/dist/cli/agent-create.js +78 -18
  47. package/dist/cli/agent-template.js +5 -3
  48. package/dist/cli/agent.js +91 -0
  49. package/dist/cli/aun-commands.js +92 -34
  50. package/dist/cli/bench.js +5 -2
  51. package/dist/cli/config.js +22 -6
  52. package/dist/cli/daemon-commands.js +245 -101
  53. package/dist/cli/directory.js +6 -1
  54. package/dist/cli/ecmsg-gateway.js +11 -9
  55. package/dist/cli/index.js +30 -5
  56. package/dist/cli/init.js +39 -63
  57. package/dist/cli/managed-command-guard.js +3 -0
  58. package/dist/cli/menu-client.js +32 -7
  59. package/dist/cli/model.js +20 -5
  60. package/dist/cli/pay-command.js +30 -0
  61. package/dist/cli/provider-command.js +6 -2
  62. package/dist/cli/quota.js +89 -0
  63. package/dist/cli/restart-monitor.js +2 -2
  64. package/dist/cli/role.js +1 -0
  65. package/dist/cli/services-command.js +12 -9
  66. package/dist/cli/team-workspace-command.js +56 -2
  67. package/dist/cli/thread-command.js +78 -12
  68. package/dist/config/access-policy.js +16 -3
  69. package/dist/config/config-field-policy.js +88 -9
  70. package/dist/config/config-manager.js +97 -47
  71. package/dist/config/config-operation-service.js +22 -1
  72. package/dist/config/gateway-config.js +9 -8
  73. package/dist/config/owner-config.js +0 -16
  74. package/dist/config/peer-role-resolver.js +1 -7
  75. package/dist/config/providers-config.js +107 -20
  76. package/dist/config/providers-management.js +45 -21
  77. package/dist/config/resolved-config-op.js +4 -44
  78. package/dist/config/schema-migration.js +78 -5
  79. package/dist/config/schema-registry.js +52 -7
  80. package/dist/config-store.js +1309 -17
  81. package/dist/core/agent-application-service.js +220 -1
  82. package/dist/core/agent-ipc-registration.js +19 -2
  83. package/dist/core/agent-reload-coordinator.js +5 -0
  84. package/dist/core/agent-runtime.js +198 -54
  85. package/dist/core/auth/agent-delegation.js +14 -0
  86. package/dist/core/auth/delegation-authorization.js +33 -26
  87. package/dist/core/auth/operation-authorizer.js +16 -1
  88. package/dist/core/auth/operation-catalog.js +59 -7
  89. package/dist/core/baseagent-loader.js +30 -3
  90. package/dist/core/capability/capability-manager.js +16 -7
  91. package/dist/core/channel-runtime.js +4 -2
  92. package/dist/core/command/agent-control.js +20 -2
  93. package/dist/core/command/agent-template-menu.js +4 -3
  94. package/dist/core/command/cli-intent-parser.js +28 -0
  95. package/dist/core/command/command-handler.js +45 -2
  96. package/dist/core/command/menu-catalog.js +20 -4
  97. package/dist/core/command/menu-file-path.js +70 -0
  98. package/dist/core/command/menu-handler.js +97 -73
  99. package/dist/core/command/menu-protocol.js +29 -0
  100. package/dist/core/command/menu-query-batch.js +2 -2
  101. package/dist/core/command/private-mention-menu.js +71 -0
  102. package/dist/core/command/remote-shell.js +565 -0
  103. package/dist/core/command/slash-handler.js +17 -26
  104. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  105. package/dist/core/command/topic-slash.js +7 -1
  106. package/dist/core/daemon-bootstrap.js +0 -4
  107. package/dist/core/daemon-control.js +58 -1
  108. package/dist/core/daemon-lifecycle.js +29 -7
  109. package/dist/core/evolagent-registry.js +18 -9
  110. package/dist/core/handoff/runtime.js +1 -1
  111. package/dist/core/host-snapshot.js +8 -3
  112. package/dist/core/initialization/service.js +3 -0
  113. package/dist/core/interaction-router.js +130 -0
  114. package/dist/core/ipc-registration.js +5 -0
  115. package/dist/core/memory/consolidation-context.js +2 -1
  116. package/dist/core/memory/consolidation.js +35 -64
  117. package/dist/core/message/aun-ipc-sender.js +213 -74
  118. package/dist/core/message/aun-request-registry.js +31 -0
  119. package/dist/core/message/contact-admission.js +91 -6
  120. package/dist/core/message/contact-pending-inbound.js +113 -0
  121. package/dist/core/message/contact-thread-approval.js +212 -0
  122. package/dist/core/message/im-renderer.js +40 -1
  123. package/dist/core/message/message-admission.js +5 -39
  124. package/dist/core/message/message-bridge.js +197 -45
  125. package/dist/core/message/message-log.js +32 -0
  126. package/dist/core/message/message-queue.js +102 -18
  127. package/dist/core/message/peer-mode.js +15 -4
  128. package/dist/core/message/response-engine.js +174 -26
  129. package/dist/core/message/send-options.js +37 -3
  130. package/dist/core/message/send-routing.js +11 -7
  131. package/dist/core/model/config-scope.js +6 -14
  132. package/dist/core/model/model-catalog.js +5 -5
  133. package/dist/core/model/model-diagnostics.js +19 -0
  134. package/dist/core/model/model-fallback.js +13 -2
  135. package/dist/core/ownership/owner-resolver.js +12 -86
  136. package/dist/core/pack-auth.js +7 -0
  137. package/dist/core/pack-install.js +1 -1
  138. package/dist/core/permission/ec-command-parser.js +288 -77
  139. package/dist/core/permission/protected-paths.js +64 -9
  140. package/dist/core/permission/services-path-acl.js +458 -0
  141. package/dist/core/permission/tool-policy.js +26 -10
  142. package/dist/core/relation/peer-identity.js +13 -0
  143. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  144. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  145. package/dist/core/session/session-manager.js +47 -10
  146. package/dist/core/session/session-mapper.js +16 -0
  147. package/dist/core/skill/index-generator.js +2 -3
  148. package/dist/core/skill/switch-resolver.js +3 -0
  149. package/dist/core/task/task-recovery-service.js +1 -0
  150. package/dist/core/thread/command-parser.js +4 -1
  151. package/dist/core/thread/ipc-operation.js +4 -2
  152. package/dist/core/thread/thread-operation.js +25 -10
  153. package/dist/core/thread/thread-service.js +294 -55
  154. package/dist/core/thread/topic-id.js +67 -2
  155. package/dist/core/thread/types.js +15 -1
  156. package/dist/directory/owner-directory-admission.js +11 -8
  157. package/dist/directory/owner-directory-cache.js +19 -0
  158. package/dist/directory/owner-directory-markdown.js +1 -1
  159. package/dist/directory/owner-directory-policy.js +5 -30
  160. package/dist/directory/owner-directory-request-operation.js +5 -2
  161. package/dist/eck/kit-renderer.js +3 -2
  162. package/dist/eck/message-renderer.js +28 -5
  163. package/dist/ecweb/basic-settings-service.js +5 -9
  164. package/dist/ecweb/providers-service.js +4 -2
  165. package/dist/ecweb/runtime/supervisor.js +36 -8
  166. package/dist/event-center/center-config.js +9 -5
  167. package/dist/event-center/dispatcher.js +10 -1
  168. package/dist/event-center/ipc-operation.js +19 -0
  169. package/dist/event-center/registry.js +20 -5
  170. package/dist/event-center/runtime.js +10 -7
  171. package/dist/index.js +120 -41
  172. package/dist/ipc.js +83 -3
  173. package/dist/outputs/authorization.js +16 -0
  174. package/dist/outputs/cards.js +336 -0
  175. package/dist/outputs/events.js +3 -2
  176. package/dist/outputs/protocol.js +1 -0
  177. package/dist/outputs/service.js +2 -15
  178. package/dist/paths.js +48 -1
  179. package/dist/pay/command.js +38 -0
  180. package/dist/pay/protocol.js +136 -0
  181. package/dist/pay/runtime.js +188 -0
  182. package/dist/pay/service.js +384 -0
  183. package/dist/pay/store.js +81 -0
  184. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  185. package/dist/services/dispatcher.js +23 -5
  186. package/dist/services/host/main.js +388 -0
  187. package/dist/services/host/protocol.js +118 -0
  188. package/dist/services/host/resident.js +310 -0
  189. package/dist/services/host-client.js +386 -0
  190. package/dist/services/host-deploy.js +180 -0
  191. package/dist/services/host-launch.js +117 -0
  192. package/dist/services/host-recycle.js +203 -0
  193. package/dist/services/host-runtime.js +802 -0
  194. package/dist/services/idempotency.js +44 -86
  195. package/dist/services/index-generator.js +4 -3
  196. package/dist/services/index.js +204 -22
  197. package/dist/services/ipc-operation.js +288 -44
  198. package/dist/services/pack-manager.js +1 -0
  199. package/dist/services/script-runner.js +515 -83
  200. package/dist/services/service-payload.js +13 -7
  201. package/dist/services/validation.js +109 -4
  202. package/dist/stats/budget.js +1 -1
  203. package/dist/stats/model-resolver.js +2 -2
  204. package/dist/stats/quota-query.js +95 -0
  205. package/dist/trigger/application-service.js +6 -4
  206. package/dist/trigger/local-files.js +19 -9
  207. package/dist/trigger/scheduler.js +22 -12
  208. package/dist/trigger/script-sandbox.js +51 -8
  209. package/dist/utils/aid-bind.js +3 -0
  210. package/dist/utils/atomic-write.js +22 -8
  211. package/dist/utils/evolcore-version.js +2 -2
  212. package/dist/utils/host-info.js +173 -1
  213. package/dist/utils/logger.js +2 -2
  214. package/dist/utils/media-cache.js +190 -43
  215. package/dist/utils/npm-ops.js +43 -8
  216. package/dist/utils/restart-safety.js +14 -1
  217. package/dist/utils/system-memory.js +113 -25
  218. package/dist/utils/systemd-lifecycle.js +154 -0
  219. package/dist/utils/windows-shell-trust.js +7 -3
  220. package/dist/workbench/service.js +1 -1
  221. package/kits/docs/INDEX.md +3 -2
  222. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
  223. package/kits/docs/channels/aun.md +1 -1
  224. package/kits/docs/evolcore/INDEX.md +9 -6
  225. package/kits/docs/evolcore/agent.md +36 -1
  226. package/kits/docs/evolcore/aid.md +45 -3
  227. package/kits/docs/evolcore/config.md +5 -2
  228. package/kits/docs/evolcore/directory.md +8 -9
  229. package/kits/docs/evolcore/group.md +2 -1
  230. package/kits/docs/evolcore/memory-tags.md +2 -0
  231. package/kits/docs/evolcore/menu-client.md +3 -3
  232. package/kits/docs/evolcore/menu-protocol.md +7 -0
  233. package/kits/docs/evolcore/model.md +3 -0
  234. package/kits/docs/evolcore/msg.md +77 -10
  235. package/kits/docs/evolcore/pay.md +34 -0
  236. package/kits/docs/evolcore/provider.md +22 -1
  237. package/kits/docs/evolcore/quota.md +54 -0
  238. package/kits/docs/evolcore/role.md +3 -0
  239. package/kits/docs/evolcore/services.md +46 -18
  240. package/kits/docs/evolcore/stats.md +2 -0
  241. package/kits/docs/evolcore/thread-chain.md +2 -0
  242. package/kits/docs/evolcore/tool-authorization.md +10 -0
  243. package/kits/docs/evolcore/trigger.md +2 -0
  244. package/kits/rules/01-overview.md +11 -32
  245. package/kits/rules/02-navigation.md +7 -0
  246. package/kits/rules/06-channel.md +3 -3
  247. package/kits/schemas/_meta.json +38 -5
  248. package/kits/schemas/agent-config.schema.20.json +24 -0
  249. package/kits/schemas/agent-config.schema.21.json +974 -0
  250. package/kits/schemas/agent-config.schema.22.json +977 -0
  251. package/kits/schemas/agent-config.schema.23.json +958 -0
  252. package/kits/schemas/daemon.schema.10.json +373 -0
  253. package/kits/schemas/daemon.schema.9.json +12 -0
  254. package/kits/schemas/defaults.schema.7.json +472 -0
  255. package/kits/schemas/providers.schema.3.json +18 -2
  256. package/kits/schemas/relation-config.schema.13.json +289 -0
  257. package/kits/skills/.switches.json +17 -1
  258. package/kits/skills/ability/SKILL.md +229 -34
  259. package/kits/skills/ability/STRUCTURE.md +333 -0
  260. package/kits/skills/ability/references/cli.md +208 -0
  261. package/kits/skills/ability/references/development.md +107 -37
  262. package/kits/skills/ability/references/management.md +106 -46
  263. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  264. package/kits/skills/agent-output-cards/SKILL.md +64 -0
  265. package/kits/skills/ec-group/SKILL.md +8 -6
  266. package/kits/skills/ec-group/TASK.md +186 -0
  267. package/kits/skills/ec-group/WORKLOG.md +180 -0
  268. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  269. package/kits/skills/ec-pay/SKILL.md +101 -0
  270. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  271. package/kits/skills/ec-provider/SKILL.md +58 -9
  272. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  273. package/kits/skills/ec-service-call/SKILL.md +135 -0
  274. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  275. package/kits/skills/ec-trigger/SKILL.md +1 -1
  276. package/kits/templates/memory-consolidation/notes.md +2 -2
  277. package/kits/templates/memory-consolidation/workflow.md +46 -0
  278. package/kits/templates/roles/visitor.json +1 -0
  279. package/kits/templates/system-fragments/channel.md +13 -4
  280. package/kits/templates/system-fragments/commands.md +5 -3
  281. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  282. package/kits/templates/system-fragments/reply.md +1 -0
  283. package/kits/templates/system-fragments/session.md +1 -1
  284. package/kits/templates/system-fragments/thread.md +27 -128
  285. package/kits/templates/system-fragments/venue.md +27 -0
  286. package/package.json +4 -5
  287. package/scripts/agent-template/inspect.mjs +79 -29
  288. package/scripts/agent-template/overlay.mjs +20 -2
  289. package/scripts/agent-template/shared/common.mjs +24 -6
  290. package/scripts/agent-template/shared/team-schema.json +23 -5
  291. package/scripts/agent-template/shared/template-contract.mjs +107 -17
  292. package/scripts/agent-template/shared/template-package.mjs +254 -29
  293. package/scripts/agent-template/shared/template-runtime.mjs +145 -2
  294. package/scripts/agent-template/shared/template.mjs +67 -9
  295. package/scripts/agent-template/team-pack.mjs +132 -41
  296. package/scripts/agent-template/team-preview.mjs +249 -5
  297. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  298. package/kits/docs/evolcore/ability.md +0 -185
  299. package/kits/skills/ability/references/calling.md +0 -56
  300. package/kits/skills/ability/references/contract-checklist.md +0 -37
  301. package/kits/skills/ability/references/recovery.md +0 -27
  302. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -23,7 +23,8 @@ export function resolveTeamWorkspaceIdentity(agentAid) {
23
23
  const config = read(ConfigTarget.Agent, { self: agentAid }, { cache: false });
24
24
  if (!config)
25
25
  return null;
26
- const ownerAid = ownerResolver.owner(agentAid) ?? config.owner ?? config.owners?.[0];
26
+ // Ownership comes from the protocol alone; config never supplies an Owner.
27
+ const ownerAid = ownerResolver.owner(agentAid);
27
28
  if (!ownerAid || !isValidAid(ownerAid))
28
29
  return null;
29
30
  return { agentAid, ownerAid };
@@ -314,7 +314,13 @@ export async function handleTopicSlash(ctx) {
314
314
  name,
315
315
  ...(status ? { topicStatus: status } : {}),
316
316
  });
317
- return result(`✅ 已创建话题: ${created.name}\nref: ${created.threadId}`);
317
+ // 本地无名片缓存只提示、不阻止:建话题不发消息,离线也必须可建。
318
+ // 提示必须带补救动作,否则用户只知道"可能投递不了"却不知道下一步做什么。
319
+ const unverified = created.peerUnverified === true
320
+ ? `\n⚠ 对端 ${created.peer} 本地无名片缓存,消息可能无法投递`
321
+ + `\n 补拉名片后即可正常发送:ec aid agentmd get ${created.peer}`
322
+ : '';
323
+ return result(`✅ 已创建话题: ${created.name}\nref: ${created.threadId}${unverified}`);
318
324
  }
319
325
  if (sub === 'rename') {
320
326
  const ref = refSource(positional, flags);
@@ -42,10 +42,6 @@ export async function runBindBootstrapDaemon(daemonCfg, ecwebSupervisor) {
42
42
  });
43
43
  bindService.startCleanup();
44
44
  ownerResolver.setDaemonAid(daemonCfg.aid);
45
- ownerResolver.setConfiguredOwners(daemonCfg.aid, [
46
- daemonCfg.owner,
47
- ...(daemonCfg.owners ?? []),
48
- ].filter((owner) => typeof owner === 'string'));
49
45
  let controlChannel;
50
46
  let shutdown;
51
47
  let pendingShutdownReason;
@@ -9,6 +9,7 @@ import { authorizationDenialData, formatAuthorizationDenial } from './auth/autho
9
9
  import { controlReplyContext } from './message/outbound.js';
10
10
  import { deliverMenuResponse, enforceMenuResponseSize, evaluateMenuClientCompatibility, evolMenuResponseTransportMetadata, hasValidMenuId, logMenuRequestCompleted, logMenuRequestReceived, logMenuResponseRetry, MENU_RESPONSE_MAX_BYTES, MENU_RESPONSE_SAFETY_MARGIN_BYTES, MenuRequestDeduper, menuFailure, menuPayloadFingerprint, normalizeMenuResponseTiming, parseMenuControl, validateMenuRequest, withMenuProcessingTime, beginMenuDeliveryTiming, } from './command/menu-protocol.js';
11
11
  import { isProcessLevelOwner } from './command/command-handler.js';
12
+ import { RemoteShellService } from './command/remote-shell.js';
12
13
  import { onShutdown } from '../utils/cross-platform.js';
13
14
  import { logger } from '../utils/logger.js';
14
15
  import { resolvePaths } from '../paths.js';
@@ -27,6 +28,8 @@ export function startDaemonControlAid({ daemonCfg, cmdHandler, bindService, diag
27
28
  agentName: daemonCfg.aid,
28
29
  channelName: 'control',
29
30
  pureIdentity: true,
31
+ // No configured Owner: card publication validates whatever the remote
32
+ // ownership consensus reports, never a local declaration.
30
33
  defaultEncrypt: daemonCfg.aun?.defaultEncrypt,
31
34
  aunTrace: daemonCfg.debug?.aunTrace,
32
35
  aunSdkLog: daemonCfg.debug?.aunSdkLog,
@@ -52,7 +55,61 @@ export function startDaemonControlAid({ daemonCfg, cmdHandler, bindService, diag
52
55
  });
53
56
  if (!controlChannel)
54
57
  return undefined;
58
+ const currentShellOwner = () => {
59
+ const view = ownerResolver.snapshot(daemonCfg.aid);
60
+ const aid = ownerResolver.owner(daemonCfg.aid);
61
+ const relationVersion = view.relation?.relationVersion;
62
+ return aid && relationVersion !== undefined ? {
63
+ aid, relationVersion,
64
+ ...(view.validUntil !== undefined && !view.refreshFailure?.fallbackUsed
65
+ ? { validForMs: Math.max(0, view.validUntil - Date.now()) } : {}),
66
+ } : undefined;
67
+ };
68
+ const remoteShell = new RemoteShellService({
69
+ controlAid: daemonCfg.aid,
70
+ currentOwner: currentShellOwner,
71
+ refreshOwner: async () => {
72
+ await ownerResolver.refresh(daemonCfg.aid, {
73
+ source: 'remote-shell', maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, allowTransient: true,
74
+ });
75
+ return currentShellOwner();
76
+ },
77
+ connected: () => controlChannel.isConnected(),
78
+ send: async (input, text) => {
79
+ const result = await controlChannel.sendMessage(input.peerId, text, {
80
+ ...controlReplyContext(input, { encrypted: true }),
81
+ toDeviceId: input.peerDeviceId,
82
+ });
83
+ if (result.status === 'failed')
84
+ throw new Error('Remote shell text delivery failed');
85
+ },
86
+ notice: async (input, text, subtype) => {
87
+ await controlChannel.sendStructuredOrThrow(input.peerId, {
88
+ type: 'notice', subtype, severity: 'info', text,
89
+ }, {
90
+ ...controlReplyContext(input, { encrypted: true }),
91
+ toDeviceId: input.peerDeviceId,
92
+ });
93
+ },
94
+ });
95
+ const stopShellTransport = controlChannel.onTransportState(connected => {
96
+ if (!connected)
97
+ void remoteShell.closeAll('disconnected');
98
+ });
99
+ const stopShellOwnership = ownerResolver.onUpdate(aid => {
100
+ if (aid === daemonCfg.aid)
101
+ remoteShell.revalidateOwner();
102
+ });
103
+ onShutdown(async () => {
104
+ stopShellTransport();
105
+ stopShellOwnership();
106
+ await remoteShell.dispose();
107
+ });
55
108
  controlChannel.onMessage(async (opts) => {
109
+ if (remoteShell.handles(opts)) {
110
+ await remoteShell.handleText(opts);
111
+ return;
112
+ }
56
113
  const text = (opts.content || '').trim();
57
114
  let activeMenuRequest;
58
115
  let menuCompletionLogged = false;
@@ -239,7 +296,7 @@ export function startDaemonControlAid({ daemonCfg, cmdHandler, bindService, diag
239
296
  }
240
297
  return;
241
298
  }
242
- await controlChannel.sendMessage(opts.channelId, '可用指令:/pair(获取远程控制配对码)、/diag <问题描述>、/diag stop', controlReplyContext(opts));
299
+ await controlChannel.sendMessage(opts.channelId, '可用指令:/pair(获取远程控制配对码)、/diag <问题描述>、/diag stop、/exec(查询终端状态)、/exec on(进入终端,直接发送单条命令)、/exec off、/stop(兼容 /exec stop)', controlReplyContext(opts));
243
300
  }
244
301
  catch (e) {
245
302
  if (activeMenuRequest && !menuCompletionLogged) {
@@ -348,6 +348,7 @@ export class StartupTaskQueue {
348
348
  active = 0;
349
349
  stopped = false;
350
350
  timer;
351
+ immediate;
351
352
  constructor(concurrency = 2, intervalMs = 50) {
352
353
  this.concurrency = concurrency;
353
354
  this.intervalMs = intervalMs;
@@ -368,16 +369,20 @@ export class StartupTaskQueue {
368
369
  this.stopped = true;
369
370
  if (this.timer)
370
371
  clearTimeout(this.timer);
372
+ if (this.immediate)
373
+ clearImmediate(this.immediate);
371
374
  this.timer = undefined;
375
+ this.immediate = undefined;
372
376
  for (const task of this.pending.splice(0))
373
377
  task.resolve(false);
374
378
  }
375
379
  schedule() {
376
- if (this.stopped || this.timer || this.active >= this.concurrency || !this.pending.length)
380
+ if (this.stopped || this.timer || this.immediate || this.active >= this.concurrency || !this.pending.length)
377
381
  return;
378
382
  // Yield between admissions even when tasks finish synchronously.
379
- this.timer = setTimeout(() => {
383
+ const admit = () => {
380
384
  this.timer = undefined;
385
+ this.immediate = undefined;
381
386
  // Choose at admission time, so newly classified priority work can pass
382
387
  // queued idle channels. Never hold a free slot for unclassified work;
383
388
  // already-running connections finish within the existing concurrency cap.
@@ -398,7 +403,11 @@ export class StartupTaskQueue {
398
403
  this.schedule();
399
404
  });
400
405
  this.schedule();
401
- }, this.intervalMs);
406
+ };
407
+ if (this.intervalMs === 0)
408
+ this.immediate = setImmediate(admit);
409
+ else
410
+ this.timer = setTimeout(admit, this.intervalMs);
402
411
  }
403
412
  }
404
413
  /** Observe startup task admission without delaying IPC or background services. */
@@ -467,8 +476,17 @@ export async function recoverStartupObserverHints(options) {
467
476
  }
468
477
  catch (error) {
469
478
  attempts++;
479
+ // 一个永久失败的 Agent 不能无限期占住它自己的输入,更不能拖住宿主的总就绪
480
+ // 判定(`startupRecoveryPending` 会一直不清)。到上限后按降级放行,
481
+ // 并把被跳过的提示作为显式错误报出来,而不是静默丢弃。
482
+ if (attempts >= MAX_OBSERVER_HINT_ATTEMPTS) {
483
+ options.trace?.addSpan('daemon.observerHints', started, Date.now(), `${aid}; giving up after ${attempts} attempts`);
484
+ logger.error(`[startup] observer hint registration gave up for ${aid} after ${attempts} attempts; pending hints in this Agent are not restored: ${error}`);
485
+ options.onAgentHintsRecovered(aid);
486
+ return;
487
+ }
470
488
  options.trace?.addSpan('daemon.observerHints', started, Date.now(), `${aid}; retry pending`);
471
- logger.warn(`[startup] observer hint registration waits for ${aid} (attempt ${attempts}): ${error}`);
489
+ logger.warn(`[startup] observer hint registration waits for ${aid} (attempt ${attempts}/${MAX_OBSERVER_HINT_ATTEMPTS}): ${error}`);
472
490
  await recoveryRetryDelay();
473
491
  }
474
492
  }
@@ -481,6 +499,8 @@ export async function recoverStartupObserverHints(options) {
481
499
  function recoveryRetryDelay() {
482
500
  return new Promise(resolve => { const timer = setTimeout(resolve, 1_000); timer.unref?.(); });
483
501
  }
502
+ /** Observer hint 注册的连续失败上限:超过即降级放行,避免单个 Agent 拖住整个宿主就绪。 */
503
+ const MAX_OBSERVER_HINT_ATTEMPTS = 30;
484
504
  /**
485
505
  * Background recovery never gates Ready. Until an Agent's scan completes its
486
506
  * inputs stay queued; afterwards only sessions referenced by unfinished
@@ -499,8 +519,11 @@ export class StartupHandoffRecovery {
499
519
  const state = this.states.get(aid);
500
520
  if (!state || state.phase === 'ready')
501
521
  return;
522
+ // 扫描尚未产出结论时不阻塞:没有证据说明这个会话受任何未完成的 Handoff 影响,
523
+ // 退回 'startup Handoff scan' 会把该 Agent 的每个会话都挂在一次可能永远
524
+ // 等不到结果的后台扫描后面(与类注释的「后台恢复永不 gate Ready」矛盾)。
502
525
  if (!state.sessions)
503
- return 'startup Handoff scan';
526
+ return;
504
527
  if (state.sessions.has(sessionId))
505
528
  return 'session Handoff recovery';
506
529
  }
@@ -655,7 +678,7 @@ export async function resumePendingSessions({ sessionManager, messageQueue, drop
655
678
  sessionManager.clearProcessing(session.id);
656
679
  }
657
680
  }
658
- export function createDaemonShutdown({ disposePluginResources, lifecycleNotices, stopOwnership, ipcServer, readySignalPath, bindService, ecwebSupervisor, messageQueue, permissionGateway, removePermissionConfigListener, stopStatsPersistence, triggerSchedulers, agentMap, eventBus, removeGroupInviteConfigListener, groupInviteReviewService, channelLoader, channelInstances, startupRunners, waitForRunnerLoads, cancelStartup, controlChannel, sessionManager, removeAll, exit, }) {
681
+ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices, stopOwnership, ipcServer, readySignalPath, bindService, ecwebSupervisor, messageQueue, permissionGateway, removePermissionConfigListener, stopStatsPersistence, triggerSchedulers, agentMap, eventBus, groupInviteReviewService, channelLoader, channelInstances, startupRunners, waitForRunnerLoads, cancelStartup, controlChannel, sessionManager, removeAll, exit, }) {
659
682
  let shutdownSignal = 'unknown';
660
683
  let shutdownInProgress = false;
661
684
  return async (signal, traceId) => {
@@ -781,7 +804,6 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
781
804
  });
782
805
  });
783
806
  eventBus.publish({ type: 'system:shutdown', timestamp: Date.now() });
784
- removeGroupInviteConfigListener();
785
807
  await shutdownStep('daemon.groupInvite', 'stop group invitation review', () => groupInviteReviewService.dispose());
786
808
  await shutdownStep('daemon.skillWatcher', 'stop global skill watcher', async () => {
787
809
  const { stopGlobalSkillWatcher } = await import('./skill/global-watcher.js');
@@ -5,12 +5,11 @@ import { logger } from '../utils/logger.js';
5
5
  import { aidLocalDir } from '../paths.js';
6
6
  import { readSoulContent } from './soul.js';
7
7
  import { invalidateAgentDisplayName, resolveAgentDisplayName } from '../aun/aid/agentmd.js';
8
- import { loadAllAgents, ensureAgentDirSkeleton, loadAgent, validateAgentConfig, } from '../config-store.js';
8
+ import { loadAllAgents, ensureAgentDirSkeleton, loadAgent, agentProjectChangeGate, assertAgentProjectChangeReady, validateAgentConfig, } from '../config-store.js';
9
9
  import { ConfigTarget, assertAgentAidAvailable, read as readConfig, resolveEffective } from '../config/config-manager.js';
10
10
  import { ensureInitialRoleRegistry } from '../config/role-service.js';
11
11
  import { resolveAgentLifecycle } from '../config/lifecycle.js';
12
12
  import { getOwners, getPrimaryOwner, ownerResolver } from './ownership/owner-resolver.js';
13
- import { configuredOwnerList } from '../config/owner-config.js';
14
13
  import { assertTemplateInstallationReady } from '../agent-template/jobs.js';
15
14
  // ── Channel Fingerprint ───────────────────────────────────────────────────
16
15
  // 用于检测多 agent 之间复用同一外部凭证的冲突(appId、aid、token 等)。
@@ -96,7 +95,6 @@ export class EvolAgentRegistry {
96
95
  for (const expandedRaw of rawAgents) {
97
96
  try {
98
97
  const raw = readConfig(ConfigTarget.Agent, { self: expandedRaw.aid }, { cache: true }) ?? expandedRaw;
99
- ownerResolver.setAgentConfiguredOwners(expandedRaw.aid, configuredOwnerList(raw));
100
98
  const precheck = precheckAgentConfig(expandedRaw.aid, raw);
101
99
  if (precheck) {
102
100
  this.registerErrorAgent(raw, `${precheck.code}: ${precheck.detail}`);
@@ -106,6 +104,13 @@ export class EvolAgentRegistry {
106
104
  // still reload through ConfigManager's normal atomic reader.
107
105
  const merged = resolveEffective({ self: expandedRaw.aid }, { cache: true });
108
106
  const agent = new EvolAgent(raw, merged);
107
+ const projectGate = agentProjectChangeGate(agent.aid);
108
+ if (projectGate) {
109
+ agent.status = projectGate.state === 'recovery' ? 'error' : 'stopped';
110
+ if (projectGate.state === 'recovery')
111
+ agent.error = 'PROJECT_RECOVERY_REQUIRED';
112
+ this.manuallyStopped.add(agent.aid);
113
+ }
109
114
  ensureAgentDirSkeleton(expandedRaw.aid);
110
115
  ensureInitialRoleRegistry(expandedRaw.aid);
111
116
  this.agents.set(agent.aid, agent);
@@ -116,7 +121,6 @@ export class EvolAgentRegistry {
116
121
  }
117
122
  for (const { agent: expandedRaw, reason } of invalidAgents) {
118
123
  const raw = readConfig(ConfigTarget.Agent, { self: expandedRaw.aid }, { cache: true }) ?? expandedRaw;
119
- ownerResolver.setAgentConfiguredOwners(expandedRaw.aid, configuredOwnerList(raw));
120
124
  this.registerErrorAgent(raw, reason);
121
125
  }
122
126
  this.detectAndFlagConflicts();
@@ -242,12 +246,13 @@ export class EvolAgentRegistry {
242
246
  this.personalNameCache.delete(aid);
243
247
  }
244
248
  runnableAgents() {
245
- return this.allAgents().filter(a => a.status === 'stopped');
249
+ return this.allAgents().filter(a => a.status === 'stopped' && !agentProjectChangeGate(a.aid));
246
250
  }
247
251
  getSkipped() {
248
252
  return [...this.skipped];
249
253
  }
250
254
  loadNewAgent(aid) {
255
+ assertAgentProjectChangeReady(aid);
251
256
  assertAgentAidAvailable(aid);
252
257
  if (this.agents.has(aid)) {
253
258
  logger.info(`[EvolAgentRegistry] agent ${aid} already loaded, skipping`);
@@ -288,7 +293,6 @@ export class EvolAgentRegistry {
288
293
  return this.registerErrorAgent(expandedRaw, `${precheck.code}: ${precheck.detail}`);
289
294
  }
290
295
  const raw = readConfig(ConfigTarget.Agent, { self: aid }, { cache: true }) ?? expandedRaw;
291
- ownerResolver.setAgentConfiguredOwners(aid, configuredOwnerList(raw));
292
296
  const merged = resolveEffective({ self: aid }, {});
293
297
  const agent = new EvolAgent(raw, merged);
294
298
  ensureAgentDirSkeleton(aid);
@@ -305,6 +309,7 @@ export class EvolAgentRegistry {
305
309
  if (!oldAgent)
306
310
  throw new Error(`Agent "${aidOrName}" not found`);
307
311
  assertTemplateInstallationReady(oldAgent.aid, options.recoveryJobId);
312
+ assertAgentProjectChangeReady(oldAgent.aid);
308
313
  await hooks.beforeAgentOperation?.(oldAgent.aid);
309
314
  const expandedRaw = loadAgent(oldAgent.aid);
310
315
  if (!expandedRaw)
@@ -316,7 +321,6 @@ export class EvolAgentRegistry {
316
321
  if (precheck)
317
322
  throw new Error(`Precheck failed: ${precheck.detail}`);
318
323
  const raw = readConfig(ConfigTarget.Agent, { self: oldAgent.aid }, { cache: true }) ?? expandedRaw;
319
- ownerResolver.setAgentConfiguredOwners(oldAgent.aid, configuredOwnerList(raw));
320
324
  const merged = resolveEffective({ self: raw.aid }, {});
321
325
  if (oldAgent.status === 'disabled' && raw.enabled === false
322
326
  || (options.preserveStopped && oldAgent.status === 'stopped' || options.restoreStopped) && raw.enabled !== false) {
@@ -578,6 +582,7 @@ export class EvolAgentRegistry {
578
582
  logger.info(`[Registry] Stopped agent ${aidOrName}`);
579
583
  }
580
584
  async startAgent(aidOrName, hooks) {
585
+ assertAgentProjectChangeReady(aidOrName);
581
586
  assertAgentAidAvailable(aidOrName);
582
587
  assertTemplateInstallationReady(aidOrName);
583
588
  const agent = this.agents.get(aidOrName);
@@ -704,8 +709,12 @@ function safeInfoValue(fn, fallback) {
704
709
  function findInstanceByKey(raw, agent, channelKey) {
705
710
  return raw.channels.find(c => agent.effectiveChannelName(c.type, c.name) === channelKey) ?? null;
706
711
  }
707
- /** active Agent 只有本地私钥和证书齐全,才参与启动编排。 */
708
- function precheckAgentConfig(aid, config) {
712
+ /**
713
+ * active Agent 只有本地私钥和证书齐全,才参与启动编排。
714
+ *
715
+ * 纯本地文件判定(不读注册表状态),导出以便单测直接覆盖各 lifecycle / 文件组合。
716
+ */
717
+ export function precheckAgentConfig(aid, config) {
709
718
  if (resolveAgentLifecycle(config) !== 'active')
710
719
  return null;
711
720
  const directory = aidLocalDir(aid);
@@ -39,7 +39,7 @@ export class HandoffDeliveryFailedError extends Error {
39
39
  export class TriggerHandoffRequiredForbiddenError extends Error {
40
40
  code = 'TRIGGER_HANDOFF_REQUIRED_FORBIDDEN';
41
41
  constructor() {
42
- super('Trigger 的跨会话 ec msg/group send 只允许 --return none,不能使用 required');
42
+ super('Trigger 的跨会话 ecmsg send 只允许 --return none,不能使用 required');
43
43
  this.name = 'TriggerHandoffRequiredForbiddenError';
44
44
  }
45
45
  }
@@ -10,7 +10,7 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { parseDocument } from 'yaml';
12
12
  import { resolvePaths, agentMdPath } from '../paths.js';
13
- import { readHostInfo, probeVirtualization, probeRuntimes, readVersionInfo, readRuntimeInfo } from '../utils/host-info.js';
13
+ import { readHostInfo, probeVirtualization, probeOsProductName, probeRuntimes, readVersionInfo, readRuntimeInfo } from '../utils/host-info.js';
14
14
  import { loadDaemonConfig } from '../config-store.js';
15
15
  const EMPTY_RUNTIMES = { python: null, go: null, claudeCode: null, claudeCodeBundled: null, codex: null, ecagent: null };
16
16
  function staticCachePath() {
@@ -24,6 +24,7 @@ function readStaticCache() {
24
24
  return {
25
25
  virtualization: (raw.virtualization ?? 'unknown'),
26
26
  runtimes: { ...EMPTY_RUNTIMES, ...(raw.runtimes ?? {}) },
27
+ productName: typeof raw.productName === 'string' && raw.productName.trim() ? raw.productName.trim() : null,
27
28
  cachedAt: typeof raw.cachedAt === 'string' ? raw.cachedAt : new Date(0).toISOString(),
28
29
  };
29
30
  }
@@ -133,26 +134,30 @@ export function createHostSnapshotProvider(deps) {
133
134
  const staticState = {
134
135
  virtualization: cached?.virtualization ?? 'unknown',
135
136
  runtimes: cached?.runtimes ?? EMPTY_RUNTIMES,
137
+ productName: cached?.productName ?? null,
136
138
  cachedAt: cached?.cachedAt ?? null,
137
139
  virtualizationProbed: false,
138
140
  runtimesProbed: false,
139
141
  };
140
142
  const versions = readVersionInfo();
141
143
  const probe = async () => {
142
- const [virtualization, runtimes] = await Promise.all([
144
+ const [virtualization, runtimes, productName] = await Promise.all([
143
145
  probeVirtualization().then(value => ({ value }), () => ({ value: staticState.virtualization })),
144
146
  probeRuntimes().then(value => ({ value }), () => ({ value: staticState.runtimes })),
147
+ probeOsProductName().then(value => ({ value }), () => ({ value: staticState.productName })),
145
148
  ]);
146
149
  staticState.virtualization = virtualization.value;
147
150
  staticState.runtimes = runtimes.value;
151
+ staticState.productName = productName.value;
148
152
  staticState.virtualizationProbed = true;
149
153
  staticState.runtimesProbed = true;
150
154
  staticState.cachedAt = new Date().toISOString();
151
- writeStaticCache({ virtualization: staticState.virtualization, runtimes: staticState.runtimes, cachedAt: staticState.cachedAt });
155
+ writeStaticCache({ virtualization: staticState.virtualization, runtimes: staticState.runtimes, productName: staticState.productName, cachedAt: staticState.cachedAt });
152
156
  };
153
157
  const getHost = () => {
154
158
  const host = readHostInfo(versions.evolcore, resolvePaths().root, { runtimes: staticState.runtimes });
155
159
  host.os.virtualization = staticState.virtualization;
160
+ host.os.productName = staticState.productName;
156
161
  // CPU 只有 daemon 有采样值;采样未启动时宁可给 null,也不给一个骗人的数字。
157
162
  host.hardware.cpuUsagePercent = deps.getSystemCpuPercent?.() ?? null;
158
163
  return host;
@@ -1,5 +1,6 @@
1
1
  import crypto from 'node:crypto';
2
2
  import fs from 'node:fs';
3
+ import os from 'node:os';
3
4
  import path from 'node:path';
4
5
  import { createRequire } from 'node:module';
5
6
  import { resolvePaths } from '../../paths.js';
@@ -270,6 +271,8 @@ export class EcwebInitializationService {
270
271
  qrSvg: scannable ? qrSvg({
271
272
  type: 'evolcore.bind', version: readInstalledEvolcoreVersion(),
272
273
  platform: process.platform === 'win32' ? 'windows' : process.platform,
274
+ // 机器名随二维码带给 App:主机列表的默认显示名要用它,而不是 agent 的名字。
275
+ hostName: os.hostname(),
273
276
  bindType: 'daemon', subjectAid: state.controlAid,
274
277
  token: binding.token, expiresAt: binding.expiresAt,
275
278
  }) : null,
@@ -1,4 +1,134 @@
1
1
  import { logger } from '../utils/logger.js';
2
+ import crypto from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { agentDataDir } from '../paths.js';
5
+ import { atomicRead, atomicWriteJson, withFileLock } from '../utils/atomic-write.js';
6
+ import { MAX_WIDGET_VALUES_BYTES } from '../aun/msg/upload.js';
7
+ function widgetCardFile(selfAid, messageId) {
8
+ const key = crypto.createHash('sha256').update(messageId).digest('hex');
9
+ return path.join(agentDataDir(selfAid), 'aun', 'widget-cards', `${key}.json`);
10
+ }
11
+ export function readWidgetCard(selfAid, messageId) {
12
+ if (!messageId || messageId.length > 512)
13
+ return undefined;
14
+ const raw = atomicRead(widgetCardFile(selfAid, messageId));
15
+ if (raw === null)
16
+ return undefined;
17
+ const record = JSON.parse(raw);
18
+ if (record.version !== 1 || record.messageId !== messageId || !record.channelId || !record.initiatorAid
19
+ || !['private', 'group'].includes(record.chatType)
20
+ || !['pending', 'submitting', 'completed', 'cancelled'].includes(record.status)
21
+ || typeof record.encrypted !== 'boolean'
22
+ || (record.expiresAt !== undefined && (typeof record.expiresAt !== 'number' || !Number.isFinite(record.expiresAt)))) {
23
+ throw new Error('Invalid WidgetCard binding');
24
+ }
25
+ return record;
26
+ }
27
+ /** Replayed outbox delivery must never re-open a card that has already been answered. */
28
+ export function registerWidgetCard(selfAid, binding) {
29
+ const previous = readWidgetCard(selfAid, binding.messageId);
30
+ if (previous) {
31
+ if (previous.channelId !== binding.channelId || previous.chatType !== binding.chatType
32
+ || previous.threadId !== binding.threadId || previous.initiatorAid !== binding.initiatorAid) {
33
+ throw new Error('WidgetCard binding conflicts with an existing delivery');
34
+ }
35
+ return;
36
+ }
37
+ atomicWriteJson(widgetCardFile(selfAid, binding.messageId), binding);
38
+ }
39
+ export function cancelWidgetCard(selfAid, messageId) {
40
+ const binding = readWidgetCard(selfAid, messageId);
41
+ if (!binding || binding.status === 'completed' || binding.status === 'cancelled')
42
+ return;
43
+ atomicWriteJson(widgetCardFile(selfAid, messageId), { ...binding, status: 'cancelled' });
44
+ }
45
+ function widgetError(message, code = 'INVALID_WIDGET_REPLY') {
46
+ throw Object.assign(new Error(message), { code });
47
+ }
48
+ export function validateWidgetValues(values) {
49
+ if (!values || typeof values !== 'object' || Array.isArray(values))
50
+ widgetError('表单结果必须是 JSON 对象');
51
+ let nodes = 0;
52
+ const visit = (value, depth) => {
53
+ if (++nodes > 5000 || depth > 16)
54
+ widgetError('表单数据结构过于复杂');
55
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
56
+ return;
57
+ if (typeof value === 'number' && Number.isFinite(value))
58
+ return;
59
+ if (!value || typeof value !== 'object')
60
+ widgetError('表单包含无效 JSON 值');
61
+ if (Array.isArray(value)) {
62
+ for (const item of value)
63
+ visit(item, depth + 1);
64
+ return;
65
+ }
66
+ for (const [key, item] of Object.entries(value)) {
67
+ if (['__proto__', 'prototype', 'constructor'].includes(key))
68
+ widgetError('表单包含保留字段名');
69
+ visit(item, depth + 1);
70
+ }
71
+ };
72
+ visit(values, 0);
73
+ if (Buffer.byteLength(JSON.stringify(values), 'utf8') > MAX_WIDGET_VALUES_BYTES)
74
+ widgetError('表单结果超过 64 KiB');
75
+ }
76
+ /** Durable one-shot reply association. An interrupted dispatch is never blindly replayed. */
77
+ export async function acceptWidgetCardReply(input) {
78
+ const payload = input.payload;
79
+ if (payload.type !== 'widget_card_reply')
80
+ widgetError('无效的表单回复类型');
81
+ const cardId = payload.card_message_id;
82
+ const submissionId = payload.submission_id;
83
+ if (typeof cardId !== 'string' || !cardId || cardId.length > 512
84
+ || typeof submissionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(submissionId)) {
85
+ widgetError('缺少有效的原卡片或提交标识');
86
+ }
87
+ if (payload.action !== 'submit' && payload.action !== 'cancel')
88
+ widgetError('无效的表单动作');
89
+ if (payload.action === 'submit')
90
+ validateWidgetValues(payload.values);
91
+ const file = widgetCardFile(input.selfAid, cardId);
92
+ return withFileLock(`${file}.lock`, async () => {
93
+ const binding = readWidgetCard(input.selfAid, cardId);
94
+ if (!binding)
95
+ widgetError('卡片已失效,请重新发起', 'WIDGET_CARD_EXPIRED');
96
+ if (!input.senderAid || input.senderAid !== binding.initiatorAid
97
+ || input.channelId !== binding.channelId || input.chatType !== binding.chatType
98
+ || (payload.thread_id !== undefined && payload.thread_id !== binding.threadId)
99
+ || (binding.encrypted && !input.encrypted)
100
+ || (binding.sensitive && (!input.encrypted || input.chatType !== 'private'))) {
101
+ widgetError('该回复不符合原卡片的操作者或会话约束', 'WIDGET_CARD_FORBIDDEN');
102
+ }
103
+ if (binding.status === 'completed' || binding.status === 'cancelled') {
104
+ if (binding.submissionId === submissionId)
105
+ return 'duplicate';
106
+ widgetError('卡片已答复,请勿重复提交', 'WIDGET_CARD_COMPLETED');
107
+ }
108
+ if (binding.expiresAt !== undefined && binding.expiresAt <= Date.now())
109
+ widgetError('卡片已失效,请重新发起', 'WIDGET_CARD_EXPIRED');
110
+ if (binding.status !== 'pending')
111
+ widgetError('上次提交正在处理或结果待核实,请勿重复提交', 'WIDGET_CARD_IN_FLIGHT');
112
+ binding.status = 'submitting';
113
+ binding.submissionId = submissionId;
114
+ atomicWriteJson(file, binding);
115
+ try {
116
+ await input.dispatch(binding, payload.action, payload.values);
117
+ }
118
+ catch (error) {
119
+ // Match ActionInteraction callback failures: a live failure remains retryable.
120
+ // A process crash leaves the durable 'submitting' marker and cannot replay blindly.
121
+ const current = readWidgetCard(input.selfAid, cardId);
122
+ if (current?.status === 'submitting' && current.submissionId === submissionId) {
123
+ atomicWriteJson(file, { ...current, status: 'pending' });
124
+ }
125
+ throw error;
126
+ }
127
+ binding.status = payload.action === 'cancel' ? 'cancelled' : 'completed';
128
+ atomicWriteJson(file, binding);
129
+ return 'accepted';
130
+ });
131
+ }
2
132
  export class InteractionRouter {
3
133
  handlers = new Map();
4
134
  /** sessionId → 该会话当前待应答的交互数量,用于触发 wait 生命周期钩子 */
@@ -1,3 +1,4 @@
1
+ import { registerPaymentRuntime } from '../pay/runtime.js';
1
2
  import { createEventsOperationExecutor } from '../event-center/ipc-operation.js';
2
3
  import { createServicesOperationExecutor } from '../services/ipc-operation.js';
3
4
  import { ecwebInitializationService } from './initialization/service.js';
@@ -292,6 +293,9 @@ export function registerDaemonIpc({ lifecycle, ipcServer, agentRegistry, agentDe
292
293
  messageQueue,
293
294
  createCrossThreadReviewTrigger: input => createManagedCrossThreadReviewTrigger(input, triggerIpcDependencies),
294
295
  });
296
+ const disposePayments = registerPaymentRuntime({ ipcServer, channelInstances, sessionManager, messageQueue,
297
+ authorize: authorizeManagedAgentOperation });
298
+ lifecycle?.defer(disposePayments, 'payment-runtime');
295
299
  if (eventCenter) {
296
300
  ipcServer.setEventsOperationExecutor(createEventsOperationExecutor({
297
301
  registry: eventCenter,
@@ -667,6 +671,7 @@ export function registerCommandIpcProviders({ lifecycle, ipcServer, agentRegistr
667
671
  ipcServer.setConfigOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, requestId) => cmdHandler.handleConfigOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId));
668
672
  ipcServer.setPeerOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleContactOperation(argv, sessionId, delegationToken, delegationCommandHash));
669
673
  ipcServer.setRoleOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, localControl) => cmdHandler.handleRoleOperation(argv, sessionId, delegationToken, delegationCommandHash, localControl));
674
+ ipcServer.setQuotaOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, localControl) => cmdHandler.handleQuotaOperation(argv, sessionId, delegationToken, delegationCommandHash, localControl));
670
675
  ipcServer.setDirectoryOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleDirectoryOperation(argv, sessionId, delegationToken, delegationCommandHash));
671
676
  ipcServer.setAidOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, requestId) => cmdHandler.handleAidOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId));
672
677
  ipcServer.setAidOwnershipExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleOwnershipOperation(argv, sessionId, delegationToken, delegationCommandHash));
@@ -642,7 +642,8 @@ export function serializeConsolidationContext(input) {
642
642
  lines.push(`\`${feedbackFilePath(batchDir)}\``);
643
643
  lines.push('');
644
644
  lines.push('这是本次会话唯一可以直接写入的文件(文件已建好,直接写即可);写别的路径会被拒绝。不要用 shell 重定向、`tee` 或其它写入命令。');
645
- lines.push('未写入则收尾时回退到默认统计模板(模式、触发方式、耗时、新建/更新/归档条数等)。');
645
+ lines.push('反馈会以系统通知的形式原样发给用户:**只写一行纯文本**,不要 Markdown、标题、列表或换行——对端不解析格式,标记会原样显示。');
646
+ lines.push('未写入则收尾时回退到默认统计模板(模式、触发方式、新建/更新/归档条数等)。');
646
647
  const text = lines.join('\n');
647
648
  // ── 写批次目录(任务书唯一落点)────────────────────────────────────────────
648
649
  // 不再写会话运行目录:任务书落在 $EVOLCORE_HOME/tmp 或 %TEMP%/ec-session-<hash>/